coding++:Java读写到览器Cookies中
首先我们认识下什么是cookies:
cookie实际上是一个存在你硬盘里的数据,但是这些数据很特殊,只能由web应用提交给浏览器帮助存储,并且我们还能读取浏览器存在本地的cookie
web应用一般只在cookie中存储一些用户信息等少量且暂时的数据,数据量大则不适合存储在cookies。
一般浏览器对于每个web应用会分别给予他们40个cookie用来存储数据,并且每个cookie的大小不超过4K(听说部分浏览器的cookie能存很大的数据,不过我们一般不会存这么大的数据,因为数据提取的效率不高,影响性能)
说了这么多废话,然后重点终于来了
java通过httpServletRequest接口来访问浏览器请求中的cookies数据(这里先了解一下cookies来龙去脉,代码待会一并给出)
每个cookie有两个属性:键 ,值(无特定格式字符串,所以可以diy存数据,不过要注意URL编码问题,编码问题待会和代码一同讲)
如果我们需要存储新的cookie我们可以new一个cookie实例 并通过httpservletRsponse提交到浏览器,进而存储到本地
下面给出cookie的一个通用类:
package com.tree.ztree_demo.cookies; import java.io.UnsupportedEncodingException; import java.net.URLEncoder; import java.util.HashMap; import java.util.Map; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class CookiesUitls { /** * 根据名字获取cookie * * @param request * @param name cookie名字 * @return */ public static Cookie getCookieByName(HttpServletRequest request, String name) { Map<String, Cookie> cookieMap = ReadCookieMap(request); if (cookieMap.containsKey(name)) { Cookie cookie = (Cookie) cookieMap.get(name); return cookie; } else { return null; } } /** * 将cookie封装到Map里面 * * @param request * @return */ private static Map<String, Cookie> ReadCookieMap(HttpServletRequest request) { Map<String, Cookie> cookieMap = new HashMap<String, Cookie>(); Cookie[] cookies = request.getCookies(); if (null != cookies) { for (Cookie cookie : cookies) { cookieMap.put(cookie.getName(), cookie); } } return cookieMap; } /** * 保存Cookies * * @param response servlet请求 * @param value 保存值*/ public static HttpServletResponse setCookie(HttpServletResponse response, String name, String value, int time) { // new一个Cookie对象,键值对为参数 Cookie cookie = new Cookie(name, value); // tomcat下多应用共享 cookie.setPath("/"); // 如果cookie的值中含有中文时,需要对cookie进行编码,不然会产生乱码 try { URLEncoder.encode(value, "utf-8"); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } cookie.setMaxAge(time); // 将Cookie添加到Response中,使之生效 response.addCookie(cookie); // addCookie后,如果已经存在相同名字的cookie,则最新的覆盖旧的cookie return response; } /** * <p>删除无效cookie</p> * <p>无效☞1.过时 2.未发布</p> * * @param request * @param response */ public static void delectCookieByName(HttpServletRequest request, HttpServletResponse response, String deleteKey) throws NullPointerException { Map<String, Cookie> cookieMap = ReadCookieMap(request); for (String key : cookieMap.keySet()) { if (key == deleteKey && key.equals(deleteKey)) { Cookie cookie = cookieMap.get(key); cookie.setValue(null); cookie.setMaxAge(0);//设置cookie有效时间为0 cookie.setPath("/");//不设置存储路径 response.addCookie(cookie); } } } }
工具类二(密文):
package com.tree.ztree_demo.cookies; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.UnsupportedEncodingException; import java.net.URLDecoder; import java.net.URLEncoder; import java.util.Base64; import java.util.HashMap; import java.util.Map; public class CookieUtil { public static String getCookieValueByName(HttpServletRequest request, String name) { Cookie[] cookies = request.getCookies(); if(cookies == null || cookies.length == 0) return ""; for(Cookie cookie : cookies) { if(cookie.getName().equalsIgnoreCase(name)) { try { byte[] asBytes = Base64.getDecoder().decode(URLDecoder.decode(cookie.getValue(), "UTF-8")); return new String(asBytes, "utf-8"); } catch(UnsupportedEncodingException e) { e.printStackTrace(); } } } return ""; } /** * 设置cookie 先base64转码然后URLEncode * * @param response * @param name * cookie名字 * @param value * cookie值 * @param maxAge * cookie生命周期 以秒为单位 */ public static void addCookie(HttpServletResponse response, String name, String value, int maxAge) { Cookie cookie = null; try { cookie = new Cookie(name, URLEncoder.encode(Base64.getEncoder().encodeToString(value.getBytes()), "UTF-8")); } catch(UnsupportedEncodingException e) { e.printStackTrace(); } cookie.setPath("/"); if(maxAge > 0) cookie.setMaxAge(maxAge); response.addCookie(cookie); } /** * 根据名字获取cookie * * @param request * @param name * cookie名字 * @return */ public static Cookie getCookieByName(HttpServletRequest request, String name) { Map<String, Cookie> cookieMap = ReadCookieMap(request); if(cookieMap.containsKey(name)) { Cookie cookie = cookieMap.get(name); return cookie; } else { return null; } } /** * 将cookie封装到Map里面 * * @param request * @return */ private static Map<String, Cookie> ReadCookieMap(HttpServletRequest request) { Map<String, Cookie> cookieMap = new HashMap<String, Cookie>(); Cookie[] cookies = request.getCookies(); if(null != cookies) { for(Cookie cookie : cookies) { cookieMap.put(cookie.getName(), cookie); } } return cookieMap; } public static void deleteCookie(HttpServletRequest request, HttpServletResponse response) { Cookie[] cookies = request.getCookies(); if(null != cookies) { for(Cookie cookie : cookies) { cookie.setValue(null); cookie.setMaxAge(0);// 立即销毁cookie cookie.setPath("/"); System.out.println("被删除的cookie名字为:" + cookie.getName()); response.addCookie(cookie); } } } }