java解决xss问题
1. 配置过滤器
package com.thunisoft.dzsjfcg.config; import javax.servlet.*; import javax.servlet.annotation.WebFilter; import javax.servlet.http.HttpServletRequest; import java.io.IOException; /** * @Author ZhPJ * @Date 2019/10/22 002216:24 * @Version 1.0 * @Description: */ @WebFilter(urlPatterns = "/*") public class XssFilter implements Filter { @Override public void init(FilterConfig filterConfig) throws ServletException { } @Override public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException { filterChain.doFilter(new XssFilterWrapper((HttpServletRequest) servletRequest), servletResponse); } @Override public void destroy() { } }
2. 配置参数拦截器
package com.thunisoft.dzsjfcg.config; import org.apache.commons.lang.StringUtils; import org.springframework.web.util.HtmlUtils; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletRequestWrapper; public class XssFilterWrapper extends HttpServletRequestWrapper { public XssFilterWrapper(HttpServletRequest request) { super(request); } /** * 对数组参数进行特殊字符过滤 */ @Override public String[] getParameterValues(String name) { String[] values = super.getParameterValues(name); String[] newValues = new String[values.length]; for (int i = 0; i < values.length; i++) { newValues[i] = HtmlUtils.htmlEscape(values[i]); } return newValues; } @Override public String getParameter(String name) { String value = super.getParameter(name); if (StringUtils.isNotBlank(value)) { return HtmlUtils.htmlEscape(value); } return value; } }