signed

QiShunwang

“诚信为本、客户至上”

SpringBoot Controller接收参数的几种常用方式

2021/4/26 15:36:08   来源:

SpringBoot Controller接收参数的几种常用方式

第一类:请求路径参数

  • @PathVariable

    • 获取路径参数。即url/{id}
  • @RequestParam

    • 获取查询参数。即url?name=我是渣渣辉
//GET
http://localhost:8080/linjing/3?name=小布

//____________________________________________________________________
@GetMapping("/linjing/{id}")
public void test(@PathVariable(name = "id") String id, @RequestParam(name = "name") String name) {
    System.out.println("id="+id);
    System.out.println("name="+name);
}
//输出结果 
id=3
name=小布

第二类:Body参数

*‘content-type’ : application/json*

@PostMapping(path = "/linjing")
public void test(@RequestBody Person person) {
    System.out.println(person.toString());
}
@PostMapping(path = "/linjing")
public void test(@RequestBody Map<String, String> person) {
    System.out.println(person.get("name"));
}

*‘content-type’ : form-data*

@PostMapping(path = "/linjing")
public void test(Person person) {
    System.out.println(person.toString());
}

’content-type’ :x-www-form-urlencoded

//multipart/form-data与x-www-form-urlencoded的区别:
//multipart/form-data:可以上传文件或者键值对,最后都会转化为一条消息
//x-www-form-urlencoded:只能上传键值对,而且键值对都是通过&间隔分开的。

第三类:请求头参数以及Cookie

@GetMapping("/linjing")
public void test(@RequestHeader(name = "myHeader") String myHeader,
        @CookieValue(name = "myCookie") String myCookie) {
    System.out.println("myHeader=" + myHeader);
    System.out.println("myCookie=" + myCookie);
}
@GetMapping("/linjing")
public void test(HttpServletRequest request) {
    System.out.println(request.getHeader("myHeader"));
    for (Cookie cookie : request.getCookies()) {
        if ("myCookie".equals(cookie.getName())) {
            System.out.println(cookie.getValue());
        }
    }
}