Spring MVC RequestMapping Example

When calling a Spring MVC application we generally use a URL which calls the Controller. In the Controller to map a given URL we use RequestMapping annotation – @RequestMapping
RequestMapping can be used in many ways. Lets see some of most widely used Spring MVC RequestMapping Examples

1. RequestMapping in Class Level

@RequestMapping can be added at Controller Level. This way the URI provided will act as base URI for all other methods in the Controller.

Now any requests with /employee as URL will hit this Controller class.

2. RequestMapping in Method level

@RequestMapping can also be added in methods of a controller.

In the code above we have a Class level @RequestMapping /employee and a Method level @RequestMapping /display
So to call the method showEmployeeForm() we will use
/employee/display. We can have multiple methods in a Controller with @RequestMapping.

3. RequestMapping using @Pathvariable

@RequestMapping can be used to construct dynamic URI, to pass in parameters. This can be achieved using @PathVariable

In this case you can pass empID and empName as parameters to the method showEmployeeForm() using

4. RequestMapping using HTTP methods

We have different HTTP methods like POST, GET, DELETE etc. We can call a controller method for each of these methods using @RequestMapping and RequestMethod

We also can have one Controller method to use more than one RequestMethod. In below code if the URL is /display and HTTP method is either POST or GET, the showEmployeeForm() method will be called.

5. RequestMapping using @RequestParam

In some case we need to pass parameters in a URL or a post request. Similar to the Pathvariable we can get parameters to the method using @RequestParam.

here the URL will be /display?empId=12345

It's only fair to share...Share on FacebookShare on Google+Tweet about this on TwitterShare on LinkedIn