標籤:常用 快速 key UI log logs 屬性 null util
說明:Cookie下用Key取值沒有快速的方法,只能便利迴圈去取。
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 CookieTool { /** * 添加cookie * * @param response * @param name Key * @param value Value * @param maxAge 有效時間 */ public static void addCookie(HttpServletResponse response, String name, String value, int maxAge) { Cookie cookie = new Cookie(name, value); cookie.setPath("/"); cookie.setMaxAge(maxAge); cookie.setDomain(".jsoft.me"); // cookie範圍 response.addCookie(cookie); } /** * 檢索所有Cookie封裝到Map集合 * * @param request * @return */ public static Map<String, String> readCookieMap(HttpServletRequest request) { Map<String, String> cookieMap = new HashMap<String, String>(); Cookie[] cookies = request.getCookies(); if (null != cookies) { for (Cookie cookie : cookies) { cookieMap.put(cookie.getName(), cookie.getValue()); } } return cookieMap; } /** * 通過Key擷取Value * * @param request * @param name Key * @return Value */ public static String getCookieValueByName(HttpServletRequest request, String name) { Map<String, String> cookieMap = readCookieMap(request); if (cookieMap.containsKey(name)) { String cookieValue = (String) cookieMap.get(name); return cookieValue; } else { return null; } }}
在Spring MVC的Controller中使用:
在Spring MVC中使用CookieValue註解映射請求參數,@CookieValue有三個屬性,分別如下:
- value請求參數的參數名;
- required該參數是否必填,預設為true(必填),當設定成必填時,如果沒有傳入參數,報錯;
- defaultValue 佈建要求參數的預設值;
參考:
http://www.cnblogs.com/jun-ma/p/5679459.html
http://blog.csdn.net/u011848397/article/details/52201339
http://www.ibloger.net/article/33.html(以上內容轉自此篇文章)
Java中Cookie常用操作類(Spring中操作Cookie)