一、Filter的介绍及使用

什么是过滤器?

与Servlet类似,过滤器是一些web应用程序组件,能够绑定到一个web应用程序中。可是与其它web应用程序组件不同的是,过滤器是"链"在容器的处理过程中的。这就意味着它们会在servlet处理器之前訪问一个进入的请求,而且在外发响应信息返回到客户前訪问这些响应信息。这样的訪问使得过滤器能够检查并改动请求和响应的内容。

过滤器适用于那些地方?

l  为一个web应用程序的新功能建立模型(可被加入到web应用程序中或者从web应用程序中删除而不须要重写基层应用程序代码);

l  向过去的代码加入新功能。

过滤器放在容器结构的什么位置?

过滤器放在web资源之前,能够在请求抵达它所应用的web资源(能够是一个Servlet、一个Jsp页面,甚至是一个HTML页面)之前截获进入的请求,而且在它返回到客户之前截获输出请求。Filter:用来拦截请求,处于client与被请求资源之间,目的是重用代码。Filter链,在web.xml中哪个先配置,哪个就先调用。在filter中也能够配置一些初始化參数。

Java中的Filter 并非一个标准的Servlet ,它不能处理用户请求,也不能对client生成响应。 主要用于对HttpServletRequest 进行预处理,也能够对HttpServletResponse 进行后处理,是个典型的处理链。

Filter 有例如以下几个用处:

l  在HttpServletRequest 到达Servlet 之前,拦截客户的HttpServletRequest 。

l  依据须要检查HttpServletRequest ,也能够改动HttpServletRequest 头和数据。

l  在HttpServletResponse 到达client之前,拦截HttpServletResponse 。

l  依据须要检查HttpServletResponse ,能够改动HttpServletResponse 头和数据。

Filter 有例如以下几个种类:

l  用户授权的Filter: Filter 负责检查用户请求,依据请求过滤用户非法请求。

l  日志Filter: 具体记录某些特殊的用户请求。

l  负责解码的Filter: 包含对非标准编码的请求解码。

l  能改变XML 内容的XSLTFilter 等。

一个Filter 可负责拦截多个请求或响应:一个请求或响应也可被多个请求拦截。

创建一个Filter 仅仅需两个步骤: 
(1)创建Filter 处理类:

(2)在web.xml 文件里配置Filter 。 
创建Filter 必须实现javax.servlet.Filter 接口,在该接口中定义了三个方法。 
• void init(FilterConfig config): 用于完毕Filter 的初始化。 
• void destroy(): 用于Filter 销毁前,完毕某些资源的回收。 
• void doFilter(ServletRequest request, ServletResponse response,FilterChain chain): 实现过滤功能,该方法就是对每一个请求及响应添加的额外处理。

过滤器Filter也具有生命周期:init()->doFilter()->destroy(),由部署文件里的filter元素驱动。在servlet2.4中,过滤器相同能够用于请求分派器,但须在web.xml中声明,<dispatcher>INCLUDE或FORWARD或REQUEST或ERROR</dispatcher>该元素位于filter-mapping中。

Filter经常使用的场景:

例一、  日志的记录,当有请求到达时,在该过滤器中进行日志的记录。处理完毕后,进入兴许的Filter或者处理。

:编写Filter类

package test.filter;

import javax.servlet.Filter;

import javax.servlet.FilterChain;

import javax.servlet.FilterConfig;

import javax.servlet.ServletContext;

import javax.servlet.ServletRequest;

import javax.servlet.ServletResponse;

import javax.servlet.http.HttpServletRequest;

public class LogFilter implements Filter {

private FilterConfig config;

// 实现初始化方法

public void init(FilterConfig config) {

this.config = config;

}

// 实现销毁方法

public void destroy() {

this.config = null;

}

public void doFilter(ServletRequest request, ServletResponse response,

FilterChain chain) {

// 获取ServletContext 对象,用于记录日志

ServletContext context = this.config.getServletContext();

long before = System.currentTimeMillis();

System.out.println("開始过滤... ");

// 将请求转换成HttpServletRequest 请求

HttpServletRequest hrequest = (HttpServletRequest) request;

// 记录日志

context.log("Filter已经截获到用户的请求的地址: " + hrequest.getServletPath());

try {

// Filter 仅仅是链式处理,请求依旧转发到目的地址。

chain.doFilter(request, response);

} catch (Exception e) {

e.printStackTrace();

}

long after = System.currentTimeMillis();

// 记录日志

context.log("过滤结束");

// 再次记录日志

context.log(" 请求被定位到" + ((HttpServletRequest) request).getRequestURI()

+ "所花的时间为: " + (after - before));

}

}

