Servlet Menu


Cookies in Servlet




A cookie is a piece of data from a website that is stored within a web browser(Client side) that the website can retrieve at a later time. Cookies are used to tell the server that users have returned to a particular website.

How cookies work

When you send a request to the server, the server sends a reply in which it embeds the cookie which serves as an identifier to identify the user. So, next time when you visit the same website, the cookie lets the server know that you are visiting the website again.

Cookies Used For?

Session management. For example, cookies let websites recognize users and recall their individual login information and preferences, such as sports news versus politics.

Personalization. Customized advertising is the main way cookies are used to personalize your sessions. You may view certain items or parts of a site, and cookies use this data to help build targeted ads that you might enjoy.

Tracking. Shopping sites use cookies to track items users previously viewed, allowing the sites to suggest other goods they might like and keep items in shopping carts while they continue shopping.

Commonly used Methods in Cookie

public String getName( ) Returns the name of the cookies.
public String getPath( ) Returns the path of the server to which the browser returns the cookie.
public String getValue( ) Returns the value of the cookie.
public int getMaxAge( ) Returns the maximum age limit to the cookie, specified in seconds.
public void setMaxAge(int expiry) Sets the maximum age of the cookies in seconds.
public void setValue(String newValue) Allocates a new value to a cookie after the cookie is created.

Create a Cookie Object

The constructor of Cookie class creates the cookie object with corresponding cookie name and value.

//creating cookie object 
Cookie cookie = new Cookie("username","Studyglance");

//adding cookie to the response
Response.addCookie(cookie);

Get Cookie from client request

Cookie ck[ ]=request.getCookies();

cookiedemo.html
<html> 
	<head> 
		<title>Cookie Demo</title> 
	</head> 
	<body> 
		<form action="servlet1" method="post"> 
			Enter Your Name:<input type="text" name="userName"/><br/><br/> 
			<input type="submit" value="SUBMIT"/> 
		</form> 
	</body> 
</html> 

SetCookieServlet.java
import java.io.*; 
import javax.servlet.*; 
import javax.servlet.http.*; 
public class SetCookieServlet extends HttpServlet {
    public void doPost(HttpServletRequest request, HttpServletResponse response){
        try{
            response.setContentType("text/html");
            PrintWriter out = response.getWriter();
            String name=request.getParameter("userName");
            //creating cookie object
            Cookie ck=new Cookie("uname",name);
            //adding cookie in the response
            response.addCookie(ck);
            out.print("Cookie Saved");
            //creating submit button 
            out.print("<br><form action='servlet2' method='post'>");
            out.print("<input type='submit' value='View the cookie value'>");
            out.print("</form>");
            out.close();
        }
        catch(Exception e){
            System.out.println(e);
        }
    }
} 

GetCookieServlet.java
import java.io.*; 
import javax.servlet.*; 
import javax.servlet.http.*; 

public class GetCookieServlet extends HttpServlet {
    public void doPost(HttpServletRequest request, HttpServletResponse response){
        try{ 
            response.setContentType("text/html");
            PrintWriter out = response.getWriter();
            Cookie ck[]=request.getCookies();
            out.println("<h3>Reading the cookies</h3>");
            out.println("<br/>");
            out.println("Name of the cookie : " + ck[0].getName() + "<br/>");
            out.println("Value in cookie : " + ck[0].getValue());
            out.close(); 
        }catch(Exception e){
            System.out.println(e);
        }
    }
}

web.xml
<web-app> 
	<servlet> 
		<servlet-name>set</servlet-name> 
		<servlet-class>SetCookieServlet</servlet-class> 
	</servlet> 
	<servlet-mapping> 
		<servlet-name>set</servlet-name> 
		<url-pattern>/servlet1</url-pattern> 
	</servlet-mapping> 
	<servlet> 
		<servlet-name>get</servlet-name> 
		<servlet-class>GetCookieServlet</servlet-class> 
	</servlet> 
	<servlet-mapping> 
		<servlet-name>get</servlet-name> 
		<url-pattern>/servlet2</url-pattern> 
	</servlet-mapping> 
</web-app> 


Next Topic :HTTPSession

Suggestion/Feedback Form :




Excellent  Very Good  Good  Average  Poor


This is a Compliment
This is a Suggestion for improvement
This is Feedback
This is Grievance