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

來源:互聯網
上載者:User

標籤:常用   快速   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有三個屬性,分別如下:

  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)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.