原文地址:

@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.

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

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

    1
    2
    3
    4
    5
    @Controller
    @RequestMapping("/home")
    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:
    1
    2
    3
    4
    5
    @RequestMapping(value="/method0")
    @ResponseBody
    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:
    1
    2
    3
    4
    5
    @RequestMapping(value={"/method1","/method1/second"})
    @ResponseBody
    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:
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    @RequestMapping(value="/method2", method=RequestMethod.POST)
    @ResponseBody
    public String method2(){
        return "method2";
    }
     
    @RequestMapping(value="/method3", method={RequestMethod.POST,RequestMethod.GET})
    @ResponseBody
    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:
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    @RequestMapping(value="/method4", headers="name=pankaj")
    @ResponseBody
    public String method4(){
        return "method4";
    }
     
    @RequestMapping(value="/method5", headers={"name=pankaj", "id=1"})
    @ResponseBody
    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:
    1
    2
    3
    4
    5
    @RequestMapping(value="/method6", produces={"application/json","application/xml"}, consumes="text/html")
    @ResponseBody
    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. @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:
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    @RequestMapping(value="/method7/{id}")
    @ResponseBody
    public String method7(@PathVariable("id") int id){
        return "method7 with id="+id;
    }
     
    @RequestMapping(value="/method8/{id:[\\d]+}/{name}")
    @ResponseBody
    public String method8(@PathVariable("id") long id, @PathVariable("name") String name){
        return "method8 with id= "+id+" and name="+name;
    }
  8. @RequestMapping with @RequestParam for URL parameters: Sometimes we get parameters in the request URL, mostly in GET requests. We can use @RequestMapping with @RequestParam annotationto retrieve the URL parameter and map it to the method argument. For example:
    1
    2
    3
    4
    5
    @RequestMapping(value="/method9")
    @ResponseBody
    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.

  9. @RequestMapping default method: If value is empty for a method, it works as default method for the controller class. For example:
    1
    2
    3
    4
    5
    @RequestMapping()
    @ResponseBody
    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.

  10. @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.
    1
    2
    3
    4
    5
    @RequestMapping("*")
    @ResponseBody
    public String fallbackMethod(){
        return "fallback method";
    }

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 to invoke all the above methods and print their output. It looks like below.

springTest.sh
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
#!/bin/bash
 
echo "curl http://localhost:9090/SpringRequestMappingExample/home/method0";
curl http://localhost:9090/SpringRequestMappingExample/home/method0;
printf "\n\n*****\n\n";
 
echo "curl http://localhost:9090/SpringRequestMappingExample/home";
curl http://localhost:9090/SpringRequestMappingExample/home;
printf "\n\n*****\n\n";
 
echo "curl http://localhost:9090/SpringRequestMappingExample/home/xyz";
curl http://localhost:9090/SpringRequestMappingExample/home/xyz;
printf "\n\n*****\n\n";
 
echo "curl http://localhost:9090/SpringRequestMappingExample/home/method1";
curl http://localhost:9090/SpringRequestMappingExample/home/method1;
printf "\n\n*****\n\n";
 
echo "curl http://localhost:9090/SpringRequestMappingExample/home/method1/second";
curl http://localhost:9090/SpringRequestMappingExample/home/method1/second;
printf "\n\n*****\n\n";
 
echo "curl -X POST http://localhost:9090/SpringRequestMappingExample/home/method2";
curl -X POST http://localhost:9090/SpringRequestMappingExample/home/method2;
printf "\n\n*****\n\n";
 
echo "curl -X POST http://localhost:9090/SpringRequestMappingExample/home/method3";
curl -X POST http://localhost:9090/SpringRequestMappingExample/home/method3;
printf "\n\n*****\n\n";
 
echo "curl -X GET http://localhost:9090/SpringRequestMappingExample/home/method3";
curl -X GET http://localhost:9090/SpringRequestMappingExample/home/method3;
printf "\n\n*****\n\n";
 
echo "curl -H "name:pankaj" http://localhost:9090/SpringRequestMappingExample/home/method4";
curl -H "name:pankaj" http://localhost:9090/SpringRequestMappingExample/home/method4;
printf "\n\n*****\n\n";
 