在上面的请求Filter中,仅在日志中记录请求的URL,对全部的请求都运行chain.doFilter(request,reponse)方法,当Filter 对请求过滤后,依旧将请求发送到目的地址。

步骤2:在web.xml中配置Filter

<!-- 定义Filter -->

<filter>

<!-- Filter 的名字 -->

<filter-name>log</filter-name>

<!-- Filter 的实现类 -->

<filter-class> test.filter.LogFilter</filter-class>

</filter>

<!-- 定义Filter 拦截地址 -->

<filter-mapping>

<!-- Filter 的名字 -->

<filter-name>log</filter-name>

<!-- Filter 负责拦截的URL -->

<url-pattern>/filter/*</url-pattern>

</filter-mapping>

通过上述步骤的操作,此时就能够通过URI进行訪问。详细訪问后会在log文件里的localhost文件里产生详细的訪问日志。例如以下所看到的:

2010-12-28 21:12:50 org.apache.catalina.core.ApplicationContext log

信息:  请求被定位到/examples/jsp/jsp2/el/basic-arithmetic.jsp所花的时间为: 0

2010-12-28 21:14:55 org.apache.catalina.core.ApplicationContext log

信息: Filter已经截获到用户的请求的地址: /jsp/jsp2/el/basic-comparisons.jsp

2010-12-28 21:14:56 org.apache.catalina.core.ApplicationContext log

信息: 过滤结束

例二、      进行编码的修正,当有新的请求时,须要将用户传送过来的字符进行又一次编码,以使其能够满足server的编码格式。

1、   编写EncodingFilter类

package test.filter;

import java.io.IOException;

import javax.servlet.Filter;

import javax.servlet.FilterChain;

import javax.servlet.FilterConfig;

import javax.servlet.ServletContext;

import javax.servlet.ServletException;

import javax.servlet.ServletRequest;

import javax.servlet.ServletResponse;

public class EncodingFilter implements Filter {

private FilterConfig filterConfig = null;

private String encoding = null;

//实现销毁方法

public void destroy() {

encoding = null;

}

//进行详细的过滤

public void doFilter(ServletRequest request, ServletResponse response,

FilterChain chain) throws IOException, ServletException {

// 获取ServletContext 对象,用于记录日志

ServletContext context = this.filterConfig.getServletContext();

context.log("開始设置编码格式");

String encoding = getEncoding();

if (encoding == null){

encoding = "gb2312";

}

// 在请求里设置上指定的编码

request.setCharacterEncoding(encoding);

chain.doFilter(request, response);

context.log("成功设置了编码格式");

}

//初始化配置

public void init(FilterConfig filterConfig) throws ServletException {

this.filterConfig = filterConfig;

this.encoding = filterConfig.getInitParameter("encoding");

}

private String getEncoding() {

return this.encoding;

}

}

步骤2:在web.xml中配置Filter

<!-- 定义Filter -->

<filter>

<!-- Filter 的名字 -->

<filter-name>encoding</filter-name>

<!-- Filter 的实现类 -->

<filter-class> test.filter.EncodingFilter</filter-class>

<init-param>

<param-name>encoding</param-name>

<param-value>gb2312</param-value>

</init-param>

</filter>

<!-- 定义Filter 拦截地址 -->

<filter-mapping>

<!-- Filter 的名字 -->

<filter-name> encoding </filter-name>

<!-- Filter 负责拦截的URL -->

<url-pattern>/encode/*</url-pattern>

</filter-mapping>

通过上述步骤的操作,此时就能够通过URI进行訪问。

例三、用户权限的认证,当用户发送请求时,可以对用户的身份信息进行验证,假设可以通过验证则接下来再进行其他操作,否则直接不进入下一步的处理。

1、   编写身份认证SecurityFilter类

package test.filter;

import java.io.IOException;

import javax.servlet.Filter;

import javax.servlet.FilterChain;

import javax.servlet.FilterConfig;

import javax.servlet.ServletContext;

import javax.servlet.ServletException;

import javax.servlet.ServletRequest;

import javax.servlet.ServletResponse;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;

import javax.servlet.http.HttpSession;

public class SecurityFilter implements Filter {

private FilterConfig filterConfig;

//初始化方法实现

@Override

public void init(FilterConfig filterConfig) throws ServletException {

this.filterConfig = filterConfig;

}

//身份认证的过滤

@Override

public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)

throws IOException, ServletException {

ServletContext context = this.filterConfig.getServletContext();

HttpServletRequest req = (HttpServletRequest) request;

HttpServletResponse res = (HttpServletResponse) response;

HttpSession session = req.getSession();

//登录后才干进入下一步处理,否则直接进入错误提示页面

if (session.getAttribute("username") != null) {

context.log("身份认证通过,进入下一步处理 ");

chain.doFilter(request, response);

} else {

context.log("身份认证失败,直接返回");

res.sendRedirect("../failure.jsp");

}

}

//实现销毁方法

@Override

public void destroy() {

this.filterConfig = null;

}

}

步骤2:在web.xml中配置Filter

<!-- 定义Filter -->

<filter>

<!-- Filter 的名字 -->

<filter-name>security</filter-name>

<!-- Filter 的实现类 -->

<filter-class> test.filter.SecurityFilter</filter-class>

</filter>

<!-- 定义Filter 拦截地址 -->

<filter-mapping>

<!-- Filter 的名字 -->

<filter-name> security </filter-name>

<!-- Filter 负责拦截的URL -->

<url-pattern>/security/*</url-pattern>

</filter-mapping>

通过上述步骤的操作,此时就行通过URI进行訪问。此时假设可以取得Session中的username值时,会直接进入下一步处理,否则直接进入错误页面。

二、过滤链FilterChain

两个过滤器,EncodingFilter负责设置编码,SecurityFilter负责控制权限,server会依照web.xml中过滤器定义的先后循序组装成一条链,然后一次运行当中的doFilter()方法。运行的顺序就例如以下图所看到的,运行第一个过滤器的chain.doFilter()之前的代码,第二个过滤器的chain.doFilter()之前的代码,请求的资源,第二个过滤器的chain.doFilter()之后的代码,第一个过滤器的chain.doFilter()之后的代码,最后返回响应。

运行的代码顺序是:

l  运行EncodingFilter.doFilter()中chain.doFilter()之前的部分;request.setCharacterEncoding(encoding);

l  运行SecurityFilter.doFilter()中chain.doFilter()之前的部分:推断用户是否已登录。

l  假设用户已登录,则訪问请求的资源。

l  假设用户未登录,则页面重定向到:/failure.jsp。

l  运行SecurityFilter.doFilter()中chain.doFilter()之后的部分:这里没有代码。

l  运行EncodingFilter.doFilter()中chain.doFilter()之后的部分:写入已经完毕的日志。

过滤链的优点是,运行过程中不论什么时候都能够打断,仅仅要不运行chain.doFilter()就不会再运行后面的过滤器和请求的内容。而在实际使用时,就要特别注意过滤链的运行顺序问题,像EncodingFilter就一定要放在全部Filter之前,这样才干确保在使用请求中的数据前设置正确的编码。

Filter和FilterChain具体的使用说明的更多相关文章

  1. Filter及FilterChain的使用详解(转)

    一.Filter的介绍及使用 什么是过滤器? 与Servlet相似,过滤器是一些web应用程序组件,可以绑定到一个web应用程序中.但是与其他web应用程序组件不同的是,过滤器是"链&quo ...

  2. Filter及FilterChain的使用详解

    原文地址:http://blog.csdn.net/zhaozheng7758/article/details/6105749 一.Filter的介绍及使用 什么是过滤器? 与Servlet相似,过滤 ...

  3. Filter及FilterChain的使用具体解释

    一.Filter的介绍及使用 什么是过滤器? 与Servlet类似,过滤器是一些web应用程序组件,能够绑定到一个web应用程序中.可是与其它web应用程序组件不同的是,过滤器是"链&quo ...

  4. Filter及FilterChain的详解

    一.Filter的介绍及使用 什么是过滤器? 与Servlet相似,过滤器是一些web应用程序组件,可以绑定到一个web应用程序中.但是与其他web应用程序组件不同的是,过滤器是"链&quo ...

  5. Python【map、reduce、filter】内置函数使用说明(转载)

    转自:http://www.blogjava.net/vagasnail/articles/301140.html?opt=admin 介绍下Python 中 map,reduce,和filter 内 ...

  6. Python【map、reduce、filter】内置函数使用说明

    题记 介绍下Python 中 map,reduce,和filter 内置函数的方法 一:map map(...) map(function, sequence[, sequence, ...]) -& ...

  7. Spring Security 入门(1-6-2)Spring Security - 内置的filter顺序、自定义filter、http元素和对应的filterChain

    Spring Security 的底层是通过一系列的 Filter 来管理的,每个 Filter 都有其自身的功能,而且各个 Filter 在功能上还有关联关系,所以它们的顺序也是非常重要的. 1.S ...

  8. JavaWeb——Filter

    一.基本概念 之前我们用一篇博文介绍了Servlet相关的知识,有了那篇博文的知识积淀,今天我们学习Filter将会非常轻松,因为Filter有很多地方和Servlet类似,下面在讲Filter的时候 ...

  9. .NET NLog 详解(四) - filter

    我们将版本向前切换到20051025,这期的关注点是filter.我们在使用日志的时候可能希望加上一些过滤器,在满足某些特定条件的时候才输出.举个简单的使用方式如下: <nlog> < ...

随机推荐

  1. 比赛--找丢失的数--解题报告T

    找丢失的数 题目大意: There is a permutation without two numbers in it, and now you know what numbers the perm ...

  2. ulipad双击无反应

    所有的东西都配好后,执行ulipad需要注意的是: 1,必须以管理员身份运行ulipad. 2,当运行有道词典的时候,双击ulipad是没有反应, 至于为什么会出现这种情况,我也不太清除,等我查到 原 ...

  3. pycharm+QT4的helloworld

    # -*- coding: utf-8 -*- from PyQt4 import QtCore, QtGui try: _fromUtf8 = QtCore.QString.fromUtf8 exc ...

  4. ORACLE存储过程笔记2

    ORACLE存储过程笔记2 运算符和表达式     关系运算 =等于<>,!=不等于<小于>大于<=小于等于>=大于等于       一般运算   +加-减*乘/除 ...

  5. 基于visual Studio2013解决算法导论之022队列实现(基于链表)

     题目 基于链表的队列实现 解决代码及点评 #include <stdio.h> #include <stdlib.h> #include <time.h> ...

  6. SilkTest天龙八部系列6-用open agent进行测试

    SilkTest支持两种测试模式,一种是用classic agent,另一种就是用我们今天要介绍的open agent. open agent可以提供和classic agent差不多的录制回放功能. ...

  7. opencv开源库

    opencv是开源库 在Windows下编译扩展OpenCV 3.1.0 + opencv_contrib 为什么要CMake,这里我陈述自己的想法,作为一个刚使用opencv库的小白来说,有以下大概 ...

  8. two sets of Qt binaries into the same process的解决办法

    突然出现了这样问题,吓死我,然后只是把原来编译好的app里面所有的东西删除再编译就好了. 如果删除后不行,可以试试后面的截图所说,反正我是没有试过的 Starting /Qtwork/build-te ...

  9. WebStorm 7.0 注册码

    User Name: EMBRACE License Key:===== LICENSE BEGIN =====24718-1204201000001h6wzKLpfo3gmjJ8xoTPw5mQvY ...

  10. cmake手册详解----转

    参考链接:http://www.cnblogs.com/coderfenghc/tag/cmake/