SpringBoot请求参数过滤空格
前言
博主github
博主个人博客http://blog.healerjean.com
1、参数修改SpaceHttpServletRequestWrapper
public class SpaceHttpServletRequestWrapper extends HttpServletRequestWrapper {
public SpaceHttpServletRequestWrapper(HttpServletRequest servletRequest) {
super(servletRequest);
}
@Override
public String[] getParameterValues(String parameter) {
String[] values = super.getParameterValues(parameter);
if (values == null) {
return new String[0];
}
int count = values.length;
String[] encodedValues = new String[count];
for (int i = 0; i < count; i++) {
encodedValues[i] = values[i].trim();
}
return encodedValues;
}
@Override
public String getParameter(String parameter) {
String value = super.getParameter(parameter);
if (value == null) {
return null;
}
return value.trim();
}
}
2、空格过滤器
public class SpaceFilter implements Filter {
private FilterConfig filterConfig;
@Override
public void init(FilterConfig filterConfig) throws ServletException {
this.filterConfig = filterConfig;
}
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws
IOException, ServletException {
filterChain.doFilter(new SpaceHttpServletRequestWrapper(
(HttpServletRequest) servletRequest), servletResponse);
}
@Override
public void destroy() {
this.filterConfig = null;
}
}
3、过滤器初始化
@Configuration
public class WebMvcConfiguration implements WebMvcConfigurer {
@Bean
public FilterRegistrationBean spaceFilter() {
FilterRegistrationBean fitler = new FilterRegistrationBean();
fitler.setFilter(new SpaceFilter());
fitler.addUrlPatterns("/*");
fitler.setName("SpaceFilter");
fitler.setDispatcherTypes(DispatcherType.REQUEST);
return fitler;
}
}
感兴趣的,欢迎添加博主微信
哈,博主很乐意和各路好友交流,如果满意,请打赏博主任意金额,感兴趣的在微信转账的时候,备注您的微信或者其他联系方式。添加博主微信哦。
请下方留言吧。可与博主自由讨论哦
微信 | 微信公众号 | 支付宝 |
---|---|---|