echo "curl -H "name:pankaj" -H "id:1" http://localhost:9090/SpringRequestMappingExample/home/method5";
curl -H "name:pankaj" -H "id:1" http://localhost:9090/SpringRequestMappingExample/home/method5;
printf "\n\n*****\n\n";
 
echo "curl -H "Content-Type:text/html" http://localhost:9090/SpringRequestMappingExample/home/method6";
curl -H "Content-Type:text/html" http://localhost:9090/SpringRequestMappingExample/home/method6;
printf "\n\n*****\n\n";
 
echo "curl http://localhost:9090/SpringRequestMappingExample/home/method6";
curl http://localhost:9090/SpringRequestMappingExample/home/method6;
printf "\n\n*****\n\n";
 
echo "curl -H "Content-Type:text/html" -H "Accept:application/json" -i http://localhost:9090/SpringRequestMappingExample/home/method6";
curl -H "Content-Type:text/html" -H "Accept:application/json" -i http://localhost:9090/SpringRequestMappingExample/home/method6;
printf "\n\n*****\n\n";
 
echo "curl -H "Content-Type:text/html" -H "Accept:application/xml" -i http://localhost:9090/SpringRequestMappingExample/home/method6";
curl -H "Content-Type:text/html" -H "Accept:application/xml" -i http://localhost:9090/SpringRequestMappingExample/home/method6;
printf "\n\n*****\n\n";
 
echo "curl http://localhost:9090/SpringRequestMappingExample/home/method7/1";
curl http://localhost:9090/SpringRequestMappingExample/home/method7/1;
printf "\n\n*****\n\n";
 
echo "curl http://localhost:9090/SpringRequestMappingExample/home/method8/10/Lisa";
curl http://localhost:9090/SpringRequestMappingExample/home/method8/10/Lisa;
printf "\n\n*****\n\n";
 
echo "curl http://localhost:9090/SpringRequestMappingExample/home/method9?id=20";
curl http://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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
pankaj:~ pankaj$ ./springTest.sh
curl http://localhost:9090/SpringRequestMappingExample/home/method0
method0
 
*****
 
curl http://localhost:9090/SpringRequestMappingExample/home
default method
 
*****
 
curl http://localhost:9090/SpringRequestMappingExample/home/xyz
fallback method
 
*****
 
curl http://localhost:9090/SpringRequestMappingExample/home/method1
method1
 
*****
 
curl http://localhost:9090/SpringRequestMappingExample/home/method1/second
method1
 
*****
 
curl -X POST http://localhost:9090/SpringRequestMappingExample/home/method2
method2
 
*****
 
curl -X POST http://localhost:9090/SpringRequestMappingExample/home/method3
method3
 
*****
 
curl -X GET http://localhost:9090/SpringRequestMappingExample/home/method3
method3
 
*****
 
curl -H name:pankaj http://localhost:9090/SpringRequestMappingExample/home/method4
method4
 
*****
 
curl -H name:pankaj -H id:1 http://localhost:9090/SpringRequestMappingExample/home/method5
method5
 
*****
 
curl -H Content-Type:text/html http://localhost:9090/SpringRequestMappingExample/home/method6
method6
 
*****
 
curl http://localhost:9090/SpringRequestMappingExample/home/method6
fallback method
 
*****
 
curl -H Content-Type:text/html -H Accept:application/json -i http://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
 
method6
 
*****
 
curl -H Content-Type:text/html -H Accept:application/xml -i http://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
 
method6
 
*****
 
curl http://localhost:9090/SpringRequestMappingExample/home/method7/1
method7 with id=1
 
*****
 
curl http://localhost:9090/SpringRequestMappingExample/home/method8/10/Lisa
method8 with id= 10 and name=Lisa
 
*****
 
curl http://localhost:9090/SpringRequestMappingExample/home/method9?id=20
method9 with id= 20
 
*****DONE*****
 
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.

