Java 后台操作 Cookie 记录 token

xiaoxiao2021-02-28  22

在做用户登录的时候,Java 后台往往需要向前台传递 cookie 或者 session

现在我们使用 token 做用户登录验证时,用户登录成功之后生产token,之后用户的每次访问都需要使用token

那么用户从哪里取得token呢?当然是 cookie 了

所以在登录时,后台要做的就是生产 token 并传送 cookie 给前台

设置 Cookie 做法如下

Cookie cookie_token = new Cookie("token",jwt); cookie_token.setMaxAge(60*60*60); cookie_token.setPath("/"); response.addCookie(cookie_token);

但是,如果我们传输的 cookie 的值包含了中文字符的话,就需要给字符进行编码

request.setCharacterEncoding("UTF-8"); String cookieValue = URLEncoder.encode("中文 Cookie 值", "UTF-8"); Cookie cookie_token = new Cookie("myCookie", cookieValue); cookie_token.setMaxAge(60 * 60 * 60); cookie_token.setPath("/"); response.addCookie(cookie_token);

注意,一定要给 cookie 设置 path,否则在删除的时候会出问题

读取 Cookie 做法如下

Cookie cookies[] = request.getCookies(); System.out.println("Cookie长度:" + cookies.length); if (cookies != null) { for (int i = 0; i < cookies.length; i++) { if (cookies[i].getName().equals("nick")) { System.out.println("For 内部Cookie" + URLDecoder.decode(cookies[i].getValue(), "UTF-8")); } } }

删除 Cookie 做法如下

Cookie cookie_token = new Cookie("token",null); cookie_token.setMaxAge(0); cookie_token.setPath("/"); response.addCookie(cookie_token);

前面设置 Cookie 的时候提到一定要设置 Path,这是因为,如果你不设置Path,那么你删除 Cookie 的这个操作无效,他只会当成你新设置了一个 Cookie,而不会与同名的那个冲突,因为 Cookie 不单单只是通过名字区分,还有 Path

转载请注明原文地址: https://www.6miu.com/read-2630691.html

最新回复(0)