What is cookie? How can you store and read cookies by using servlet? Explain with example.

 COOKIES IN SERVLET

A cookie is a small piece of information that is persisted between the multiple client requests. A cookie has a name, a single value, and optional attributes such as a comment, path and domain qualifiers, a maximum age, and a version number. There are three steps involved in identifying returning users:

✓ Server script sends a set of cookies to the browser. For example name, age, or identification number etc.

✓ Browser stores this information on local machine for future use. When next time browser sends any request to web server then it sends those cookies information to the server and server uses that information to identify the user.


How Cookie works

By default, each request is considered as a new request. In cookies technique, we add cookie with response from the servlet. So cookie is stored in the cache of the browser. After that if request is sent by the user, cookie is added with request by default. Thus, we recognize the user as the old user.


Advantage of Cookies

  • Simplest technique of maintaining the state.
  • Cookies are maintained at client side.

Disadvantage of Cookies

  • It will not work if cookie is disabled from the browser.
  • Only textual information can be set in Cookie object.

Cookie class
javax.servlet.http.Cookie class provides the functionality of using cookies. It provides a lot of useful methods for cookies.

Constructor of Cookie class
Constructor
Cookie()//constructs a cookie.
Cookie(String name, String value)//constructs a cookie with a specified name and value.

Useful Methods of Cookie class
There are given some commonly used methods of the Cookie class.

Method
public void setMaxAge(int expiry)//Sets the maximum age of the cookie in seconds.
public String getName()//Returns the name of the cookie. The name cannot be changed after creation.
public String getValue()//Returns the value of the cookie.
public void setName(String name)//changes the name of the cookie.
public void setValue(String value)//changes the value of the cookie.

Other methods required for using Cookies
For adding cookie or getting the value from the cookie, we need some methods provided by other interfaces. They are:
public void addCookie(Cookie ck):method of HttpServletResponse interface is used to add cookie in response object.
public Cookie[] getCookies():method of HttpServletRequest interface is used to return all the cookies from the browser.

How to create Cookie?
Let's see the simple code to create cookie.
Cookie ck=new Cookie("user","sonoo jaiswal");//creating cookie object  
response.addCookie(ck);//adding cookie in the response  

How to read cookies
Cookie c[]=request.getCookies(); 
//c.length gives the cookie count 
for(int i=0;i<c.length;i++){  
 out.print("Name: "+c[i].getName()+" & Value: "+c[i].getValue());
}

How to delete Cookie?
Let's see the simple code to delete cookie. It is mainly used to logout or signout the user.
Cookie ck=new Cookie("user","");//deleting value of cookie  
ck.setMaxAge(0);//changing the maximum age to 0 seconds  
response.addCookie(ck);//adding cookie in the response  

How to get Cookies?
Let's see the simple code to get all the cookies.
Cookie ck[]=request.getCookies();  
for(int i=0;i<ck.length;i++){  
 out.print("<br>"+ck[i].getName()+" "+ck[i].getValue());//printing name and value of cookie  
}  

Example of storing and reading cookies 
//cookies.html file
<html>
<body>
<form action="SetServlet" method="POST">
Name: <input type="text" name="uname"/><br/> <input type="submit" value="go" /> </form>  </html>
</body>

//SetServlet.java File-Sets cookies
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class SetServlet extends HttpServlet
{
public void doPost (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
response.setContentType("text/html");
Printwriter out = response.getWriter();
 String n=request.getParameter("uname");
out.print("Welcome"+n);
Cookie ck=new Cookie("name",n);//creating cookie object 
ck.setMaxAge (60*60*24);
response.addCookie(ck);//adding cookie in the response
//creating submit button
out.print("<form action='ReadServlet' method='POST'>"); out.print("<input type=submit value='go' >"); 
out.print("</form>"); 
out.close();

//ReadServlet.java File----Reads Cookies
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class ReadServlet extends HttpServlet
{
public void doPost (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
response.setContent Type("text/html");
Printwriter out = response.getWriter();
Cookie[] ck=request.getCookies();
if(ck!=null)
out.print("Hello "+ck [0].getValue()); txtsiya
out.close();
}
}
Output

Comments

Popular posts from this blog

What are different steps used in JDBC? Write down a small program showing all steps.

Suppose that a data warehouse for Big-University consists of the following four dimensions: student, course, semester, and instructor, and two measures count and avg_grade. When at the lowest conceptual level (e.g., for a given student, course, semester, and instructor combination), the avg_grade measure stores the actual course grade of the student. At higher conceptual levels, avg_grade stores the average grade for the given combination. a) Draw a snowflake schema diagram for the data warehouse. b) Starting with the base cuboid [student, course, semester, instructor], what specific OLAP operations (e.g., roll-up from semester to year) should one perform in order to list the average grade of CS courses for each BigUniversity student. c) If each dimension has five levels (including all), such as “student < major < status < university < all”, how many cuboids will this cube contain (including the base and apex cuboids)?

Discuss classification or taxonomy of virtualization at different levels.