@CookieValue是Spring MVC中用于自动绑定HTTP请求中指定名称Cookie值的注解,支持value、required、defaultValue等属性,可简化参数获取并处理缺失场景。

在 Spring MVC 中,@CookieValue 是专门用于从 HTTP 请求的 Cookie 中提取指定名称值的注解,用法简洁直接,无需手动解析 HttpServletRequest.getCookies()。
基本用法:绑定单个 Cookie 值
只需在控制器方法参数上添加 @CookieValue("cookieName"),Spring 会自动查找同名 Cookie 并注入其 value:
@GetMapping("/user")
public String showUser(@CookieValue("JSESSIONID") String sessionId) {
// sessionId 就是浏览器发送的 JSESSIONID Cookie 的值
return "user";
}
注意:如果该 Cookie 不存在,默认会抛出 IllegalArgumentException(因为参数不可为空)。
设置默认值与可选性
通过 defaultValue 和 required 属性控制容错行为:
-
required = false表示该 Cookie 可缺失,此时必须设defaultValue或允许参数为String、Optional<String>等可空类型 -
defaultValue = "unknown"在 Cookie 不存在时提供兜底值
示例:
@GetMapping("/theme")
public String getTheme(
@CookieValue(value = "theme", required = false, defaultValue = "light") String theme) {
return "theme-" + theme;
}
绑定到封装对象(如 Cookie 实体)
若需获取 Cookie 的元信息(如 path、maxAge、secure 等),不能直接用 @CookieValue,它只支持取 value。此时应使用 HttpServletRequest 手动遍历:
@GetMapping("/cart")
public String getCart(HttpServletRequest request) {
Cookie[] cookies = request.getCookies();
if (cookies != null) {
for (Cookie cookie : cookies) {
if ("cartId".equals(cookie.getName())) {
String cartId = cookie.getValue();
int maxAge = cookie.getMaxAge(); // 单位秒
boolean isSecure = cookie.getSecure();
// 处理逻辑...
break;
}
}
}
return "cart";
}
常见问题与注意事项
- Cookie 名称区分大小写,确保传入的 name 与浏览器实际发送的完全一致(如
"auth_token"≠"Auth_Token") - 中文或特殊字符 Cookie 值通常被 URL 编码,
@CookieValue自动解码,无需额外处理 - HTTP Only 的 Cookie(如
Set-Cookie: token=xxx; HttpOnly)仍可被服务端读取,不影响@CookieValue使用 - 不建议用
@CookieValue获取敏感信息(如密码、token)做校验——应配合服务端 session 或 JWT 验证机制


















