SpringBoot请求参数过滤空格
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;
}
}
|
SpringBoot指定执行参数,参数值包含空格问题
SpringBoot启动参数可以通过 --key1=value1 这样设置,如下:
java -jar xx.jar --server.port=9301
|
但是对于有空格的参数,比如 sync.email.cron=0 0 9 * * ?,如何设置?
我的环境:windows
方式一(错误):
java -jar xx.jar --sync.email.cron=0 0 9 * * ?
|
方式二(错误):
set mailCron=0 0 9 * * ?
java -jar xx.jar --sync.email.cron=%mailCron%
|
方式三(错误):
set mailCron=`0 0 9 * * ?`
java -jar xx.jar --sync.email.cron=%mailCron%
|
等同于
java -jar xx.jar --sync.email.cron=`0 0 9 * * ?`
|
方式四(错误):
set mailCron='0 0 9 * * ?'
java -jar xx.jar --sync.email.cron=%mailCron%
|
等同于
java -jar xx.jar --sync.email.cron='0 0 9 * * ?'
|
方式五(正确):
set mailCron="0 0 9 * * ?"
java -jar xx.jar --sync.email.cron=%mailCron%
|
等同于
java -jar xx.jar --sync.email.cron="0 0 9 * * ?"
|
如上,正确的方式只有想办法将带有空格的字符串用双引号包起来,而直接设置、反引号设置、单引号设置都会将字符串分割开来,都是不正确的。Linux下也同样适用。
java -jar xx.jar --server.port=9301
|