Cookies in Servlet

Cookies in Servlet

Posted in : Java Posted on : June 23, 2011 at 8:08 PM Comments : [ 0 ]

In this section we will discuss what are the uses of Cookies in servlet.

Cookies in Servlet

In this section we will discuss what are the uses of Cookies in servlet.

Cookies are a small text information that are stored at the client side, sent by the server. Using cookies we can keep track of the user as well as the client computer name, IP address and the other details can be found by the server by finding the remote host address of the client where the cookies are stored.

One can also see the cookies. To see the cookies you can follow the following steps (I follow the Mozilla FireFox browser):

Step 1 : Go to the Toolbar.

Step 2 : Select Tool -> Page Info.

Step 3 : Go to the Security looking at header.

Step 4 : Click on the View Cookies button.

Using the above steps you can do easily work with cookies.

Example :

import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class CookieExample extends HttpServlet {
protected void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
PrintWriter pw = res.getWriter();
Cookie cok = new Cookie("name","20");
pw.println("Hi Viewr's<br>");
String s = cok.getDomain();
pw.println("Domain is : "+s+"<br>");
pw.println("Maximum age of cookies is "+cok.getMaxAge()+" sec <br>");
pw.println("Set value = "+cok.getValue());
pw.println("<br>Path = "+cok.getPath()+"<br>");
pw.println("Cookies is sent using secure protocols : "+cok.getSecure()+"<br>");


web.xml file



Output : When you will execute the above example the following output will show.

Download Source Code

Go to Topic «PreviousHomeNext»

Your Comment:

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

Tutorial Topics