session与cookie
cookie
会话数据保存再客户端,不能跨浏览器。
-
服务端给客户端设置cookie
1 2 3 4 5 6
| protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { Cookie cookie = new Cookie("username", "123456"); resp.addCookie(cookie); }
|
浏览器请求的响应头中会带有设置cookie的信息
-
服务端获取客户端的cookie(同一浏览器)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
| protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { Cookie[] cookies = req.getCookies(); if (cookies != null) { String username = ""; for (int i = 0; i < cookies.length; i++) { if ("username".equals(cookies[i].getName())) { username = cookies[i].getValue(); break; } } resp.getWriter().write("the value of username in cookie is " + username); } else { resp.getWriter().write("the cookie is null"); } }
|
浏览器的请求头中会带有cookie信息
-
设置cookie有效时长
默认关闭浏览器后cookie失效。
1 2
| cookie.setMaxAge(60*3);
|
cookie的局限
- cookie只能存字符串类型,不能保存对象
- 只能存非中文
- 1个cookie的容量不超过4kb
session
会话数据保存再服务器端,内存中,客户端与服务端之间通讯使用sessionid
。
自定义session
Cache:
1 2 3 4 5 6 7 8 9
| public class Cache { @MetaData(name = "键", desc = "") private String key; @MetaData(name = "值", desc = "") private Object value; @MetaData(name = "有效期", desc = "") private Long timeout; }
|
CacheManager:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46
| public class CacheManager {
private Map<String, Cache> cacheMap = new HashMap<>();
public synchronized void put(String key, Object value, Long timeout) { Cache cache = new Cache(); cache.setKey(key); cache.setValue(value); if (timeout != null) { cache.setTimeout(System.currentTimeMillis() + timeout); } cacheMap.put(key, cache); }
public synchronized void put(String key, Object value) { put(key, value, null); }
public synchronized Object get(String key) { if (cacheMap.containsKey(key)) { return cacheMap.get(key).getValue(); } return null; }
public synchronized void remove(String key) { if (cacheMap.containsKey(key)) { cacheMap.remove(key); } } public synchronized void checkValidityData() { for (Map.Entry<String, Cache> entry : cacheMap.entrySet()) { Cache cache = entry.getValue(); if (cache == null) { continue; } Long timeout = cache.getTimeout(); Long now = System.currentTimeMillis(); if (now > timeout) { remove(entry.getKey()); } } } }
|
TokenUtil:
1 2 3 4 5 6
| public class TokenUtil {
public static String getToken() { return UUID.randomUUID().toString(); } }
|
SessionUtil:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
| public class SessionUtil {
private static final CacheManager cacheManager = new CacheManager();
public static String setAtttibute(Object value) { String sessionId = TokenUtil.getToken(); cacheManager.put(sessionId, value); return sessionId; }
public static Object getAtttibute(String key) { return cacheManager.get(key); }
}
|