CookieValue

CookieValue注解是帮助开发者方便获取客户端提交的Cookie值的。

示例

在不使用CookieValue注解的情况下,我们是这样获取Cookie值的:

@RestController
class UserController {

    @GetMapping(path = "/get")
    String info(HttpRequest request) {
        Cookie cookie = request.getCookie("account");
        String cookieValue = cookie == null ? null : cookie.getValue();
        ...
    }
}

在使用了CookieValue注解时:

@RestController
class UserController {

    @GetMapping(path = "/get")
    String info(@CookieValue("account") String cookie) {
        ...
    }
}

CookieValue注解的参数默认是必须的,如果此参数为空,则会抛出CookieMissingException异常,异常处理请参考ExceptionResolver

如果开发者想让CookieValue注解的参数为非必填参数:

@RestController
class UserController {

    @GetMapping(path = "/get")
    String info(@CookieValue(name = "account", required = false) String cookie) {
        ...
    }
}

results matching ""

    No results matching ""