package com.system.filter; import java.io.IOException; import java.util.Enumeration; 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; import org.apache.log4j.Logger; /** * 非法字符过滤器 * 1.所有非法字符配置在web.xml中,如需添加新字符,请自行配置 * 2.请注意请求与相应的编码格式设置 * @author lee * */ public class XSSFilter implements Filter{ private static final Logger log = Logger.getLogger(XSSFilter.class); private String encoding; private String[] illegalChars; private final String str="<,>"; @Override public void destroy() { // TODO Auto-generated method stub encoding = null; illegalChars = null; } @Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain) throws IOException, ServletException { // TODO Auto-generated method stub HttpServletRequest req = (HttpServletRequest)request; HttpServletResponse res = (HttpServletResponse) response; //必须手动指定编码格式 req.setCharacterEncoding(encoding); String tempURL = req.getRequestURI(); log.info(tempURL); Enumeration params = req.getParameterNames(); //是否执行过滤 true:执行过滤 false:不执行过滤 boolean executable = true; //非法状态 true:非法 false;不非法 boolean illegalStatus = false; String illegalChar = ""; //对参数名与参数进行判断 w:while(params.hasMoreElements()){ String paramName = (String) params.nextElement(); executable = true; //密码不过滤 if(paramName.toLowerCase().contains("password")){ executable = false; } if(executable){ String[] paramValues = req.getParameterValues(paramName); f1:for(int i=0;iwindow.alert('当前链接中存在非法字符');window.history.go(-1);"); }else{ filterChain.doFilter(request, response); } } @Override public void init(FilterConfig filterConfig) throws ServletException { // TODO Auto-generated method stub encoding = filterConfig.getInitParameter("encoding"); illegalChars = str.split(","); } }