Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PUT request in Spring MVC

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

@RequestMapping(value = "/users/{id}", method = RequestMethod.PUT) 
public @ResponseBody User updateUser(@PathVariable("id") long id, 
                                     String name, 
                                     String email) {
        User user = repository.findOne(id);
        user.setName(name);
        user.setEmail(email);
        System.out.println(user.toString());
        repository.save(user);
        return user; 
} 

Which is obviously wrong, because it returns the following:

User{id=1, name='null', email='null'}

I also tried with @RequestBody annotation, but that also did not help. Any ideas what I'm doing wrong here would be greatly appreciated.

like image 346
Maciej Szlosarczyk Avatar asked Mar 08 '16 21:03

Maciej Szlosarczyk


Video Answer


2 Answers

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: enter image description here

like image 172
inafalcao Avatar answered Oct 21 '22 15:10

inafalcao


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 protected], you will get this response:

User{id=1, name='Josh', email='[email protected]'}

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

like image 45
Ali Dehghani Avatar answered Oct 21 '22 15:10

Ali Dehghani