Cookies in Servlets with Example

The following tutorial brings you an understanding of how-to use cookies in Java servlets, one of the interesting and important concepts to go around. In this post, i'll explain about cookies pragmatically for a better understand. All complete files of the application along with folder structure are discussed.

 

Folder Structure

Webapps folder: C:\Program Files\Apache Software Foundation\Tomcat 7.0\webapps

Project structure


cookies
           |_ index.html 
           |_ WEB-INF
                              |_ web.xml 
                              |_ classes
                                             |_ CookieExample.java
                                             |_ CookieExample.class
                                             |_ GetCookie.java
                                             |_ GetCookie.class
Now it's time to know what those files really contain. Isn't it? Let's see

HTML Files

index.html


<html>

    <head>
        <title>Cookies Example in Servlets</title>
    </head>

<body bgcolor=wheat>

<center>
    <h1>Cookies Example in Java</h1>

    <form action="http://localhost:8080/cookies/co" method="Post">
        First name: <input type="text" name="fname">
        Last name: <input type="text" name="lname">
        <input type="submit"value="SUBMIT">
    </form>

</center>

</body>

</html>

Deployment Descriptor

web.xml


<web-app>

    <servlet>
        <servlet-name>mys</servlet-name>
        <servlet-class>CookieExample</servlet-class>
    </servlet>
   
    <servlet-mapping>
        <servlet-name>mys</servlet-name>
        <url-pattern>/co</url-pattern>
    </servlet-mapping>


    <servlet>
        <servlet-name>mls</servlet-name>
        <servlet-class>GetCookie</servlet-class>
    </servlet>
   
    <servlet-mapping>
        <servlet-name>mls</servlet-name>
        <url-pattern>/st</url-pattern>
    </servlet-mapping>

</web-app>

Servlet Programs

CookieExample.java


import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
public class CookieExample extends HttpServlet
{
    public void doPost(HttpServletRequest req,HttpServletResponse res) throws ServletException,IOException
    {
    String fname=req.getParameter("fname");   
    String lname=req.getParameter("lname");

    Cookie f=new Cookie("first_name",fname);
    Cookie l=new Cookie("last_name",lname);

    res.addCookie(f);
    res.addCookie(l);

    res.sendRedirect("http://localhost:8080/cookies/st");
    }
}

GetCookie.java


import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
public class GetCookie extends HttpServlet
{
    public void doGet(HttpServletRequest req,HttpServletResponse res) throws ServletException,IOException
    {
    PrintWriter pw=res.getWriter();
   
    pw.println("<h1>");
    Cookie[] c=req.getCookies();
        for(Cookie k:c)
        {
        pw.println(k.getValue());
        }
    pw.println("</h1>");
    }
}

Working? Yes it works.

Invoke the Tomcat at the port installed in your PC or if you are accessing it from another PC, probably then, tomcat installed in that PC. Write the programs, create folders in accordance with the given structure and there will be what you want. Don't forget to compile the classes!!

In my PC, Tomcat is installed in the port 8080 and i will access it as, the project name is cookies i will type the same URL in the address bar of my favorite browser.

http://localhost:8080/cookies

As the default file is index.html the above URL will suffice to load the index.html file, an addition of /index.html is not necessary at the end.

You'll see the following output.

An application on cookies in Java servlets
index.html file in Firefox


 Click on the SUBMIT then,

Value of a cookie is retrieved from another servlet
Output produced by GetCookie class

Let me explain

The HTML file

The html file is as usual, a very normal HTML file you might undergo when working out with most servlet programs. The HTML file here consists of input fields with names fname and lname which are used to get the values in them. The other input field is a SUBMIT button which submits the HTML form to the url specified in the <form> tag. The type of method i used here is post.

The web.xml

web.xml file contains two <servlet> and <servlet-mapping> tags (importantly) which are written for two classes. One is the main class i.e. the class that gets the request made by the user, i.e. the data sent by the user can be caught be this servlet. Another class is GetCookie which is a class that gets the cookies stored by the previous servlet.

Servlet Programs

CookieExample.java

req.getParameter("fname") and req.getParameter("lname"): These methods take in the name of the input field and return the value in them. The values are stored in fname and lname respectively.

Cookie f=new Cookie("first_name", fname): This is the constructor of the javax.servlet.http.Cookie takes in a name (the name of the cookie) and value (value to set in the cookie). The other method is also the same but stores a different value under a different name.

res.addCookie(f), res.addCookie(l): Creating a cookie isn't enough. You'll have to set them in the client's web browser so are these methods.

res.sendRedirect("http://localhost:8080/cookies/st"): Redirect to the specified URL. This URL is associated with GetCookie class (refer web.xml). You can also simply write /cookies/st instead of such lengthy URL.

What is a cookie?
A cookie is a name-value pair which is stored in a user's browser for the sake of the user by the web server when the servlet program says to do so.

GetCookie.java

Here i am writing  doGet() because in the above servlet, sendRedirect() method is called stating to redirect to the URL pattern associated with GetCookie. It is a doGet() call in fact.

PrintWriter pw=res.getWriter(): The java.io.PrintWriter class is used to write (print) something on the dynamic page that is generated. To get a PrintWriter object we need to call the getWriter() method present in the HttpServletResponse.

pw.println("<h1>"): Open the <h1> tag.

Cookie[] c=req.getCookies(): To get cookies stored by this application we need to call the getCookies() method present in the HttpServletRequest class. This gives an array of cookies (Cookie[]).

pw.println(k.getValue()): Get value stored in each cookie and print them. The for-each loop is explained by me before.

pw.println("</h1>"): Close the <h1> tag.

No comments: