setMaxAge Cookie Java

In this tutorial you will learn how to use setMaxAge() of Cookie class in java

setMaxAge Cookie Java

In this tutorial you will learn how to use setMaxAge() of Cookie class in java

setMaxAge Cookie Java

setMaxAge Cookie Java

In this tutorial you will learn how to use setMaxAge() of Cookie class in java

setMaxAge() method sets the age of the cookie that how long it will be live. In other word we can say when a cookie will be expired.

Syntax :

void setMaxAge(int expiry)

In the parameter of this method an integer value is passed. This value denotes the expiration time of a cookie in seconds.

Example :

In the example given below I set the maximum expiration time of a cookie is 60 sec. This means after 60 sec. this cookie will automatically will be inactivated. And use the getMaxAge() method of Cookie class to show the maximum expiration time of a cookie.

SetMaxAgeCookieExample.java

package roseindia.Cookie;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet("/SetMaxAgeCookieExample")
public class SetMaxAgeCookieExample extends HttpServlet {
private static final long serialVersionUID = 1L;

public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
Cookie cookie = new Cookie("CookieName","Cookie");
cookie.setMaxAge(60);
response.addCookie(cookie);
int age= cookie.getMaxAge();
out.println("Maximum time of cookie expiration is : "+age+" sec.");
}

public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}

}

Output :

When you will execute the above example you will get the output as :

Download Source Code