Difference between Requestmapping and Postmapping

Asked

Viewed 3,450 times

0

I was taking a look at the requisitions from Spring Boot and I saw that you can make a requisition POST, in two ways:

//primeira forma
@RequestMapping(value = "/dev", method = RequestMethod.POST)
    public ResponseEntity<String> dev(@RequestParam("nome") String nome) {
    return new ResponseEntity<String>(nome, HttpStatus.OK);
}

//segunda forma
@PostMapping("/dev")
    public ResponseEntity<String> nome(@RequestParam("nome") String nome) {
    return new ResponseEntity<String>(nome, HttpStatus.OK);
}

I tested with the Postman and both return the same result.

  • What’s the difference in these two ways?

  • Is there any limitation in either?

  • What is the most appropriate, when will send data from a form, by example?

2 answers

1


@RequestMapping is the annotation traditionally used to implement Handler URL, it supports Post, Get, Put, Delete and Pacth methods.

@PostMapping is a simpler way to implement Handler annotation URL @RequestMapping with the Post method. In the implementation of @PostMapping it is noted with @RequestMapping specifying the Post method, can be seen on link:

@Target(value=METHOD)
 @Retention(value=RUNTIME)
 @Documented
 @RequestMapping(method=POST)
public @interface PostMapping

Other types of requests also have simpler forms: @GetMapping, @PutMapping, @DeleteMapping and @PatchMapping, all use the annotation internally @RequestMapping, specifying the type of request.

There is no limitation of one form or another, only in the second form you do not need to specify the type of request, because the annotation itself specifies, thus having a simpler syntax.

0

Both do the same job. The difference is that @PostMapping is part of a predefined group of compound annotations that internally use @RequestMapping. These annotations serve as shortcuts to simplify the mapping of HTTP methods and to express more concisely the manipulation methods. The advantage of compound annotations is the semantic aspect, because with them the code is cleaner and easier to read.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.