一个替换敏感词的filter

一个过滤敏感词的filter,看书学到的,小结之:

原理是将内容输出到response时,response将缓存起来,在filter中替换,然后再输出到客户端浏览器.因为默认的response不能缓存输出内容,

因此要自定义response,可以通过扩展HttpServletResponseWrapper获得,

importjava.io.CharArrayWriter;

importjava.io.IOException;

importjava.io.PrintWriter;

importjavax.servlet.http.HttpServletResponse;

importjavax.servlet.http.HttpServletResponseWrapper;

publicclassHttpCharacterResponseWrapperextendsHttpServletResponseWrapper{

privateCharArrayWritercharArrayWriter=newCharArrayWriter();

publicHttpCharacterResponseWrapper(HttpServletResponseresponse){

super(response);

}

@Override

publicPrintWritergetWriter()throwsIOException{

returnnewPrintWriter(charArrayWriter);

}

publicCharArrayWritergetCharArrayWriter(){

returncharArrayWriter;

}

}

filter需要将自定义的response传到servlet中,代码如下:

publicclassOutputReplaceFilterimplementsFilter{

privatePropertiespp=newProperties();

publicvoidinit(FilterConfigconfig)throwsServletException{

Stringfile=config.getInitParameter("file");

StringrealPath=config.getServletContext().getRealPath(file);

try{

pp.load(newFileInputStream(realPath));

}catch(IOExceptione){

}

}

publicvoiddoFilter(ServletRequestreq,ServletResponseres,

FilterChainchain)throwsIOException,ServletException{

//自定义的response

HttpCharacterResponseWrapperresponse=newHttpCharacterResponseWrapper(

(HttpServletResponse)res);

//提交给Servlet或者下一个Filter

chain.doFilter(req,response);

//得到缓存在自定义response中的输出内容

Stringoutput=response.getCharArrayWriter().toString();

//修改,替换

for(Objectobj:pp.keySet()){

Stringkey=(String)obj;

output=output.replace(key,pp.getProperty(key));

}

//输出

PrintWriterout=res.getWriter();

out.write(output);

out.println("<!--Generatedat"+newjava.util.Date()+"-->");

}

publicvoiddestroy(){

}

相关推荐