在論壇或者網站中,咱們會發現一些用戶發表一些不文明或者非法的文字。這樣可能致使論壇的不文明和諧,甚至還可能帶來一些法律上的糾紛。咱們能夠使用過濾器來幫助咱們過濾掉這些不文明的文字。 java
統一維護非法文字,爲了提升程序運行效率,能夠將其緩存到內存中。當用戶提交請求後,利用過濾器對指定程序(如發表言論)請求的內容進行過濾。發現有非法字符後替換成合法字符(如「*」)。 緩存
keyword.properties app
討哥=** 盪漾=xx
這裏咱們使用properties文件保存非法字符。 ide
key是非法文字,value是要被替換後的文字。 網站
ContentFilter.java spa
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 code
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; } }