Get cookie value by name from Servlet. - Java Servlet JSP

Java examples for Servlet JSP:Servlet

Description

Get cookie value by name from Servlet.

Demo Code


import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class Main{
    /**/*  w w w .  ja  v  a2 s  . c  om*/
     * Get cookie value by name. Return null if cookie is not found.
     * 
     * @param name Cookie name.
     * @return Cookie value.
     */
    public static String getCookie(String name) {
        return getCookie(name, null);
    }
    /**
     * Get cookie value by name. Return default value if cookie is not found.
     * 
     * @param name Cookie name.
     * @param defaultValue Cookie default value.
     * @return Cookie value.
     */
    public static String getCookie(String name, String defaultValue) {
        HttpServletRequest request = ActionContext.getActionContext()
                .getHttpServletRequest();
        Cookie[] cookies = request.getCookies();
        if (cookies != null) {
            for (Cookie cookie : cookies) {
                if (cookie.getName().equals(name)) {
                    return cookie.getValue();
                }
            }
        }
        return defaultValue;
    }
}

Related Tutorials