web.xml中元素执行的顺序listener->filter->struts拦截器->servlet。

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配置

  1. <!-- 编码过滤器 -->
  2. <filter>
  3. <filter-name>setCharacterEncoding</filter-name>
  4. <filter-class>com.company.strutstudy.web.servletstudy.filter.EncodingFilter</filter-class>
  5. <init-param>
  6. <param-name>encoding</param-name>
  7. <param-value>utf-8</param-value>
  8. </init-param>
  9. </filter>
  10. <filter-mapping>
  11. <filter-name>setCharacterEncoding</filter-name>
  12. <url-pattern>/*</url-pattern>
  13. </filter-mapping>
  14. <!-- 请求url日志记录过滤器 -->
  15. <filter>
  16. <filter-name>logfilter</filter-name>
  17. <filter-class>com.company.strutstudy.web.servletstudy.filter.LogFilter</filter-class>
  18. </filter>
  19. <filter-mapping>
  20. <filter-name>logfilter</filter-name>
  21. <url-pattern>/*</url-pattern>
  22. </filter-mapping>

编码拦截器:

  1. public class EncodingFilter implements Filter {
  2. private String encoding;
  3. private Map<String, String> params = new HashMap<String, String>();
  4. // 项目结束时就已经进行销毁
  5. public void destroy() {
  6. System.out.println("end do the encoding filter!");
  7. params=null;
  8. encoding=null;
  9. }
  10. public void doFilter(ServletRequest req, ServletResponse resp,
  11. FilterChain chain) throws IOException, ServletException {
  12. //UtilTimerStack.push("EncodingFilter_doFilter:");
  13. System.out.println("before encoding " + encoding + " filter!");
  14. req.setCharacterEncoding(encoding);
  15. // resp.setCharacterEncoding(encoding);
  16. // resp.setContentType("text/html;charset="+encoding);
  17. chain.doFilter(req, resp);
  18. System.out.println("after encoding " + encoding + " filter!");
  19. System.err.println("----------------------------------------");
  20. //UtilTimerStack.pop("EncodingFilter_doFilter:");
  21. }
  22. // 项目启动时就已经进行读取
  23. public void init(FilterConfig config) throws ServletException {
  24. System.out.println("begin do the encoding filter!");
  25. encoding = config.getInitParameter("encoding");
  26. for (Enumeration e = config.getInitParameterNames(); e
  27. .hasMoreElements();) {
  28. String name = (String) e.nextElement();
  29. String value = config.getInitParameter(name);
  30. params.put(name, value);
  31. }
  32. }
  33. }

日志拦截器:

  1. public class LogFilter implements Filter {
  2. FilterConfig config;
  3. public void destroy() {
  4. this.config = null;
  5. }
  6. public void doFilter(ServletRequest req, ServletResponse res,
  7. FilterChain chain) throws IOException, ServletException {
  8. // 获取ServletContext 对象,用于记录日志
  9. ServletContext context = this.config.getServletContext();
  10. //long before = System.currentTimeMillis();
  11. System.out.println("before the log filter!");
  12. //context.log("开始过滤");
  13. // 将请求转换成HttpServletRequest 请求
  14. HttpServletRequest hreq = (HttpServletRequest) req;
  15. // 记录日志
  16. System.out.println("Log Filter已经截获到用户的请求的地址:"+hreq.getServletPath() );
  17. //context.log("Filter已经截获到用户的请求的地址: " + hreq.getServletPath());
  18. try {
  19. // Filter 只是链式处理,请求依然转发到目的地址。
  20. chain.doFilter(req, res);
  21. } catch (Exception e) {
  22. e.printStackTrace();
  23. }
  24. System.out.println("after the log filter!");
  25. //long after = System.currentTimeMillis();
  26. // 记录日志
  27. //context.log("过滤结束");
  28. // 再次记录日志
  29. //context.log(" 请求被定位到" + ((HttpServletRequest) req).getRequestURI()
  30. //      + "所花的时间为: " + (after - before));
  31. }
  32. public void init(FilterConfig config) throws ServletException {
  33. System.out.println("begin do the log filter!");
  34. this.config = config;
  35. }
  36. }

HelloServlet类:

  1. public class HelloWorldServlet extends HttpServlet{
  2. /**
  3. * 查看httpservlet实现的service一看便知,起到了一个controll控制器的作用(转向的)
  4. * 之后便是跳转至我们熟悉的doget,dopost等方法中
  5. */
  6. @Override
  7. protected void service(HttpServletRequest req, HttpServletResponse resp)
  8. throws ServletException, IOException {
  9. System.out.println("doservice..."+this.getInitParameter("encoding"));
  10. super.service(req, resp);
  11. }
  12. @Override
  13. protected void doGet(HttpServletRequest req, HttpServletResponse resp)
  14. throws ServletException, IOException {
  15. System.out.println("doget...");
  16. doPost(req, resp);
  17. }
  18. @Override
  19. protected void doPost(HttpServletRequest req, HttpServletResponse resp)
  20. throws ServletException, IOException {
  21. System.out.println("dopost...");
  22. }
  23. }

