Java

First Attempt @ Servlets, JSP and Cookies

I have been doing Servlets and JSPs from quite some days and yeah they have been lots of interesting stuff in it, And this is my first attempt at Web Technologies. I would recommend beginners to use Head First Servlets and JSP book. It’s a superb book to read, one can enjoy reading and the concepts are taught in terms of process- like how they happen. Some time back i had recommended Head First Java. One can read the review here.

As it is the first time i am doing some thing in Servlets and Cookies, the below given example is a pretty simple one which explains the use of cookies in communication between client and server lasting more than one request.

The example consists of two servlets and two JSPs. The following are the servlets used:

CookieTest: This servlet creates and SETS the cookie into the response streame. The cookie stores the username entered in the text box in the index.jsp page. The code for CookieTest.java is given below:

import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 *
 * @author Mohamed Sanaulla
 */
public class CookieTest extends HttpServlet {
    /**
    * Handles the HTTP <code>POST</code> method.
    * @param request servlet request
    * @param response servlet response
    */
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        response.setContentType("text/html");
        String name= request.getParameter("username");
        Cookie cookie= new Cookie("username", name);
        cookie.setMaxAge(30*60);
        response.addCookie(cookie);

        RequestDispatcher view = request.getRequestDispatcher("cookieresult.jsp");
        view.forward(request, response);

    }

    /**
    * Returns a short description of the servlet.
    */
    public String getServletInfo() {
        return "CookieTest";
    }
}

In the above code snippet I have used the doPost() method- Why it is used i will come to it later when i will talk about index.jsp. In the doPost() method the value of the parameter “username” passed along with the HttpServletRequest object is assigned to a local variable “name” .

String name= request.getParameter("username"); //Getting the Name entered

Cookie object is then created passing “username” and name as the name/value pair.

Cookie cookie= new Cookie("username", name); //Cookie Constructor
cookie.setMaxAge(30*60); //Setting the duration for the cookie to last

The created cookie object is added to the response stream i.e added to the HttpServletResponse object which is then sent back to the client. Cookie is mainly useful for exchanging information between client and container which lasts for more than single request.

response.addCookie(cookie);// Adding cookie to the response object for use by Client

The Username details are then dispatched to another component in the Container to handle the client request. How is it sent? Sent by means of Cookie. In this case the username is dispatched to the JSP page “cookieresult.jsp” which will then handle accordingly.

<pre>RequestDispatcher view = request.getRequestDispatcher("cookieresult.jsp");
        view.forward(request, response);

Now coming to the “index.jsp” page:

<pre>
<!--index.jsp-->

    
        
        JSP Page
    
    
<h1>JSP Page</h1>

            User Name: 
            
        

    

index.jsp

index.jsp

There is no JSP written here. Its just simple HTML page with a Textbox and a submit button :). On clicking the submit button the request is sent to the servlet “CookieTest” mentioned earlier. Look at the code:


The name used in the action attribute is not the same as the name of the Servlet. It is given a different name- Client known URL name which is configured in the Deployment Descriptor (DD)web.xml.

I had mentioned earlier that i had used another jsp page- “cookieresult.jsp“. In the earlier code we had dispatched the request to this jsp to take over the proceedings. Yeah once u submit the username u will be directed to cookieresult.jsp in the process the CookieTest comes into play in the background.

cookieresult.jsp:


<!-- cookieresult.jsp-->

    
        
        JSP Page
    
    
        <a href="checkcookie.do"> Click Here</a>
    

cookieresult.jsp

cookieresult.jsp

The above page then calls the servlet “CheckCookie” which is mapped to URL /checkcookie.do.

CheckCookie: This is the main culprit 😉 Its not that way.. This is the servlet that writes to the response streame. What does it write? It writes the username to the response streame. From where does it get the username? Remember the Cookie sent earlier along with the response? Yes that cookie is carrying the information between the container components. And u must be thinking how come its been alive- the cookie object? Remember the MaxAge being set to 30 Minutes (30*60). Yes, the cookie lasts for 30 minurtes before its destroyed. This servlet gets the value from the cookie and writes it to the response streame.

CheckCookie.java:

<pre>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;

/**
 *
 * @author Mohamed Sanaulla
 */
public class CheckCooikie extends HttpServlet {
     /**
    * Handles the HTTP <code>GET</code> method.
    * @param request servlet request
    * @param response servlet response
    */
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        response.setContentType("text/html");
        PrintWriter out = response.getWriter();
        Cookie[] cookies = request.getCookies();
        if(cookies!=null)
        {
            for(Cookie c:cookies)
            {
                if(c.getName().equals("username"))
                {
                    String userName = c.getValue();
                    out.println("Hello "+userName);
                    break;

                }

            }
        }
    }
    /**
    * Returns a short description of the servlet.
    */
    public String getServletInfo() {
        return "Check Cookie";

    }
}

How are we going to get the Information from the Cookies:

 Cookie[] cookies = request.getCookies();
        if(cookies!=null)
        {
            for(Cookie c:cookies)
            {
                if(c.getName().equals("username"))
                {
                    String userName = c.getValue();
                    out.println("Hello "+userName);
                    break;

                }

            }
        }

The above code gets the Cookies from the request object and then checks for the cookie with name “username“, if found gets the value from the cookie and prints it to the response streame. In this example we have used only one Cookie.

Final Output

Final Output

I used Netbeans IDE for the above example. Will upload the screenshots of how to do it using Netbean soon. And also i would in the future try to post basics of Servlets, JSPs.

Advertisements

Categories: Java

Tagged as: , , ,

2 replies »

  1. This method is not really recommended. It’s better to store these types of data in the session. The session exists on the server side, so it cannot be tampered with.

    With this cookie method, a user could tamper with their cookie and possibly see another user’s data.

    Be careful using the session though, storing too much info could use too much server RAM. Instead of storing a User object in the session, store a Long representing the User ID. Then, look the user up from your DB.

    Like

  2. @Sam
    Thanks for the info!!!Yeah you are right one can use Session for this. But the session underlying uses either cookies or URL Rewriting. So was just trying with how one can use cookies 🙂

    Like

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s