如何匹配包含“/”@pathVariable的春季@RequestMapping?

2022-09-03 05:25:25

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

/search/hello%2Fthere/

其中搜索词“hello/there”已被 URLencoded。

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


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

但是我在服务器上收到错误404,因为我没有任何与URL匹配的匹配项。我注意到URL在Spring获得它之前就被解码了。因此,正在尝试匹配 /search/hello/there,其中没有任何匹配项。

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

有什么想法吗?

谢谢


答案 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());

    ...
}

答案 2
    @Configuration
    public class AdditionalWebConfig extends WebMvcConfigurationSupport {
     .......
     ...........
     ...........
    @Override
    public void configureContentNegotiation(ContentNegotiationConfigurer 
    configurer) {
       configurer.favorPathExtension(false);
    }
    .......
    .......
  }

并在@PathVariable中添加这样的正则表达式(“user/{username:.+}”)


推荐