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:

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.

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.

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.


Add Comment