什么是java过滤器是什么! 它的功能和作用是什么啊?

[转]Java Servlet过滤器是什么?
[转]Java Servlet过滤器是什么?
文章转自:
什么叫过滤器呢?
  过滤器就是可以对浏览器向jsp,servlet,html等这些web资源发出请求和
服务器回应给浏览器的内容,他可以进行过滤。这个过滤过程中可以拦截浏览
器发出的请求和服务器回应给浏览器的内容。拦截之后,就可以进行查看,并且
可以对拦截内容进行提取,或者进行修改。
  Servlet过滤器拦截请求和响应,以便查看,提取或操作客户机和服务器之间
交换数据。    
Servlet过滤器的用途:
    用户认证与授权管理:我们开发一个web应用,肯定有不同权限的用户,有管理员,有普通
用户。而管理员又可能分为一级管理员,二级管理员,三级管理员。每一级管理员可能又有不同的管理权限
操作,访问不同的资源。过去我们可能都是在jsp页面,servlet中加以权限的控制。通过session,看他是否
有这个权限,如果有,则让他操作某个资源。这些都是些共性。那么现在我们就可以把他提取出来。让他通过
过滤器来实现;用户来访问一个资源,我们通过过滤器来过滤这个请求,在程序中判断是否有权限来访问这个资源;
有,则让他去访问,没有,就让他转到另外一个页面。这样通过过滤器就实现了授权管理;
    统计web应用的访问量,和访问的命中率,报告;
    实现web应用的日志处理功能;
    实现数据压缩功能;
    对传输的数据进行加密;
    实现XML文件的XSLT转换;
