一个替换敏感词的filter

Posted on 2010-03-02 22:59  FreeSkyCD  阅读(315)  评论(0编辑  收藏  举报

阅读: 30 评论: 0 作者: jackyrong的世界 发表于 2010-03-02 22:59 原文链接

   一个过滤敏感词的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() {
 }

 

 

评论: 0 查看评论 发表评论

找优秀程序员,就在博客园


最新新闻:
· IBM发布第五代X架构 打破X86系统30年技术局限(2010-03-03 22:47)
· 互联网手机业务成香馍馍 上海电信盯牢3G市场(2010-03-03 22:38)
· Twitter信息总量即将突破100亿条大关(2010-03-03 22:34)
· Opera为何无法进一步拓展市场(2010-03-03 21:38)
· Symbian版 Skype登陆诺基亚Ovi Store(2010-03-03 21:04)

编辑推荐:Opera为何无法进一步拓展市场

网站导航:博客园首页  个人主页  新闻  闪存  小组  博问  社区  知识库

Copyright © 2024 FreeSkyCD
Powered by .NET 9.0 on Kubernetes