Filter 技术是servlet 2.3 新增加的功能.servlet2.3是sun公司与2000年10月发布的,它的开发者包括许多个人和公司团体,充分体现了sun公司所倡导的代码开放性原则.由于众多的参与者的共同努力,servlet2.3比以往功能都强大了许多,而且性能也有了大幅提高.
它新增加的功能包括:
1. 应用程序生命周期事件控制;
2. 新的国际化;
3. 澄清了类的装载规则;
4. 新的错误及安全属性;
5. 不赞成使用HttpUtils 类;
6. 各种有用的方法;
7. 阐明并扩展了几个servlet DTD;
8. filter功能.
其中最重要的就是filter功能.它使用户可以改变一个request和修改一个response. Filter 不是一个servlet,它不能产生一个response,它能够在一个request到达servlet之前预处理request,也可以在离开servlet时处理response.换种说法,filter其实是一个”servlet chaining”(servlet 链).一个filter 包括:
1. 在servlet被调用之前截获;
2. 在servlet被调用之前检查servlet request;
3. 根据需要修改request头和request数据;
4. 根据需要修改response头和response数据;
5. 在servlet被调用之后截获.
你能够配置一个filter 到一个或多个servlet;单个servlet或servlet组能够被多个filter 使用.几个实用的filter 包括:
用户辨认filter,日志filter,审核filter,加密filter,符号filter,能改变xml内容的XSLT filter等.
一个filter必须实现javax.servlet.Filter接口并定义三个方法:
1. void setFilterConfig(FilterConfig config) //设置filter 的配置对象;
2. FilterConfig getFilterConfig() //返回filter的配置对象;
3. void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) //执行filter 的工作.
服务器每次只调用setFilterConfig方法一次准备filter 的处理;调用doFilter方法多次以处理不同的请求.FilterConfig接口有方法可以找到filter名字及初始化参数信息.服务器可以设置FilterConfig为空来指明filter已经终结.
每一个filter从doFilter()方法中得到当前的request及response.在这个方法里,可以进行任何的针对request及response的操作.(包括收集数据,包装数据等).filter调用chain.doFilter()方法把控制权交给下一个filter.一个filter在doFilter()方法中结束.如果一个filter想停止request处理而获得对response的完全的控制,那它可以不调用下一个filter.
一个filter可以包装request 或response以改变几个方法和提供用户定制的属性.Api2.3提供了HttpServletRequestWrapper 和HttpServletResponseWrapper来实现.它们能分派最初的request和response.如果要改变一个方法的特性,必须继承wapper和重写方法.下面是一段简单的日志filter用来记录所有request的持续时间.
EXAMPLE 1(用filter来验证Session):
1 web.xml里添加filter配置信息。
<
filter
>
<
filter-name
>
Authentication
</
filter-name
>
<
filter-class
>
com.nova.colimas.web.filters.AuthenticationFilter
</
filter-class
>
<
init-param
>
<
param-name
>
onError
</
param-name
>
<
param-value
>
/pages/index.jsp
</
param-value
>
</
init-param
>
</
filter
>
<
filter-mapping
>
<
filter-name
>
Authentication
</
filter-name
>
<
url-pattern
>
/protect/*
</
url-pattern
>
</
filter-mapping
>
<filter-class>定义使用com.nova.colimas.web.filters.AuthenticationFilter类执行过滤Action。
<init-param>当验证失败后Forward到/pages/index.jsp
<filter-mapping>只有当地址包括/protect/时运行filter类
2 实现com.nova.colimas.web.filters.AuthenticationFilter
package
com.nova.colimas.web.filters;
import
java.io.IOException;
import
javax.servlet.RequestDispatcher;
import
javax.servlet.ServletException;
import
javax.servlet.http.
*
;
import
javax.servlet.Filter;
import
javax.servlet.FilterChain;
import
javax.servlet.FilterConfig;
import
com.nova.colimas.web.bean.UserBean;
import
javax.servlet.ServletRequest;
import
javax.servlet.ServletResponse;
import
org.apache.struts.Globals;
import
org.apache.struts.action.
*
;
import
com.nova.colimas.web.constants.Constants;
/** */
/** * Filter implementation for user authentication。
必须实现Filter接口 *
@author DREAN*
@version $Id: AuthenticationFilter.java,v 1.0 */
public
class
AuthenticationFilter
implements
Filter
...
{
/** *//** * filterConfig will store the reference of FilterConfig */
private FilterConfig filterConfig;
private String onErrorUrl;
/** *//** * store the reference of the FilterConfig.
* @param config FilterConfig object
* @throws ServletException */
public void init(FilterConfig config) throws ServletException
...{//获得验证失败forward地址
filterConfig = config;
onErrorUrl=filterConfig.getInitParameter("onError");
if (onErrorUrl==null || "".equals(onErrorUrl))
...{
onErrorUrl="/pages/index.jsp";
}
}
/** *//** * User Authentication is done. If User is authenticated successful then
* control is transferred to logon URI
* @param ServletRequest Request
* @param ServletRequest Response
* @param FilterChain Filter Chain
* @throws ServletException,IOException */
public void doFilter(ServletRequest request, ServletResponse response, FilterChain next) throws
IOException,ServletException
...{
HttpServletRequest httpRequest = (HttpServletRequest)request;
HttpServletResponse httpResponse=(HttpServletResponse)response;
// Current session
HttpSession httpSession = httpRequest.getSession();
//Session里是否有用户信息。
if (httpSession.getAttribute(Constants.USER_KEY) == null)
...{
ActionErrors errors=new ActionErrors();
errors.add(ActionErrors.GLOBAL_ERROR,
new ActionError("error authentication"));
httpRequest.setAttribute(Globals.ERROR_KEY,errors);
//没有,验证失败forward到/pages/index.jsp
httpRequest.getRequestDispatcher(onErrorUrl).forward(httpRequest,httpResponse);
}
else
//成果过滤Action结束
next.doFilter(request,response);
}
/** *//** * destroy() method is called by the servlet container */
public void destroy()
...{ .... }
}
EXAMPLE 2(用filter来解决Struts中文乱码的问题):
首先,实现javax.servlet.Filter接口,编写一个处理request编码的过滤器类...
package
tutorial.struts.filter;
import
javax.servlet.Filter;
import
javax.servlet.FilterConfig;
import
javax.servlet.ServletException;
import
javax.servlet.ServletRequest;
import
javax.servlet.ServletResponse;
import
javax.servlet.FilterChain;
import
java.io.IOException;
public
class
SetCharacterEncodingFilter
implements
Filter
...
{
protected FilterConfig filterConfig;
protected String encodingName;
protected boolean enable;
public SetCharacterEncodingFilter() ...{
this.encodingName = "UTF-8";
this.enable = false;
}
public void init(FilterConfig filterConfig) throws ServletException ...{
this.filterConfig = filterConfig;
loadConfigParams();
}
private void loadConfigParams() ...{
//encoding
this.encodingName = this.filterConfig.getInitParameter("encoding");
//filter enable flag...
String strIgnoreFlag = this.filterConfig.getInitParameter("enable");
if (strIgnoreFlag.equalsIgnoreCase("true")) ...{
this.enable = true;
} else ...{
this.enable = false;
}
}
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException ...{
if(this.enable) ...{
request.setCharacterEncoding(this.encodingName);
}
chain.doFilter(request, response);
}
public void destroy() ...{
}
}
然后,需要在web.xml中注册我们的过滤器类:
<
filter
>
<
filter-name
>
Set Character Encoding
</
filter-name
>
<
filter-class
>
tutorial.struts.filter.SetCharacterEncodingFilter
</
filter-class
>
<
init-param
>
<
param-name
>
encoding
</
param-name
>
<
param-value
>
UTF-8
</
param-value
>
</
init-param
>
<
init-param
>
<
param-name
>
enable
</
param-name
>
<
param-value
>
true
</
param-value
>
</
init-param
>
</
filter
>
<
filter-mapping
>
<
filter-name
>
Set Character Encoding
</
filter-name
>
<
servlet-name
>
Action Servlet
</
servlet-name
>
</
filter-mapping
>
<
filter-mapping
>
<
filter-name
>
Set Character Encoding
</
filter-name
>
<
servlet-name
>
Faces Servlet
</
servlet-name
>
</
filter-mapping
>
任何通过Struts,或是JSF的Controller Servlet处理的request,都会在过滤器中先行处理,才把控制权交还给Struts或是JSF,而且Filter中有一个Process Chain的概念