一、概述
在论坛或者网站中,我们会发现一些用户发表一些不文明或者非法的文字。这样可能导致论坛的不文明和谐,甚至还可能带来一些法律上的纠纷。我们可以使用过滤器来帮助我们过滤掉这些不文明的文字。
二、思路
统一维护非法文字,为了提高程序运行效率,可以将其缓存到内存中。当用户提交请求后,利用过滤器对指定程序(如发表言论)请求的内容进行过滤。发现有非法字符后替换成合法字符(如“*”)。
三、具体实现
keyword.properties
讨哥=**荡漾=xx
这里我们使用properties文件保存非法字符。
key是非法文字,value是要被替换后的文字。
ContentFilter.java
package cn.heimar.filter.contentfilter.util;import java.io.IOException;import javax.servlet.Filter;import javax.servlet.FilterChain;import javax.servlet.FilterConfig;import javax.servlet.ServletException;import javax.servlet.ServletRequest;import javax.servlet.ServletResponse;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;public class ContentFilter implements Filter { @Override public void init(FilterConfig config) throws ServletException { // TODO Auto-generated method stub } @Override public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws IOException, ServletException { HttpServletRequest request = (HttpServletRequest) req; HttpServletResponse response = (HttpServletResponse) resp; //思路:得到提交数据,替换,重新设置进去 //使用包装对象来包裹原请求对象 //如果是第一次请求,则加载关键字,缓存到ServletContext ContentReplaceHttpServletRequestWapper wapper=new ContentReplaceHttpServletRequestWapper(request); chain.doFilter(wapper, resp); } @Override public void destroy() { // TODO Auto-generated method stub }}
ContentReplaceHttpServletRequestWapper.java
package cn.heimar.filter.contentfilter.util;import java.io.IOException;import java.io.UnsupportedEncodingException;import java.util.Properties;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletRequestWrapper;/** * 使用装饰模式,来修改getParameter方法返回的参数值 * * @author yan * */public class ContentReplaceHttpServletRequestWapper extends HttpServletRequestWrapper { private static Properties keywords; static { keywords = new Properties(); try { keywords.load(ContentReplaceHttpServletRequestWapper.class .getClassLoader().getResourceAsStream("keyword.properties")); } catch (IOException e) { e.printStackTrace(); } } public ContentReplaceHttpServletRequestWapper(HttpServletRequest request) { super(request); } @Override public String getParameter(String name) { //content和name是要过滤的请求参数名称 if ("content".equals(name) || "title".equals(name)) { String old = super.getParameter(name); old = doFilter(old); return old; } return super.getParameter(name); } private String doFilter(String old) { for (Object temp : keywords.keySet()) { try { String key = new String(((String) temp).getBytes("ISO-8859-1"),"UTF-8"); old = old.replaceAll(key, keywords.getProperty((String)temp)); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } } return old; }}