【问题标题】:Spring @PathVariable get everything after /Spring @PathVariable 在 / 之后获取所有内容
【发布时间】:2016-05-24 14:12:35
【问题描述】:

我有一些类型的网址:"/something/some/random/path"

对于所有以"/something/" 开头的网址,我希望它之后的所有内容都被视为路径变量

@RequestMapping("/something/{path}")
public MyCustomObj get(@PathVariable("path") String path){
    System.out.println(path); // "some/random/path"
}

我知道重定向是可能的,但不是我需要的。 我尝试了正则表达式,但似乎不起作用

@RequestMapping("/spring-web/{path:.*}

有什么办法可以做到这一点,或者可能有一些工作方法?

谢谢

【问题讨论】:

    标签: spring-boot path-variables


    【解决方案1】:

    我在这里看到了 2 个解决方法:

    1. @RequestMapping("/something/**") 并注入 HttpServletRequest: public MyCustomObj get(HttpServletRequest) 并使用 request.getServletPath() 手动解析路径
    2. 使用自定义HandlerMethodArgumentResolver 执行与上述相同的操作。您可以为此创建自定义注释,例如@MyPath

      public class MyPathResolver implements HandlerMethodArgumentResolver {
      
          @Override
          public boolean supportsParameter(MethodParameter parameter) {
              return parameter.hasParameterAnnotation(MyPath.class);
          }
      
          @Override
          public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer,
          NativeWebRequest webRequest, WebDataBinderFactory binderFactory) throws Exception {
              return ((ServletWebRequest) webRequest).getRequest().getServletPath().split("/")[2]; 
             //you can do whatever you want here, you can even get a value from your RequestMapping annotation 
               and customize @MyPath value as you want
          }
      }
      

    然后你可以像这样注入你新创建的注解: public MyCustomObj get(@MyPath String path)。记得注册你的参数解析器。

    【讨论】:

      猜你喜欢
      • 2020-01-25
      • 1970-01-01
      • 2022-12-04
      • 1970-01-01
      • 2020-10-06
      • 1970-01-01
      • 1970-01-01
      • 2012-03-14
      • 2011-11-07
      相关资源
      最近更新 更多