Define HTTP request method for Controller in Spring MVC

The @RequestMapping annotation beside allows us to define the request URL, it also allows us to define the HTTP request method for the controller in Spring MVC using its method attribute. In this tutorial, we will learn more about this method property.

In the project that I created in the previous tutorial, the home() method defines an @RequestMapping annotation with the value of the method attribute RequestMethod.GET.

This means that the user accesses this request URL with the GET method.

The org.springframework.web.bind.annotation.RequestMethod is the object that defines the request methods for Spring MVC.

The methods that the @RequestMapping annotation supports are defined in the org.springframework.web.bind.annotation.RequestMethod enum as follows:

  • GET
  • HEAD
  • POST
  • PUT
  • PATCH
  • DELETE
  • OPTIONS
  • TRACE

Let’s take another example.

As you can see, here I have defined a request with the POST method.

By default, when using the @RequestMapping annotation, if you do not define method attribute, the request method will be GET, POST, or HEAD. Outside these request methods, if you request other methods, 405 errors will occur.

For example:

Result:

Define HTTP request method for Controller in Spring MVC

Or

Define HTTP request method for Controller in Spring MVC

From version 4.3 onwards, Spring introduces a number of annotations to make it easier to declare the method call. These are the following annotations:

  • Annotation @GetMapping for the GET method.
  • Annotation @PostMapping for the POST method.
  • Annotation @PutMapping for the PUT method.
  • Annotation @DeleteMapping for the DELETE method.
  • Annotation @PatchMapping for the PATCH method.

Now we do not need to declare:

just declare:

If you look at the @GetMapping annotation code then you’ll understand why we just use the @GetMapping annotation without using the @RequestMapping annotation anymore.

 

Add Comment