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="http://img.my.csdn.net/uploads/201211/30/1354261672_8450.jpg" alt=""><img src="http://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>
Servlet中的过滤器Filter用法的更多相关文章
- java Servlet中的过滤器Filter
web.xml中元素执行的顺序listener->filter->struts拦截器->servlet. 1.过滤器的概念 Java中的Filter 并不是一个标准的Servlet ...
- Servlet中的过滤器Filter详解
加载执行顺序 context-param->listener->filter->servlet web.xml中元素执行的顺序listener->filter->stru ...
- Servlet中的过滤器Filter
链web.xml中元素执行的顺序listener->filter->struts拦截器->servlet. 1.过滤器的概念 Java中的Filter 并不是一个标准的Servlet ...
- Angularjs在控制器(controller.js)的js代码中使用过滤器($filter)格式化日期/时间实例
Angularjs内置的过滤器(filter)为我们的数据信息格式化提供了比较强大的功能,比如:格式化时间,日期.格式化数字精度.语言本地化.格式化货币等等.但这些过滤器一般都是在VIEW中使用的,比 ...
- servlet中的过滤器 国际化
1. 过滤器 基本概念 过滤器是需要在xml中配置的. 为什么需用到过滤器? 项目开发中,经常会涉及到重复代码的实现! 注册 ----à Servlet [1. 设置编码] ----à JSP 修改 ...
- serlvet中的过滤器filter
1.概念 过滤作用,对从客户端向服务器端发送的请求进行过滤,也可以对服务器端返回的响应进行处理.它使用户可以改变一个request和修改一个 response..Filter 不是一个servlet, ...
- java中的过滤器 --Filter
package filter; import java.io.IOException; import javax.servlet.Filter; import javax.servlet.Filter ...
- Java过滤器—Filter用法简介
一.什么是Filter? Filter译为过滤器. 由于年,Sun公司在Servlet2.3规范中添加了Filter功能,并在Servlet2.4中对Filter进行了细节上的补充. 二.运行原理: ...
- Servlet中的过滤器和监听器
1.什么是过滤器? Servlet规范中定义的一种特殊的组件,用来拦截容器的调用过程.容器收到请求之后,首先调用过滤器,然后再调用Servlet 2.生命周期: 1.servlet:servlet的生 ...
随机推荐
- 好的 小图标 html
只需引用样式,加入字体文件到项目中就可实现 <link href="css/font-awesome.min.css" rel="stylesheet"& ...
- HDU ACM 1495 非常可乐(广搜BFS)
非常可乐 Time Limit : 2000/1000ms (Java/Other) Memory Limit : 32768/32768K (Java/Other) Total Submissi ...
- FZU 1914 Funny Positive Sequence(线性算法)
这个当时我没有做出来,看了很多人包括学长的代码才懂,我感觉最好的方法还是下面那一种,标记以谁开头的是不行的,我感觉有点不好理解,如果不懂举组样例在纸上写一下就会比较清楚了 #include<io ...
- Ubuntu下安装Node.js
下载Linux Binaries (.tar.gz)二进制包 解压 重命名为node 移动到/usr/local/目录下 创建软连接 ln -s /usr/local/node/bin/node ...
- 转:Linux基本命令大全
Linux基本命令大全 新手刚刚接触Linux的时候可能处处感到不便,不过没有关系,接触新的事物都有这样的一个过程,在你用过Linux一段时间后,你就会逐渐了解Linux其实和Windows一样容 ...
- Chapter 1 First Sight——16
I drove around the school, following the line of traffic. 我开车绕学校随着交通线. 我开车穿过校园,紧跟着大部队. I was glad to ...
- Java项目开发第二天
相对来说今天还是轻松了挺多的,好了,刚刚跑完步,今天心情不错,直接进入主题,就不废话了. (PS:室友都去准备迎新了,老大也是,还好都将课本留给我了,可以好好的看看书了,好好学习,天天向上.) 图形用 ...
- ptrace
http://zhangwenxin82.blog.163.com/blog/static/114595956201171510512459/
- .htaccess 保护文件夹
想要保护admin文件夹,经过以下两个步骤: 步骤一.可以用记事本新建文件.htaccess,输入以下内容: AuthType BasicAuth UserFile D:/AppServ/www/Hi ...
- js学习之函数
1/.js中函数就是对象. 2/以表达式方式定义的函数一般不要函数名以使代码紧凑. 3/js中函数声明的方式会被默认提到外部脚本或最前面,所以在其定义前的代码也可调用. 然而以表达式方式的则不行. 4 ...