SpringBoot Controller接收参数的几种常用注解

2021-12-16  本文已影响0人  wyn_做自己

今日份鸡汤:一岁一礼,一寸欢喜,往后余生,积极向上的生活,热气腾腾的活着。

1、请求路径中带参数 使用 @PathVariable 获取路径参数。即url/{id}这种形式。
demo:

@RestController
public class GetRequestParamDemo {

    @RequestMapping(path = "/pathVariableTest/{userId}")
    public String pathVariableTest(@PathVariable(name = "userId") String userId, String userName) {
        return "hello " + userName + " your id is " + userId;
    }
}

运行结果展示:


image.png

2、@RequestParam 获取查询参数。即url?name=这种形式,用于get/post。springboot默认情况就是它,类似不写注解
demo:

@RestController
public class GetRequestParamDemo {

    @RequestMapping(path = "/requestParamTest")
    public String requestParamTest(@RequestParam(value = "name", required = true) String name, @RequestParam(value = "id", required = true) int id) {
        return "this is " + name + " and his number is " + id;
    }
}

运行结果展示:


image.png

3、@RequestBody获取POST请求参数
demo:

@RestController
public class GetRequestParamDemo {

    @RequestMapping(path = "/postParamTest")
    public Book postParamTest(@RequestBody Book book) {
        return book;
    }

}

运行结果展示:


image.png

4、请求头参数以及Cookie
(1)@RequestHeader
(2)@CookieValue
demo:
方式一:

@RestController
public class GetRequestParamDemo {

    @RequestMapping(path = "/headerAndCookieTest")
    public String headerAndCookieTest(@RequestHeader(name = "myHeader") String myHeader, @CookieValue(name = "myCookie") String myCookie) {
        return "myHeader: " + myHeader + ",and myCookie: " + myCookie;
    }

}

运行结果展示:


image.png

方式二:

@RestController
public class GetRequestParamDemo {

    @RequestMapping(path = "/headerAndCookieTest2")
    public String headerAndCookieTest2(HttpServletRequest request) {
        AtomicReference<String> myCookie = new AtomicReference<>("");
        Arrays.stream(request.getCookies()).filter(c -> Objects.equals("myCookie", c.getName())).forEach(m -> myCookie.set(m.getValue()));
        return "myHeader: " + request.getHeader("myHeader") + ",and myCookie: " + myCookie.get();
    }

}

运行结果展示:


image.png
上一篇下一篇

猜你喜欢

热点阅读