【问题标题】:How to match a Spring @RequestMapping having a @pathVariable containing "/"?如何匹配具有包含“/”的@pathVariable 的Spring @RequestMapping?
【发布时间】:2011-01-21 01:03:42
【问题描述】:

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

/search/hello%2Fthere/

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

在服务器上,我尝试使用以下请求映射匹配此 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。但我仍然不知道如何解决我的问题。

有什么想法吗?

谢谢

【问题讨论】:

    标签: java spring spring-mvc


    【解决方案1】:
        @Configuration
        public class AdditionalWebConfig extends WebMvcConfigurationSupport {
         .......
         ...........
         ...........
        @Override
        public void configureContentNegotiation(ContentNegotiationConfigurer 
        configurer) {
           configurer.favorPathExtension(false);
        }
        .......
        .......
      }
    

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

    【讨论】:

      【解决方案2】:

      没有很好的方法来做到这一点(不处理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());
      
          ...
      }
      

      【讨论】:

      • 对我来说,而不是 request.getServletPath() 工作 request.getPathInfo()
      • AntPathMatcher 是线程安全的。共享一个实例完全没问题。
      猜你喜欢
      • 2018-07-11
      • 2015-05-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-02-21
      • 2019-08-21
      • 1970-01-01
      相关资源
      最近更新 更多