八、RestFul风格路径
8.1、REST
Rest( Representational State Transfer 即表述性状态传递) 一种网络资源的访问风格,定义了网络资源的访问方式;
-
传统风格访问路径 ①http://localhost/user/getUser?id=1 ②http://localhost/deleteUser?id=1
-
Rest风格访问路径 ① http://localhost/user/1 请求方式:get
② http://localhost/user/1 请求方式:delete
-
Restful是按照Rest风格访问网络资源
-
优点 ①隐藏资源的访问行为,通过地址无法得知做的是何种操作② 书写简化
8.2、Rest行为约定方式
- GET(查询) http://localhost/user/1 GET
- POST(保存) http://localhost/user POST
- PUT(更新) http://localhost/user PUT
- DELETE(删除) http://localhost/user DELETE
注意:
1.上述行为是约定方式,约定不是规范,可以打破,所以称Rest风格,而不是Rest规范 ;
2.RESTFul就是路径编写的另一种格式,这种格式面向的是资源(核心思想:资源即路径),而非具体的功能.;
3.在springmvc中使用@PathVariable注解就可以从Rest风格的URL中获取参数的值;
8.3、测例
//@Controller
//@ResponseBody
@RestController//等价于@Controller+@ResponseBody
public class RestfulController {
/**
* 请求路径中 {占位符} 接收请求路径中当前位置的值
* @PathVariable: 解析请求路径中的值,并将值赋给形参变量
*/
@GetMapping("user/{uaername}/{age}")
// @ResponseBody
public UserVo t1(
@PathVariable String uaername,
@PathVariable Integer age) {
UserVo userVo = new UserVo(uaername + "get", age);
return userVo;
}
@PostMapping("user/{uaername}/{age}")
// @ResponseBody
public UserVo t2(
@PathVariable String uaername,
@PathVariable Integer age) {
UserVo userVo = new UserVo(uaername + "post", age);
return userVo;
}
@DeleteMapping("user/{uaername}/{age}")
// @ResponseBody
public UserVo t3(
@PathVariable String uaername,
@PathVariable Integer age) {
UserVo userVo = new UserVo(uaername + "delete", age);
return userVo;
}
@PutMapping("user/{uaername}/{age}")
// @ResponseBody
public UserVo t4(
@PathVariable String uaername,
@PathVariable Integer age) {
UserVo userVo = new UserVo(uaername + "put", age);
return userVo;
}
}