servlet Filter过滤javascript
新建HttpServletRequestWrapper子类XssHttpServletRequestWrapper
import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletRequestWrapper; public class XssHttpServletRequestWrapper extends HttpServletRequestWrapper { public XssHttpServletRequestWrapper(HttpServletRequest request){ super(request); } public String[] getParameterValues(String parameter){ String[] values = super.getParameterValues(parameter); if(values==null){ return null; } int count = values.length; String[] encodedValues = new String[count]; for (int i = 0;i<count;i++){ encodedValues[i] = this.cleanXss(values[i]); } return encodedValues; } public String getParameter(String parameter){ String value = super.getParamerter(parameter); if(valuee == null){ return null; } return cleanXss(value); } private String cleanXss(String value){ value = value.replaceAll("<","<").replaceAll(">",">"); value = value.replaceAll("script",""); return value; } }
在Fileter中调用
import javax.servlet.Filter; import javax.servlet.FilterChain; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class HttpMethodFilter implements Filter { public void doFilter(ServletRequest request,ServletResponse response,FilterChain chain) throws IOException,ServletException { HttpServletRequest hsreq = (HttpServletResponse) request; HttpServletResponse hsrep = (HttpServletResponse) response; chain.doFilter(new XssHttpServletRequestWrapper((HttpServletRequest) request),response); } }