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

@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/bash

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.

请注意,我已经在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 GMT

method6

*****

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

method6

*****

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的全部内容,希望它能帮助您理解此注释及其各种功能。 您应该从下面的链接下载示例项目,然后尝试不同的情况进行进一步的研究。

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值