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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2334787/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-29 20:39:33  来源:igfitidea点击:

How to match a Spring @RequestMapping having a @pathVariable containing "/"?

javaspringspring-mvc

提问by yeforriak

I am doing the following request from the client:

我正在执行来自客户的以下请求:

/search/hello%2Fthere/

/search/hello%2Fthere/

where the search term "hello/there" has been URLencoded.

其中搜索词“hello/there”已被 URL 编码。

On the server I am trying to match this URL using the following request mapping:

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


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

But I am getting error 404 on the server, due I don't have any match for the URL. I noticed that the URL is decoded before Spring gets it. Therefore is trying to match /search/hello/there which does not have any match.

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

I found a Jira related to this problem here: http://jira.springframework.org/browse/SPR-6780.But I still don't know how to solve my problem.

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

Any ideas?

有任何想法吗?

Thanks

谢谢

回答by axtavt

There are no good ways to do it (without dealing with HttpServletResponse). You can do something like this:

没有好的方法可以做到(不处理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());

    ...
}