/* (non-Javadoc)
* @see javax.servlet.Filter#doFilter(javax.servlet.ServletRequest, javax.servlet.ServletResponse, javax.servlet.FilterChain)
*/
@Override
public void doFilter(ServletRequest arg0, ServletResponse arg1,FilterChain arg2) throws IOException, ServletException {
HttpServletRequest request = (HttpServletRequest) arg0;
HttpServletResponse response = (HttpServletResponse) arg1;
//敏感词汇过滤
GetHttpServletRequestWrapper req = new GetHttpServletRequestWrapper((HttpServletRequest)arg0,"utf-8",request.getRequestURI());
arg2.doFilter(req, response);
}
}
public class GetHttpServletRequestWrapper extends HttpServletRequestWrapper {web.xml中配置
private String charset = "UTF-8";
private String url;
public GetHttpServletRequestWrapper(HttpServletRequest request) {
super(request);
}
/**
* 获得被装饰对象的引用和采用的字符编码
*
* @param request
* @param charset
*/
public GetHttpServletRequestWrapper(HttpServletRequest request,String charset, String url) {
super(request);
this.charset = charset;
this.url = url;
}
/**
* 重写getParameter方法获得参数,对特殊字符进行过滤
*/
public String getParameter(String name) {
String value = super.getParameter(name);
value = value == null ? null : convert(value);
return value;
}
/**
* 重写getParameterValues方法获得参数,对特殊字符进行过滤
*/
public String[] getParameterValues(String name){
String[] values = super.getParameterValues(name);
if(values!=null && values.length>0){
values[0] = values[0] == null ? null : convert(values[0]);
}
return values;
}
/**
* 过滤规则
* @param target
* @return
*/
public String convert(String target) {
//target = StringEscapeUtils.escapeHtml(target);
//target = StringEscapeUtils.escapeJavaScript(target);
//敏感词汇信息
List<SensitiveWord> swList = SwConstant.ALL_SW_LIST;
//判断是否拦截,把拦截的内容替换为相应的*
if(null != url && (url.contains("/discuss/add") || url.contains("/discuss/addLivelDiscuss") || url.contains("/suggestion/add"))){
if(null != swList && !swList.isEmpty()){
int num = 0;
for(SensitiveWord sw : swList){
if(null != sw.getSw() && !"".equals(sw.getSw()) && target.contains(sw.getSw().trim())){
StringBuffer repStr = new StringBuffer();
num = sw.getSw().trim().length();
for(int i=0;i<num;i++){
repStr.append("*");
}
target = target.replace(sw.getSw(), repStr);
}
}
}
}
return target;
}
}
<filter>
<filter-name>RequestFilter</filter-name>
<filter-class>gt.common.RequestFilter</filter-class>
<async-supported>true</async-supported>
</filter>
<filter-mapping>
<filter-name>RequestFilter</filter-name>
<url-pattern>*.action</url-pattern>
</filter-mapping>
<filter-mapping>
<filter-name>RequestFilter</filter-name>
<url-pattern>*.jsp</url-pattern>
</filter-mapping>