Cookies
Cookies are small text files that are stored by an application server in the client browser to keep track of all the users.
A cookie has values in the form of name/value pairs.
They are created by the server and are sent to the client with the HTTP response headers.
The client saves the cookies in the local hard disk and sends them along with the HTTP request headers to the server.
A Web browser is expected to support 20 cookies per host and the size of each cookies can be a maximum of 4 bytes each.
Various characteristics of cookies are:
1. Cookies can only be read by the application server that had written them in the client browser.
2. Cookies can be used by the server to find out the computer name , IP address or any other details of the client computer by retrieving the remote host address of the client where the cookies are stored.
3. An application server can store cookies in the client machine only when the cookie are enabled in the client browser.
Cookies Description:
The Cookie class of javax.servlet.http package represents a cookie.
The Cookie class provides a constructor that accepts the name and value to create a cookie.
The following code snippet shows the constructor for creating a cookie with name and value.
public Cookie(String cname, String cvalue);
The HttpServletResponse interface provides the addCookie() method to add a cookie to the response object, for sending it to the client.
The following code snippet shows how to add a cookie:
req.addCookie(Cookie cookie);
Retrive the Cookies
The HttpServletRequest provides the getCookies() method that returns an array of cookies that the request object contains.The following code snippet shows how to retrieve cookies:
Cookie cookie [ ] = req.getCookies();
The Cookie class provides several methods to set and retrieve various properties of a cookie.
The various methods of the Cookie class:1. public String getName()
Returns the name of the cookie.
2. public void setMaxAge(int expiry)
Sets the maximum time for which the client browser retains the cookie value.
3. public int getMaxAge()
Returns the maximum age of the cookie in seconds.
4. public void setValue(String value)
Sets a new value to the cookie
5. public String getValue()
Returns the value of the cookie
Creating a Simple Program in Servlet using Cookies: In this we receive data from index.jsp and Store it in Cookies after that call it inwelcome.jsp
Steps to create Cookies:
Step 1 : Create index.jsp with two fields and form action.
Step 2 : Create a new file web.xml under WebContent/WEB-INF folder and write the code given below:
Step 3 : Create a package com.javat.CookiesDemo under Java resources-> src folder and then create the servlet class Login.java. Once you are ready then write the code given below:
Step 4: Create a new file welcome.jsp under Webpages and write the code given below.
Call data that Store we have stored in Session.
No comments:
Post a Comment