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 java.io.IOException;
import java.io.PrintWriter;
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();
res.setContentType("text/html");
Cookie cok = new Cookie("name","20");
res.addCookie(cok);
pw.println("Hi Viewr's<br>");
cok.setDomain("www.Devmauals.com");
String s = cok.getDomain();
pw.println("Domain is : "+s+"<br>");
cok.setMaxAge(10);
pw.println("Maximum age of cookies is "+cok.getMaxAge()+" sec <br>");
cok.setValue("4");
pw.println("Set value = "+cok.getValue());
cok.setPath("/cookieExample");
pw.println("<br>Path = "+cok.getPath()+"<br>");
cok.setSecure(true);
pw.println("Cookies is sent using secure protocols : "+cok.getSecure()+"<br>");

}
}

web.xml file

<web-app>
<servlet>
<servlet-name>CookieExample</servlet-name>
<servlet-class>CookieExample</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>CookieExample</servlet-name>
<url-pattern>/CookieExample</url-pattern>
</servlet-mapping>

</web-app>

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