常用cookie處理方法工具類,cookie工具類

來源:互聯網
上載者:User

常用cookie處理方法工具類,cookie工具類

功能:cookie的添加、刪除、擷取值

 1 import java.io.UnsupportedEncodingException; 2 import java.net.URLDecoder; 3  4 import javax.servlet.http.Cookie; 5 import javax.servlet.http.HttpServletRequest; 6 import javax.servlet.http.HttpServletResponse; 7  8 /** 9  * 常用cookie處理方法工具類10  */11 public class CookieUtil {12     13     /**14      * 添加cookie15      * @param response16      * @param key cookie主鍵17      * @param value cookie值18      */19     public static void addCookie(HttpServletResponse response, String key, String value){20         Cookie cookie = new Cookie(key, value);21         cookie.setPath("/");// 這個要設定  22         cookie.setMaxAge(60*60*24*30);//保留一個月 以秒為單位  23         response.addCookie(cookie);24     }25     26     /**27      * 刪除cookie28      * @param request29      * @param response30      * @param key cookie主鍵31      */32     public static void deleteCookie(HttpServletRequest request, HttpServletResponse response, String key){33         Cookie cookies[] = request.getCookies();  34         if (cookies != null) {  35             for (int i = 0; i < cookies.length; i++) {  36                 if (cookies[i].getName().equals(key)) {  37                     Cookie cookie = new Cookie(key,null);38                     cookie.setPath("/");//設定成跟寫入cookies一樣的  39                     cookie.setMaxAge(0);  40                     response.addCookie(cookie);  41                 }  42             }  43         }  44     }45     46     /**47      * 取得cookie的值48      * @param request49      * @param key cookie主鍵50      */51     public static String getCookieValue(HttpServletRequest request, String key) throws UnsupportedEncodingException{52         for(Cookie cookie : request.getCookies()){53             if (cookie.getName().equals(key)) {   54                 return URLDecoder.decode(cookie.getValue(), "UTF-8");  55             }  56         }57         return null;58     }59 }

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.