<filter> <filter-name>XssEscape</filter-name> <filter-class>cn.pconline.morden.filter.XssFilter</filter-class> </filter> <filter-mapping> <filter-name>XssEscape</filter-name> <url-pattern>/*</url-pattern> <dispatcher>REQUEST</dispatcher> </filter-mapping>
XssFilter 的实现方式是实现servlet的Filter接口
package cn.pconline.morden.filter; 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; public class XssFilter implements Filter { @Override public void init(FilterConfig filterConfig) throws ServletException { } @Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { chain.doFilter(new XssHttpServletRequestWrapper((HttpServletRequest) request), response); } @Override public void destroy() { } }
package cn.pconline.morden.filter; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletRequestWrapper; import org.apache.commons.lang3.StringEscapeUtils; public class XssHttpServletRequestWrapper extends HttpServletRequestWrapper { public XssHttpServletRequestWrapper(HttpServletRequest request) { super(request); } @Override public String getHeader(String name) { return StringEscapeUtils.escapeHtml4(super.getHeader(name)); } @Override public String getQueryString() { return StringEscapeUtils.escapeHtml4(super.getQueryString()); } @Override public String getParameter(String name) { return StringEscapeUtils.escapeHtml4(super.getParameter(name)); } @Override public String[] getParameterValues(String name) { String[] values = super.getParameterValues(name); if(values != null) { int length = values.length; String[] escapseValues = new String[length]; for(int i = 0; i < length; i++){ escapseValues[i] = StringEscapeUtils.escapeHtml4(values[i]); } return escapseValues; } return super.getParameterValues(name); } }
到此为止,在输入的过滤就完成了。
在页面显示数据的时候,只是简单地用fn:escapeXml()对有可能出现xss漏洞的地方做一下转义输出。
复杂内容的显示,具体问题再具体分析。
另外,有些情况不想显示过滤后内容的话,可以用StringEscapeUtils.unescapeHtml4()这个方法,把StringEscapeUtils.escapeHtml4()转义之后的字符恢复原样。
Atas ialah kandungan terperinci Java中HttpServletRequestWrapper实现xss注入的实例. Untuk maklumat lanjut, sila ikut artikel berkaitan lain di laman web China PHP!