PUT request in Spring MVC

前端 未结 2 983
离开以前
离开以前 2021-01-06 03:52

I\'m trying to write a simple PUT request method in Spring MVC. I got the following:

@RequestMapping(value = \"/users/{id}\", method = RequestMe         


        
相关标签:
2条回答
  • 2021-01-06 04:09

    You did not tell spring how to bind the name and email parameters from the request. For example, by adding a @RequestParam:

    public @ResponseBody User updateUser(@PathVariable("id") long id, 
                                         @RequestParam String name, 
                                         @RequestParam String email) { ... }
    

    name and email parameters will be populated from the query strings in the request. For instance, if you fire a request to /users/1?name=Josh&email=jb@ex.com, you will get this response:

    User{id=1, name='Josh', email='jb@ex.com'}
    

    In order to gain more insight about defining handler methods, check out the spring documentation.

    0 讨论(0)
  • 2021-01-06 04:10

    You can receive name and email whith the @RequestBody annotation:

    @RequestMapping(value = "/users/{id}", method = RequestMethod.PUT) 
    public @ResponseBody User updateUser(@PathVariable("id") long id, 
                                         @RequestBody User user) {}
    

    This is a better practice when it comes to REST applications, as your URL becomes more clean and rest-style. You can even put a @Valid annotation on the User and validate its properties.

    On your postman client, you send the User as a JSON, on the body of your request, not on the URL. Don't forget that your User class should have the same fields of your sent JSON object.

    See here:

    0 讨论(0)
提交回复
热议问题