@RequestMapping是最基础的指定分发地址的注解,它既可以标注在XxxController类上,也可以标注在其中的方法上。理论上有三种组合方式:类、方法和类+方法。但是,实际上只有后面两种方式能起作用。
@RestController
public class StudentController {
@RequestMapping("/getStudent")
public Student getStudent() {
// 简单模拟获取student流程
return new Student("Xianhuii", 18);
}
}
此时,@RequestMapping的/getStudent属性值表示相对于服务端套接字的请求地址。
从浏览器发送GET http://localhost:8080/getStudent请求,会得到如下响应,响应体是Student对象的JSON字符串:
HTTP/1.1 200
Content-Type: application/json
Transfer-Encoding: chunked
Date: Sun, 02 May 2021 13:23:02 GMT
Keep-Alive: timeout=60
Connection: keep-alive
{
"name": "Xianhuii",
"age": 18
}
@RequestMapping("/student")
@RestController
public class StudentController {
@RequestMapping("/getStudent")
public Student getStudent() {
// 简单模拟获取student流程
return new Student("Xianhuii", 18);
}
}
此时,标注在类上的@RequestMapping是内部所有方法分发地址的基础。因此,getStudent()方法的完整分发地址应该是/student/getStudent。
从浏览器发送GET http://localhost:8080/student/getStudent请求,会得到如下响应,响应体是Student对象的JSON字符串:
HTTP/1.1 200
Content-Type: application/json
Transfer-Encoding: chunked
Date: Sun, 02 May 2021 13:26:57 GMT
Keep-Alive: timeout=60
Connection: keep-alive
{
"name": "Xianhuii",
"age": 18
}
@RequestMapping("/student")
@RestController
public class StudentController {
public Student getStudent() {
// 简单模拟获取student流程
return new Student("Xianhuii", 18);
}
}
我们仅将@RequestMapping标注在StudentController类上。需要注意的是,这种标注方式是错误的,服务器不能确定具体的分发方法到底是哪个(尽管我们仅定义了一个方法)。
如果从浏览器发送GET http://localhost:8080/student请求,会得到如下404的响应:
HTTP/1.1 404
Vary: Origin
Vary: Access-Control-Request-Method
Vary: Access-Control-Request-Headers
Content-Type: application/json
Transfer-Encoding: chunked
Date: Sun, 02 May 2021 13:36:56 GMT
Keep-Alive: timeout=60
Connection: keep-alive
{
"timestamp": "2021-05-02T13:36:56.056+00:00",
"status": 404,
"error": "Not Found",
"message": "",
"path": "/student"
}
以上介绍了@RequestMapping的标注位置,在此做一个小结:
提枪策马乘胜追击04-21 20:01
代码小兵92504-17 16:07
代码小兵98804-25 13:57
杨晶珍05-11 14:54