Spring MVC @RequestMapping Annotation Example with Controller, Methods, Headers, Params, @RequestParam, @PathVariable--转载的更多相关文章

  1. spring mvc: 多动作控制器(Controller下面实现多个访问的方法)MultiActionController / BeanNameUrlHandlerMapping

    spring mvc: 多动作控制器(Controller下面实现多个访问的方法) 比如我的控制器是UserController.java,下面有home, add, remove等多个方法 访问地址 ...

  2. Spring MVC — @RequestMapping原理讲解-1

    转载地址 :http://blog.csdn.net/j080624/article/details/56278461 为了降低文章篇幅,使得文章更目标化,简洁化,我们就不例举各种@RequestMa ...

  3. Spring MVC中基于注解的 Controller

         终于来到了基于注解的 Spring MVC 了.之前我们所讲到的 handler,需要根据 url 并通过 HandlerMapping 来映射出相应的 handler 并调用相应的方法以响 ...

  4. Spring MVC @RequestMapping注解详解

    @RequestMapping 参数说明 value:定义处理方法的请求的 URL 地址.(重点) method:定义处理方法的 http method 类型,如 GET.POST 等.(重点) pa ...

  5. [Spring MVC]学习笔记--@Controller

    在讲解@Controller之前,先说明一下Spring MVC的官方文档在哪. 可能会有人和我一样,在刚接触Spring MVC时,发现在Spring的网站上找不到Spring MVC这个项目. 这 ...

  6. Spring MVC @RequestMapping注解详解(2)

    @RequestMapping 参数说明 value:定义处理方法的请求的 URL 地址.(重点) method:定义处理方法的 http method 类型,如 GET.POST 等.(重点) pa ...

  7. spring mvc中的service和controller中读取不到properties值

    根据web.xml读取配置文件中的顺序来看 controller层和service层来自于spring mvc.xml中读取,所以必须要在spring mvc.xml中配置读取资源文件夹方式

  8. spring mvc requestmapping 配置多个

    参考 import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation. ...

  9. Spring MVC @RequestMapping浅析

    简介:@RequestMappingRequestMapping是一个用来处理请求地址映射的注解,可用于类或方法上.用于类上,表示类中的所有响应请求的方法都是以该地址作为父路径.RequestMapp ...

随机推荐

  1. Mapreduce执行过程分析(基于Hadoop2.4)——(三)

    4.4 Reduce类 4.4.1 Reduce介绍 整完了Map,接下来就是Reduce了.YarnChild.main()—>ReduceTask.run().ReduceTask.run方 ...

  2. 非对称认证方式 可以用在 asp.net webapi 的安全机制里面

    //Client端调用 static void Main(string[] args) { string publicKey = "DpLMCOihcYI2i6DaMbso9Dzo1miy7 ...

  3. css3 钟表

    <!doctype html> <html> <head> <meta charset="utf-8"> <title> ...

  4. linux中ctrl+z和ctrl+c的区别

    ctrl+c和ctrl+z都是中断命令,但是他们的作用却不一样.ctrl+c是强制中断程序的执行,而ctrl+z的是将任务中断,但是此任务并没有结束,他仍然在进程中他只是维持挂起的状态,用户可以使用f ...

  5. jquery获取显示器,屏幕的宽度,和高度

    Javascript: 网页可见区域宽: document.body.clientWidth网页可见区域高: document.body.clientHeight网页可见区域宽: document.b ...

  6. [翻译]Behavior-Driven Development (BDD)行为驱动开发(一)

    简单而言,BDD是一系列基于TDD的工具和方法集发展而来的开发模式,一般不认为是一种新的开发模式,而是作为TDD的补充.因此,首先对TDD的概念进行进行. 测试驱动开发(TDD) TDD模式采取的是迭 ...

  7. C#操作Access的一些小结

    C#操作Access的一些小结 好久没有写blog,感觉今年一年都没怎么真正开心过,整天有一些事围绕在身边,使心情难以平静下来,真正写点有意义的东西.博客园是天天看的,看得多,写的少,偶尔也是Copy ...

  8. CSU1612Destroy Tunnels(强连通)

    Destroy Tunnels 原来早忘记了离散里含有这么一个叫传递闭包的东西 矩阵A的闭包B = A U A^2 U A^3 U ... 所以这里直接如果A[i][j]!= 0,建边i->j跑 ...

  9. Odoo的Domain (一)

    Odoo 的Domain:多个条件的列表. 条件:(字段名,操作符,值)三元式(列表或者元组) 字段名:当前模型的字段或者是通过点操作符访问的Many2one/Many2Many对象,当是Many2M ...

  10. 免费的天气Web Service接口

    免费的天气Web Service接口 在android应用当中很多时候需要获取天气的信息,这里提供怎么获取天气信息: 1. http://www.ayandy.com/Service.asmx?wsd ...