1 简单的参数传递
url地址: http://localhost:8090/getUserById?id=100
编辑后台Controller代码:
2 对象的方式传递
URL: http://localhost:8090/getUser?id=100&name=“tomcat”&age=18
后台代码说明:
3 RestFul风格
特点:
1. 参数需要使用/ 进行分割
2. 参数的位置是固定的.
3. restFul请求方法路径不能出现动词
作用:
用户可以通过一个URL请求的地址,可以实现不同的业务操作
知识回顾:
查询: http://localhost:8090/getUserById?id=100 类型:get
新增: http://localhost:8090/insertUser 类型:post
更新: http://localhost:8090/updateUser 类型:post
删除: http://localhost:8090/deleteUserById?id=200 类型:get
意图明显: 常规的请求的方式其中包含了动词,导致操作的意图非常明显.
RestFul风格实现CURD操作:
1.查询: http://localhost:8090/user/100 type:GET
2.新增: http://localhost:8090/user/tomcat/18/男 type:POST
3.删除: http://localhost:8090/user/100 type:DELETE
4.更新: http://localhost:8090/user/mysql/100 type:PUT
3.1 RestFul风格-简单参数接收
/**
* 1.restFul实现用户查询
* URL: http://localhost:8090/user/100
* type: GET
* RequestMapping 默认的可以接收所有的请求类型
* RestFul语法:
* 1.参数的位置固定.
* 2.参数必须使用{}包裹
* 3.必须使用@PathVariable 动态的接收参数
* 注意事项: {参数名称}必须与方法中的名称一致.
*/
//@RequestMapping(value = "/user", method = RequestMethod.GET)
@GetMapping("user/{id}")
public String restFulGet(@PathVariable Integer id){
return "restFul动态的获取参数:"+id;
}
3.2 RestFul风格-对象参数接收
/**
* 需求: 查询name=tomcat age=18 sex=女的用户
* 要求使用:restFul
* URL: http://localhost:8090/user/tomcat/18/女
* restFul的优化:
* 如果{参数名称}与对象中的属性名称一致,
* 则SpringMVC动态的为对象赋值,
* @PathVariable 可以省略
* 注意事项:
* 前后端的参数的传递必须保持一致!!!!
*/
@GetMapping("user/{id}/{name}/{age}/{sex}")
public User restFulGet2(User user){
//执行后续的业务操作 userService
return user;
}