第一类:请求路径参数
1、@PathVariable
@GetMapping("getcitylist/{id}")
public List<Classify> getCityList(@PathVariable("id") Long id) {
获取路径参数。即url/{id}这种形式。
2、@RequestParam
@GetMapping("ceshi")
public List<Long> getCityList(@RequestParam("name") String name) {
获取查询参数。即url?name=这种形式
第二类:Body参数
3、@RequestBody
传入Json时,请求方式不能用Get请求
@PostMapping("/getCustomerList")
public JsonObject getCustomerList(@RequestBody Customer customer){
Customer为项目中的POJO类,用于接收对象
也可以这样
@PostMapping(path = "/demo1")
public void demo1(@RequestBody Map<String, String> person) {
使用Map接收时不需要POJO类
第三类:请求头参数以及Cookie
1、@RequestHeader
2、@CookieValue
@GetMapping("/demo3")
public void demo3(@RequestHeader(name = "myHeader") String myHeader,
@CookieValue(name = "myCookie") String myCookie) {
System.out.println("myHeader=" + myHeader);
System.out.println("myCookie=" + myCookie);
}
也可以这样
@GetMapping("/demo3")
public void demo3(HttpServletRequest request) {
System.out.println(request.getHeader("myHeader"));
for (Cookie cookie : request.getCookies()) {
if ("myCookie".equals(cookie.getName())) {
System.out.println(cookie.getValue());
}
}
}
本文介绍了SpringBoot在Controller中处理请求参数的多种方式,包括@PathVariable用于获取路径参数,@RequestParam用于获取查询参数,@RequestBody用于接收JSON格式的Body参数,以及如何通过@RequestHeader和@CookieValue获取请求头和Cookie值。
1806

被折叠的 条评论
为什么被折叠?



