欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

SpringBoot中Controller接收参数的几种方式

程序员文章站 2022-07-12 20:31:32
...

第一类:请求路径参数

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
SpringBoot中Controller接收参数的几种方式 传入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());
        }
    }
}
相关标签: java