找了几个java后台拦截xss的代码,大致都是下面这样
package com.ibm.web.beans;
import java.util.Enumeration;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
public class XssHttpServletRequestWrapper extends HttpServletRequestWrapper {
public XssHttpServletRequestWrapper(HttpServletRequest servletRequest) {
super(servletRequest);
}
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 < count; i++) {
encodedValues[i] = cleanXSS(values[i]);
}
return encodedValues;
}
public String getParameter(String parameter) {
String value = super.getParameter(parameter);
if (value == null) {
return null;
}
return cleanXSS(value);
}
public String getHeader(String name) {
String value = super.getHeader(name);
if (value == null)
return null;
return cleanXSS(value);
}
private String cleanXSS(String value) {
//You'll need to remove the spaces from the html entities below
value = value.replaceAll("", "& gt;");
value = value.replaceAll("\\(", "& #40;").replaceAll("\\)", "& #41;");
value = value.replaceAll("'", "& #39;");
value = value.replaceAll("eval\\((.*)\\)", "");
value = value.replaceAll("[\\\"\\\'][\\s]*javascript:(.*)[\\\"\\\']", "\"\"");
value = value.replaceAll("script", "");
return value;
}
}
这里只对param做了转义,请问如何对ajax的json请求进行转义?
前台代码
$.ajaxSetup({
contentType: 'application/json'
});
var obj = {"name" : "'", "code" : "
$.post("/submit", JSON.stringify(obj), function (result, status) {
alert('ok');
}, "json");
后台代码
@RequestMapping(value = "/submit", method = RequestMethod.POST)
public void submit(@RequestBody Student student) {
System.out.println(student.getName());
System.out.println(student.getCode());
}
这里对ajax提交的json代码就没有做转义,我用的是spring,请问该如何对ajax请求转义,是使用aop对set方法拦截,还是修改HttpMessageConverter在json转为java对象时转义,还是其他方式?