Sobes.tech
Junior — Middle

What is the difference between @RequestMapping and @PutMapping annotations in Spring MVC?

sobes.tech AI

Answer from AI

In Spring MVC, the @RequestMapping annotation is used to handle HTTP requests and can be applied at both the class and method levels. It allows specifying the path, HTTP methods (GET, POST, PUT, etc.), parameters, and other conditions for request handling.

The @PutMapping annotation is a specialized version of @RequestMapping that, by default, handles only the HTTP PUT method. It simplifies the code when you need to handle specifically PUT requests.

Example:

@RestController
@RequestMapping("/users")
public class UserController {

    @RequestMapping(value = "/{id}", method = RequestMethod.PUT)
    public ResponseEntity<?> updateUserOld(@PathVariable Long id, @RequestBody User user) {
        // handle PUT request
    }

    @PutMapping("/{id}")
    public ResponseEntity<?> updateUser(@PathVariable Long id, @RequestBody User user) {
        // same as above, but using @PutMapping
    }
}

Thus, @PutMapping is a more concise and specialized way to specify handling of PUT requests, whereas @RequestMapping is more versatile.

What is the difference between @RequestMapping and… - sobes.tech