servlet过滤器实现过滤敏感文字

实现思路:通过过滤器对jsp页面进行拦截,对出现的敏感文字进行替换,然后替换后的内容再输出到jsp页面,敏感文字替换内容从proppreties配置文件中读取(内容过多的话也可从数据库中读取)。

首先建一个servlet过滤器类,在web.xml配置好过滤器:

<filter>
<filter-name>TextFilter</filter-name>
<filter-class>cn.servlet.filter.TextFilter</filter-class>
<init-param>
          <param-name>file</param-name>
          <param-value>/WEB-INF/textfilter.properties</param-value>
        </init-param>
</filter>
<filter-mapping>
<filter-name>TextFilter</filter-name>
<url-pattern>*.jsp</url-pattern>

</filter-mapping>


在过滤器类中读取配置和proppreties文件

过滤器类代码:

public class TextFilter implements Filter {


private FilterConfig config;
private Properties pp=new Properties();
@Override
public void destroy() {
// TODO Auto-generated method stub
}


@Override
public void doFilter(ServletRequest req, ServletResponse res,
FilterChain chain) throws IOException, ServletException {
// TODO Auto-generated method stub
//自定义response
HttpCharacterResponseWapper response=new HttpCharacterResponseWapper((HttpServletResponse)res);
//System.out.println("character");
//提交给servlet
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);
}

@Override
public void init(FilterConfig filterConfig) throws ServletException {
// TODO Auto-generated method stub
config=filterConfig;
String file=config.getInitParameter("file");
//或者绝对路径
String realpath=config.getServletContext().getRealPath(file);
try {
pp.load(new FileInputStream(realpath));
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}


}

doFilter方法中的HttpCharacterResponseWapper 是自定义的response,HttpCharacterResponseWapper 类如下:

public class HttpCharacterResponseWapper extends HttpServletResponseWrapper {

private CharArrayWriter charArrayWriter=new CharArrayWriter();

public HttpCharacterResponseWapper(HttpServletResponse response) {
super(response);
// TODO Auto-generated constructor stub
}

@Override
public PrintWriter getWriter() throws IOException {
// TODO Auto-generated method stub
return new PrintWriter(charArrayWriter);
}


public CharArrayWriter getCharArrayWriter() {
return charArrayWriter;
}

}

这里需要定义一个CharArrayWriter 字符输出流对jsp内容进行包装,相当于缓存流,不然代码执行chain.doFilter(req, response)后就直接到下一个filter或jsp页面,无法获取到jsp内容,所以需要自定义一个waapper对jsp内容进行缓存,才能对其进行替换;替换完通过out输出到页面。

阅读更多
想对作者说点什么?

博主推荐

换一批

没有更多推荐了,返回首页