struts2如何防止XSS脚本攻击(XSS防跨站脚本攻击过滤器)
只需要配置一个拦截器即可解决参数内容替换
一、配置web.xml
struts-xssFilter *.*.filters.XssFilter struts-xssFilter /*
二、编写XssFilter
import javax.servlet.*; import javax.servlet.http.HttpServletRequest; import java.io.IOException; public class XssFilter implements Filter{ FilterConfig filterConfig = null; /** * Default constructor. */ public XssFilter() { } public void destroy() { this.filterConfig = null; } public void init(FilterConfig fConfig) throws ServletException { this.filterConfig = fConfig; } public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { HttpServletRequest req = (HttpServletRequest) request; String url = req.getRequestURI(); //过滤不需要拦截的action if(url.indexOf("*.action") != -1){ chain.doFilter(request, response); }else{ chain.doFilter(new XssHttpServletRequestWrapper((HttpServletRequest) request), response); } } }
三、XssHttpServletRequestWrapper 实现 StrutsRequestWrapper完成参数替换
import cn.hutool.http.HtmlUtil; import org.apache.commons.lang.StringUtils; import org.apache.struts2.dispatcher.StrutsRequestWrapper; import org.springframework.util.CollectionUtils; import javax.servlet.http.HttpServletRequest; import java.util.Enumeration; import java.util.Map; import java.util.regex.Pattern; public class XssHttpServletRequestWrapper extends StrutsRequestWrapper { HttpServletRequest orgRequest = null; public XssHttpServletRequestWrapper(HttpServletRequest servletRequest) { super(servletRequest); orgRequest = servletRequest; } /** * 重写getParameterValues方法 * 通过循环取出每一个请求结果 * 再对请求结果进行过滤 * */ 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四、pom需要引入hutool
cn.hutool hutool-all 5.6.0五、测试结果通过
文章版权声明:除非注明,否则均为主机测评原创文章,转载或复制请以超链接形式并注明出处。