一直对java web service中的过滤器比较迷惑,仔细读了一下sun 的文章《The Essentials of Filters》。作一下总结:
文章网址:htttp://java.sun.com/products/servlet/Filters.html
- Filter是用来拦截request 或 response的程序。对request或response作相应转换,或使用其中的信息。Filter本身不不创建response,通常是提供通用功能,以便可以附加在某中servlet中或jsp页面中运行.
- Filter的使用包括两个步骤: 开发和配置,配置的作用是,指明当应用程序部署到容器中时,所编写的Filter如何映射到正确的servlet.因为Filter的作用就是要拦截servlet的请求和响应。
- Filter 编程接口(API):
需要的三个接口,这三个接口都是在javax.servlet包中:- Filter
- FilterChain: 由Container传入,提供一种机制说明如何调用一系列Filter.
- FilterConfig: 包含初始化数据。
- 创建Filter: 实现接口Filter,这个接口中最重要的方法是doFilter, 它是Filter的核心。在这个方法中通常做下面的事情:
- 检查request 头
- 定制 request 对象
- 定制 response 对象
- 调用 FilterChain中的下一个实体
- 在上一步之后,检查response header
- 抛出处理异常
- 例子1: 给现有网站增加计数功能,不能修改现有代码
- 编写一个类HitCounterFilter,让它实现接口Filter:
public final class HitCounterFilter implements Filter {
private FilterConfig filterConfig = null;
public void init(FilterConfig filterConfig) throws ServletException {
this.filterConfig = filterConfig;
}
public void destroy() {
this.filterConfig = null;
}
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException {
if (filterConfig == null)
return;
StringWriter sw = new StringWriter();
PrintWriter writer = new PrintWriter(sw);
Counter counter = (Counter)filterConfig.getServletContext().getAttribute("hitCounter");
writer.println();
writer.println("===============");
writer.println("The number of hits is: " + counter.incCounter());
writer.println("===============");
// Log the resulting string
writer.flush();
filterConfig.getServletContext().log(sw.getBuffer().toString());
...
chain.doFilter(request, wrapper);
...
}
}
- 在web.xml中配置
<filter>
<filter-name>HitCounterFilter</filter-name>
<filter-class>HitCounterFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>HitCounterFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
- 编写一个类HitCounterFilter,让它实现接口Filter:
- 上面的链接中还包含其它几个Filter使用的例子。有时间再细看。