Spring MVC – @RequestMapping with Methods, Headers, Params, @PathVariable and @RequestParam

Creating RESTful web services is more comfortable and simpler when using Spring MVC Annotation.
The tutorial shows you how to use @RequestMapping with Methods, Headers, Params, @PathVariable and @RequestParam.
We will have an example which almost covers all @RequestMapping cases.

I. Ways to use @RequestMapping
1. Class or Method

2. Path/multi-Path

To test, we can access these addresses:

If we have applied @RequestMapping for the wrapping class before:

The addresses to be tested will be:

3. With HTTP Request Method/multi-Method

If we don’t add HTTP Request Method to @RequestMapping, by default, it will map to all types of HTTP Request.
When specifying the RequestMethod, for example, GET or POST, it will filter to map the right ones:

4. With Header/multi-Header

5. With Consumes and Produces/multi-Produces

B using produces and consumes, we can specify Content-Type of request for the method we want to invoke and Content-Type of the response.

6. @PathVariable

For dynamic URI (path value with input parameters), Spring has @PathVariable annotation with:
– automatic type conversion
– auto-detected (same text)
– regular expression

7. @RequestParam/multi-@RequestParam

If we want to get parameters in the request URL, we use @RequestParam annotation map with method argument.

The address to be tested will be:

8. default Mapping

If we want a method for controller class URI (/customers in this case), @RequestMapping without parameter is helpful. The method will be invoked when we run:

9. all cases Mapping

To have a simple fallback for all requests:

It will handle the case that no matching handler method is detected for the request.

II. Practice
1. Technology

– Java 1.8
– Maven 3.3.9
– Spring Tool Suite – Version 3.8.1.RELEASE
– Spring Boot: 1.4.0.RELEASE

2. Step by Step

2.1 Create Spring Boot project
Open Spring Tool Suite, on Menu, choose File -> New -> Spring Starter Project, then fill each field:

Click Next, in Web: choose Web:

Click Finish. Spring Boot project will be created successfully.
2.2 Create Controllers
Under package controller, create WebController.java.

2.3 Run Spring Boot Application & Enjoy Result
– Config maven build:
clean install
– Run project with mode Spring Boot App
– Check results using Cygwin.
This is list of commands we use:

And here is the results:

III. Source Code


Related Posts

Got Something To Say:

Your email address will not be published. Required fields are marked *