web.xml配置:
<filter>
<filter-name>XssSqlFilter</filter-name>
<filter-class>具体处理类</filter-class>
</filter>
<filter-mapping>
<filter-name>XssSqlFilter</filter-name>
<url-pattern>/*</url-pattern>
<dispatcher>REQUEST</dispatcher>
</filter-mapping>
具体实现代码
public class XSSFilter implements Filter {
private FilterConfig filterConfig = null;
@Override
public void destroy() {
this.setFilterConfig(null);
}
@Override
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException {
chain.doFilter(new XssHttpServletRequestWrapper( (HttpServletRequest) request), response);
}
@Override
public void init(FilterConfig filterConfig) throws ServletException {
this.setFilterConfig(filterConfig);
}
public FilterConfig getFilterConfig() {
return filterConfig;
}
public void setFilterConfig(FilterConfig filterConfig) {
this.filterConfig = filterConfig;
}
}
public class XssHttpServletRequestWrapper extends HttpServletRequestWrapper {
public XssHttpServletRequestWrapper(HttpServletRequest request) {
super(request);
}
@Override
public String[] getParameterValues(String parameter) {
String[] values = super.getParameterValues(parameter);
if (null == values) {
return null;
}
String[] encodedValues = new String[values.length];
for (int i = 0; i < values.length; i++) {
encodedValues[i] = cleanXSS(values[i]);
}
return encodedValues;
}
@Override
public String getParameter(String parameter) {
String value = super.getParameter(parameter);
if (null == value) {
return null;
}
return cleanXSS(value);
}
@Override
public String getHeader(String header) {
String value = super.getHeader(header);
if (null == value) {
return null;
}
return cleanXSS(value);
}
private String cleanXSS(String value) {
return HtmlUtils.htmlEscape(value);
}
}
HtmlUtils.htmlUnescape(input): 可以将替换的字符串转换为未替换前的字符串