如何匹配包含"/"的@pathVariable的Spring @RequestMapping?

yef*_*iak 14 java spring spring-mvc

我正在做客户的以下请求:

/search/hello%2Fthere/

其中搜索词"hello/there"已经过网址编码.

在服务器上,我尝试使用以下请求映射匹配此URL:


@RequestMapping("/search/{searchTerm}/") 
public Map searchWithSearchTerm(@PathVariable String searchTerm) {
// more code here 
}
Run Code Online (Sandbox Code Playgroud)

但我在服务器上收到错误404,因为我没有任何匹配的URL.我注意到在Spring获取之前解码了URL.因此,尝试匹配/ search/hello /那里没有任何匹配.

我在这里找到了一个与此问题相关的Jira:http://jira.springframework.org/browse/SPR-6780.但我仍然不知道如何解决我的问题.

有任何想法吗?

谢谢

axt*_*avt 25

没有好的方法可以做到(没有处理HttpServletResponse).你可以这样做:

@RequestMapping("/search/**")  
public Map searchWithSearchTerm(HttpServletRequest request) { 
    // Don't repeat a pattern
    String pattern = (String)
        request.getAttribute(HandlerMapping.BEST_MATCHING_PATTERN_ATTRIBUTE);  

    String searchTerm = new AntPathMatcher().extractPathWithinPattern(pattern, 
        request.getServletPath());

    ...
}
Run Code Online (Sandbox Code Playgroud)

  • 对我来说,而不是request.getServletPath()工作request.getPathInfo() (5认同)
  • AntPathMatcher是线程安全的.共享一个实例非常好. (2认同)