Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to inject the full request path in Spring @RestController?

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
    }
}
like image 543
membersound Avatar asked Oct 19 '25 05:10

membersound


1 Answers

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

like image 190
Rambler Avatar answered Oct 21 '25 20:10

Rambler