Spring MVC @RequestMapping Annotation Example with Controller, Methods, Headers, Params, @RequestParam, @PathVariable

Filed Under: Spring

@RequestMapping is one of the most widely used Spring MVC annotation. org.springframework.web.bind.annotation.RequestMapping annotation is used to map web requests onto specific handler classes and/or handler methods.

Spring @RequestMapping @RequestParam and @PathVariable example

@RequestMapping can be applied to the controller class as well as methods. Today we will look into various usage of this annotation with example and other annotations @PathVariable and @RequestParam.

Spring @RequestMapping

  1. @RequestMapping with Class: We can use it with class definition to create the base URI. For example:
    public class HomeController {

    Now /home is the URI for which this controller will be used. This concept is very similar to servlet context of a web application.

  2. @RequestMapping with Method: We can use it with method to provide the URI pattern for which handler method will be used. For example:
    public String method0(){
    	return "method0";

    Above annotation can also be written as @RequestMapping("/method0"). On a side note, I am using @ResponseBody to send the String response for this web request, this is done to keep the example simple. Like I always do, I will use these methods in Spring MVC application and test them with a simple program or script.

  3. @RequestMapping with Multiple URI: We can use a single method for handling multiple URIs, for example:
    public String method1(){
    	return "method1";

    If you will look at the source code of RequestMapping annotation, you will see that all of it’s variables are arrays. We can create String array for the URI mappings for the handler method.

  4. @RequestMapping with HTTP Method: Sometimes we want to perform different operations based on the HTTP method used, even though request URI remains same. We can use @RequestMapping method variable to narrow down the HTTP methods for which this method will be invoked. For example:
    @RequestMapping(value="/method2", method=RequestMethod.POST)
    public String method2(){
    	return "method2";
    @RequestMapping(value="/method3", method={RequestMethod.POST,RequestMethod.GET})
    public String method3(){
    	return "method3";
  5. @RequestMapping with Headers: We can specify the headers that should be present to invoke the handler method. For example:
    @RequestMapping(value="/method4", headers="name=pankaj")
    public String method4(){
    	return "method4";
    @RequestMapping(value="/method5", headers={"name=pankaj", "id=1"})
    public String method5(){
    	return "method5";
  6. @RequestMapping with Produces and Consumes: We can use header Content-Type and Accept to find out request contents and what is the mime message it wants in response. For clarity, @RequestMapping provides produces and consumes variables where we can specify the request content-type for which method will be invoked and the response content type. For example:
    @RequestMapping(value="/method6", produces={"application/json","application/xml"}, consumes="text/html")
    public String method6(){
    	return "method6";

    Above method can consume message only with Content-Type as text/html and is able to produce messages of type application/json and application/xml.

  7. Spring @PathVariable

  8. @RequestMapping with @PathVariable: RequestMapping annotation can be used to handle dynamic URIs where one or more of the URI value works as a parameter. We can even specify Regular Expression for URI dynamic parameter to accept only specific type of input. It works with @PathVariable annotation through which we can map the URI variable to one of the method arguments. For example:
    public String method7(@PathVariable("id") int id){
    	return "method7 with id="+id;
    public String method8(@PathVariable("id") long id, @PathVariable("name") String name){
    	return "method8 with id= "+id+" and name="+name;
  9. Spring @RequestParam

  10. @RequestMapping with @RequestParam for URL parameters: Sometimes we get parameters in the request URL, mostly in GET requests. We can use @RequestMapping with @RequestParam annotation to retrieve the URL parameter and map it to the method argument. For example:
    public String method9(@RequestParam("id") int id){
    	return "method9 with id= "+id;

    For this method to work, the parameter name should be “id” and it should be of type int.

  11. @RequestMapping default method: If value is empty for a method, it works as default method for the controller class. For example:
    public String defaultMethod(){
    	return "default method";

    As you have seen above that we have mapped /home to HomeController, this method will be used for the default URI requests.

  12. @RequestMapping fallback method: We can create a fallback method for the controller class to make sure we are catching all the client requests even though there are no matching handler methods. It is useful in sending custom 404 response pages to users when there are no handler methods for the request.
    public String fallbackMethod(){
    	return "fallback method";

Spring RestMapping Test Program

We can use Spring RestTemplate to test the different methods above, but today I will use cURL commands to test these methods because these are simple and there are not much data flowing around.

I have created a simple shell script springTest.sh to invoke all the above methods and print their output. It looks like below.


echo "curl https://localhost:9090/SpringRequestMappingExample/home/method0";
curl https://localhost:9090/SpringRequestMappingExample/home/method0;
printf "\n\n*****\n\n";

echo "curl https://localhost:9090/SpringRequestMappingExample/home";
curl https://localhost:9090/SpringRequestMappingExample/home;
printf "\n\n*****\n\n";

echo "curl https://localhost:9090/SpringRequestMappingExample/home/xyz";
curl https://localhost:9090/SpringRequestMappingExample/home/xyz;
printf "\n\n*****\n\n";

echo "curl https://localhost:9090/SpringRequestMappingExample/home/method1";
curl https://localhost:9090/SpringRequestMappingExample/home/method1;
printf "\n\n*****\n\n";

echo "curl https://localhost:9090/SpringRequestMappingExample/home/method1/second";
curl https://localhost:9090/SpringRequestMappingExample/home/method1/second;
printf "\n\n*****\n\n";

echo "curl -X POST https://localhost:9090/SpringRequestMappingExample/home/method2";
curl -X POST https://localhost:9090/SpringRequestMappingExample/home/method2;
printf "\n\n*****\n\n";

echo "curl -X POST https://localhost:9090/SpringRequestMappingExample/home/method3";
curl -X POST https://localhost:9090/SpringRequestMappingExample/home/method3;
printf "\n\n*****\n\n";

echo "curl -X GET https://localhost:9090/SpringRequestMappingExample/home/method3";
curl -X GET https://localhost:9090/SpringRequestMappingExample/home/method3;
printf "\n\n*****\n\n";

echo "curl -H "name:pankaj" https://localhost:9090/SpringRequestMappingExample/home/method4";
curl -H "name:pankaj" https://localhost:9090/SpringRequestMappingExample/home/method4;
printf "\n\n*****\n\n";

echo "curl -H "name:pankaj" -H "id:1" https://localhost:9090/SpringRequestMappingExample/home/method5";
curl -H "name:pankaj" -H "id:1" https://localhost:9090/SpringRequestMappingExample/home/method5;
printf "\n\n*****\n\n";

echo "curl -H "Content-Type:text/html" https://localhost:9090/SpringRequestMappingExample/home/method6";
curl -H "Content-Type:text/html" https://localhost:9090/SpringRequestMappingExample/home/method6;
printf "\n\n*****\n\n";

echo "curl https://localhost:9090/SpringRequestMappingExample/home/method6";
curl https://localhost:9090/SpringRequestMappingExample/home/method6;
printf "\n\n*****\n\n";

echo "curl -H "Content-Type:text/html" -H "Accept:application/json" -i https://localhost:9090/SpringRequestMappingExample/home/method6";
curl -H "Content-Type:text/html" -H "Accept:application/json" -i https://localhost:9090/SpringRequestMappingExample/home/method6;
printf "\n\n*****\n\n";

echo "curl -H "Content-Type:text/html" -H "Accept:application/xml" -i https://localhost:9090/SpringRequestMappingExample/home/method6";
curl -H "Content-Type:text/html" -H "Accept:application/xml" -i https://localhost:9090/SpringRequestMappingExample/home/method6;
printf "\n\n*****\n\n";

echo "curl https://localhost:9090/SpringRequestMappingExample/home/method7/1";
curl https://localhost:9090/SpringRequestMappingExample/home/method7/1;
printf "\n\n*****\n\n";

echo "curl https://localhost:9090/SpringRequestMappingExample/home/method8/10/Lisa";
curl https://localhost:9090/SpringRequestMappingExample/home/method8/10/Lisa;
printf "\n\n*****\n\n";

echo "curl https://localhost:9090/SpringRequestMappingExample/home/method9?id=20";
curl https://localhost:9090/SpringRequestMappingExample/home/method9?id=20;
printf "\n\n*****DONE*****\n\n";

Note that I have deployed my web application on Tomcat-7 and it’s running on port 9090. SpringRequestMappingExample is the servlet context of the application. Now when I execute this script through command line, I get following output.

pankaj:~ pankaj$ ./springTest.sh 
curl https://localhost:9090/SpringRequestMappingExample/home/method0


curl https://localhost:9090/SpringRequestMappingExample/home
default method


curl https://localhost:9090/SpringRequestMappingExample/home/xyz
fallback method


curl https://localhost:9090/SpringRequestMappingExample/home/method1


curl https://localhost:9090/SpringRequestMappingExample/home/method1/second


curl -X POST https://localhost:9090/SpringRequestMappingExample/home/method2


curl -X POST https://localhost:9090/SpringRequestMappingExample/home/method3


curl -X GET https://localhost:9090/SpringRequestMappingExample/home/method3


curl -H name:pankaj https://localhost:9090/SpringRequestMappingExample/home/method4


curl -H name:pankaj -H id:1 https://localhost:9090/SpringRequestMappingExample/home/method5


curl -H Content-Type:text/html https://localhost:9090/SpringRequestMappingExample/home/method6


curl https://localhost:9090/SpringRequestMappingExample/home/method6
fallback method


curl -H Content-Type:text/html -H Accept:application/json -i https://localhost:9090/SpringRequestMappingExample/home/method6
HTTP/1.1 200 OK
Server: Apache-Coyote/1.1
Content-Type: application/json
Content-Length: 7
Date: Thu, 03 Jul 2014 18:14:10 GMT



curl -H Content-Type:text/html -H Accept:application/xml -i https://localhost:9090/SpringRequestMappingExample/home/method6
HTTP/1.1 200 OK
Server: Apache-Coyote/1.1
Content-Type: application/xml
Content-Length: 7
Date: Thu, 03 Jul 2014 18:14:10 GMT



curl https://localhost:9090/SpringRequestMappingExample/home/method7/1
method7 with id=1


curl https://localhost:9090/SpringRequestMappingExample/home/method8/10/Lisa
method8 with id= 10 and name=Lisa


curl https://localhost:9090/SpringRequestMappingExample/home/method9?id=20
method9 with id= 20


pankaj:~ pankaj$ 

Most of these are self understood, although you might want to check default and fallback methods. That’s all for Spring RequestMapping Example, I hope it will help you in understanding this annotation and it’s various features. You should download the sample project from below link and try different scenarios to explore it further.


  1. RAMAM says:

    Hi Pankaj,

    if we have placed multiple request mapping in our class with a fallback then request will be handled by which of the request mapping/method handler, fallback or matching handler.
    Given below 2 sequences –

    public String fallbackMethod(){}

    public String home(){}

    public String home(){}

    public String fallbackMethod(){}

    Please let me know in both cases which method will run for “/home” and why?


  2. Thiyagarajan says:

    Hi Pankaj,
    Its Really helpful in understanding basics

  3. Rohit says:

    Hi Pankaj,
    Thanks for explaining it from basic and providing enough explanatory examples.

  4. Arif Heer says:

    Well Explained, Thanks.!

  5. Hari says:

    Hi, I have request URL as https://localhost:8080/api?arg=10

    when I am trying to get arg using @RequestParam I am getting a null value.

    How to get XML contention as String?

  6. arun singh says:

    can some please help me answering
    how is a url template with integer value generated: “https://localhost:8080/springmvc/hello/101”

    It is about @PathVariable.
    How to pass integer value along with url in the above form? How does this happen dynamically?


    1. banan314 says:

      @RequestMapping(value = “springmvc/hello/{number:\\d+}”)
      public void hello(@PathVariable(value = “number”) int n) {
      System.out.println(n); // 101
      This happens dynamically because servlet recognizes the same identifier (`number`) in the request mapping and `PathVariable` annotations, processes URL and passes the found number into the function parameter (`n`).

  7. Sheela says:

    How to make the requestParam key as case insensitive?
    For Example : public String welcome(@RequestParam(“orgID”) String orgID, ModelMap model)

    The request parameter “orgID” should be case insensitive. How to do this ?.

    I should be able to give the query-string as “orgid” or “orgId”. The parameter should be completely case-insensitive.

  8. arun singh says:


  9. Prakash says:

    Thanking you

  10. NAVEENSNH says:

    Thank you sir very nice explanation on each annotations

  11. Luiz Couto says:

    Very simple and well explained, thanks !

  12. Rohit Singh says:

    Good post Pankaj. This was very crisp and clear 馃檪

  13. Fin says:

    I got an problem to get url param like this:

    I want to sort param by :
    customer_name = field param will be sorting
    asc = ascending sorting

    @RequestMapping(value=”/listsort”,method = RequestMethod.GET)
    public String listAll(@RequestParam(value=”sort[customer_name]”, required=false) String sort){
    return “Test with sort field = “+sort;

  14. Rasu says:

    This is my fallback method,

    public String fallBackMethod()
    return “Error404”;

    here, Error404 is my JSP page. if i gave any wrong URI it displays Error404 msg only, but it did’t display my Error404 JSP page,

    Now i want to display my Error404 JSP page if i gave any wrong URI

    1. Pankaj says:

      Here in this case you have to define model if you want to send this msg to pass to Jsp page and use any of resource view handler for ex . InternalResourceViewResolver


  15. vasanth says:

    Hello Pankaj… Good snippet to understand the concepts. Thanks.

  16. Shiva kumar says:

    in method level request mapping that method return some string like method1, method2, where we need to configure relevant jsp to forward? In my case I want to redirect to customers list and my method is like

    @RequestMapping(value = “customers”, method = RequestMethod.GET)
    public String getCustomers(Model model, HttpServletRequest request) {
    return “customers”

    is it enough to have customers.jsp or need to configure this “/customers” to customers.jsp

  17. Rahul says:

    Thank you so much, it helped clearing my doubts.

  18. madhusmita says:

    very nice.thank u.

  19. Vijay G says:

    I have to use dynamic URI but it fails for me. Assume the method value in controller is given below,


    public String method7(@PathVariable(“id”) int id){
    return “method7 with id=”+id;


    when i click the above link, it binds the dynamic id with the url and throws 404 as below,

    The requested resource (/updateSpecifiCertificate/CERT22) is not available.

    How to call my controller in this case, Please help me i have tried so many ways…..

    Thank You So Much…


    1. Mak says:

      You declare id parameter as int.

  20. madhu says:


    How to handle the multiple actions in single jsp using springMVC like





    Madhu R.

  21. Rajesh says:

    while passing json code through restfull service by using soap ui tool.getting 415 error
    “AuthToken” : “token”,
    “empName”: “Name”,
    “empNo”: 111,
    “locName”: “kolkata”,
    “locNumber”: 713156

    2)bean class:

    private String AuthToken ;
    private String empName;
    private String name;
    private String empNo;
    private String locName ;
    private String locNumber;
    public void setAuthToken(String AuthToken) {
    this.AuthToken = AuthToken;

    public String getAuthToken() {
    return AuthToken;

    public void setEmpName(String empName) {
    this.empName = empName;

    public String getEmpName() {
    return empName;

    public void setName(String name) {
    this.name = name;
    public String getName() {
    return name;

    public void setEmpNo(String empNo) {
    this.empNo = empNo;
    public String getEmpNo() {
    return empNo;

    public void setLocName(String locName) {
    this.locName = locName;
    public String getLocName() {
    return locName;

    public void setLocNumber(String locNumber) {
    this.locNumber = locNumber;
    public String getLocNumber() {
    return locNumber;


    @RequestMapping(value=”/upload”, method={RequestMethod.POST},consumes={“application/json” },produces={“application/xml” })
    public NurseInfo uploadNote(@Validated @RequestBody NurseInfo nurseInfo) throws Exception {
    // TODO Auto-generated method stub


    String json=””+nurseInfo.getEmpName()+””;
    return nurseInfo;


    Apache Tomcat/7.0.16 – Error report
    <!–H1 {font-family:Tahoma,Arial,sans-serif;color:white;background-color:#525D76;font-size:22px;} H2 {font-family:Tahoma,Arial,sans-serif;color:white;background-color:#525D76;font-size:16px;} H3 {font-family:Tahoma,Arial,sans-serif;color:white;background-color:#525D76;font-size:14px;} BODY {font-family:Tahoma,Arial,sans-serif;color:black;background-color:white;} B {font-family:Tahoma,Arial,sans-serif;color:white;background-color:#525D76;} P {font-family:Tahoma,Arial,sans-serif;background:white;color:black;font-size:12px;}A {color : black;}A.name {color : black;}HR {color : #525D76;}–>

    HTTP Status 415 –

    Status report


    The server refused this request because the request entity is in a format not supported by the requested resource for the requested method ().

    Apache Tomcat/7.0.16

    Thanks in advancs

  22. divyesh shani says:

    It works fine but what if multiple json array is there (array inside array and again inside array)??

    how can i create this type of web services with Spring RestTemplate??

  23. Ram says:

    Nice one..

Comments are closed.

Generic selectors
Exact matches only
Search in title
Search in content