Thursday 30 March 2017

Handling HTTP Requests and Responses, Using Cookies & Session Tracking - Java Tutorials

Handling HTTP Requests and Responses

The HttpServlet class provides specialized methods that handle the various types of HTTP requests. A servlet developer typically overrides one of these methods. These methods are doDelete( ), doGet( ), doHead( ), doOptions( ), doPost( ), doPut( ), and doTrace( ). A complete description of the different types of HTTP requests is beyond the scope of this book. However, the GET and POST requests are commonly used when handling form input. Therefore, this section presents examples of these cases.

Handling HTTP GET Requests

Here we will develop a servlet that handles an HTTP GET request. The servlet is invoked when a form on a Web page is submitted. The example contains two files. A Web page is defined in ColorGet.htm and a servlet is defined in ColorGetServlet.java. The HTML source code for ColorGet.htm is shown in the following listing. It defines a form that contains a select element and a submit button. Notice that the action parameter of the form tag specifies a URL. The URL identifies a servlet to process the HTTP GET request.

  <html>
  <body>
  <center>
  <form name="Form1"
    action="http://localhost:8080/examples/servlet/ColorGetServlet">
  <B>Color:</B>
  <select name="color" size="1">
  <option value="Red">Red</option>
  <option value="Green">Green</option>
  <option value="Blue">Blue</option>
  </select>
  <br><br>
  <input type=submit value="Submit">
  </form>
  </body>
  </html>

The source code for ColorGetServlet.java is shown in the following listing. The doGet( ) method is overridden to process any HTTP GET requests that are sent to this servlet. It uses the getParameter( ) method of HttpServletRequest to obtain the selection that was made by the user. A response is then formulated.

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

  public class ColorGetServlet extends HttpServlet {

    public void doGet(HttpServletRequest request,
      HttpServletResponse response)
    throws ServletException, IOException {

      String color = request.getParameter("color");
      response.setContentType("text/html");
      PrintWriter pw = response.getWriter();
      pw.println("<B>The selected color is: ");
      pw.println(color);
      pw.close();
    }
  }

Compile the servlet and perform these steps to test this example:
  1. Start Tomcat, if it is not already running.
  2. Display the Web page in a browser.
  3. Select a color.
  4. Submit the Web page.

After completing these steps, the browser will display the response that is dynamically generated by the servlet.

One other point: Parameters for an HTTP GET request are included as part of the URL that is sent to the Web server. Assume that the user selects the red option and submits the form. The URL sent from the browser to the server is

  http://localhost:8080/examples/servlet/ColorGetServlet?color=Red

The characters to the right of the question mark are known as the query string.

Handling HTTP POST Requests
Here we will develop a servlet that handles an HTTP POST request. The servlet is invoked when a form on a Web page is submitted. The example contains two files. A Web page is defined in ColorPost.htm and a servlet is defined in ColorPostServlet.java.

The HTML source code for ColorPost.htm is shown in the following listing. It is identical to ColorGet.htm except that the method parameter for the form tag explicitly specifies that the POST method should be used, and the action parameter for the form tag specifies a different servlet.

 <html>
 <body>
 <center>
 <form name="Form1"
   method="post"
   action="http://localhost:8080/examples/servlet/ColorPostServlet">
 <B>Color:</B>
 <select name="color" size="1">
 <option value="Red">Red</option>
 <option value="Green">Green</option>
 <option value="Blue">Blue</option>
 </select>
 <br><br>
 <input type=submit value="Submit">
 </form>
 </body>
 </html>

The source code for ColorPostServlet.java is shown in the following listing. The doPost( ) method is overridden to process any  HTTP POST requests that are sent to this servlet. It uses the getParameter ( ) method of HttpServletRequest to obtain the selection that was made by the user. A response is then formulated.

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

  public class ColorPostServlet extends HttpServlet {

    public void doPost(HttpServletRequest request,
      HttpServletResponse response)
    throws ServletException, IOException {

      String color = request.getParameter("color");
      response.setContentType("text/html");
      PrintWriter pw = response.getWriter();
      pw.println("<B>The selected color is: ");
      pw.println(color);
      pw.close();
    }
  }

Compile the servlet and perform the same steps as described in the previous section to test it.

Note: Parameters for an HTTP POST request are not included as part of the URL that is sent to the Web server. In this example, the URL sent from the browser to the server is:

  http://localhost:8080/examples/servlet/ColorGetServlet

The parameter names and values are sent in the body of the HTTP request.




Using Cookies

Now, let’s develop a servlet that illustrates how to use cookies. The servlet is invoked when a form on a Web page is submitted. The example contains three files as summarized here:

File  --  Description

AddCookie.htm:  Allows a user to specify a value for the cookie named MyCookie.

AddCookieServlet.java:  Processes the submission of AddCookie.htm.

GetCookiesServlet.java:  Displays cookie values.

