关键字过滤 脏话过滤



//

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.HttpServletRequestWrapper;
import javax.servlet.http.HttpServletResponse;

public class KeyWordFilter implements Filter{

 public void destroy() {
  // TODO Auto-generated method stub
  
 }

 public void doFilter(ServletRequest req, ServletResponse resp,
   FilterChain chain) throws IOException, ServletException {
  HttpServletRequest request = (HttpServletRequest)req;
  HttpServletResponse response = (HttpServletResponse)resp;
  KeyWordHttpServletRequest drequest = new KeyWordHttpServletRequest(request);
  chain.doFilter(drequest, response);
 }

 public void init(FilterConfig arg0) throws ServletException {
  // TODO Auto-generated method stub
  
 }

}

class KeyWordHttpServletRequest extends HttpServletRequestWrapper{
 private String words[] = {"傻B","白痴","禽兽"}; //过滤的关键字


 public KeyWordHttpServletRequest(HttpServletRequest request){
  super(request);
 }

 public String getParameter(String name) { // 获取到待转换的 内容
  String value = super.getParameter(name);
  if(value==null)
   return "木有";
  for(String dword:words){
   if(value.contains(dword)){//判断用户输入的内容中包含脏话
    value = value.replace(dword, "**");
   }
  }
  return value;
 }
 
}

你可能感兴趣的:(关键字过滤 脏话过滤)