Skip to content

Cookie 读取与设置 ​

Cookie 用于在浏览器与服务器之间保存少量状态。框架提供请求读取、响应设置及有效期配置,可以直接在 Handler 中使用。

java
import nexus.io.model.body.RespBodyVo;
import nexus.io.tio.boot.http.TioRequestContext;
import nexus.io.tio.http.common.Cookie;
import nexus.io.tio.http.common.HttpRequest;
import nexus.io.tio.http.common.HttpResponse;

public class ReadThemeCookieHandler {
  public HttpResponse handle(HttpRequest request) {
    Cookie cookie = request.getCookie("theme");
    String theme = cookie == null ? "default" : cookie.getValue();
    return TioRequestContext.getResponse().respond(RespBodyVo.ok(theme));
  }
}

请求中的 theme= 和 theme="" 都保留为空字符串,可以与未携带 theme Cookie 的情况区分。值中已有的等号保持原样,例如 token=abc== 的值为 abc==。框架保留原始编码,业务按约定决定是否解码。

java
import nexus.io.model.body.RespBodyVo;
import nexus.io.tio.boot.http.TioRequestContext;
import nexus.io.tio.http.common.Cookie;
import nexus.io.tio.http.common.HttpRequest;
import nexus.io.tio.http.common.HttpResponse;

public class SetThemeCookieHandler {
  public HttpResponse handle(HttpRequest request) {
    Cookie cookie = new Cookie(null, "theme", "dark", 3600L);
    cookie.setPath("/");
    cookie.setHttpOnly(true);
    cookie.setSecure(true);
    HttpResponse response = TioRequestContext.getResponse();
    response.addCookie(cookie);
    return response.respond(RespBodyVo.ok("已设置"));
  }
}

此示例适用于 HTTPS,Cookie 有效期为一小时,HttpOnly 属性用于限制浏览器脚本读取。按接口分别注册读取和设置 Handler,即可将 Cookie 管理加入业务流程。

构造参数依次是 domain、name、value、maxAge。domain 为 null 时不输出 Domain 属性;maxAge 的单位为秒,为 null 时不输出 Max-Age。默认 Path 为 /。

有效期与删除 ​

setExpires 接收 HTTP 日期文本并输出 Expires 属性;可以使用 DateUtil.httpDate 生成 GMT 日期。

java
import nexus.io.tio.http.common.Cookie;
import nexus.io.tio.utils.hutool.DateUtil;

public class ThemeCookieFactory {
  public Cookie expiredCookie() {
    Cookie cookie = new Cookie(null, "theme", "", 0L);
    cookie.setPath("/");
    cookie.setExpires(DateUtil.httpDate(0L));
    return cookie;
  }
}

将返回的 Cookie 加入响应即可发送删除请求。删除时应使用与原 Cookie 相同的名称、Path 和 Domain 范围。设置了 Max-Age 和 Expires 时,两项都会序列化输出。

发送前配置属性 ​

通过 setter 修改名称、值、域、路径、有效期、Secure 或 HttpOnly 时,编码缓存同步失效,下次编码使用新的属性值。建议每个响应创建自己的 Cookie 对象,并在交给发送流程前完成配置。

请求 Cookie 中的每一项都按名称和值读取,path、domain、max-age、secure、httponly、expires 同样可以作为请求 Cookie 名称。它们只有在响应 Set-Cookie 的属性位置才具有属性含义,请求解析保留其原始名称和值。

MIT Licensed