是否有可能在springMVC @PathVariable上设置全局正则表达式模式?

时间:2015-05-21 13:35:04

标签: regex spring spring-mvc

与标题一样,您是否知道有可能在@PathVariable下的春季为所有@RequestMapping设置全局正则表达式?例如:

@RequestMapping(value = "/view/{id:[a-z]{5}|[1-9]{7}}", method = RequestMethod.GET)
    @PreAuthorize("hasRole('XXXX')")
    public String viewId(@PathVariable String id, Model model) {
        ...
    }

我不想将regexp本地设置为{id:[a-z]{5}|[1-9]{7}},但我想在可能的地方设置它。另外我有配置,我不想改变:

@Configuration
@EnableWebMvc
@ComponentScan(basePackages = {"com.xxxx.yyy.zzz.controller.formatters"})
public class MediaPortalWebConfig extends WebMvcConfigurationSupport {
@Override
    @Bean
    public RequestMappingHandlerMapping requestMappingHandlerMapping() {
        RequestMappingHandlerMapping requestMappingHandlerMapping = super.requestMappingHandlerMapping();
        requestMappingHandlerMapping.setUseSuffixPatternMatch(false);
        return requestMappingHandlerMapping;
    }
}

所以我知道setUseSuffixPatternMatch(false);的意思是什么,这必须保持弹簧配置。

1 个答案:

答案 0 :(得分:0)

您可以编写自定义路径匹配器,例如CustomRegexPathMatcher通过扩展默认AntPathMatcher并覆盖其doMatch方法,以便在对网址执行匹配时考虑您的正则表达式

比你想要的更像

@Configuration
@EnableWebMvc
@ComponentScan(basePackages = {"com.xxxx.yyy.zzz.controller.formatters"})
public class MediaPortalWebConfig extends WebMvcConfigurationSupport {
@Override
    @Bean
    public RequestMappingHandlerMapping requestMappingHandlerMapping() {
        RequestMappingHandlerMapping requestMappingHandlerMapping = super.requestMappingHandlerMapping();
        requestMappingHandlerMapping.setUseSuffixPatternMatch(false);
        requestMappingHandlerMapping.setPathMatcher(new CustomRegexPathMatcher());
        return requestMappingHandlerMapping;
    }
}