SpringBoot请求参数过滤空格
1、参数修改SpaceHttpServletRequestWrapper
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
|
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、空格过滤器
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
|
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、过滤器初始化
1
2
3
4
5
6
7
8
9
10
11
12
|
@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 这样设置,如下:
1
|
java -jar xx.jar --server.port= 9301 |
但是对于有空格的参数,比如 sync.email.cron=0 0 9 * * ?,如何设置?
- 我的环境:windows
方式一(错误):
1
|
java -jar xx.jar --sync.email.cron= 0 0 9 * * ? |
方式二(错误):
1
2
|
set mailCron= 0 0 9 * * ? java -jar xx.jar --sync.email.cron=%mailCron% |
方式三(错误):
1
2
|
set mailCron=` 0 0 9 * * ?` java -jar xx.jar --sync.email.cron=%mailCron% |
等同于
1
|
java -jar xx.jar --sync.email.cron=` 0 0 9 * * ?` |
方式四(错误):
1
2
|
set mailCron= '0 0 9 * * ?' java -jar xx.jar --sync.email.cron=%mailCron% |
等同于
1
|
java -jar xx.jar --sync.email.cron= '0 0 9 * * ?' |
方式五(正确):
1
2
|
set mailCron= "0 0 9 * * ?" java -jar xx.jar --sync.email.cron=%mailCron% |
等同于
1
|
java -jar xx.jar --sync.email.cron= "0 0 9 * * ?" |
如上,正确的方式只有想办法将带有空格的字符串用双引号包起来,而直接设置、反引号设置、单引号设置都会将字符串分割开来,都是不正确的。Linux下也同样适用。
以上为个人经验,希望能给大家一个参考,也希望大家多多支持服务器之家。
原文链接:https://blog.csdn.net/u012954706/article/details/101691462