by BehindJava
How to handle HTTP PUT request to update user details in Spring Boot
In this tutorial we are going to learn about updating the user details stored into a Map using POST request.
Firstly, we will send a POST request to save user details as shown in the previous tutorial. Now in the controller class we will specify @PutMapping i.e. same as the @PostMapping as shown in the below code snippet.
Sample Code Snippet:
import java.util.HashMap;
import java.util.Map;
import javax.validation.Valid;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.behindjava.tutorial.model.UserModel;
@RestController
@RequestMapping("/users")
public class UserController {
HashMap<String, UserModel> user;
@PostMapping(produces = { MediaType.APPLICATION_JSON_VALUE, MediaType.APPLICATION_XML_VALUE }, consumes = {
MediaType.APPLICATION_JSON_VALUE, MediaType.APPLICATION_XML_VALUE })
public ResponseEntity<UserModel> createUser(@Valid @RequestBody UserModel us) {
UserModel um = new UserModel();
um.setEmail(us.getEmail());
um.setFirstname(us.getFirstname());
um.setLastname(us.getLastname());
um.setUserId(us.getUserId());
if (user == null)
user = new HashMap<>();
user.put(us.getUserId(), um);
return new ResponseEntity<UserModel>(um, HttpStatus.CREATED);
}
@GetMapping(path = "/{userId}", produces = { MediaType.APPLICATION_XML_VALUE, MediaType.APPLICATION_JSON_VALUE })
public ResponseEntity<UserModel> getUser(@PathVariable String userId) {
if (user.containsKey(userId)) {
return new ResponseEntity<UserModel>(user.get(userId), HttpStatus.CREATED);
} else {
return new ResponseEntity<UserModel>(HttpStatus.NO_CONTENT);
}
}
@PutMapping(path = "/{userId}", produces = { MediaType.APPLICATION_JSON_VALUE,
MediaType.APPLICATION_XML_VALUE }, consumes = { MediaType.APPLICATION_JSON_VALUE,
MediaType.APPLICATION_XML_VALUE })
public UserModel updateUser(@Valid @PathVariable String userId, @RequestBody UserModel us) {
UserModel usr = user.get(userId);
usr.setFirstname(us.getFirstname());
usr.setLastname(us.getLastname());
usr.setEmail(us.getEmail());
user.put(userId, usr);
return usr;
}
}
Using postman firstly send a HTTP POST request as shown in the below image.
After sending the post request user details are stored in the Map. Now using put method we will update the user details as shown in the below image.
You can check whether user details are updated or not by send a get request to the controller.