赞
踩
建议使用rest Client测试接口
参数以key-value形式传递,参数和值会直接拼接到请求url后边显示存在(POST http://localhost:8080/users/insert?id=5&userName=刘明);
适用于所有请求方式;
后台接收参数时使用注解@RequestParam
提交资源时一般post请求方式,当然所有的增删改也可已使用post请求
使用@RequestParam(value = “key”) 绑定请求参数到方法入参时,参数名可以不与前台key一致
@RestController
@RequestMapping("/users")
public class UsersController {
@PostMapping("/insert")
public RestResult insertUserInfo(@RequestParam("userId") int id, String userName, String passWord, int age,String sex, String phone) {...}
}
请求参数可以这样显示接收,也可以从 request 中获取
insertUserInfo(HttpServletRequest request) {
String userId = request.getParameter("userId");
String phone = request.getParameter("phone");
...
}
如果请求参数为定义的对象属性时,可以直接使用对象接收参数
public class User {
private int id;
private String userName;
private String passWord;
private int age;
private String sex;
private String phone;
}
@PostMapping("/insert")
public RestResult insertUserInfo(User user) {...}
删除资源
使用@PathVariable 获取url路径中的参数
@DeleteMapping("/delete/{id}")
public RestResult deleteUser(@PathVariable("id") int userId) {...}
更新资源
@PutMapping("/update/{id}")
public RestResult updateUser(@PathVariable int id, String phone) {...}
获取资源
@GetMapping("/query/{id}")
public RestResult queryUser(@PathVariable int id) {...}
因为GET请求头中无content-type字段,所以此种方式只适用于POST/DELETE/PUT请求,用来处理:applicatin/json格式的参数
参数以json形式传递,后台获取参数时使用注解@RequestBody
@PostMapping("/insert")
public RestResult insertUserInfo(@RequestBody User user) {...}
我们也可以使用@JsonProperty 注解来绑定Json中的key和Bean实体的属性
这时候,前台在传递参数时,可以使用与属性名一致,也可以与注解中的value一致
但是这里得注意:这里返回给前台的json对象中的key将会是直接中的值
public class User {
private Integer id;
@JsonProperty("name")
private String userName;
@JsonProperty("pass")
private String passWord;
private Integer age;
private String sex;
private String phone;
}
很明显,方式一在传递参数时,如果传入的参数太长时,或许会超过某些浏览器与服务器对URL的长度限制,会导致请求失败,因此在实际应用中,对于GET请求我们一般使用form表单形式传递参数,POST/DELETE/PUT请求我们考虑使用方式二;
对于请求参数过多的,我们可以使用Java Bean来接收参数
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。