Latest Tutorials| Questions and Answers|Ask Questions?|Site Map



Home Java Javaee6 setMaxAge Cookie Java

Related Tutorials


 
 

Share on Google+Share on Google+

setMaxAge Cookie Java

Advertisement
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() 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

Advertisements

If you enjoyed this post then why not add us on Google+? Add us to your Circles



Liked it!  Share this Tutorial


Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.

Posted on: December 30, 2011

Related Tutorials

Discuss: setMaxAge Cookie Java  

Post your Comment


Your Name (*) :
Your Email :
Subject (*):
Your Comment (*):
  Reload Image
 
 
Comments:0
DMCA.com