Spring @PathVariable之后得到的一切/

时间:2016-05-24 14:12:36

标签: spring-boot path-variables

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

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

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

我知道重定向是可能的,但不是我需要的。 我尝试使用regexp,但似乎无法正常工作

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

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

由于

1 个答案:

答案 0 :(得分:2)

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

  1. @RequestMapping("/something/**")并注入HttpServletRequest: public MyCustomObj get(HttpServletRequest)并使用request.getServletPath()
  2. 手动解析路径
  3. 使用自定义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
        }
    }
    
  4. 然后您可以像这样注入新创建的注释: public MyCustomObj get(@MyPath String path)。记得注册你的论证解析器。