1. 程式人生 > >Java中Cookie常用操作類(Spring中操作Cookie)

Java中Cookie常用操作類(Spring中操作Cookie)

方法 .net str blog .cn shm efault csdn int

說明: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有三個屬性,分別如下:

  1. value請求參數的參數名;
  2. required該參數是否必填,默認為true(必填),當設置成必填時,如果沒有傳入參數,報錯;
  3. 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)