Filter(转载)
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配置
- <!-- 编码过滤器 -->
- <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.常用过滤器
- <pre name="code" class="plain"><pre></pre><pre name="code" class="plain"></pre><pre></pre>
- <pre></pre>
- <pre></pre>
- <pre></pre>
- <pre></pre>
- <pre></pre>
- <pre></pre>
- </pre>
原文链接:http://blog.csdn.net/sd0902/article/details/8395641
Filter(转载)的更多相关文章
- 卡尔曼滤波器 Kalman Filter (转载)
在学习卡尔曼滤波器之前,首先看看为什么叫“卡尔曼”.跟其他著名的理论(例如傅立叶变换,泰勒级数等等)一样,卡尔曼也是一个人的名字,而跟他们不同的是,他是个现代人! 卡 尔曼全名Rudolf Emil ...
- Django(六)Session、CSRF、中间件
大纲 二.session 1.session与cookie对比 2.session基本原理及流程 3.session服务器操作(获取值.设置值.清空值) 4.session通用配置(在配置文件中) 5 ...
- ELK 学习笔记之 elasticsearch bool组合查询
elasticsearch bool组合查询: 相当于sql:where _type = 'books' and (price = 500 or title = 'bigdata') Note: mu ...
- [转]细说OpenSessionInView问题
转载:https://www.cnblogs.com/zjrodger/p/4615809.html. [环境参数] 环境:SSH框架 [问题描述] NoSession问题 HibernateTem ...
- django 操作数据库--orm(object relation mapping)---models
思想 django为使用一种新的方式,即:关系对象映射(Object Relational Mapping,简称ORM). PHP:activerecord Java:Hibernate C#:Ent ...
- 【转载】CSS3 filter:drop-shadow滤镜与box-shadow区别应用
文章转载自 张鑫旭-鑫空间-鑫生活 http://www.zhangxinxu.com/wordpress/ 原文链接:http://www.zhangxinxu.com/wordpress/?p=5 ...
- [转载] 布隆过滤器(Bloom Filter)详解
转载自http://www.cnblogs.com/haippy/archive/2012/07/13/2590351.html 布隆过滤器[1](Bloom Filter)是由布隆(Burton ...
- [转载]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] ...
- (转载)js数组中的find、filter、forEach、map四个方法的详解和应用实例
数组中的find.filter.forEach.map四个语法很相近,为了方便记忆,真正的掌握它们的用法,所以就把它们总结在一起喽. find():返回通过测试的数组的第一个元素的值 在第一次调用 c ...
随机推荐
- iframe无刷新跨域上传文件并获得返回值
原文:http://geeksun.iteye.com/blog/1070607 需求:从S平台上传文件到R平台,上传成功后R平台返回给S平台一个值,S平台是在一个页面弹出的浮窗里上传文件,所以不能用 ...
- Tensorflow张量
张量常规解释 张量(tensor)理论是数学的一个分支学科,在力学中有重要应用.张量这一术语起源于力学,它最初是用来表示弹性介质中各点应力状态的,后来张量理论发展成为力学和物理学的一个有力的数学工具. ...
- python +百度语音识别+图灵对话
https://github.com/Dongvdong/python_Smartvoice 上电后,只要周围声音超过 2000,开始录音5S 录音上传百度识别,并返回结果文字输出 继续等待,周围声音 ...
- SpringBoot实战(十四)之整合KafKa
本人今天上午参考了不少博文,发现不少博文不是特别好,不是因为依赖冲突问题就是因为版本问题. 于是我结合相关的博文和案例,自己改写了下并参考了下,于是就有了这篇文章.希望能够给大家帮助,少走一些弯路. ...
- centos时区设置
[root@ logs]# tzselect Please identify a location so that time zone rules can be set correctly.Pleas ...
- https安全协议原理
那么什么是HTTPS? HTTPS(Hypertext Transfer Protocol Secure)是一种通过计算机网络进行安全通信的传输协议.HTTPS经由HTTP进行通信,但利用TLS来加密 ...
- 【原创】MVC +WebUploader 实现分片上传大文件
大文件的上传是我一直以来想学习的一个技术点,今天在项目闲暇之时,终于有机会自己尝试了一把,本文仅仅是个Demo,各种错误处理都么有,仅限于大家来学习思路. 参考博文:http://www.cnblog ...
- JaxbUtil转json转XML工具类
json转换为XML工具类 package com.cxf.value; import org.springframework.util.StringUtils; import javax.xml.b ...
- java中的SHA单向加密
SHA全名叫做安全散列算法,是FIPS所认证的安全散列算法.能计算出一个数字消息所对应到的,长度固定的字符串(又称消息摘要)的算法.且若输入的消息不同,它们对应到不同字符串的机率很高. package ...
- C# 判断一个文本文件的编码格式(转载)
文件的字符集在Windows下有两种,一种是ANSI,一种Unicode.对于Unicode,Windows支持了它的三种编码方式,一种是小尾编码(Unicode),一种是大尾编码(BigEndian ...