结果:

  1. before encoding utf-8 filter!
  2. before the log filter!
  3. Log Filter已经截获到用户的请求的地址:/hello
  4. doservice...UTF-8
  5. doget...
  6. dopost...
  7. after the log filter!
  8. after encoding utf-8 filter!
  9. ----------------------------------------

总结:

1.过滤器执行流程

2.常用过滤器

  1. <pre name="code" class="plain"><pre></pre><pre name="code" class="plain"></pre><pre></pre>
  2. <pre></pre>
  3. <pre></pre>
  4. <pre></pre>
  5. <pre></pre>
  6. <pre></pre>
  7. <pre></pre>
  8. </pre>
分享到:    

原文链接:http://blog.csdn.net/sd0902/article/details/8395641

Filter(转载)的更多相关文章

  1. 卡尔曼滤波器 Kalman Filter (转载)

    在学习卡尔曼滤波器之前,首先看看为什么叫“卡尔曼”.跟其他著名的理论(例如傅立叶变换,泰勒级数等等)一样,卡尔曼也是一个人的名字,而跟他们不同的是,他是个现代人! 卡 尔曼全名Rudolf Emil ...

  2. Django(六)Session、CSRF、中间件

    大纲 二.session 1.session与cookie对比 2.session基本原理及流程 3.session服务器操作(获取值.设置值.清空值) 4.session通用配置(在配置文件中) 5 ...

  3. ELK 学习笔记之 elasticsearch bool组合查询

    elasticsearch bool组合查询: 相当于sql:where _type = 'books' and (price = 500 or title = 'bigdata') Note: mu ...

  4. [转]细说OpenSessionInView问题

    转载:https://www.cnblogs.com/zjrodger/p/4615809.html. [环境参数] 环境:SSH框架 [问题描述]  NoSession问题 HibernateTem ...

  5. django 操作数据库--orm(object relation mapping)---models

    思想 django为使用一种新的方式,即:关系对象映射(Object Relational Mapping,简称ORM). PHP:activerecord Java:Hibernate C#:Ent ...

  6. 【转载】CSS3 filter:drop-shadow滤镜与box-shadow区别应用

    文章转载自 张鑫旭-鑫空间-鑫生活 http://www.zhangxinxu.com/wordpress/ 原文链接:http://www.zhangxinxu.com/wordpress/?p=5 ...

  7. [转载] 布隆过滤器(Bloom Filter)详解

    转载自http://www.cnblogs.com/haippy/archive/2012/07/13/2590351.html   布隆过滤器[1](Bloom Filter)是由布隆(Burton ...

  8. [转载]JS中 map, filter, some, every, forEach, for in, for of 用法总结

    转载地址:http://codebay.cn/post/2110.html 1.map 有返回值,返回一个新的数组,每个元素为调用func的结果. let list = [1, 2, 3, 4, 5] ...

  9. (转载)js数组中的find、filter、forEach、map四个方法的详解和应用实例

    数组中的find.filter.forEach.map四个语法很相近,为了方便记忆,真正的掌握它们的用法,所以就把它们总结在一起喽. find():返回通过测试的数组的第一个元素的值 在第一次调用 c ...

随机推荐

  1. Nginx主程序使用介绍

    守护进程和服务 <br\>在首次运行Nginx之前,了解此应用程序的性质很重要. 有两种类型的计算机应用程序 – 那些需要用户输入,因此在前台运行,另一种在后台运行. Nginx是后一种类 ...

  2. react redux学习之路

    React 自学 chapter one React新的前端思维方式 React的首要思想是通过组件(Component)来开发应用.所谓组件,简单说,指的是能够完成某个特定功能的独立的.可重用的代码 ...

  3. 寒假训练 A - A Knight's Journey 搜索

    Background The knight is getting bored of seeing the same black and white squares again and again an ...

  4. (9)Python循环结构

  5. css权重 vs 浏览器渲染 -- css之弊病

    昨日,突现一个bug,令人十分恼火. 基本场景 自己实现一多选日历,可多选多天(相连或不相连均可)."贵司"的需求真心有些小复杂了,"市面"上没有这样的相似的东 ...

  6. ethereum/EIPs-155 Simple replay attack protection 35,36

    EIP 155:重放攻击保护——防止了在一个以太坊链上的交易被重复广播到另外一条链. 在看椭圆曲线时有提到,与r.s.v中的v相关 不同的共有链定义不同的chainId, 防止同一笔交易在不同的共有链 ...

  7. oracle 查询 归档日志最大值和平均值

    select max(ss.size_GB), avg(ss.size_GB)  from (select s.*, rownum rn2          from (select a.*      ...

  8. python对word的操作

    from docx import Document from docx.shared import Inches document = Document() document.add_heading( ...

  9. Runloop深入理解

    一.什么是Runloop?为什么需要Runloop? Runloop,顾名思义,即运行循环. 没有Runloop的情况下,一个线程执行完一个任务,就会退出并销毁.等到需要处理下一个任务时,再重新创建一 ...

  10. MySQL(四)字段及常用函数

    一.字段 数据库表中的每一行叫做一个“记录”,每一个记录包含这行中的所有信息,但记录在数据库中并没有专门的记录名,常常用它所在的行数表示这是第几个记录. 在数据库中存放在表行列交叉处的数据叫做“值”, ...