Servlet Tutorial

Cookies

A cookie is the peace of information which contains an identity of the client in the form of (key, value) pair. Key always represents cookie name and value represents value of the cookie.

A Cookie is the class developed according to http protocol specification for maintaining for identity of client and it is present in a package called javax.servlet.http.* package.

Steps for developing Cookie:

  1. Create an object of a Cookie.
  2. Cookie ck=new Cookie (String, Object);

    For example:

    Cookie c1=new Cookie ("fno","10"); 
    Cookie c2=new Cookie ("sno","20");
    
  3. Every cookie must be added as a part of response (add the cookie to response object).

    For example:

    res.addCookie (c1); 
    res.addCookie (c2);
    
    Here, c1 and c2 are Cookie class objects created in step-1 and addCookie () is an instance method present in HttpServletResponse interface.
  4. add cookie
  5. In order to get the cookies we must use the following method which is present in HttpServletRequest.
  6. get cookies

    For example:

    Cookie ck []=req.getCookies (); 
    if (ck!=null)
    {
        pw.println ("COOKIES ARE PRESENT");
    }
    else
    {
        pw.println ("COOKIES ARE NOT PRESENT");
    }
    
  7. In order to obtain cookie name, cookie value and to set its age we have to use the following methods:
  8. public String getName ();
    public Object getValue ();
    public void setMaxAge (long sec); 
    public long getMaxAge ();
    

Methods 1 and 2 are used for obtaining name and value of the cookie. Methods 3 and 4 are used for setting and obtaining the age of the cookie.

The default age of the cookie will be -1 and it will be available only for current browsing session and a cookie will not be available when the browser is closed, the system is rebooted. Cookies are prepared by server side program and there will be residing in client side.

For example:

Cookie c1=new Cookie ();
c1.setMaxAge (24*60*60); // setting the cookie age for 24 hours. 
String s=c1.getName ();
Object obj=c1.getValue ();

Write a java program which illustrates the concept of setting and getting cookies by specifying maximum age, default age and obtaining the cookies which are present at client side?

Answer:

web.xml:

<web-app>
    <servlet>
        <servlet-name>abc</servlet-name>
        <servlet-class>SetCookie</servlet-class>
    </servlet>
    <servlet>
        <servlet-name>pqr</servlet-name>
        <servlet-class>ShowCookie</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>abc</servlet-name>
        <url-pattern>/test1</url-pattern>
    </servlet-mapping>
    <servlet-mapping>
        <servlet-name>pqr</servlet-name>
        <url-pattern>/test2</url-pattern>
    </servlet-mapping>
</web-app>

SetCookie.java:

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

public class SetCookie extends HttpServlet {

    public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
        // default maximum age is -1, indicating cookie applies only to current browsing session
        res.setContentType("text/html");
        Cookie c1 = new Cookie("ANDHRA PRADESH", "HYDERABAD");
        Cookie c2 = new Cookie("TAMILNADU", "CHENNAI");
        res.addCookie(c1);
        res.addCookie(c2);
        // c3 is valid for 5mins & c4 for 10mins, regardless of user quits browser, reboots computer
        Cookie c3 = new Cookie("KARNATAKA", "BANGLORE");
        Cookie c4 = new Cookie("BIHAR", "PATNA");
        c3.setMaxAge(300);
        c4.setMaxAge(600);
        res.addCookie(c3);
        res.addCookie(c4);
        System.out.println("SUCCESSFUL IN SETTING COOKIES");
    }

    public void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
        doGet(req, res);
    }
};

ShowCookie.java:

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

public class ShowCookie extends HttpServlet {

    public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
        res.setContentType("text/html");
        PrintWriter pw = res.getWriter();
        String title = "Active Cookies";
        pw.println("<html><head><title>" + title + "</title></head></body>");
        pw.println("<table border=\"1\" align=\"center\">");
        pw.println("<tr><th>Cookie Name</th><th>Cookie Value</th></tr>");
        Cookie ck[] = req.getCookies();
        if (ck != null) {
            for (int i = 0; i < ck.length; i++) {
                pw.println("<tr><td>" + ck[i].getName() + "</td><td>" + ck[i].getValue() + "</td></tr>");
            }
        } else {
            System.out.println("NO COOKIES PRESENT");
        }
        pw.println("</table></body></html>");
    }

    public void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
        doGet(req, res);
    }
};

Implement the following screen by using cookies?

implement using cookies

Answer:

web.xml:

<web-app>
    <servlet>
        <servlet-name>s1</servlet-name>
        <servlet-class>FirstServ</servlet-class>
    </servlet>
    <servlet>
        <servlet-name>s2</servlet-name>
        <servlet-class>SecondServ</servlet-class>
    </servlet>
    <servlet>
        <servlet-name>s3</servlet-name>
        <servlet-class>FinalServ</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>s1</servlet-name>
        <url-pattern>/test1</url-pattern>
    </servlet-mapping>
    <servlet-mapping>
        <servlet-name>s2</servlet-name>
        <url-pattern>/test2</url-pattern>
    </servlet-mapping>
    <servlet-mapping>
        <servlet-name>s3</servlet-name>
        <url-pattern>/test3</url-pattern>
    </servlet-mapping>
</web-app>

personal.html:

