web.xml添加过滤器
<!-- 解决xss漏洞 --> <filter> <filter-name>xssFilter</filter-name>
<filter-class>com.quickly.exception.common.filter.XssFilter</filter-class>
</filter> <!-- 解决xss漏洞 --> <filter-mapping>
<filter-name>xssFilter</filter-name> <url-pattern>*</url-pattern>
</filter-mapping>
过滤器代码
package com.quickly.exception.common.filter; import javax.servlet.*; import
javax.servlet.http.HttpServletRequest; import java.io.IOException; /** *
作用:Xss过滤器 * 作者:Tiddler * 时间:2018/11/11 10:21 * 类名: XssFilter **/ 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 { //使用包装器
XssFilterWrapper xssFilterWrapper=new XssFilterWrapper((HttpServletRequest)
servletRequest); filterChain.doFilter(xssFilterWrapper,servletResponse); }
@Override public void destroy() { } }
过滤器包装器代码
package com.quickly.exception.common.filter; import
org.springframework.web.util.HtmlUtils; import
javax.servlet.http.HttpServletRequest; import
javax.servlet.http.HttpServletRequestWrapper; /** * 作用:防Xss过滤器[包装器] *
作者:Tiddler * 时间:2018/11/11 10:20 * 类名: XssFilterWrapper **/ public class
XssFilterWrapper extends HttpServletRequestWrapper { public
XssFilterWrapper(HttpServletRequest request) { super(request); } /** *
对数组参数进行特殊字符过滤 */ @Override public String[] getParameterValues(String name) {
if("content".equals(name)){//不想过滤的参数,此处content参数是 富文本内容 return
super.getParameterValues(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]);//spring的HtmlUtils进行转义 } return newValues; } }
总结:

主要是使用Java
Web的过滤器,将所有的request请求参数修改(主要是把存在xss风险的标签转义,如:<script></script>),在转义时我没有自己实现替换与转义,是直接使用的spring自带的HtmlUtils类的htmlEscape方法转义的,方便很多