【问题标题】:Disable trimming of whitespace from path variables in Spring 3.2在 Spring 3.2 中禁用路径变量中的空格修剪
【发布时间】:2017-01-03 07:57:10
【问题描述】:

默认情况下,Spring 会从用作路径变量的字符串中修剪前导/尾随空格。我发现这是因为 trimTokens 标志在 AntPathMatcher 中默认设置为 true

不过,我想不通的是如何将该标志设置为 false

使用我将其设置为 falseAntPathMatcher 提供我自己的 RequestMappingHandlerMapping bean 不起作用。

如何使用 JavaConfig 更改此标志?

谢谢。

【问题讨论】:

  • 您能提供一个示例网址吗?您是否对您的网址进行了编码([space] --> %20)?

标签: java spring spring-mvc


【解决方案1】:

问题

正如您指出的那样,问题是因为所有带有 trimTokens 标志的 Spring Framework before 4.3.0 have the default antPathMatcher 版本都设置为 true。


解决方案

添加一个配置文件,该文件返回默认的 antPathMatcher,但将 trimTokens 标志设置为 false

@Configuration
@EnableAspectJAutoProxy
public class PricingConfig extends WebMvcConfigurerAdapter {

  @Bean
  public PathMatcher pathMatcher() {

    AntPathMatcher pathMatcher = new AntPathMatcher();
    pathMatcher.setTrimTokens(false);
    return pathMatcher;
  }

  @Override
  public void configurePathMatch(PathMatchConfigurer configurer) {        
    configurer.setPathMatcher(pathMatcher());
  }
}

【讨论】:

    【解决方案2】:

    让您的配置扩展 WebMvcConfigurationSupport 覆盖 requestMappingHandlerMapping() 并进行相应的配置。

    @Configuration
    public MyConfig extends WebMvcConfigurationSupport {
    
        @Bean
        public PathMatcher pathMatcher() {
          // Your AntPathMatcher here.
        }
    
        @Bean
        public RequestMappingHandlerMapping requestMappingHandlerMapping() {
            RequestMappingHandlerMapping  rmhm = super.requestMappingHandlerMapping();
            rmhm.setPathMatcher(pathMatcher());
            return rmhm;
        }
    } 
    

    【讨论】:

    • 成功了,谢谢!我正在扩展 WebMvcConfigurerAdapter 而不是 WebMvcConfigurationSupport。
    • 从 spring 4.0.3 开始,您还可以覆盖 configurePathMatch() 来设置路径匹配器。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-12-05
    • 2014-05-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多