I have some url of type: "/something/some/random/path"
For all urls that start with "/something/"
I want everything after it to be considered as a path variable
@RequestMapping("/something/{path}")
public MyCustomObj get(@PathVariable("path") String path){
System.out.println(path); // "some/random/path"
}
I know is possible with redirect but is not what I need. I tried with regexp but doesn't seems to work
@RequestMapping("/spring-web/{path:.*}
There is any way to do that, or maybe some work arrounds?
Thanks
I see 2 workarounds here:
@RequestMapping("/something/**")
and inject HttpServletRequest:
public MyCustomObj get(HttpServletRequest)
and manually parse path using request.getServletPath()
Do the same as above using custom HandlerMethodArgumentResolver
. You could create custom annotation for this e.g. @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
}
}
Then you can inject your newly created annotation like this:
public MyCustomObj get(@MyPath String path)
. Remember to register your argument resolver.