Search code examples
javaspringrestput

need explanation about rest PUT method


here is some controller:

@RequestMapping(value="/rest/put/{login}", method = RequestMethod.PUT)
    public @ResponseBody User putUser(@RequestBody User user, @PathVariable String login){
        return user;
    }

when i send this request

{"login":"ale"}

to this URL

http://localhost:8080/Application/rest/put/termination

i receive normal response like this:

{"login":"ale","password":"password","email":"email"}

My question: why in controller must be @PathVariable login(at least it is in all tutorials) instead just static URL, and what the reason be here it?


Solution

  • Firstly, your question is not quite accurate. It is not a must to include @PathVariable inside the controller method. You can use static URL whenever you like.

    Secondly, it is not a must to put @PathVariable for REST, but a standard. The standard is trying to map common CRUD operations with common HTTP verbs (POST, GET, PUT, DELETE), and the URL would typically include the resource name and resource ID. Usually, @PathVariable represents resource ID in REST-standard URL.

    An example of such URL would be /user/{user_id}, where user is the resource name and user_id would be the resource id.

    So, lastly, by looking at the code you posted. That @PathVariable String login does not really align with the REST standard. As in your example URL,

    http://localhost:8080/Application/rest/put/termination
    

    That means login = termination, which is obviously nothing related to REST.