Common cookie processing tools and cookie tools

Source: Internet
Author: User

Common cookie processing tools and cookie tools

Function: adds, deletes, and obtains values of cookies.

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 * Common cookie Processing Methods tool class 10 */11 public class CookieUtil {12 13/** 14 * Add cookie15 * @ param response16 * @ param key cookie primary key 17 * @ param value cookie value 18 */19 public static void addCookie (H TtpServletResponse response, String key, String value) {20 Cookie cookie = new Cookie (key, value); 21 cookie. setPath ("/"); // you need to set 22 cookies. setMaxAge (60*60*24*30); // The unit of seconds for a month is 23 response. addCookie (cookie ); 24} 25 26/** 27 * Delete cookie28 * @ param request29 * @ param response30 * @ param key cookie primary key 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 ("/"); // set to 39 cookies that are the same as cookies. setMaxAge (0); 40 response. addCookie (cookie ); 41} 42} 43} 44} 45 46/** 47 * obtain the cookie value 48 * @ param request49 * @ param key cookie primary key 50 */51 public static String getCookieValue (HttpServletRequest request, string key) throws UnsupportedEncodingException {52 for (Cookie: request. getCookies () {53 if (cookie. getName (). equals (key) {54 return URLDecoder. decode (cookie. getValue (), "UTF-8"); 55} 56} 57 return null; 58} 59}

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.