一个过滤敏感词的filter,看书学到的,小结之:
原理是将内容输出到response时,response将缓存起来,在filter中替换,然后再输出到客户端浏览器.因为默认的response不能缓存输出内容,
因此要自定义response,可以通过扩展HttpServletResponseWrapper 获得,
import java.io.CharArrayWriter;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpServletResponseWrapper;
public class HttpCharacterResponseWrapper extends HttpServletResponseWrapper {
private CharArrayWriter charArrayWriter = new CharArrayWriter();
public HttpCharacterResponseWrapper(HttpServletResponse response) {
super(response);
}
@Override
public PrintWriter getWriter() throws IOException {
return new PrintWriter(charArrayWriter);
}
public CharArrayWriter getCharArrayWriter() {
return charArrayWriter;
}
}
filter需要将自定义的response传到servlet中,代码如下:
public class OutputReplaceFilter implements Filter {
private Properties pp = new Properties();
public void init(FilterConfig config) throws ServletException {
String file = config.getInitParameter("file");
String realPath = config.getServletContext().getRealPath(file);
try {
pp.load(new FileInputStream(realPath));
} catch (IOException e) {
}
}
public void doFilter(ServletRequest req, ServletResponse res,
FilterChain chain) throws IOException, ServletException {
// 自定义的 response
HttpCharacterResponseWrapper response = new HttpCharacterResponseWrapper(
(HttpServletResponse) res);
// 提交给 Servlet 或者下一个 Filter
chain.doFilter(req, response);
// 得到缓存在自定义 response 中的输出内容
String output = response.getCharArrayWriter().toString();
// 修改,替换
for (Object obj : pp.keySet()) {
String key = (String) obj;
output = output.replace(key, pp.getProperty(key));
}
// 输出
PrintWriter out = res.getWriter();
out.write(output);
out.println("<!-- Generated at " + new java.util.Date() + " -->");
}
public void destroy() {
}