The HTML source code for AddCookie.htm is shown in the following listing. This page contains a text field in which a value can be entered. There is also a submit button on the page. When this button is pressed, the value in the text field is sent to AddCookieServlet via an HTTP POST request.

 <html>
 <body>
 <center>
 <form name="Form1"
   method="post"
   action="http://localhost:8080/examples/servlet/AddCookieServlet">
 <B>Enter a value for MyCookie:</B>
 <input type=textbox name="data" size=25 value="">
 <input type=submit value="Submit">
 </form>
 </body>
 </html>

The source code for AddCookieServlet.java is shown in the following listing. It gets the value of the parameter named “data”. It then creates a Cookie object that has the name “MyCookie” and contains the value of the “data” parameter. The cookie is then added to the header of the HTTP response via the addCookie( ) method. A feedback message is then written to the browser.

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

  public class AddCookieServlet extends HttpServlet {

    public void doPost(HttpServletRequest request,
      HttpServletResponse response)
    throws ServletException, IOException {

      // Get parameter from HTTP request.
      String data = request.getParameter("data");

      // Create cookie.
      Cookie cookie = new Cookie("MyCookie", data);

      // Add cookie to HTTP response.
      response.addCookie(cookie);

      // Write output to browser.
      response.setContentType("text/html");
      PrintWriter pw = response.getWriter();
      pw.println("<B>MyCookie has been set to");
      pw.println(data);
      pw.close();
    }
  }

The source code for GetCookiesServlet.java is shown in the following listing. It invokes the getCookies( ) method to read any cookies that are included in the HTTP GET request. The names and values of these cookies are then written to the HTTP response. Observe that the getName( ) and getValue( ) methods are called to obtain this information.

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

  public class GetCookiesServlet extends HttpServlet {

    public void doGet(HttpServletRequest request,
      HttpServletResponse response)
    throws ServletException, IOException {

      // Get cookies from header of HTTP request.
      Cookie[] cookies = request.getCookies();

      // Display these cookies.
      response.setContentType("text/html");
      PrintWriter pw = response.getWriter();
      pw.println("<B>");
      for(int i = 0; i < cookies.length; i++) {
        String name = cookies[i].getName();
        String value = cookies[i].getValue();
        pw.println("name = " + name +
          "; value = " + value);
      }
      pw.close();
    }
  }

Compile the servlet and perform these steps:
  1. Start Tomcat, if it is not already running.
  2. Display AddCookie.htm in a browser.
  3. Enter a value for MyCookie.
  4. Submit the Web page.

After completing these steps you will observe that a feedback message is displayed by the browser.

Next, request the following URL via the browser:

  http://localhost:8080/examples/servlet/GetCookiesServlet

Observe that the name and value of the cookie are displayed in the browser. In this example, an expiration date is not explicitly assigned to the cookie via the setMaxAge( ) method of Cookie. Therefore, the cookie expires when the browser session ends. You can experiment by using setMaxAge( ) and observe that the cookie is then saved to the disk on the client machine.




Session Tracking

HTTP is a stateless protocol. Each request is independent of the previous one. However, in some applications, it is necessary to save state information so that information can be collected from several interactions between a browser and a server. Sessions provide such a mechanism.

A session can be created via the getSession( ) method of HttpServletRequest. An HttpSession object is returned. This object can store a set of bindings that associate names with objects. The setAttribute( ), getAttribute( ), getAttributeNames( ), and removeAttribute( ) methods of HttpSession manage these bindings. It is important to note that session state is shared among all the servlets that are associated with a particular client.

The following servlet illustrates how to use session state. The getSession( ) method gets the current session. A new session is created if one does not already exist. The getAttribute( ) method is called to obtain the object that is bound to the name “date”. That object is a Date object that encapsulates the date and time when this page was last accessed. (Of course, there is no such binding when the page is first accessed.) A Date object encapsulating the current date and time is then created. The setAttribute( ) method is called to bind the name “date” to this object.

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

  public class DateServlet extends HttpServlet {

    public void doGet(HttpServletRequest request,
      HttpServletResponse response)
    throws ServletException, IOException {

      // Get the HttpSession object.
      HttpSession hs = request.getSession(true);

      // Get writer.
      response.setContentType("text/html");
      PrintWriter pw = response.getWriter();
      pw.print("<B>");

      // Display date/time of last access.
      Date date = (Date)hs.getAttribute("date");
      if(date != null) {
        pw.print("Last access: " + date + "<br>");
      }

      // Display current date/time.
      date = new Date();
      hs.setAttribute("date", date);
      pw.println("Current date: " + date);
    }
  }

When you first request this servlet, the browser displays one line with the current date and time information. On subsequent invocations, two lines are displayed. The first line shows the date and time when the servlet was last accessed. The second line shows the current date and time.


Security Issues

In earlier chapters of this book, you learned that untrusted applets are constrained to operate in a “sandbox”. They cannot perform operations that are potentially dangerous to a user’s machine. This includes reading and writing files, opening sockets to arbitrary machines, calling native methods, and creating new processes. Other restrictions also apply.

Similar constraints also exist for untrusted servlets. Code that is loaded from a remote machine is untrusted. However, trusted servlets are not limited in this manner. Trusted servlets are those which are loaded from the local machine.

No comments:

Post a Comment