前端请求的数据中,有一些数据前后空格、制表符等数据是不期望的,有一些含有非法参数,需要统一过滤这些内容。
springboot拦截请求的参数
参数获取方式
三种方式:
- HttpServletRequest getParameter、getParameterValues方法获取参数
- Controller方法自动封装的bean参数
- Controller方法用@RequestBody接收的json格式数据
对于1、2 重写HttpServletRequestWrapper并加入filter
对于3 重写ObjectMapper在json反序列化时过滤
重写HttpServletRequestWrapper
1 | public class ParameterRequestWrapper extends HttpServletRequestWrapper { |
filter配置
filter类
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21 public class ParamsFilter implements Filter {
private Logger log = LoggerFactory.getLogger(this.getClass());
public void doFilter(ServletRequest arg0, ServletResponse arg1,
FilterChain arg2) throws IOException, ServletException {
ParameterRequestWrapper parmsRequest = new ParameterRequestWrapper(
(HttpServletRequest) arg0);
arg2.doFilter(parmsRequest, arg1);
}
public void init(FilterConfig arg0) throws ServletException {
log.info("ParamsFilter init");
}
public void destroy() {
log.info("ParamsFilter destroy");
}
}
注册filter
1
2
3
4
5
6
7
8
9
10
public FilterRegistrationBean parmsFilterRegistration() {
FilterRegistrationBean registration = new FilterRegistrationBean();
registration.setDispatcherTypes(DispatcherType.REQUEST);
registration.setFilter(new ParamsFilter());
registration.addUrlPatterns("/*");
registration.setName("paramsFilter");
registration.setOrder(Integer.MAX_VALUE-1);
return registration;
}
这样可以处理前两种方式获取参数的情况
json格式参数
json格式SrpingMVC通过@RequestBody注解接收,需要配置全局json转换
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
public ObjectMapper jsonObjectMapper(Jackson2ObjectMapperBuilder builder) {
//解析器
ObjectMapper objectMapper = builder.createXmlMapper(false).build();
objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
//注册xss解析器
SimpleModule xssModule = new SimpleModule("ParamStringJsonSerializer");
//json string反序列化成bean
xssModule.addDeserializer(String.class, new JsonDeserializer<String>() {
public String deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException, JsonProcessingException {
String value = jsonParser.getText();
//过滤参数方法
value = ParameterUtil.handleParam(value);
return value;
}
});
objectMapper.registerModule(xssModule);
return objectMapper;
}