I'm using wildcard mapping on controller action, and want to get string matched by wildcard. How can I do it the correct way? Without using substring etc.
@Controller
@RequestMapping(value = "/properties")
public class PropertiesController {
@RequestMapping(value = "/**", method=RequestMethod.GET)
public void getFoo() {
String key = (String) request. getAttribute(HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE);
// returns "/properties/foo/bar" ...
// I want only "foo/bar" part
// ...
}
}|
It seems that the question have already been addressed here : Spring 3 RequestMapping: Get path value although the accepted answer does not answer the question. One suggested solution, this one, seems to work since I just tried it :
@Controller
@RequestMapping(value = "/properties")
public class PropertiesController {
@RequestMapping(value = "/**", method=RequestMethod.GET)
public void getFoo(final HttpServletRequest request) {
String path = (String) request.getAttribute(
HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE);
String bestMatchPattern = (String ) request.getAttribute(HandlerMapping.BEST_MATCHING_PATTERN_ATTRIBUTE);
AntPathMatcher apm = new AntPathMatcher();
String finalPath = apm.extractPathWithinPattern(bestMatchPattern, path);
// on "/properties/foo/bar", finalPath contains "foo/bar"
}
}
I would advise upvoting the non-accepted answer even if there is a long way to go before it reaches the score of the accepted answer. I wouldn't be surprised to learn that the specs have changed between the time the answer was accepted on this other thread and now (since there is no way a wrong answer could have reached such a high score).
Use the @PathVariable annotation like this
@RequestMapping(value = "/{key}")
public void getFoo(@PathVariable("key") int key) {
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With