Servlet中的过滤器Filter用法
1.过滤器的概念
Java中的Filter 并不是一个标准的Servlet ,它不能处理用户请求,也不能对客户端生成响应。 主要用于对HttpServletRequest 进行预处理,也可以对HttpServletResponse 进行后处理,是个典型的处理链。
优点:过滤链的好处是,执行过程中任何时候都可以打断,只要不执行chain.doFilter()就不会再执行后面的过滤器和请求的内容。而在实际使用时,就要特别注意过滤链的执行顺序问题
2.过滤器的作用描述
- 在HttpServletRequest 到达Servlet 之前,拦截客户的HttpServletRequest 。
- 根据需要检查HttpServletRequest ,也可以修改HttpServletRequest 头和数据。
- 在HttpServletResponse 到达客户端之前,拦截HttpServletResponse 。
- 根据需要检查HttpServletResponse ,可以修改HttpServletResponse 头和数据。
3.过滤器的执行流程
4.Filter接口
1.如何驱动
在 web 应用程序启动时,web 服务器将根据 web.xml 文件中的配置信息来创建每个注册的 Filter 实例对象,并将其保存在服务器的内存中
2.方法介绍
- init() Init 方法在 Filter 生命周期中仅执行一次,web 容器在调用 init 方法时
- destory() 在Web容器卸载 Filter 对象之前被调用。该方法在Filter的生命周期中仅执行一次。在这个方法中,可以释放过滤器使用的资源。
- doFilter() Filter 链的执行
5.FilterChain接口
1.如何实例化
代表当前 Filter 链的对象。由容器实现,容器将其实例作为参数传入过滤器对象的doFilter()方法中
2.作用
调用过滤器链中的下一个过滤器
filter实例:
web.xml配置
- <!-- 编码过滤器 -->
- <filter>
- <filter-name>setCharacterEncoding</filter-name>
- <filter-class>com.company.strutstudy.web.servletstudy.filter.EncodingFilter</filter-class>
- <init-param>
- <param-name>encoding</param-name>
- <param-value>utf-8</param-value>
- </init-param>
- </filter>
- <filter-mapping>
- <filter-name>setCharacterEncoding</filter-name>
- <url-pattern>/*</url-pattern>
- </filter-mapping>
- <!-- 请求url日志记录过滤器 -->
- <filter>
- <filter-name>logfilter</filter-name>
- <filter-class>com.company.strutstudy.web.servletstudy.filter.LogFilter</filter-class>
- </filter>
- <filter-mapping>
- <filter-name>logfilter</filter-name>
- <url-pattern>/*</url-pattern>
- </filter-mapping>
编码拦截器:
- public class EncodingFilter implements Filter {
- private String encoding;
- private Map<String, String> params = new HashMap<String, String>();
- // 项目结束时就已经进行销毁
- public void destroy() {
- System.out.println("end do the encoding filter!");
- params=null;
- encoding=null;
- }
- public void doFilter(ServletRequest req, ServletResponse resp,
- FilterChain chain) throws IOException, ServletException {
- //UtilTimerStack.push("EncodingFilter_doFilter:");
- System.out.println("before encoding " + encoding + " filter!");
- req.setCharacterEncoding(encoding);
- // resp.setCharacterEncoding(encoding);
- // resp.setContentType("text/html;charset="+encoding);
- chain.doFilter(req, resp);
- System.out.println("after encoding " + encoding + " filter!");
- System.err.println("----------------------------------------");
- //UtilTimerStack.pop("EncodingFilter_doFilter:");
- }
- // 项目启动时就已经进行读取
- public void init(FilterConfig config) throws ServletException {
- System.out.println("begin do the encoding filter!");
- encoding = config.getInitParameter("encoding");
- for (Enumeration e = config.getInitParameterNames(); e
- .hasMoreElements();) {
- String name = (String) e.nextElement();
- String value = config.getInitParameter(name);
- params.put(name, value);
- }
- }
- }
日志拦截器:
- public class LogFilter implements Filter {
- FilterConfig config;
- public void destroy() {
- this.config = null;
- }
- public void doFilter(ServletRequest req, ServletResponse res,
- FilterChain chain) throws IOException, ServletException {
- // 获取ServletContext 对象,用于记录日志
- ServletContext context = this.config.getServletContext();
- //long before = System.currentTimeMillis();
- System.out.println("before the log filter!");
- //context.log("开始过滤");
- // 将请求转换成HttpServletRequest 请求
- HttpServletRequest hreq = (HttpServletRequest) req;
- // 记录日志
- System.out.println("Log Filter已经截获到用户的请求的地址:"+hreq.getServletPath() );
- //context.log("Filter已经截获到用户的请求的地址: " + hreq.getServletPath());
- try {
- // Filter 只是链式处理,请求依然转发到目的地址。
- chain.doFilter(req, res);
- } catch (Exception e) {
- e.printStackTrace();
- }
- System.out.println("after the log filter!");
- //long after = System.currentTimeMillis();
- // 记录日志
- //context.log("过滤结束");
- // 再次记录日志
- //context.log(" 请求被定位到" + ((HttpServletRequest) req).getRequestURI()
- // + "所花的时间为: " + (after - before));
- }
- public void init(FilterConfig config) throws ServletException {
- System.out.println("begin do the log filter!");
- this.config = config;
- }
- }
HelloServlet类:
- public class HelloWorldServlet extends HttpServlet{
- /**
- * 查看httpservlet实现的service一看便知,起到了一个controll控制器的作用(转向的)
- * 之后便是跳转至我们熟悉的doget,dopost等方法中
- */
- @Override
- protected void service(HttpServletRequest req, HttpServletResponse resp)
- throws ServletException, IOException {
- System.out.println("doservice..."+this.getInitParameter("encoding"));
- super.service(req, resp);
- }
- @Override
- protected void doGet(HttpServletRequest req, HttpServletResponse resp)
- throws ServletException, IOException {
- System.out.println("doget...");
- doPost(req, resp);
- }
- @Override
- protected void doPost(HttpServletRequest req, HttpServletResponse resp)
- throws ServletException, IOException {
- System.out.println("dopost...");
- }
- }
结果:
- before encoding utf-8 filter!
- before the log filter!
- Log Filter已经截获到用户的请求的地址:/hello
- doservice...UTF-8
- doget...
- dopost...
- after the log filter!
- after encoding utf-8 filter!
- ----------------------------------------
总结:
1.过滤器执行流程
2.常用过滤器
转载自http://blog.csdn.net/techbirds_bao/article/details/8243800
<div id="article_content" class="article_content">
<p>1.过滤器的概念</p>
<p style="text-align:left; text-indent:28px"><span style="font-family:Arial,sans-serif"><span style="line-height:28px"><span style="font-size:10px"><a href="http://lib.csdn.net/base/javaee" class="replace_word" title="Java EE知识库" target="_blank" style="color:#df3434; font-weight:bold;">Java</a>中的Filter 并不是一个标准的Servlet ,它不能处理用户请求,也不能对客户端生成响应。 主要用于对HttpServletRequest 进行预处理,也可以对HttpServletResponse 进行后处理,是个典型的处理链。</span><br>
</span></span></p>
<p style="text-align:left; text-indent:28px"><span style="font-family:Arial,sans-serif; font-size:10px"><span style="line-height:28px">优点:过滤链的好处是,执行过程中任何时候都可以打断,只要不执行chain.doFilter()就不会再执行后面的过滤器和请求的内容。而在实际使用时,就要特别注意过滤链的执行顺序问题</span></span></p>
<p>2.过滤器的作用描述</p>
<p></p>
<ul>
<li><span style="white-space:pre">在HttpServletRequest 到达Servlet 之前,拦截客户的HttpServletRequest 。 </span></li><li><span style="white-space:pre"> </span><span style="white-space:pre">根据需要检查HttpServletRequest ,也可以修改HttpServletRequest 头和数据。 </span></li><li><span style="white-space:pre"> </span><span style="white-space:pre"> </span><span style="white-space:pre">在HttpServletResponse 到达客户端之前,拦截HttpServletResponse 。 </span></li><li><span style="white-space:pre">根据需要检查HttpServletResponse ,可以修改HttpServletResponse 头和数据。</span></li></ul>
<p></p>
<p>3.过滤器的执行流程</p>
<p style="text-align:right"><span style="white-space:pre"><img src="//img-my.csdn.net/uploads/201211/30/1354261672_8450.jpg" alt=""><img src="//img-my.csdn.net/uploads/201211/30/1354261343_9300.png" alt="" style="white-space:pre; text-align:left"></span></p>
<p style="text-align:left"><span style="white-space:pre"><br>
</span></p>
<p>4.Filter接口</p>
<blockquote style="margin:0 0 0 40px; border:none; padding:0px">
<p>1.如何驱动</p>
</blockquote>
<p><span style="white-space:pre"></span></p>
<blockquote style="margin:0 0 0 40px; border:none; padding:0px">
<blockquote style="margin:0 0 0 40px; border:none; padding:0px">
<p>在 web 应用程序启动时,web 服务器将根据 web.xml 文件中的配置信息来创建每个注册的 Filter 实例对象,并将其保存在服务器的内存中</p>
</blockquote>
</blockquote>
<p><span style="white-space:pre"></span></p>
<blockquote style="margin:0 0 0 40px; border:none; padding:0px">
<p>2.方法介绍</p>
</blockquote>
<p><span style="white-space:pre"></span></p>
<p></p>
<ul>
<ul>
<li>init() Init 方法在 Filter 生命周期中仅执行一次,web 容器在调用 init 方法时</li><li>destory() 在Web容器卸载 Filter 对象之前被调用。该方法在Filter的生命周期中仅执行一次。在这个方法中,可以释放过滤器使用的资源。</li><li>doFilter() Filter 链的执行 </li></ul>
</ul>
<p></p>
<p>5.FilterChain接口</p>
<blockquote style="margin:0 0 0 40px; border:none; padding:0px">
<p>1.如何实例化</p>
</blockquote>
<p><span style="white-space:pre"></span></p>
<blockquote style="margin:0 0 0 40px; border:none; padding:0px">
<blockquote style="margin:0 0 0 40px; border:none; padding:0px">
<p><span style="white-space:pre">代表当前 Filter 链的对象。由容器实现,容器将其实例作为参数传入过滤器对象的doFilter()方法中</span></p>
</blockquote>
</blockquote>
<blockquote style="margin:0 0 0 40px; border:none; padding:0px">
<p>2.作用</p>
</blockquote>
<p><span style="white-space:pre"></span></p>
<blockquote style="margin:0 0 0 40px; border:none; padding:0px">
<blockquote style="margin:0 0 0 40px; border:none; padding:0px">
<p><span style="white-space:pre">调用过滤器链中的下一个过滤器</span></p>
</blockquote>
</blockquote>
<p>filter实例:</p>
<p>web.xml配置</p>
<p><span style="font-family:monospace"><span style="white-space:pre"></span></span></p>
<div class="dp-highlighter bg_html"><div class="bar"><div class="tools"><b>[html]</b> <a href="#" class="ViewSource" title="view plain" onclick="dp.sh.Toolbar.Command('ViewSource',this);return false;">view plain</a><span data-mod="popu_168"> <a href="#" class="CopyToClipboard" title="copy" onclick="dp.sh.Toolbar.Command('CopyToClipboard',this);return false;">copy</a><div style="position: absolute; left: 463px; top: 1519px; width: 24px; height: 13px; z-index: 99;"><embed id="ZeroClipboardMovie_1" src="http://static.blog.csdn.net/scripts/ZeroClipboard/ZeroClipboard.swf" loop="false" menu="false" quality="best" bgcolor="#ffffff" name="ZeroClipboardMovie_1" allowscriptaccess="always" allowfullscreen="false" type="application/x-shockwave-flash" pluginspage="http://www.macromedia.com/go/getflashplayer" flashvars="id=1&width=24&height=13" wmode="transparent" width="24" align="middle" height="13"></div></span><span data-mod="popu_169"> <a href="#" class="PrintSource" title="print" onclick="dp.sh.Toolbar.Command('PrintSource',this);return false;">print</a></span><a href="#" class="About" title="?" onclick="dp.sh.Toolbar.Command('About',this);return false;">?</a></div></div><ol start="1" class="dp-xml"><li class="alt"><span><span class="comments"><!-- 编码过滤器 --></span><span> </span></span></li><li class=""><span> <span class="tag"><</span><span class="tag-name">filter</span><span class="tag">></span><span> </span></span></li><li class="alt"><span> <span class="tag"><</span><span class="tag-name">filter-name</span><span class="tag">></span><span>setCharacterEncoding</span><span class="tag"></</span><span class="tag-name">filter-name</span><span class="tag">></span><span> </span></span></li><li class=""><span> <span class="tag"><</span><span class="tag-name">filter-class</span><span class="tag">></span><span>com.company.strutstudy.web.servletstudy.filter.EncodingFilter</span><span class="tag"></</span><span class="tag-name">filter-class</span><span class="tag">></span><span> </span></span></li><li class="alt"><span> <span class="tag"><</span><span class="tag-name">init-param</span><span class="tag">></span><span> </span></span></li><li class=""><span> <span class="tag"><</span><span class="tag-name">param-name</span><span class="tag">></span><span>encoding</span><span class="tag"></</span><span class="tag-name">param-name</span><span class="tag">></span><span> </span></span></li><li class="alt"><span> <span class="tag"><</span><span class="tag-name">param-value</span><span class="tag">></span><span>utf-8</span><span class="tag"></</span><span class="tag-name">param-value</span><span class="tag">></span><span> </span></span></li><li class=""><span> <span class="tag"></</span><span class="tag-name">init-param</span><span class="tag">></span><span> </span></span></li><li class="alt"><span> <span class="tag"></</span><span class="tag-name">filter</span><span class="tag">></span><span> </span></span></li><li class=""><span> <span class="tag"><</span><span class="tag-name">filter-mapping</span><span class="tag">></span><span> </span></span></li><li class="alt"><span> <span class="tag"><</span><span class="tag-name">filter-name</span><span class="tag">></span><span>setCharacterEncoding</span><span class="tag"></</span><span class="tag-name">filter-name</span><span class="tag">></span><span> </span></span></li><li class=""><span> <span class="tag"><</span><span class="tag-name">url-pattern</span><span class="tag">></span><span>/*</span><span class="tag"></</span><span class="tag-name">url-pattern</span><span class="tag">></span><span> </span></span></li><li class="alt"><span> <span class="tag"></</span><span class="tag-name">filter-mapping</span><span class="tag">></span><span> </span></span></li><li class=""><span> </span></li><li class="alt"><span><span class="comments"><!-- 请求url日志记录过滤器 --></span><span> </span></span></li><li class=""><span> <span class="tag"><</span><span class="tag-name">filter</span><span class="tag">></span><span> </span></span></li><li class="alt"><span> <span class="tag"><</span><span class="tag-name">filter-name</span><span class="tag">></span><span>logfilter</span><span class="tag"></</span><span class="tag-name">filter-name</span><span class="tag">></span><span> </span></span></li><li class=""><span> <span class="tag"><</span><span class="tag-name">filter-class</span><span class="tag">></span><span>com.company.strutstudy.web.servletstudy.filter.LogFilter</span><span class="tag"></</span><span class="tag-name">filter-class</span><span class="tag">></span><span> </span></span></li><li class="alt"><span> <span class="tag"></</span><span class="tag-name">filter</span><span class="tag">></span><span> </span></span></li><li class=""><span> <span class="tag"><</span><span class="tag-name">filter-mapping</span><span class="tag">></span><span> </span></span></li><li class="alt"><span> <span class="tag"><</span><span class="tag-name">filter-name</span><span class="tag">></span><span>logfilter</span><span class="tag"></</span><span class="tag-name">filter-name</span><span class="tag">></span><span> </span></span></li><li class=""><span> <span class="tag"><</span><span class="tag-name">url-pattern</span><span class="tag">></span><span>/*</span><span class="tag"></</span><span class="tag-name">url-pattern</span><span class="tag">></span><span> </span></span></li><li class="alt"><span> <span class="tag"></</span><span class="tag-name">filter-mapping</span><span class="tag">></span><span> </span></span></li></ol><div class="save_code tracking-ad" data-mod="popu_249" style="display: none;"><a href="javascript:;" target="_blank"><img src="http://static.blog.csdn.net/images/save_snippets.png"></a></div></div><pre name="code" class="html" style="display: none;"><!-- 编码过滤器 -->
<filter>
<filter-name>setCharacterEncoding</filter-name>
<filter-class>com.company.strutstudy.web.servletstudy.filter.EncodingFilter</filter-class>
<init-param>
<param-name>encoding</param-name>
<param-value>utf-8</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>setCharacterEncoding</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<!-- 请求url日志记录过滤器 -->
<filter>
<filter-name>logfilter</filter-name>
<filter-class>com.company.strutstudy.web.servletstudy.filter.LogFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>logfilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping></pre><span style="white-space:pre"></span><br>
编码拦截器:
<p></p>
<p><span style="font-family:monospace"><span style="white-space:pre"></span></span></p>
<div class="dp-highlighter bg_java"><div class="bar"><div class="tools"><b>[java]</b> <a href="#" class="ViewSource" title="view plain" onclick="dp.sh.Toolbar.Command('ViewSource',this);return false;">view plain</a><span data-mod="popu_168"> <a href="#" class="CopyToClipboard" title="copy" onclick="dp.sh.Toolbar.Command('CopyToClipboard',this);return false;">copy</a><div style="position: absolute; left: 462px; top: 2049px; width: 24px; height: 13px; z-index: 99;"><embed id="ZeroClipboardMovie_2" src="http://static.blog.csdn.net/scripts/ZeroClipboard/ZeroClipboard.swf" loop="false" menu="false" quality="best" bgcolor="#ffffff" name="ZeroClipboardMovie_2" allowscriptaccess="always" allowfullscreen="false" type="application/x-shockwave-flash" pluginspage="http://www.macromedia.com/go/getflashplayer" flashvars="id=2&width=24&height=13" wmode="transparent" width="24" align="middle" height="13"></div></span><span data-mod="popu_169"> <a href="#" class="PrintSource" title="print" onclick="dp.sh.Toolbar.Command('PrintSource',this);return false;">print</a></span><a href="#" class="About" title="?" onclick="dp.sh.Toolbar.Command('About',this);return false;">?</a></div></div><ol start="1" class="dp-j"><li class="alt"><span><span class="keyword">public</span><span> </span><span class="keyword">class</span><span> EncodingFilter </span><span class="keyword">implements</span><span> Filter { </span></span></li><li class=""><span> <span class="keyword">private</span><span> String encoding; </span></span></li><li class="alt"><span> <span class="keyword">private</span><span> Map<String, String> params = </span><span class="keyword">new</span><span> HashMap<String, String>(); </span></span></li><li class=""><span> <span class="comment">// 项目结束时就已经进行销毁</span><span> </span></span></li><li class="alt"><span> <span class="keyword">public</span><span> </span><span class="keyword">void</span><span> destroy() { </span></span></li><li class=""><span> System.out.println(<span class="string">"end do the encoding filter!"</span><span>); </span></span></li><li class="alt"><span> params=<span class="keyword">null</span><span>; </span></span></li><li class=""><span> encoding=<span class="keyword">null</span><span>; </span></span></li><li class="alt"><span> } </span></li><li class=""><span> <span class="keyword">public</span><span> </span><span class="keyword">void</span><span> doFilter(ServletRequest req, ServletResponse resp, </span></span></li><li class="alt"><span> FilterChain chain) <span class="keyword">throws</span><span> IOException, ServletException { </span></span></li><li class=""><span> <span class="comment">//UtilTimerStack.push("EncodingFilter_doFilter:");</span><span> </span></span></li><li class="alt"><span> System.out.println(<span class="string">"before encoding "</span><span> + encoding + </span><span class="string">" filter!"</span><span>); </span></span></li><li class=""><span> req.setCharacterEncoding(encoding); </span></li><li class="alt"><span> <span class="comment">// resp.setCharacterEncoding(encoding);</span><span> </span></span></li><li class=""><span> <span class="comment">// resp.setContentType("text/html;charset="+encoding);</span><span> </span></span></li><li class="alt"><span> chain.doFilter(req, resp); </span></li><li class=""><span> System.out.println(<span class="string">"after encoding "</span><span> + encoding + </span><span class="string">" filter!"</span><span>); </span></span></li><li class="alt"><span> System.err.println(<span class="string">"----------------------------------------"</span><span>); </span></span></li><li class=""><span> <span class="comment">//UtilTimerStack.pop("EncodingFilter_doFilter:");</span><span> </span></span></li><li class="alt"><span> } </span></li><li class=""><span> </span></li><li class="alt"><span> <span class="comment">// 项目启动时就已经进行读取</span><span> </span></span></li><li class=""><span> <span class="keyword">public</span><span> </span><span class="keyword">void</span><span> init(FilterConfig config) </span><span class="keyword">throws</span><span> ServletException { </span></span></li><li class="alt"><span> System.out.println(<span class="string">"begin do the encoding filter!"</span><span>); </span></span></li><li class=""><span> encoding = config.getInitParameter(<span class="string">"encoding"</span><span>); </span></span></li><li class="alt"><span> <span class="keyword">for</span><span> (Enumeration e = config.getInitParameterNames(); e </span></span></li><li class=""><span> .hasMoreElements();) { </span></li><li class="alt"><span> String name = (String) e.nextElement(); </span></li><li class=""><span> String value = config.getInitParameter(name); </span></li><li class="alt"><span> params.put(name, value); </span></li><li class=""><span> } </span></li><li class="alt"><span> } </span></li><li class=""><span> } </span></li></ol><div class="save_code tracking-ad" data-mod="popu_249" style="display: none;"><a href="javascript:;" target="_blank"><img src="http://static.blog.csdn.net/images/save_snippets.png"></a></div></div><pre name="code" class="java" style="display: none;">public class EncodingFilter implements Filter {
private String encoding;
private Map<String, String> params = new HashMap<String, String>();
// 项目结束时就已经进行销毁
public void destroy() {
System.out.println("end do the encoding filter!");
params=null;
encoding=null;
}
public void doFilter(ServletRequest req, ServletResponse resp,
FilterChain chain) throws IOException, ServletException {
//UtilTimerStack.push("EncodingFilter_doFilter:");
System.out.println("before encoding " + encoding + " filter!");
req.setCharacterEncoding(encoding);
// resp.setCharacterEncoding(encoding);
// resp.setContentType("text/html;charset="+encoding);
chain.doFilter(req, resp);
System.out.println("after encoding " + encoding + " filter!");
System.err.println("----------------------------------------");
//UtilTimerStack.pop("EncodingFilter_doFilter:");
}
// 项目启动时就已经进行读取
public void init(FilterConfig config) throws ServletException {
System.out.println("begin do the encoding filter!");
encoding = config.getInitParameter("encoding");
for (Enumeration e = config.getInitParameterNames(); e
.hasMoreElements();) {
String name = (String) e.nextElement();
String value = config.getInitParameter(name);
params.put(name, value);
}
}
}</pre>日志拦截器:<div class="dp-highlighter bg_java"><div class="bar"><div class="tools"><b>[java]</b> <a href="#" class="ViewSource" title="view plain" onclick="dp.sh.Toolbar.Command('ViewSource',this);return false;">view plain</a><span data-mod="popu_168"> <a href="#" class="CopyToClipboard" title="copy" onclick="dp.sh.Toolbar.Command('CopyToClipboard',this);return false;">copy</a><div style="position: absolute; left: 462px; top: 2751px; width: 24px; height: 13px; z-index: 99;"><embed id="ZeroClipboardMovie_3" src="http://static.blog.csdn.net/scripts/ZeroClipboard/ZeroClipboard.swf" loop="false" menu="false" quality="best" bgcolor="#ffffff" name="ZeroClipboardMovie_3" allowscriptaccess="always" allowfullscreen="false" type="application/x-shockwave-flash" pluginspage="http://www.macromedia.com/go/getflashplayer" flashvars="id=3&width=24&height=13" wmode="transparent" width="24" align="middle" height="13"></div></span><span data-mod="popu_169"> <a href="#" class="PrintSource" title="print" onclick="dp.sh.Toolbar.Command('PrintSource',this);return false;">print</a></span><a href="#" class="About" title="?" onclick="dp.sh.Toolbar.Command('About',this);return false;">?</a></div></div><ol start="1" class="dp-j"><li class="alt"><span><span class="keyword">public</span><span> </span><span class="keyword">class</span><span> LogFilter </span><span class="keyword">implements</span><span> Filter { </span></span></li><li class=""><span> FilterConfig config; </span></li><li class="alt"><span> </span></li><li class=""><span> <span class="keyword">public</span><span> </span><span class="keyword">void</span><span> destroy() { </span></span></li><li class="alt"><span> <span class="keyword">this</span><span>.config = </span><span class="keyword">null</span><span>; </span></span></li><li class=""><span> } </span></li><li class="alt"><span> </span></li><li class=""><span> <span class="keyword">public</span><span> </span><span class="keyword">void</span><span> doFilter(ServletRequest req, ServletResponse res, </span></span></li><li class="alt"><span> FilterChain chain) <span class="keyword">throws</span><span> IOException, ServletException { </span></span></li><li class=""><span> <span class="comment">// 获取ServletContext 对象,用于记录日志</span><span> </span></span></li><li class="alt"><span> ServletContext context = <span class="keyword">this</span><span>.config.getServletContext(); </span></span></li><li class=""><span> <span class="comment">//long before = System.currentTimeMillis();</span><span> </span></span></li><li class="alt"><span> System.out.println(<span class="string">"before the log filter!"</span><span>); </span></span></li><li class=""><span> <span class="comment">//context.log("开始过滤");</span><span> </span></span></li><li class="alt"><span> <span class="comment">// 将请求转换成HttpServletRequest 请求</span><span> </span></span></li><li class=""><span> HttpServletRequest hreq = (HttpServletRequest) req; </span></li><li class="alt"><span> <span class="comment">// 记录日志</span><span> </span></span></li><li class=""><span> System.out.println(<span class="string">"Log Filter已经截获到用户的请求的地址:"</span><span>+hreq.getServletPath() ); </span></span></li><li class="alt"><span> <span class="comment">//context.log("Filter已经截获到用户的请求的地址: " + hreq.getServletPath());</span><span> </span></span></li><li class=""><span> <span class="keyword">try</span><span> { </span></span></li><li class="alt"><span> <span class="comment">// Filter 只是链式处理,请求依然转发到目的地址。</span><span> </span></span></li><li class=""><span> chain.doFilter(req, res); </span></li><li class="alt"><span> } <span class="keyword">catch</span><span> (Exception e) { </span></span></li><li class=""><span> e.printStackTrace(); </span></li><li class="alt"><span> } </span></li><li class=""><span> System.out.println(<span class="string">"after the log filter!"</span><span>); </span></span></li><li class="alt"><span> <span class="comment">//long after = System.currentTimeMillis();</span><span> </span></span></li><li class=""><span> <span class="comment">// 记录日志</span><span> </span></span></li><li class="alt"><span> <span class="comment">//context.log("过滤结束");</span><span> </span></span></li><li class=""><span> <span class="comment">// 再次记录日志</span><span> </span></span></li><li class="alt"><span> <span class="comment">//context.log(" 请求被定位到" + ((HttpServletRequest) req).getRequestURI()</span><span> </span></span></li><li class=""><span> <span class="comment">// + "所花的时间为: " + (after - before));</span><span> </span></span></li><li class="alt"><span> } </span></li><li class=""><span> </span></li><li class="alt"><span> <span class="keyword">public</span><span> </span><span class="keyword">void</span><span> init(FilterConfig config) </span><span class="keyword">throws</span><span> ServletException { </span></span></li><li class=""><span> System.out.println(<span class="string">"begin do the log filter!"</span><span>); </span></span></li><li class="alt"><span> <span class="keyword">this</span><span>.config = config; </span></span></li><li class=""><span> } </span></li><li class="alt"><span> </span></li><li class=""><span> } </span></li></ol><div class="save_code tracking-ad" data-mod="popu_249" style="display: none;"><a href="javascript:;" target="_blank"><img src="http://static.blog.csdn.net/images/save_snippets.png"></a></div></div><pre name="code" class="java" style="display: none;">public class LogFilter implements Filter {
FilterConfig config;
public void destroy() {
this.config = null;
}
public void doFilter(ServletRequest req, ServletResponse res,
FilterChain chain) throws IOException, ServletException {
// 获取ServletContext 对象,用于记录日志
ServletContext context = this.config.getServletContext();
//long before = System.currentTimeMillis();
System.out.println("before the log filter!");
//context.log("开始过滤");
// 将请求转换成HttpServletRequest 请求
HttpServletRequest hreq = (HttpServletRequest) req;
// 记录日志
System.out.println("Log Filter已经截获到用户的请求的地址:"+hreq.getServletPath() );
//context.log("Filter已经截获到用户的请求的地址: " + hreq.getServletPath());
try {
// Filter 只是链式处理,请求依然转发到目的地址。
chain.doFilter(req, res);
} catch (Exception e) {
e.printStackTrace();
}
System.out.println("after the log filter!");
//long after = System.currentTimeMillis();
// 记录日志
//context.log("过滤结束");
// 再次记录日志
//context.log(" 请求被定位到" + ((HttpServletRequest) req).getRequestURI()
// + "所花的时间为: " + (after - before));
}
public void init(FilterConfig config) throws ServletException {
System.out.println("begin do the log filter!");
this.config = config;
}
}</pre>HelloServlet类:<div class="dp-highlighter bg_java"><div class="bar"><div class="tools"><b>[java]</b> <a href="#" class="ViewSource" title="view plain" onclick="dp.sh.Toolbar.Command('ViewSource',this);return false;">view plain</a><span data-mod="popu_168"> <a href="#" class="CopyToClipboard" title="copy" onclick="dp.sh.Toolbar.Command('CopyToClipboard',this);return false;">copy</a><div style="position: absolute; left: 462px; top: 3561px; width: 24px; height: 13px; z-index: 99;"><embed id="ZeroClipboardMovie_4" src="http://static.blog.csdn.net/scripts/ZeroClipboard/ZeroClipboard.swf" loop="false" menu="false" quality="best" bgcolor="#ffffff" name="ZeroClipboardMovie_4" allowscriptaccess="always" allowfullscreen="false" type="application/x-shockwave-flash" pluginspage="http://www.macromedia.com/go/getflashplayer" flashvars="id=4&width=24&height=13" wmode="transparent" width="24" align="middle" height="13"></div></span><span data-mod="popu_169"> <a href="#" class="PrintSource" title="print" onclick="dp.sh.Toolbar.Command('PrintSource',this);return false;">print</a></span><a href="#" class="About" title="?" onclick="dp.sh.Toolbar.Command('About',this);return false;">?</a></div></div><ol start="1" class="dp-j"><li class="alt"><span><span class="keyword">public</span><span> </span><span class="keyword">class</span><span> HelloWorldServlet </span><span class="keyword">extends</span><span> HttpServlet{ </span></span></li><li class=""><span> </span></li><li class="alt"><span> <span class="comment">/**</span> </span></li><li class=""><span><span class="comment"> * 查看httpservlet实现的service一看便知,起到了一个controll控制器的作用(转向的)</span> </span></li><li class="alt"><span><span class="comment"> * 之后便是跳转至我们熟悉的doget,dopost等方法中 </span> </span></li><li class=""><span><span class="comment"> */</span><span> </span></span></li><li class="alt"><span> <span class="annotation">@Override</span><span> </span></span></li><li class=""><span> <span class="keyword">protected</span><span> </span><span class="keyword">void</span><span> service(HttpServletRequest req, HttpServletResponse resp) </span></span></li><li class="alt"><span> <span class="keyword">throws</span><span> ServletException, IOException { </span></span></li><li class=""><span> System.out.println(<span class="string">"doservice..."</span><span>+</span><span class="keyword">this</span><span>.getInitParameter(</span><span class="string">"encoding"</span><span>)); </span></span></li><li class="alt"><span> </span></li><li class=""><span> <span class="keyword">super</span><span>.service(req, resp); </span></span></li><li class="alt"><span> } </span></li><li class=""><span> </span></li><li class="alt"><span> <span class="annotation">@Override</span><span> </span></span></li><li class=""><span> <span class="keyword">protected</span><span> </span><span class="keyword">void</span><span> doGet(HttpServletRequest req, HttpServletResponse resp) </span></span></li><li class="alt"><span> <span class="keyword">throws</span><span> ServletException, IOException { </span></span></li><li class=""><span> System.out.println(<span class="string">"doget..."</span><span>); </span></span></li><li class="alt"><span> doPost(req, resp); </span></li><li class=""><span> } </span></li><li class="alt"><span> </span></li><li class=""><span> <span class="annotation">@Override</span><span> </span></span></li><li class="alt"><span> <span class="keyword">protected</span><span> </span><span class="keyword">void</span><span> doPost(HttpServletRequest req, HttpServletResponse resp) </span></span></li><li class=""><span> <span class="keyword">throws</span><span> ServletException, IOException { </span></span></li><li class="alt"><span> System.out.println(<span class="string">"dopost..."</span><span>); </span></span></li><li class=""><span> } </span></li><li class="alt"><span> </span></li><li class=""><span> </span></li><li class="alt"><span> </span></li><li class=""><span> } </span></li></ol><div class="save_code tracking-ad" data-mod="popu_249" style="display: none;"><a href="javascript:;" target="_blank"><img src="http://static.blog.csdn.net/images/save_snippets.png"></a></div></div><pre name="code" class="java" style="display: none;">public class HelloWorldServlet extends HttpServlet{
/**
* 查看httpservlet实现的service一看便知,起到了一个controll控制器的作用(转向的)
* 之后便是跳转至我们熟悉的doget,dopost等方法中
*/
@Override
protected void service(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
System.out.println("doservice..."+this.getInitParameter("encoding"));
super.service(req, resp);
}
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
System.out.println("doget...");
doPost(req, resp);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
System.out.println("dopost...");
}
}</pre>结果:<br>
<p><span style="font-family:monospace"><span style="white-space:pre"></span></span></p><div class="dp-highlighter bg_plain"><div class="bar"><div class="tools"><b>[plain]</b> <a href="#" class="ViewSource" title="view plain" onclick="dp.sh.Toolbar.Command('ViewSource',this);return false;">view plain</a><span data-mod="popu_168"> <a href="#" class="CopyToClipboard" title="copy" onclick="dp.sh.Toolbar.Command('CopyToClipboard',this);return false;">copy</a><div style="position: absolute; left: 464px; top: 4191px; width: 24px; height: 13px; z-index: 99;"><embed id="ZeroClipboardMovie_5" src="http://static.blog.csdn.net/scripts/ZeroClipboard/ZeroClipboard.swf" loop="false" menu="false" quality="best" bgcolor="#ffffff" name="ZeroClipboardMovie_5" allowscriptaccess="always" allowfullscreen="false" type="application/x-shockwave-flash" pluginspage="http://www.macromedia.com/go/getflashplayer" flashvars="id=5&width=24&height=13" wmode="transparent" width="24" align="middle" height="13"></div></span><span data-mod="popu_169"> <a href="#" class="PrintSource" title="print" onclick="dp.sh.Toolbar.Command('PrintSource',this);return false;">print</a></span><a href="#" class="About" title="?" onclick="dp.sh.Toolbar.Command('About',this);return false;">?</a></div></div><ol start="1"><li class="alt"><span><span>before encoding utf-8 filter! </span></span></li><li class=""><span> before the log filter! </span></li><li class="alt"><span> Log Filter已经截获到用户的请求的地址:/hello </span></li><li class=""><span> doservice...UTF-8 </span></li><li class="alt"><span> doget... </span></li><li class=""><span> dopost... </span></li><li class="alt"><span> after the log filter! </span></li><li class=""><span> after encoding utf-8 filter! </span></li><li class="alt"><span> ---------------------------------------- </span></li></ol><div class="save_code tracking-ad" data-mod="popu_249" style="display: none;"><a href="javascript:;" target="_blank"><img src="http://static.blog.csdn.net/images/save_snippets.png"></a></div></div><pre name="code" class="plain" style="display: none;">before encoding utf-8 filter!
before the log filter!
Log Filter已经截获到用户的请求的地址:/hello
doservice...UTF-8
doget...
dopost...
after the log filter!
after encoding utf-8 filter!
----------------------------------------</pre><p></p>
<p><span style="font-family:monospace"><span style="white-space:pre">总结:</span></span></p>
<blockquote style="margin:0 0 0 40px; border:none; padding:0px">
<p><span style="font-family:monospace"><span style="white-space:pre">1.过滤器执行流程</span></span></p>
<p><span style="font-family:monospace"><span style="white-space:pre">2.常用过滤器</span></span></p>
</blockquote>
<div class="dp-highlighter bg_html"><div class="bar"><div class="tools"><b>[html]</b> <a href="#" class="ViewSource" title="view plain" onclick="dp.sh.Toolbar.Command('ViewSource',this);return false;">view plain</a><span data-mod="popu_168"> <a href="#" class="CopyToClipboard" title="copy" onclick="dp.sh.Toolbar.Command('CopyToClipboard',this);return false;">copy</a><div style="position: absolute; left: 463px; top: 4495px; width: 24px; height: 13px; z-index: 99;"><embed id="ZeroClipboardMovie_6" src="http://static.blog.csdn.net/scripts/ZeroClipboard/ZeroClipboard.swf" loop="false" menu="false" quality="best" bgcolor="#ffffff" name="ZeroClipboardMovie_6" allowscriptaccess="always" allowfullscreen="false" type="application/x-shockwave-flash" pluginspage="http://www.macromedia.com/go/getflashplayer" flashvars="id=6&width=24&height=13" wmode="transparent" width="24" align="middle" height="13"></div></span><span data-mod="popu_169"> <a href="#" class="PrintSource" title="print" onclick="dp.sh.Toolbar.Command('PrintSource',this);return false;">print</a></span><a href="#" class="About" title="?" onclick="dp.sh.Toolbar.Command('About',this);return false;">?</a></div></div><ol start="1" class="dp-xml"><li class="alt"><span><span class="tag"><</span><span class="tag-name">pre</span><span> </span><span class="attribute">name</span><span>=</span><span class="attribute-value">"code"</span><span> </span><span class="attribute">class</span><span>=</span><span class="attribute-value">"plain"</span><span class="tag">></span><span class="tag"><</span><span class="tag-name">pre</span><span class="tag">></span><span class="tag"></</span><span class="tag-name">pre</span><span class="tag">></span><span class="tag"><</span><span class="tag-name">pre</span><span> </span><span class="attribute">name</span><span>=</span><span class="attribute-value">"code"</span><span> </span><span class="attribute">class</span><span>=</span><span class="attribute-value">"plain"</span><span class="tag">></span><span class="tag"></</span><span class="tag-name">pre</span><span class="tag">></span><span class="tag"><</span><span class="tag-name">pre</span><span class="tag">></span><span class="tag"></</span><span class="tag-name">pre</span><span class="tag">></span><span> </span></span></li><li class=""><span><span class="tag"><</span><span class="tag-name">pre</span><span class="tag">></span><span class="tag"></</span><span class="tag-name">pre</span><span class="tag">></span><span> </span></span></li><li class="alt"><span><span class="tag"><</span><span class="tag-name">pre</span><span class="tag">></span><span class="tag"></</span><span class="tag-name">pre</span><span class="tag">></span><span> </span></span></li><li class=""><span><span class="tag"><</span><span class="tag-name">pre</span><span class="tag">></span><span class="tag"></</span><span class="tag-name">pre</span><span class="tag">></span><span> </span></span></li><li class="alt"><span><span class="tag"><</span><span class="tag-name">pre</span><span class="tag">></span><span class="tag"></</span><span class="tag-name">pre</span><span class="tag">></span><span> </span></span></li><li class=""><span><span class="tag"><</span><span class="tag-name">pre</span><span class="tag">></span><span class="tag"></</span><span class="tag-name">pre</span><span class="tag">></span><span> </span></span></li><li class="alt"><span><span class="tag"><</span><span class="tag-name">pre</span><span class="tag">></span><span class="tag"></</span><span class="tag-name">pre</span><span class="tag">></span><span> </span></span></li><li class=""><span> </span></li><li class="alt"><span><span class="tag"></</span><span class="tag-name">pre</span><span class="tag">></span><span> </span></span></li></ol><div class="save_code tracking-ad" data-mod="popu_249" style="display: none;"><a href="javascript:;" target="_blank"><img src="http://static.blog.csdn.net/images/save_snippets.png"></a></div></div><pre name="code" class="html" style="display: none;"><div class="dp-highlighter bg_plain"><div class="bar"><div class="tools"><b>[plain]</b> <a href="#" class="ViewSource" title="view plain" onclick="dp.sh.Toolbar.Command('ViewSource',this);return false;">view plain</a><span data-mod="popu_168"> <a href="#" class="CopyToClipboard" title="copy" onclick="dp.sh.Toolbar.Command('CopyToClipboard',this);return false;">copy</a><div style="position: absolute; left: 0px; top: 0px; width: 0px; height: 0px; z-index: 99;"><embed id="ZeroClipboardMovie_7" src="http://static.blog.csdn.net/scripts/ZeroClipboard/ZeroClipboard.swf" loop="false" menu="false" quality="best" bgcolor="#ffffff" name="ZeroClipboardMovie_7" allowscriptaccess="always" allowfullscreen="false" type="application/x-shockwave-flash" pluginspage="http://www.macromedia.com/go/getflashplayer" flashvars="id=7&width=0&height=0" wmode="transparent" width="0" align="middle" height="0"></div></span><span data-mod="popu_169"> <a href="#" class="PrintSource" title="print" onclick="dp.sh.Toolbar.Command('PrintSource',this);return false;">print</a></span><a href="#" class="About" title="?" onclick="dp.sh.Toolbar.Command('About',this);return false;">?</a></div></div><ol start="1"><li class="alt"><span><span><pre></pre><pre name="code" class="plain"></pre><pre></pre> </span></span></li><li class=""><span><pre></pre> </span></li><li class="alt"><span><pre></pre> </span></li><li class=""><span><pre></pre> </span></li><li class="alt"><span><pre></pre> </span></li><li class=""><span><pre></pre> </span></li><li class="alt"><span><pre></pre> </span></li><li class=""><span> </span></li></ol><div class="save_code tracking-ad" data-mod="popu_249"><a href="javascript:;" target="_blank"><img src="http://static.blog.csdn.net/images/save_snippets.png"></a></div></div><pre name="code" class="plain" style="display: none;"><pre></pre><div class="dp-highlighter bg_plain"><div class="bar"><div class="tools"><b>[plain]</b> <a href="#" class="ViewSource" title="view plain" onclick="dp.sh.Toolbar.Command('ViewSource',this);return false;">view plain</a><span data-mod="popu_168"> <a href="#" class="CopyToClipboard" title="copy" onclick="dp.sh.Toolbar.Command('CopyToClipboard',this);return false;">copy</a><div style="position: absolute; left: 0px; top: 0px; width: 0px; height: 0px; z-index: 99;"><embed id="ZeroClipboardMovie_8" src="http://static.blog.csdn.net/scripts/ZeroClipboard/ZeroClipboard.swf" loop="false" menu="false" quality="best" bgcolor="#ffffff" name="ZeroClipboardMovie_8" allowscriptaccess="always" allowfullscreen="false" type="application/x-shockwave-flash" pluginspage="http://www.macromedia.com/go/getflashplayer" flashvars="id=8&width=0&height=0" wmode="transparent" width="0" align="middle" height="0"></div></span><span data-mod="popu_169"> <a href="#" class="PrintSource" title="print" onclick="dp.sh.Toolbar.Command('PrintSource',this);return false;">print</a></span><a href="#" class="About" title="?" onclick="dp.sh.Toolbar.Command('About',this);return false;">?</a></div></div><ol start="1"><li class="alt"><span><span> </span></span></li></ol><div class="save_code tracking-ad" data-mod="popu_249"><a href="javascript:;" target="_blank"><img src="http://static.blog.csdn.net/images/save_snippets.png"></a></div></div><pre name="code" class="plain" style="display: none;"></pre><pre></pre>
<pre></pre>
<pre></pre>
<pre></pre>
<pre></pre>
<pre></pre>
<pre></pre>
</pre></pre></div>