get Cookie from HttpServletRequest - Java Network

Java examples for Network:Http

Description

get Cookie from HttpServletRequest

Demo Code


import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class Main{
    /**//from   www. ja  va2s.  c  om
     * Method getCookie.
     *
     * @param request
     * @param cookieName
     * @return String
     * @throws Exception
     */
    public static String getCookie(HttpServletRequest request,
            String cookieName) {
        Cookie[] cookies = request.getCookies();
        if (cookies == null) {
            return "";
        }
        String value = "";
        for (int i = 0; i < cookies.length; i++) {
            if (cookieName.equals(cookies[i].getName())) {
                try {
                    value = java.net.URLDecoder.decode(
                            cookies[i].getValue(), "utf-8");
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
                break;
            }
        }
        return value;
    }
}

Related Tutorials