小编典典

如何匹配具有包含“ /”的@pathVariable的Spring @RequestMapping?

spring-mvc

我正在从客户端执行以下请求:

/search/hello%2Fthere/

搜索字词“ hello / there”已被网址编码。

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

@RequestMapping("/search/{searchTerm}/") 
public Map searchWithSearchTerm(@PathVariable String searchTerm) {
// more code here 
}

但是我在服务器上收到错误404,因为我没有与URL匹配的内容。我注意到,URL在Spring获取之前就已解码。因此正在尝试匹配/ search /
hello /那里没有任何匹配项。

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

有任何想法吗?

谢谢


阅读 494

收藏
2020-06-01

共1个答案

小编典典

没有(没有处理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());

    ...
}
2020-06-01