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 ...
随机推荐
- centos7下安装docker(12.5容器在单个host上的网络总结)
单个host上的容器的网络:通过本章的学习,我们知道docker默认有三种网络,可以通过docker network ls查看: none:封闭的网络,通过--network=none来指定: hos ...
- Class中的getClasses与getDeclaredClasses方法作用于区别
getClasses和getDeclaredClasses的区别: getClasses得到该类及其父类所有的public的内部类. getDeclaredClasses得到该类所有的内部类,除去父类 ...
- DataX的使用
简介 DataX 是阿里巴巴集团内被广泛使用的离线数据同步工具/平台,实现包括 MySQL.Oracle.HDFS.Hive.OceanBase.HBase.OTS.ODPS 等各种异构数据源之间高效 ...
- oracle 查询 磁盘使用率
SELECT d.tablespace_name "Name", TO_CHAR(NVL(a.bytes / 1024 / 1024 / 1024, 0), '99, ...
- 使用scrapy爬取海外网学习频道
一:创建项目文件 1:首先在终端使用命令scrapy startproject huaerjieribao 创建项目 2:创建spider 首先cd进去刚刚创建的项目文件overseas 然后执行ge ...
- PAT A1150 Travelling Salesman Problem (25 分)——图的遍历
The "travelling salesman problem" asks the following question: "Given a list of citie ...
- linux mint软件安装
安装linux mint步骤请自行百度,这里略过....下载地址:https://www.linuxmint.com/edition.php?id=246文档下载:https://www.linuxm ...
- 小程序 获取微信小程序的源码
1.微信小程序是以wxapkg可执行文件的形式存在本地的 2.网上有工具可以把wxapkg文件还原成源代码: https://github.com/qwerty472123/wxappUnpacker ...
- DNS主从复制及区域传送
前言 DNS主从复制,就是将主DNS服务器的解析库复制传送至从DNS服务器,进而从服务器就可以进行正向.反向解析了.从服务器向主服务器查询更新数据,保证数据一致性,此为区域传送.也可以说,DNS区域传 ...
- STL语法——集合:set 安迪的第一个字典(Andy's First Dictionary,UVa 10815)
Description Andy, , has a dream - he wants to produce his very own dictionary. This is not an easy t ...