set Cookie to HttpServletResponse - Java Servlet JSP

Java examples for Servlet JSP:Servlet

Description

set Cookie to HttpServletResponse

Demo Code


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

public class Main{
    private final static String COOKIE_NAME = "fileDownload";
    private final static String COOKIE_VALUE = "true";
    private final static int COOKIE_EXPIRE_SECS = 10 * 60;
    /**//ww w . j  av a  2 s  .  c  om
     * 
     * @param request
     * @param resp
     */
    public final static void setCookie(HttpServletRequest request,
            HttpServletResponse resp) {

        setCookie(request, resp, null, null);
    }
    /**
     * @param request
     * @param resp
     * @param path
     * @param domain
     */
    public final static void setCookie(HttpServletRequest request,
            HttpServletResponse resp, String path, String domain) {

        Cookie c = new Cookie(COOKIE_NAME, COOKIE_VALUE);
        if (domain != null)
            c.setDomain(domain);

        if (path != null)
            c.setPath(path);

        //Set expire age.
        c.setMaxAge(COOKIE_EXPIRE_SECS);
        resp.addCookie(c);
    }
}

Related Tutorials