2016-05-24 33 views
0

我有型的一些网址:"/something/some/random/path"春@PathVariable得到一切后/

对于与"/something/"开始我想要的一切后,被视为变量路径的所有URL

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

我知道是可能的重定向,但不是我所需要的。 我试着用正则表达式,但似乎并不工作

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

有没有办法做到这一点,或者一些工作arrounds?

感谢

回答

2

我看到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)。请记住注册您的参数解析器。