javaspringrestrequest-mapping

RequestMapping: How to access the "method" value used for a rest endpoint


I have a Spring Boot REST controller endpoint that accepts both GET and POST requests:

@RequestMapping(
        value="/users",
        method= {RequestMethod.GET, RequestMethod.POST},
        headers= {"content-type=application/json"}
        )
public ResponseEntity<List<User>> getUsers() {
    if(/*Method is GET*/) {
        System.out.println("This is a GET request response.");
    } else if( /*Method is POST*/) {
        System.out.println("This is a POST request response.");
    }
}

If this endpoint is hit with a GET request, I'd like for the controller to execute something in the appropriate if statement. whereas, if the endpoint is hit with a POST request, I'd like for the controller to take another course of action.

How does one extract this information from a rest controller? I'd rather not have to split this shared endpoint into two different methods. It's seems simple enough, I just can't find any docs on it.


Solution

  • The correct approach would be to rather map two separate GET and POST methods, but if you're set on doing this approach you can get the HTTP verb of the request by accessing the HttpServletRequest as follows:

    @RequestMapping(
        value="/users",
        method= {RequestMethod.GET, RequestMethod.POST},
        headers= {"content-type=application/json"}
        )
    public ResponseEntity<List<User>> getUsers(final HttpServletRequest request) {
        if(request.getMethod().equals("GET")) {
            System.out.println("This is a GET request response.");
        } else if(request.getMethod().equals("POST")) {
            System.out.println("This is a POST request response.");
        }
    }
    

    You won't need to change your calling code, as the HttpServletRequest is automatically passed through