@RequestMapping, @GetMapping and @PostMapping in Spring

@RequestMapping

Originally, Spring had only @RequestMapping annotation for mapping all the incoming HTTP request URLs to the corresponding controller methods.

@RequestMapping(value = "/users", method = RequestMethod.GET)
public Users getUsers() {
}

@RequestMapping(value = "/users", method = RequestMethod.POST)
public User createUser(User user) {
}

@RequestMapping(value = "/users/{id}", method = RequestMethod.GET)
public User getUser(@PathVariable("id") String id) {
}

Spring 4.3 introduced five new and more specific annotations for each HTTP request type.

@GetMapping
@PostMapping
@PutMapping
@DeleteMapping
@PatchMapping

Using these new annotations, we can rewrite the @RequestMapping example as given below. If you see carefully, we do not have the method attribute anymore in the new annotations.

@GetMapping(value = "/users")
public Users getUsers() {
}

@PostMapping(value = "/users")
public User createUser(User user) {
}

@GetMapping(value = "/users/{id}")
public User getUser(@PathVariable("id") String id) {
}

@GetMapping

  • The @GetMapping annotation is a specialized version of @RequestMapping annotation that acts as a shortcut for @RequestMapping(method = RequestMethod.GET).
  • The @GetMapping annotated methods in the @Controller annotated classes handle the HTTP GET requests matched with given URI expression.
@RestController
public class UserController {

    @Autowired
    UserService userService;

    @GetMapping("users")
    public ResponseEntity<List<User>> getAll() {
        return new ResponseEntity<>(userService.getAll(), HttpStatus.OK);
    }

    @GetMapping("users/{id}")
    public ResponseEntity<User> getById(@PathVariable long id) {
        Optional<User> user = userService.getById(id);
        if (user.isPresent()) {
            return new ResponseEntity<>(user.get(), HttpStatus.OK);
        } else {
            throw new RecordNotFoundException();
        }
    }
}

@PostMapping

  • The @PostMapping is specialized version of @RequestMapping annotation that acts as a shortcut for @RequestMapping(method = RequestMethod.POST).
  • The @PostMapping annotated methods in the @Controller annotated classes handle the HTTP POST requests matched with given URI expression.
    @PostMapping(path = "users", 
        consumes = MediaType.APPLICATION_JSON_VALUE, 
        produces = MediaType.APPLICATION_JSON_VALUE)
    public ResponseEntity<User> create(@RequestBody User newUser) {
    User user = userService.save(newUser);
    if (user == null) {
        throw new ServerException();
    } else {
        return new ResponseEntity<>(user, HttpStatus.CREATED);
    }
    }