Storing data to Cookie

Storing data to Cookie


Posted in : Servlet Posted on : November 10, 2010 at 5:30 PM Comments : [ 0 ]

This section contains the details about the Storing data to Cookie.

Storing data to Cookie

In this section , you will learn how to store data to Cookie and also adding it to client's web browser. Cookie can be used by the application server , which store it to client hard disk, to find out the computer name, IP address or any other details of the client computer.The HttpServletResponse interface provides the addCookie() method to add a cookie to the response object, for sending it to the client.

Example

Given below html code which accept username and password. The username enter here will use by us to add it to cookie :

<html>
<body>
<form name="f1" action="servlet/SetCookie"><font size=4
face="Verdana" color=#120292>
<center>
<h2>Login Form</h2>
</center>
<br>
<br>
<table cellspacing=5 cellpadding=5 bgcolor=#959999 colspan=2 rowspan=2
align="center">
<tr>
<td>Customer Authentication Form</td>
</tr>
<tr>
<td>Enter Username :</td>
<td><input type=text name="user"></td>
</tr>
<tr>
<td>Enter Password:</td>
<td><input type=password name="password"></td>
</tr>
</table>
<br>
<table align="center">
<tr>
<td><input type="submit" value=" Login "></td>
<td><input type="Reset" value=" Cancel "></td>
</tr>
</table>
</font></form>
</body>
</html>

Following code is used to create a servlet, CookieServlet that retrieves the username and stores it in a cookie. The servlet then sends the cookie to the client using the response object :

package devmanuals;

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

public class SetCookie extends HttpServlet {
PrintWriter pw = null;

public void doGet(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {
// Invoke the doPost() method of HttpServlet class
doPost(req, res);
}

public void doPost(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {
pw = res.getWriter();
/* Retrieve the user information from HttpServlet request. */
String username = req.getParameter("user");
String password = req.getParameter("password");
/* Create a cookie that contains username. */
Cookie ck = new Cookie("user", username);
/* Add the cookie to the client browser. */
res.addCookie(ck);
pw.println("Cookie containing user name is stored in your browser.");
}
}

Output

Firstly, we invoke login form :

 

When you click the login button, it will add the data to cookie and show the following message :

Download Source Code

Go to Topic «PreviousHomeNext»

Your Comment:


Your Name (*) :
Your Email :
Subject (*):
Your Comment (*):
  Reload Image
 
 

 
Tutorial Topics