<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 The implementation is to implement the servlet's Filter interface
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); } }
At this point, the input filtering is completed.
When displaying data on the page, simply use fn:escapeXml() to escape the output where XSS vulnerabilities may occur.
Display of complex content, specific issues will be analyzed in detail
In addition, if you do not want to display the filtered content in some cases, you can use the StringEscapeUtils.unescapeHtml4() method to replace StringEscapeUtils.escapeHtml4(). The characters after escaping are restored to their original appearance
.The above is the detailed content of Example of xss injection implemented by HttpServletRequestWrapper in Java. For more information, please follow other related articles on the PHP Chinese website!