Spring MVC @RequestMapping annotation example

We have already seen Spring MVC hello world example. @RequestMapping is one of important annotation which you use in Spring MVC.

Spring MVC tutorial:

@RequestMapping is used to define mapping of web request to handler method or class. @RequestMapping can be used at method level or class level. We will see example of it later.
If you use @RequestMapping annotation at class level, it will be used for relative path for method level path.
Lets understand with the help of example:

@RestController
@RequestMapping(value = "/countryController")
public class CountryController {

 @RequestMapping(value = "/countries", method = RequestMethod.GET, headers = "Accept=application/json")
 public List getCountries() {

  List listOfCountries = countryService.getAllCountries();
  return listOfCountries;
 }

so web request with URL http://localhost:8080/ProjectName/countryController/countries will execute getCountries() method. Below image will make it clear:

Spring MVC RequestMapping example

Method level RequestMapping example :

When you provide @RequestMapping annotation at method level, you may call it method level request mapping.
@RestController
public class CountryController {

 @RequestMapping(value = "/countries", method = RequestMethod.GET, headers = "Accept=application/json")
 public List getCountries() {

  List listOfCountries = countryService.getAllCountries();
  return listOfCountries;
 }

so web request with URL http://localhost:8080/ProjectName/countries will execute getCountries() method.

Class level RequestMapping example :

When you provide @RequestMapping annotation at class level, you may call it class level request mapping.
@RestController
@RequestMapping(value = "/countries")
public class CountryController {
@RequestMapping(method = RequestMethod.POST, headers = "Accept=application/json")
 public Country addCountry(@RequestBody Country country) {
  return countryService.addCountry(country);
 }

 @RequestMapping(method = RequestMethod.PUT, headers = "Accept=application/json")
 public Country updateCountry(@RequestBody Country country) {
  return countryService.updateCountry(country);

 }
}

If you notice, we did not define method level request mapping here, so it will automatically call corresponding PUT or POST method when you hit :
http://localhost:8080/ProjectName/countries If you want to practice more examples for @RequestMapping annotation, you can go through Spring Rest CRUD example. It will definitely help you to understand @RequestMapping annotation better.

[social_share share_on="facebook,twitter,linkedin,whatsapp"][post_navigator in_same_term="true"]

Leave a Reply

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

Subscribe to our newletter

Get quality tutorials to your inbox. Subscribe now.