<html>
    <title>Complete example</title>
    <body>
    <center>
        <form name="ex" action="./test1" method="post">
            <table border="1">
                <tr>
                    <th align="left">Enter ur name : </th>
                    <td><input type="text" name="ex_name" value=""></td>
                </tr>
                <tr>
                    <th align="left">Enter ur address : </th>
                    <td><textarea name="ex_add" value=""></textarea></td>
                </tr>
                <tr>
                    <th align="left">Enter ur age : </th>
                    <td><input type="text" name="ex_age" value=""></td>
                </tr>
                <tr>
                <table>
                    <tr>
                        <td align="center"><input type="submit" name="ex_continue" value="Continue"></td>
                    </tr>
                </table>
                </tr>
            </table>
        </form>
    </center>
    </body>
</html>

FirstServ.java:

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

public class FirstServ extends HttpServlet {

    public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
        res.setContentType("text/html");
        PrintWriter pw = res.getWriter();
        String name = req.getParameter("ex_name");
        String address = req.getParameter("ex_add");
        String age = req.getParameter("ex_age");
        Cookie c1 = new Cookie("name", name);
        Cookie c2 = new Cookie("address", address);
        Cookie c3 = new Cookie("age", age);
        res.addCookie(c1);
        res.addCookie(c2);
        res.addCookie(c3);
        pw.println("<html><title>First Servlet</title><body bgcolor=\"green\"><center>");
        pw.println("<form name=\"first\" action=\"./test2\" method=\"post\"><table bgcolor=\"lightblue\">");
        pw.println("<tr><th>Enter   ur   experience   :   </th><td><input   type=\"text\"   name=\"first_exp\"value=\"\">");
        pw.println("</td></tr><tr><th>Enter  ur  skills  :  </th><td><input  type=\"text\"  name=\"first_skills\" value=\"\">");
        pw.println("</td></tr><table><tr><td  align=\"center\"><input type=\"submit\" name=\"first_submit\"value=\"Continue\">");
        pw.println("</td></tr></table></table></form></center></body></html>");
    }

    public void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
        doGet(req, res);
    }
};

SecondServ.java:

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

public class SecondServ extends HttpServlet {

    public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
        res.setContentType("text/html");
        PrintWriter pw = res.getWriter();
        String exp = req.getParameter("first_exp");
        String skills = req.getParameter("first_skills");
        Cookie c4 = new Cookie("exp", exp);
        Cookie c5 = new Cookie("skills", skills);
        res.addCookie(c4);
        res.addCookie(c5);
        pw.println("<html><title>Second Servlet</title><body bgcolor=\"green\"><center>");
        pw.println("<form	name=\"second\"	action=\"./test3\"	method=\"post\"><table bgcolor=\"lightblue\">");
        pw.println("<tr><th>Enter  expected  salary  :  </th><td><input  type=\"text\"  name=\"second_sal\"value=\"\">");
        pw.println("</td></tr><tr><th>Enter	preffered	location	:	</th><td><input	type=\"text\"name=\"second_loc\" value=\"\">");
        pw.println("</td></tr><table><tr><td	align=\"center\"><input	type=\"submit\" name=\"second_submit\" value=\"Submit\">");
        pw.println("</td></tr></table></table></form></center></body></html>");
    }

    public void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
        doGet(req, res);
    }
};

Databasetable (info):

create table info (
name varchar2 (13),
addr varchar2 (33),
age number (2),
exp number (2),
skills varchar2 (13),
sal number (7,2),
loc varchar2 (17)
);
/

FinalServ.java:

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

public class FinalServ extends HttpServlet {

    public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
        ArrayList al = new ArrayList();
        res.setContentType("text/html");
        PrintWriter pw = res.getWriter();
        String sal = req.getParameter("second_sal");
        float salary = Float.parseFloat(sal);
        String location = req.getParameter("second_loc");
        Cookie ck[] = req.getCookies();
        for (int i = 0; i < ck.length; i++) {
            al.add(ck[i].getValue());
        }
        String name = al.get(0).toString();
        String address = al.get(1).toString();
        String age1 = al.get(2).toString();
        int age = Integer.parseInt(age1);
        String exp = al.get(3).toString();
        int experiance = Integer.parseInt(exp);
        String skills = al.get(4).toString();
        try {
            Class.forName("oracle.jdbc.driver.OracleDriver");
            Connection con = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:Hanuman", "scott", "tiger");
            PreparedStatement ps = con.prepareStatement("insert into info values (?,?,?,?,?,?,?)");
            ps.setString(1, name);
            ps.setString(2, address);
            ps.setInt(3, age);
            ps.setInt(4, experiance);
            ps.setString(5, skills);
            ps.setFloat(6, salary);
            ps.setString(7, location);
            int j = ps.executeUpdate();
            if (j > 0) {
                pw.println("<html><body bgcolor=\"lightblue\"><center><h1><font color=\"red\"> Successfully ");
                pw.println("Inserted</font></h1></center><a  href=\"personal.html\">Home</a></body></html>");
            } else {
                pw.println("<html><body bgcolor=\"cyan\"><center><h1><font color=\"red\">Try Again");
                pw.println("</font></h1></center><a  href=\"personal.html\">Home</a></body></html>");
            }
        } catch (Exception e) {
            pw.println("<html><body bgcolor=\"cyan\"><center><h1><font color=\"red\">Try Again");
            pw.println("</font></h1></center><a href=\"personal.html\">Home</a></body></html>");
        }
    }

    public void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
        doGet(req, res);
    }
};

Disadvantages of Cookies:

  1. When we remove the cookies which are residing in client side by going to tools - internet options - delete cookies of browser, we cannot maintain identity of the client.
  2. There is a restriction on size of the cookies (i.e., 20 cookies are permitted per web application).
  3. As and when number of cookies which leads to more network traffic flow and there is a possibility of loosing performance of server side applications.