@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是使用最广泛的Spring MVC注释之一。 org.springframework.web.bind.annotation.RequestMapping注释用于将Web请求映射到特定的处理程序类和/或处理程序方法。

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

@RequestMapping可以应用于控制器类以及方法。 今天,我们将通过示例以及其他注释@PathVariable@RequestParam研究此注释的各种用法。

Spring@RequestMapping (Spring @RequestMapping)

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

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

    @RequestMapping with Class :我们可以将其与类定义一起使用以创建基本URI。 例如:

    现在,/ home是此控制器将使用的URI。 这个概念与Web应用程序的servlet上下文非常相似。

  2. @RequestMapping with Method: We can use it with method to provide the URI pattern for which handler method will be used. For example:
    @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.

    @RequestMapping with Method :我们可以将它与method一起使用,以提供将使用处理程序方法的URI模式。 例如:

    上面的注释也可以写为@RequestMapping("/method0") 。 附带说明一下,我正在使用@ResponseBody发送此Web请求的String响应,这样做是为了保持示例简单。 像往常一样,我将在Spring MVC应用程序中使用这些方法,并通过简单的程序或脚本对其进行测试。

  3. @RequestMapping with Multiple URI: We can use a single method for handling multiple URIs, for example:
    @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.

    具有多个URI的@RequestMapping :我们可以使用一种方法来处理多个URI,例如:

    如果您查看RequestMapping批注的源代码,您将看到它的所有变量都是数组。 我们可以为处理程序方法的URI映射创建String数组。

  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)
    @ResponseBody
    public String method2(){return "method2";
    }@RequestMapping(value="/method3", method={RequestMethod.POST,RequestMethod.GET})
    @ResponseBody
    public String method3(){return "method3";
    }

    使用HTTP方法的@RequestMapping :有时,即使请求URI保持不变,我们仍希望基于所使用的HTTP方法执行不同的操作。 我们可以使用@RequestMapping方法变量来缩小将为其调用该方法的HTTP方法。 例如:

  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")
    @ResponseBody
    public String method4(){return "method4";
    }@RequestMapping(value="/method5", headers={"name=pankaj", "id=1"})
    @ResponseBody
    public String method5(){return "method5";
    }

    带有标头的@RequestMapping :我们可以指定调用处理程序方法时应显示的标头。 例如:

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

    带有Produces和Consumes的@RequestMapping :我们可以使用标头Content-TypeAccept来查找请求内容以及它想要作为响应的mime消息。 为了清楚起见,@RequestMapping提供生产消费的变量,我们可以指定请求内容类型方法将被调用针对和响应的内容类型。 例如:

    上面的方法只能使用Content-Type作为text / html的消息,并且能够产生application / jsonapplication / xml类型的消息。

  7. 春天@PathVariable (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:
    @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;
    }

    @RequestMapping和@PathVariable :RequestMapping批注可用于处理动态URI,其中一个或多个URI值用作参数。 我们甚至可以为URI动态参数指定正则表达式 ,以仅接受特定类型的输入。 它与@PathVariable批注一起使用,通过它我们可以将URI变量映射到方法参数之一。 例如:

  9. Spring@RequestParam (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:
    @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.

    URL参数的@RequestMapping和@RequestParam :有时我们在请求URL中获取参数,主要是在GET请求中。 我们可以将@RequestMapping与@RequestParam批注一起使用,以检索URL参数并将其映射到方法参数。 例如:

    为了使该方法起作用,参数名称应为“ id”,并且其类型应为int。

  11. @RequestMapping default method: If value is empty for a method, it works as default method for the controller class. For example:
    @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.

    @RequestMapping默认方法 :如果某个方法的值为空,则它将用作控制器类的默认方法。 例如:

    如上所示,我们已经将/home映射到HomeController ,该方法将用于默认的URI请求。

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

    @RequestMapping fallback方法 :即使没有匹配的处理程序方法,我们也可以为控制器类创建一个fallback方法,以确保我们正在捕获所有客户端请求。 如果没有用于请求的处理程序方法,则在向用户发送自定义404响应页面时很有用。

Spring RestMapping测试程序 (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.

我们可以使用Spring RestTemplate来测试上述不同的方法,但是今天我将使用cURL命令来测试这些方法,因为它们很简单并且周围没有太多数据。

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

我创建了一个简单的shell脚本springTest.sh来调用上述所有方法并输出其输出。 如下图所示。

#!/bin/bashecho "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.

请注意,我已经在Tomcat-7上部署了Web应用程序,并且该Web应用程序在端口9090上运行。SpringRequestMappingExample是应用程序的Servlet上下文。 现在,当我通过命令行执行此脚本时,将得到以下输出。

pankaj:~ pankaj$ ./springTest.sh
curl https://localhost:9090/SpringRequestMappingExample/home/method0
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
method1*****curl https://localhost:9090/SpringRequestMappingExample/home/method1/second
method1*****curl -X POST https://localhost:9090/SpringRequestMappingExample/home/method2
method2*****curl -X POST https://localhost:9090/SpringRequestMappingExample/home/method3
method3*****curl -X GET https://localhost:9090/SpringRequestMappingExample/home/method3
method3*****curl -H name:pankaj https://localhost:9090/SpringRequestMappingExample/home/method4
method4*****curl -H name:pankaj -H id:1 https://localhost:9090/SpringRequestMappingExample/home/method5
method5*****curl -H Content-Type:text/html https://localhost:9090/SpringRequestMappingExample/home/method6
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 GMTmethod6*****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 GMTmethod6*****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*****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 RequestMapping Example的全部内容,希望它能帮助您理解此注释及其各种功能。 您应该从下面的链接下载示例项目,然后尝试不同的情况进行进一步的研究。

Download Spring MVC RequestMapping Project下载Spring MVC RequestMapping项目

翻译自: https://www.journaldev.com/3358/spring-requestmapping-requestparam-pathvariable-example

带有控制器,方法,标题,参数,@ RequestParam,@ PathVariable的Spring MVC @RequestMapping注释示例相关推荐

  1. SpringMVC控制器方法获取参数时@RequestParam注解加与不加的区别

    问题 在使用SpringMVC时获取参数时,加与不加@RequestParam都会自动传入参数值,那加与不加的区别是什么? 测试 @GetMapping("test1")publi ...

  2. SpringBoot 控制器方法自定义参数注入

    1.需求场景 在实际开发中,经常会遇到一下场景: controller 方法中拿到header中的userId,然后需要根据用户id去取到User的完整信息.在多个controller就会存在同样的重 ...

  3. java 中showinfo方法,jmockito模拟方法中参数如何指定

    在做单元测试的时候,经常会遇到mock类的方法的情景.在写单测过程中,遇到一些问题,比较困惑,便做了一些测试,并得出一个结论: 在mock类的方法时,当符合 (mock参数).equals(实际调用过 ...

  4. SpringMVC 中控制器方法的可用参数类型和返回类型

    SpringMVC 中控制器方法的参数列表可接受以下类型的参数, 并当该方法被调用时, SpringMVC 框架可使得方法能够获得正确的参数: javax.servlet.ServletRequest ...

  5. java mvc 绑定_关于Java:Spring MVC:将请求属性绑定到控制器方法参数

    在Spring MVC中,很容易将请求参数绑定到处理请求的方法参数. 我只是使用@RequestParameter("name"). 但是我可以对request属性做同样的事情吗? ...

  6. Spring MVC中@RequestParam和@PathVariable批注之间的区别?

    Spring MVC框架是在Java世界中开发Web应用程序最流行的框架之一,它还提供了一些有用的注释,可以从传入的请求中提取数据并将请求映射到控制器,例如@ RequestMapping,@ Req ...

  7. Java框架-SpringMVC的应用(json数据交互、控制器方法返回值、文件上传)

    1. 搭建SpringMVC开发环境 1.1 创建项目,添加依赖 <?xml version="1.0" encoding="UTF-8"?> &l ...

  8. Spring MVC 接收请求参数所有方式总结!

    来源:简书,作者:zhrowable 链接:https://www.jianshu.com/p/5f6abd08ee08 SpringMVC请求参数接收 其实一般的表单或者JSON数据的请求都是相对简 ...

  9. 6、Spring MVC 之 定义@RequestMapping处理方法

    @RequestMapping处理器方法可以非常灵活的签名.支持的方法参数和返回值在以下部分中描述.大多数参数可用于任意顺序除了BindingResult这个唯一的参数例外.下一节中将会描述. not ...

最新文章

  1. java-vector hashtable过时?
  2. python传参怎么校验数字_python 多个参数不为空校验方法
  3. 【Linux部署】Spring Boot 项目部署在Linux环境下的Docker容器内举例【任务调度系统 xxl-job 任务调度中心】(手动版)
  4. 实验分享:用Python生成个性化二维码
  5. linux下的各种shell介绍(bash和dash转换)
  6. 公开说说别人看不到_当听到别人在说自己坏话时,心里是什么感受?
  7. python查看数据类型type_python——获取数据类型:type()、isinstance()的使用方法:...
  8. 26_多线程_第26天(Thread、线程创建、线程池)
  9. python常用模块用法_python笔记之常用模块用法分析
  10. ARM架构、指令集、内核版本、CISC与RISC、ARM产品线
  11. RxJava 的基本使用
  12. (转)是时候说说Pivotal这个富二代了!
  13. Android信息处理机制
  14. vue图片连拼实现gif图效果
  15. Oracle 中的 unique index 和 non unique index的区别
  16. 屌丝网,上线了 哈哈,
  17. 10.Quartz 常用配置
  18. 区块链的共识机制是什么?
  19. 解决谷歌浏览器你的时钟快了和证书问题
  20. win10 设置为静态ip地址

热门文章

  1. [转载] java 捕获异常还是抛出异常
  2. [转载] python2.7中模块学习- textwrap 文本包装和填充
  3. 聊一聊FPGA的片内资源相关知识
  4. ffmpeg下载rtmp flv
  5. 1.PHP与Web页面的交互
  6. 20155226 实验三 敏捷开发与XP实践 实验报告
  7. SSH如何通过公钥连接云服务器
  8. 如何让你的JavaScript代码更加语义化
  9. 苹果被拒的血泪史。。。(update 2015.11)
  10. Ubuntu学习日记--Lesson9:显卡工作状态查看命令