xss跨站脚本攻击问题最主要是呈现在html页面的脚本被执行导致的结果,可分为两个方便作屏蔽
后台屏蔽在前端上传的各个参数后,对其进行转义后再保存至数据库,属于暴力式转义,一般不建议。下面是写的例子
创建HttpServletRequest新对象,覆盖其中的getParameterMap()方法,其会被ServletModelAttributeMethodProcessor处理方法参数时被调用,具体的读者可自行分析
package com.jing.springboot.test; import java.util.Enumeration; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletRequestWrapper; import org.springframework.util.MultiValueMap; public class FormHttpRequestWrapper extends HttpServletRequestWrapper { // 采用spring的MultiValueMap集合 private MultiValueMap<String, String> paramsMap; public FormHttpRequestWrapper(HttpServletRequest request) { super(request); } public FormHttpRequestWrapper(HttpServletRequest request, MultiValueMap<String, String> paramMap) { super(request); this.paramsMap = paramMap; } @Override public String getParameter(String name) { String param = super.getParameter(name); return param == null ? paramsMap.getFirst(name) : param; } @Override public Map<String, String[]> getParameterMap() { Map<String, String[]> paramterMap = super.getParameterMap(); Set<Entry<String, List<String>>> mapSets = paramsMap.entrySet(); for (Entry<String, List<String>> mapSet : mapSets) { String key = mapSet.getKey(); List<String> values = mapSet.getValue(); paramterMap.put(key, values.toArray(new String[values.size()])); } return paramterMap; } @Override public Enumeration<String> getParameterNames() { return super.getParameterNames(); } @Override public String[] getParameterValues(String name) { List<String> multiValues = paramsMap.get(name); String[] oldValues = super.getParameterValues(name); Set<String> trueValues = new HashSet<String>(oldValues.length + multiValues.size()); for (String multi : multiValues) { trueValues.add(multi); } for (String old : oldValues) { trueValues.add(old); } return trueValues.toArray(new String[trueValues.size()]); } }