How can I inject the complete subpath in a Spring @RestController
?
In my example, I want subpaths=/test/sub/path
being injected
@RestController
public class MyController {
@GetMapping(value = "/v1/{subpaths}", produces = MediaType.APPLICATION_JSON)
public Object handle(@PathVariable String subpaths) {
//this is not called for /v1/test/sub/path
}
}
Effectively if the idea is to have a single entry point , we can just capture everything and later just extract subpath. The following illustrates the same :
@RestController
public class MyController {
@GetMapping(value = "/v1/parentPath/**", produces = MediaType.APPLICATION_JSON)
public Object handle(@RequestParam(name = "myParam") String myParam,HttpServletRequest request) {
//Get the complete url
String url=request.getRequestURL();
String[] paths=url.split("parentPath/");
//paths[1] is the desired subPath
//Provides URI
// example : /context-path/v1/parentPath/subPath
String uri=request.getRequestURI();
//Returns query string, ex: test=abc&page=1
String queryString=request.getQueryString();
//Returns query parameters as map,Includes both query and ported form data
Map<String, String[]> parameterMap=request.getParameterMap();
}
}
HttpServletRequest : is injected automatically by Spring.(Will try to find some documentation and add it here)
Just to be safe added parentPath to ensure that we do not capture ALL of the requests under v1
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