实现Servlet过滤器  
    编写实现javax.servlet.Fillter接口的类;
      package javax.
      import java.io.IOE
      public interface Filter{
        public void init(FilterConfig filterConfig)throws ServletE
        public void doFilter(ServletRequest request,ServletResponse response,FilterChain chain)throws IOException, ServletE
        public void destroy();
      }
    配置servlet过滤器;
      过滤器需要通过web.xml进行配置
      &filter&定义过滤器的名称,并且声明实现类
      &filter-mapping&将过滤器与Servlet或URL模式关联
        &filter&
          &filter-name&EncodingFilter&/filter-name&
          &filter-class&webbook.hongten.CharacterEncodingFilter&/filter-class&
        &/filter&
        &filter-mapping&
          &filter-name&EncodingFilter&/filter-name&
          &url-pattern&/*&/url-pattern&
        &/filter-mapping&
-----------------------------------------------------------------------------
实例:使用过滤器设定传输参数编码
新建一个web项目
CharacterEnccodingFilter.java
package com.b510.hongten.
import java.io.IOE
import javax.servlet.FilterC
import javax.servlet.FilterC
import javax.servlet.ServletE
import javax.servlet.ServletR
import javax.servlet.ServletR
* @author XHW
public class CharacterEnccodingFilter implements javax.servlet.Filter {
private FilterC
private String encoding = &ISO8859_1&;
public void destroy() {
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException {
request.setCharacterEncoding(encoding);
chain.doFilter(request, response);
public void init(FilterConfig config) throws ServletException {
this.config =
encoding = config.getInitParameter(&encoding&);
-----------------------------------------------------------------------------
&?xml version=&1.0& encoding=&UTF-8&?&
&web-app version=&2.5& xmlns=&/xml/ns/javaee&
xmlns:xsi=&http://www.w3.org/2001/XMLSchema-instance&
xsi:schemaLocation=&/xml/ns/javaee
/xml/ns/javaee/web-app_2_5.xsd&&
&filter-name&Encoding&/filter-name&
&filter-class&com.b510.hongten.filter.CharacterEnccodingFilter&/filter-class&
&init-param&
&param-name&encoding&/param-name&
&param-value&UTF-8&/param-value&
&/init-param&
&filter-mapping&
&filter-name&Encoding&/filter-name&
&url-pattern&/*&/url-pattern&
&/filter-mapping&
&welcome-file-list&
&welcome-file&index.jsp&/welcome-file&
&/welcome-file-list&
&/web-app&
-----------------------------------------------------------------------------
&language=&java& pageEncoding=&UTF-8&%&
&uri=&/jsp/jstl/core& prefix=&c& %&
&title&demo Parameter Encoding&/title&
用户名:&c:out value=&${param.username}& default=&none&/&&br&
密码:&c:out value=&${param.password}& default=&none&/&&br&
&form action=&index.jsp& method=&post&&
&table border=&0&&
&td&用户名:&/td&
&td&&input type=&text& name=&username&&&/td&
&td&密码:&/td&
&td&&input type=&password& name=&password&&&/td&
&td colspan=&2& align=&center&&&input type=&submit&&&/td&
我的热门文章
即使是一小步也想与你分享深入解析Java的Servlet过滤器的原理及其应用
作者:zhangjunhd
字体:[ ] 类型:转载 时间:
这篇文章主要介绍了深入解析Java的Servlet过滤器的原理及应用,Java编写的Servlet通常是一个与网页一起作用于浏览器客户端的程序,需要的朋友可以参考下
1.Servlet过滤器
1.1 什么是过滤器
过滤器是一个程序,它先于与之相关的servlet或JSP页面运行在服务器上。过滤器可附加到一个或多个servlet或JSP页面上,并且可以检查进入这些资源的请求信息。在这之后,过滤器可以作如下的选择:
①以常规的方式调用资源(即,调用servlet或JSP页面)。
②利用修改过的请求信息调用资源。
③调用资源,但在发送响应到客户机前对其进行修改。
④阻止该资源调用,代之以转到其他的资源,返回一个特定的状态代码或生成替换输出。
1.2 Servlet过滤器的基本原理
在Servlet作为过滤器使用时,它可以对客户的请求进行处理。处理完成后,它会交给下一个过滤器处理,这样,客户的请求在过滤链里逐个处理,直到请求发送到目标为止。例如,某网站里有提交“修改的注册信息”的网页,当用户填写完修改信息并提交后,服务器在进行处理时需要做两项工作:判断客户端的会话是否有效;对提交的数据进行统一编码。这两项工作可以在由两个过滤器组成的过滤链里进行处理。当过滤器处理成功后,把提交的数据发送到最终目标;如果过滤器处理不成功,将把视图派发到指定的错误页面。
2.Servlet过滤器开发步骤
开发Servlet过滤器的步骤如下:
①编写实现Filter接口的Servlet类。
②在web.xml中配置Filter。
开发一个过滤器需要实现Filter接口,Filter接口定义了以下方法:
①destory()由Web容器调用,初始化此Filter。
②init(FilterConfig filterConfig)由Web容器调用,初始化此Filter。
③doFilter(ServletRequest request,ServletResponse response,FilterChain chain)具体过滤处理代码。
3.一个过滤器框架实例
SimpleFilter1.java
package com.zj.
import java.io.IOE
import javax.servlet.F
import javax.servlet.FilterC
import javax.servlet.FilterC
import javax.servlet.ServletE
import javax.servlet.ServletR
import javax.servlet.ServletR
public class SimpleFilter1 implements Filter {
@SuppressWarnings("unused")
private FilterConfig filterC
public void init(FilterConfig config) throws ServletException {
this.filterConfig =
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) {
System.out.println("Within SimpleFilter1:Filtering the Request...");
chain.doFilter(request, response);// 把处理发送到下一个过滤器
System.out .println("Within SimpleFilter1:Filtering the Response...");
} catch (IOException ioe) {
ioe.printStackTrace();
} catch (ServletException se) {
se.printStackTrace();
public void destroy() {
this.filterConfig =
SimpleFilter2.java
package com.zj.
import java.io.IOE
import javax.servlet.F
import javax.servlet.FilterC
import javax.servlet.FilterC
import javax.servlet.ServletE
import javax.servlet.ServletR
import javax.servlet.ServletR
public class SimpleFilter2 implements Filter {
@SuppressWarnings("unused")
private FilterConfig filterC
public void init(FilterConfig config) throws ServletException {
this.filterConfig =
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) {
System.out.println("Within SimpleFilter2:Filtering the Request...");
chain.doFilter(request, response); // 把处理发送到下一个过滤器
System.out.println("Within SimpleFilter2:Filtering the Response...");
} catch (IOException ioe) {
ioe.printStackTrace();
} catch (ServletException se) {
se.printStackTrace();
public void destroy() {
this.filterConfig =
&filter-name&filter1&/filter-name&
&filter-class&com.zj.sample.SimpleFilter1&/filter-class&
&filter-mapping&
&filter-name&filter1&/filter-name&
&url-pattern&/*&/url-pattern&//为所有的访问做过滤
&/filter-mapping&
&filter-name&filter2&/filter-name&
&filter-class&com.zj.sample.SimpleFilter2&/filter-class&
&filter-mapping&
&filter-name&filter2&/filter-name&
&url-pattern&/*&/url-pattern&//为所有的访问做过滤
&/filter-mapping&
打开web容器中任意页面输出结果:(注意过滤器执行的请求/响应顺序)
Within SimpleFilter1:Filtering the Request...
Within SimpleFilter2:Filtering the Request...
Within SimpleFilter2:Filtering the Response...
Within SimpleFilter1:Filtering the Response...
4.报告过滤器
我们来试验一个简单的过滤器,只要调用相关的servlet或JSP页面,它就打印一条消息到标准输出。为实现此功能,在doFilter方法中执行过滤行为。每当调用与这个过滤器相关的servlet或JSP页面时,doFilter方法就生成一个打印输出,此输出列出请求主机和调用的URL。因为getRequestURL方法位于HttpServletRequest而不是ServletRequest中,所以把ServletRequest对象构造为HttpServletRequest类型。我们改动一下章节3的SimpleFilter1.java。
SimpleFilter1.java
package com.zj.
import java.io.IOE
import java.util.D
import javax.servlet.F
import javax.servlet.FilterC
import javax.servlet.FilterC
import javax.servlet.ServletE
import javax.servlet.ServletR
import javax.servlet.ServletR
import javax.servlet.http.HttpServletR
public class SimpleFilter1 implements Filter {
@SuppressWarnings("unused")
private FilterConfig filterC
public void init(FilterConfig config) throws ServletException {
this.filterConfig =
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) {
System.out.println("Within SimpleFilter1:Filtering the Request...");
HttpServletRequest req = (HttpServletRequest)
System.out.println(req.getRemoteHost() + " tried to access "
+ req.getRequestURL() + " on " + new Date() + ".");
chain.doFilter(request, response);
System.out.println("Within SimpleFilter1:Filtering the Response...");
} catch (IOException ioe) {
ioe.printStackTrace();
} catch (ServletException se) {
se.printStackTrace();
public void destroy() {
this.filterConfig =
web.xml设置不变,同章节3。
输入[url]http://localhost:8080/Test4Jsp/login.jsp[/url]
Within SimpleFilter1:Filtering the Request...
0:0:0:0:0:0:0:1 tried to access [url]http://localhost:8080/Test4Jsp/login.jsp[/url] on Sun Mar 04 17:01:37 CST 2007.
Within SimpleFilter2:Filtering the Request...
Within SimpleFilter2:Filtering the Response...
Within SimpleFilter1:Filtering the Response...
5.访问时的过滤器(在过滤器中使用servlet初始化参数)
下面利用init设定一个正常访问时间范围,对那些不在此时间段的访问作出记录。我们改动一下章节3的SimpleFilter2.java。
SimpleFilter2.java。
package com.zj.
import java.io.IOE
import java.text.DateF
import java.util.C
import java.util.GregorianC
import javax.servlet.F
import javax.servlet.FilterC
import javax.servlet.FilterC
import javax.servlet.ServletC
import javax.servlet.ServletE
import javax.servlet.ServletR
import javax.servlet.ServletR
import javax.servlet.http.HttpServletR
public class SimpleFilter2 implements Filter {
@SuppressWarnings("unused")
private FilterC
private ServletC
private int startTime, endT
private DateF
public void init(FilterConfig config) throws ServletException {
this.config =
context = config.getServletContext();
formatter = DateFormat.getDateTimeInstance(DateFormat.MEDIUM,
DateFormat.MEDIUM);
startTime = Integer.parseInt(config.getInitParameter("startTime"));// web.xml
endTime = Integer.parseInt(config.getInitParameter("endTime"));// web.xml
} catch (NumberFormatException nfe) { // Malformed or null
// Default: access at or after 10 p.m. but before 6 a.m. is
// considered unusual.
startTime = 22; // 10:00 p.m.
endTime = 6; // 6:00 a.m.
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) {
System.out.println("Within SimpleFilter2:Filtering the Request...");
HttpServletRequest req = (HttpServletRequest)
GregorianCalendar calendar = new GregorianCalendar();
int currentTime = calendar.get(Calendar.HOUR_OF_DAY);
if (isUnusualTime(currentTime, startTime, endTime)) {
context.log("WARNING: " + req.getRemoteHost() + " accessed "
+ req.getRequestURL() + " on "
+ formatter.format(calendar.getTime()));
// The log file is under &CATALINA_HOME&/logs.One log per day.
chain.doFilter(request, response);
System.out
.println("Within SimpleFilter2:Filtering the Response...");
} catch (IOException ioe) {
ioe.printStackTrace();
} catch (ServletException se) {
se.printStackTrace();
public void destroy() {}
// Is the current time between the start and end
// times that are marked as abnormal access times?
private boolean isUnusualTime(int currentTime, int startTime, int endTime) {
// If the start time is less than the end time (i.e.,
// they are two times on the same day), then the
// current time is considered unusual if it is
// between the start and end times.
if (startTime & endTime) {
return ((currentTime &= startTime) && (currentTime & endTime));
// If the start time is greater than or equal to the
// end time (i.e., the start time is on one day and
// the end time is on the next day), then the current
// time is considered unusual if it is NOT between
// the end and start times.
return (!isUnusualTime(currentTime, endTime, startTime));
web.xml设置不变。
关于Tomcat日志处理,这里补充介绍一下。config.getServletContext().log("log message")会将日志信息写入&CATALINA_HOME&/logs文件夹下,文件名应该为localhost_log..txt这样的形式(按日期每天产生一个,第二天可以看见)。要得到这样一个日志文件,应该在server.xml中有:
&Logger className="org.apache.catalina.logger.FileLogger" prefix="catalina_log." suffix=".txt" timestamp="true"/&
6.禁止站点过滤器
如果你希望在你的过滤器检测到不正常的异常而中途中断后面的过滤过程时,可这样做:
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws ServletException, IOException {
HttpServletRequest req = (HttpServletRequest)
HttpServletResponse res = (HttpServletResponse)
if (isUnusualCondition(req)) {
res.sendRedirect("");
chain.doFilter(req, res);
下例是一个禁止站点过滤器,如果不希望某些站点访问你的网站,你可以在web.xml的param-value中列出它的站点,然后应用上面的原理跳出常规过滤,给出禁止访问的页面。
BannedAccessFilter.java
package com.zj.
import java.io.IOE
import java.io.PrintW
import java.net.MalformedURLE
import java.net.URL;
import java.util.HashS
import java.util.StringT
import javax.servlet.F
import javax.servlet.FilterC
import javax.servlet.FilterC
import javax.servlet.ServletE
import javax.servlet.ServletR
import javax.servlet.ServletR
import javax.servlet.http.HttpServletR
public class BannedAccessFilter implements Filter {
private HashSet&String& bannedSiteT
* Deny access if the request comes from a banned site or is referred here
* by a banned site.
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws ServletException, IOException {
System.out.println("Within BannedAccessFilter:Filtering the Request...");
HttpServletRequest req = (HttpServletRequest)
String requestingHost = req.getRemoteHost();
String referringHost = getReferringHost(req.getHeader("Referer"));
String bannedSite =
boolean isBanned =
if (bannedSiteTable.contains(requestingHost)) {
bannedSite = requestingH
isBanned =
} else if (bannedSiteTable.contains(referringHost)) {
bannedSite = referringH
isBanned =
if (isBanned) {
showWarning(response, bannedSite);
chain.doFilter(request, response);
System.out.println("Within BannedAccessFilter:Filtering the Response...");
* Create a table of banned sites based on initialization parameters.
* Remember that version 2.3 of the servlet API mandates the use of the
* Java 2 Platform. Thus, it is safe to use HashSet (which determines
* whether a given key exists) rather than the clumsier Hashtable
* (which has a value for each key).
public void init(FilterConfig config) throws ServletException {
bannedSiteTable = new HashSet&String&();
String bannedSites = config.getInitParameter("bannedSites");
// Default token set: white space.
StringTokenizer tok = new StringTokenizer(bannedSites);
while (tok.hasMoreTokens()) {
String bannedSite = tok.nextToken();
bannedSiteTable.add(bannedSite);
System.out.println("Banned " + bannedSite);
public void destroy() {}
private String getReferringHost(String refererringURLString) {
URL referringURL = new URL(refererringURLString);
return (referringURL.getHost());
} catch (MalformedURLException mue) { // Malformed or null
return (null);
// Replacement response that is returned to users
// who are from or referred here by a banned site.
private void showWarning(ServletResponse response, String bannedSite)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String docType = "&!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0 "
+ "Transitional//EN\"&\n";
out.println(docType + "&HTML&\n"
+ "&HEAD&&TITLE&Access Prohibited&/TITLE&&/HEAD&\n"
+ "&BODY BGCOLOR=\"WHITE\"&\n" + "&H1&Access Prohibited&/H1&\n"
+ "Sorry, access from or via " + bannedSite + "\n"
+ "is not allowed.\n" + "&/BODY&&/HTML&");
&filter-name&BannedAccessFilter&/filter-name&
&filter-class&com.zj.sample.BannedAccessFilter&/filter-class&
&init-param&
&param-name&bannedSites&/param-name&
&param-value&
[[/url] [url][/url]
[url][/url] 127.0.0.1//我们测试这个
&/param-value&
&/init-param&
&filter-mapping&
&filter-name&BannedAccessFilter&/filter-name&
&url-pattern&/*&/url-pattern&
&/filter-mapping&
[url]http://localhost:8080/Test4Jsp/[/url]
7.替换过滤器
7.1修改响应
过滤器能够阻止对资源的访问或者阻止激活它们。但如果过滤器想更改资源所生成的响应。怎么办呢?似乎没有办法能够对一个资源所生成的响应进行访问。DoFilter的第二个参数(ServletResponse)给过滤器提供了一种发送新输出到客户机的办法,但没有给过滤器提供对servlet或JSP页面输出进行访问的办法。为什么会这样呢?因为在第一次调用doFilter方法时,servlet或JSP页面甚至还没有执行。一旦调用了FilterChain对象中的doFilter方法,要修改响应似乎就太迟了,这是数据已经发送到客户机。
不过,办法是有的,那就是修改传递给FilterChain对象的doFilter方法的响应对象。一般,建立缓存servlet或JSP页面生成的所有输出的版本。Servlet API 2.3版为此提供了一种有用的资源,即,HttpServletResponseWrapper类。这个类的使用包括以下五个步骤:
1)建立一个响应包装器。扩展javax.servlet.http.HttpServletResponseWrapper。
2)提供一个缓存输出的PrintWriter。重载getWriter方法,返回一个保存发送给它的所有东西的PrintWriter,并把结果存进一个可以稍后访问的字段中。
3)传递该包装器给doFilter。此调用是合法的,因为HttpServletResponseWrapper实现HttpServletResponse。
4)提取和修改输出。在调用FilterChain的doFilter方法后,原资源的输出只要利用步骤2中提供的机制就可以得到。只要对你的应用适合,就可以修改或替换它。
5)发送修改过的输出到客户机。因为原资源不再发送输出到客户机(这些输出已经存放到你的响应包装器中了),所以必须发送这些输出。这样,你的过滤器需要从原响应对象中获得PrintWriter或OutputStream,并传递修改过的输出到该流中。
7.2一个可重用的响应包装器
下例程序给出了一个包装器,它可用于希望过滤器修改资源的输出的大多数应用中。CharArrayWrapper类重载getWriter方法以返回一个PrintWriter,它累积一个大字符数组中的所有东西。开发人员可利用toCharArray(原始char[])或toString(从char[]得出的一个String)方法得到这个结果。
CharArrayWrapper.java
package com.zj.
import java.io.CharArrayW
import java.io.PrintW
import javax.servlet.http.HttpServletR
import javax.servlet.http.HttpServletResponseW
* A response wrapper that takes everything the client would normally
* output and saves it in one big character array.
public class CharArrayWrapper extends HttpServletResponseWrapper {
private CharArrayWriter charW
* Initializes wrapper.
* First, this constructor calls the parent constructor. That call
*is crucial so that the response is stored and thus setHeader, *setStatus, addCookie, and so forth work normally.
* Second, this constructor creates a CharArrayWriter that will
* be used to accumulate the response.
public CharArrayWrapper(HttpServletResponse response) {
super(response);
charWriter = new CharArrayWriter();
* When servlets or JSP pages ask for the Writer, don't give them
* the real one. Instead, give them a version that writes into
* the character array.
* The filter needs to send the contents of the array to the
* client (perhaps after modifying it).
public PrintWriter getWriter() {
return (new PrintWriter(charWriter));
* Get a String representation of the entire buffer.
* Be sure &B&not&/B& to call this method multiple times on the same
* wrapper. The API for CharArrayWriter does not guarantee that it
* "remembers" the previous value, so the call is likely to make
* a new String every time.
public String toString() {
return (charWriter.toString());
/** Get the underlying character array. */
public char[] toCharArray() {
return (charWriter.toCharArray());
7.3 替换过滤器
这里展示前一节中给出的CharArrayWrapper的一个常见的应用:更改一个多次出现的目标串为某个替代串的过滤器。
7.3.1通用替换过滤器
ReplaceFilter.java给出一个过滤器,它在CharArraryWrapper中包装响应,传递该包装器到FilterChain对象的doFilter方法中,提取一个给出所有资源的输出的String型值,用一个替代串替换某个目标串的所有出现,并发送此修改过的结果到客户机。
关于这个过滤器,有两件事情需要注意。首先,它是一个抽象类。要使用它,必须建立一个提供getTargetString和getReplacementString方法的实现的子类。下一小节中给出了这种处理的一个例子。其次,它利用一个较小的实用类(见FilterUtils.java)来进行实际的串替换。你可使用新的常规表达式包而不是使用String和StringTokenizer中低级的和繁琐的方法。
ReplaceFilter.java
package com.zj.
import java.io.IOE
import java.io.PrintW
import javax.servlet.F
import javax.servlet.FilterC
import javax.servlet.FilterC
import javax.servlet.ServletE
import javax.servlet.ServletR
import javax.servlet.ServletR
import javax.servlet.http.HttpServletR
* Filter that replaces all occurrences of a given string with a
* replacement.
* This is an abstract class: you &I&must&/I& override the getTargetString
* and getReplacementString methods in a subclass.
* The first of these methods specifies the string in the response
* that should be replaced. The second of these specifies the string
* that should replace each occurrence of the target string.
public abstract class ReplaceFilter implements Filter {
private FilterC
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws ServletException, IOException {
CharArrayWrapper responseWrapper = new CharArrayWrapper(
(HttpServletResponse) response);
// Invoke resource, accumulating output in the wrapper.
chain.doFilter(request, responseWrapper);
// Turn entire output into one big String.
String responseString = responseWrapper.toString();
// In output, replace all occurrences of target string with replacement
// string.
responseString = FilterUtils.replace(responseString, getTargetString(),
getReplacementString());
// Update the Content-Length header.
updateHeaders(response, responseString);
PrintWriter out = response.getWriter();
out.write(responseString);
* Store the FilterConfig object in case subclasses want it.
public void init(FilterConfig config) throws ServletException {
this.config =
protected FilterConfig getFilterConfig() {
return (config);
public void destroy() {
* The string that needs replacement.
*Override this method in your subclass.
public abstract String getTargetString();
* The string that replaces the target. Override this method in
* your subclass.
public abstract String getReplacementString();
* Updates the response headers. This simple version just sets
*the Content-Length header, assuming that we are using a
*character set that uses 1 byte per character.
* For other character sets, override this method to use
* different logic or to give up on persistent HTTP connections.
* In this latter case, have this method set the Connection header
* to "close".
public void updateHeaders(ServletResponse response, String responseString) {
response.setContentLength(responseString.length());
FilterUtils.java
package com.zj.
* Small utility to assist with response wrappers that return strings.
public class FilterUtils {
* Change all occurrences of orig in mainString to replacement.
public static String replace(String mainString, String orig,
String replacement) {
String result = "";
int oldIndex = 0;
int index = 0;
int origLength = orig.length();
while ((index = mainString.indexOf(orig, oldIndex)) != -1) {
result = result + mainString.substring(oldIndex, index)
oldIndex = index + origL
result = result + mainString.substring(oldIndex);
return (result);
7.3.2实现一个字符替换过滤器
假设百度收购了google(只是假设),现在所有的页面上凡是出现google字样的文字都必须替换为百度!ReplaceSiteNameFilter.java继承上文ReplaceFilter.java来实现这一功能。
ReplaceSiteNameFilter.java
package com.zj.
public class ReplaceSiteNameFilter extends ReplaceFilter {
public String getTargetString() {
return (".cn");
public String getReplacementString() {
return ("");
&filter-name&ReplaceSiteNameFilter&/filter-name&
&filter-class&com.zj.sample.ReplaceSiteNameFilter&/filter-class&
&filter-mapping&
&filter-name&ReplaceSiteNameFilter&/filter-name&
&url-pattern&/login.jsp&/url-pattern&
&/filter-mapping&
测试结果:
8.压缩过滤器
有几个最新的浏览器可处理压缩的内容,自动解开以gzip作为Content-Encoding响应头值的压缩文件,然后就像对原文档那样处理结果。发送这样的压缩内容可以节省很多时间,因为在服务器上压缩文档,然后在客户机上解开文档所需的时间与下载文件的时间相比是微不足道的。程序LongServlet.java给出了一个具有很长的、重复的纯文本输出的servlet,这是一个可供压缩使用的成熟的servlet。如果使用gzip,它可以把输出结果压缩到1/300!
在浏览器支持这个压缩能力时,压缩过滤器可利用章节7介绍的CharArrayWrapper来压缩内容,完成此任务需要下列内容:
1)实现Filter接口的类。这个类名为CompressionFIlter。init方法存放FilterConfig对象在一个字段中,以防子类需要访问servlet环境或过滤器名。destory方法体为空。
2)包装的响应对象。DoFilter方法将ServletResponse对象包装在一个CharArrayWrapper中,并传递此包装器到FilterChain对象的doFilter方法上。在此调用完成后,所有其他过滤器和最终资源都已执行,且输出结果位于包装器之内。这样,原doFilter提取一个代表所有资源的输出的字符数组。如果客户机指出它支持压缩(即,以gzip作为Accept-Encoding头的一个值),则过滤器附加一个GZIPOutputStream到ByteArrayOutputStream上,将字符数组复制到此流中,并设置Content-Encoding响应头为gzip。如果客户机不支持gzip,则将未修改过的字符数组复制到ByteArrayOutputStream。最后,doFilter通过将整个字符数组(可能是压缩过的)写到与original响应相关的OutputStream中,发送结果到客户机。
3)对LongServlet进行注册。
CompressionFilter.java
package com.zj.
import java.io.ByteArrayOutputS
import java.io.IOE
import java.io.OutputS
import java.io.OutputStreamW
import java.util.zip.GZIPOutputS
import javax.servlet.F
import javax.servlet.FilterC
import javax.servlet.FilterC
import javax.servlet.ServletE
import javax.servlet.ServletR
import javax.servlet.ServletR
import javax.servlet.http.HttpServletR
import javax.servlet.http.HttpServletR
* Filter that compresses output with gzip (assuming that browser supports
public class CompressionFilter implements Filter {
private FilterC
* If browser does not support gzip, invoke resource normally. If browser
* &I&does&/I& support gzip, set the Content-Encoding response header and
* invoke resource with a wrapped response that collects all the output.
* Extract the output and write it into a gzipped byte array. Finally, write
* that array to the client's output stream.
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws ServletException, IOException {
HttpServletRequest req = (HttpServletRequest)
HttpServletResponse res = (HttpServletResponse)
if (!isGzipSupported(req)) {
// Invoke resource normally.
chain.doFilter(req, res);
// Tell browser we are sending it gzipped data.
res.setHeader("Content-Encoding", "gzip");
// Invoke resource, accumulating output in the wrapper.
CharArrayWrapper responseWrapper = new CharArrayWrapper(res);
chain.doFilter(req, responseWrapper);
// Get character array representing output.
char[] responseChars = responseWrapper.toCharArray();
// Make a writer that compresses data and puts it into a byte array.
ByteArrayOutputStream byteStream = new ByteArrayOutputStream();
GZIPOutputStream zipOut = new GZIPOutputStream(byteStream);
OutputStreamWriter tempOut = new OutputStreamWriter(zipOut);
// Compress original output and put it into byte array.
tempOut.write(responseChars);
// Gzip streams must be explicitly closed.
tempOut.close();
// Update the Content-Length header.
res.setContentLength(byteStream.size());
// Send compressed result to client.
OutputStream realOut = res.getOutputStream();
byteStream.writeTo(realOut);
* Store the FilterConfig object in case subclasses want it.
public void init(FilterConfig config) throws ServletException {
this.config =
protected FilterConfig getFilterConfig() {
return (config);
public void destroy() {}
private boolean isGzipSupported(HttpServletRequest req) {
String browserEncodings = req.getHeader("Accept-Encoding");
return ((browserEncodings != null) && (browserEncodings.indexOf("gzip") != -1));
LongServlet.java
package com.zj.
import java.io.IOE
import java.io.PrintW
import javax.servlet.ServletE
import javax.servlet.http.HttpS
import javax.servlet.http.HttpServletR
import javax.servlet.http.HttpServletR
* Servlet with &B&long&/B& output. Used to test the effect of the compression
* filter of Chapter 9.
public class LongServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String docType = "&!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0 "
+ "Transitional//EN\"&\n";
String title = "Long Page";
out.println(docType + "&HTML&\n" + "&HEAD&&TITLE&" + title
+ "&/TITLE&&/HEAD&\n" + "&BODY BGCOLOR=\"#FDF5E6\"&\n"
+ "&H1 ALIGN=\"CENTER\"&" + title + "&/H1&\n");
String line = "Blah, blah, blah, blah, blah. "
+ "Yadda, yadda, yadda, yadda.";
for (int i = 0; i & 10000; i++) {
out.println(line);
out.println("&/BODY&&/HTML&");
&filter-name&CompressionFilter&/filter-name&
&filter-class&com.pressionFilter&/filter-class&
&filter-mapping&
&filter-name&CompressionFilter&/filter-name&
&servlet-name&LongServlet&/servlet-name&
&/filter-mapping&
&servlet-name&LongServlet&/servlet-name&
&servlet-class&com.zj.sample.LongServlet&/servlet-class&
&/servlet&
&servlet-mapping&
&servlet-name&LongServlet&/servlet-name&
&url-pattern&/LongServlet&/url-pattern&
&/servlet-mapping&
您可能感兴趣的文章:
大家感兴趣的内容
12345678910
最近更新的内容
常用在线小工具

我要回帖

更多关于 java过滤器的作用 的文章

 

随机推荐