导航

spring mvc @PathVariable匹配特殊字符

Posted on 2018-04-03 10:50  yjss  阅读(1037)  评论(0编辑  收藏  举报

1、使用**匹配任意Url:

@RequestMapping("/file/**")  
public void file(HttpServletRequest request) { 
    String pattern = (String) request.getAttribute(HandlerMapping.BEST_MATCHING_PATTERN_ATTRIBUTE);  
    String path= new AntPathMatcher().extractPathWithinPattern(pattern,request.getServletPath());
}

 

2、使用.+匹配任意字符:

@RequestMapping(value = "/file/{path:.+}", method = RequestMethod.GET)
public void file(@PathVariable String path)

{path:.+}表示匹配任意字符,但是由于Spring MVC默认将/作为Url分隔符,所以需要更改一下配置:

@Configuration
@EnableWebMvc
public class WebMvc extends WebMvcConfigurerAdapter {

    @Override
    public void configurePathMatch(PathMatchConfigurer configurer) {
        UrlPathHelper urlPathHelper = new UrlPathHelper();
        urlPathHelper.setUrlDecode(false);
        configurer.setUrlPathHelper(urlPathHelper);
    }
}