作用
在Spring MVC 中使用 @RequestMapping 来映射请求,也就是通过它来指定控制器可以处理哪些URL请求,即将请求和处理请求的控制器方法关联起来,建立映射关系。
如上图,我创建了一个controller包,并在其内创建了HelloController的Java文件,具体代码为:
package com.example.demo.controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class HelloController {
@RequestMapping("/hello2")
public String hello(){
return "helloworld";
}
}
这边的@RequestMapping使用了最简单的效果,在项目URL后加入/hello2即可出现return的内容,如下:
这说明可以使用@RequestMapping注解来将请求URL,如/hello2等,映射到整个类上或某个特定的处理器方法上。类级别的注解负责将一个特定(或符合某种模式)的请求路径映射到一个控制器上,同时通过方法级别的注解来细化映射,即根据特定的HTTP请求方法(“GET”“POST”方法等)、HTTP请求中是否携带特定参数等条件,将请求映射到匹配的方法上。
一般属性
path|value : 指定访问路径
method : 指定请求方式GET/POST/PUT/DELETE…
params : 指定请求该路径必须携带的参数
@RequestMapping可以选用其中任意部分来完成约束控制,也可以像上面的例子一样只将请求路径映射。
path|value : 指定访问路径
直接使用@RequestMapping(“xxxx”)亦或是@RequestMapping(path=“xxxx”)、@RequestMapping(value=“xxxx”)
效果是一样的。
经测试xxxx中首位的/是否加上对结果没有影响,即@RequestMapping("/hello")与@RequestMapping(“hello”)效果上是一致的。
package com.example.demo.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class HelloController2 {
@RequestMapping("/hello2-2")
public String hello2(){
return "hello2-2";
}
@RequestMapping(path="hello3-2")
public String hello3(){
return "rello3-2";
}
@RequestMapping(value="hello4-2")
public String hello4(){
return "rello4-2";
}
// @RequestMapping()
}
method : 指定请求方式GET/POST/PUT/DELETE…
@GetMapping即@RequestMapping(method = RequestMethod.GET)
@PostMapping即@RequestMapping(method = RequestMethod.POST)
GET、POST是方法的映射。
表示为@RequestMapping(method = RequestMethod.${方法})
如今往往使用@GetMapping、@PostMapping、@PutMapping、@DeleteMapping、@PatchMapping注解来帮助简化常用的HTTP方法的映射。
GET方法可以携带交互需要的所有数据,因此搜索百度或谷歌的时候,点击搜索形成的URL搜索关键字。但是对一些有安全需求的请求,如账号密码等,HTTP设计了POST请求,把请求信息放在HTTP请求里,防止信息泄露等问题。
@GetMapping只能通过url传参数。所对应的接口参数只能是用@RequestParam注解或者不注解
@RequestMapping(value = "/hello-get",method= RequestMethod.GET)
public String hello_get(@RequestParam(value = "name", defaultValue = "World") String name){
return String.format("您好,%s",name);
}
@GetMapping("hello-get2")
public String hello_get2(@RequestParam(value = "name", defaultValue = "World") String name){
return String.format("您好,%s",name);
}
通过测试可以看到两种方法效果一致。
对参数测试可以用?参数名=参数值
,如下:
使用post不能在网页上测试,可以用apipost测试
@PostMapping("hello-post")
public String hello_post( String name){
return String.format("您好,%s",name);
}