Implementing HTTP Servlets

 < Free Open Study > 



In this section we are going to use what we have learned so far to develop some HTTP servlets, and then run them. We'll start off with a few relatively simple examples, and then at the end of the chapter we'll implement a more complex web application based upon HTTP servlets.

Implementing HttpRequestResponseServlet

Let's start by looking at two basic HTTP servlets. The first is a development of the RequestResponseServlet from Chapter 2. Here we will develop a similar HttpRequestResponseServlet, however, this class will extend from the HttpServlet class and will demonstrate how we can extract HTTP-specific client information such as headers, cookies, and the request path. We will also set some cookies each time we load the page, so we will see our cookies being returned to the server with each refresh. Here's what the HTTP request and response tables look like:

click to expand

This example also uses the HTMLTable utility class developed in Chapter 2, that allows us to build a fully formatted HTML table of data to send to the client.

The HttpRequestResponseServlet is similar to that in Chapter 2, so if you are familiar with the examples there you should focus on the HTTP-specific methods available to extract client request data:

    package httpExamples;    import javax.servlet.*;    import javax.servlet.http.*;    import java.io.IOException;    import java.io.PrintWriter;    import java.util.Enumeration;    import java.util.Date;    public class HttpRequestResponseServlet extends HttpServlet {      private static int cookiesCreated = 0; 

First we store a count of cookies created by the servlet, and we will use this to set the name of the cookies. Then, the doGet() method calls the getHttpRequestTable and the getHttpResponseTable methods with their respective Request and Response objects. These extract the data and prepare an HTML table for return to the client.

      public void doGet(HttpServletRequest request,                        HttpServletResponse response)                        throws ServletException, IOException {        StringBuffer httpRequestTable = getHttpRequestTable(request);        StringBuffer httpResponseTable = getHttpResponseTable(response); 

Then we output the HTML page, including the two HTML tables just created.

        response.setContentType("text/html");        PrintWriter out = response.getWriter();        //HTML page        out.println("<html><head><title>RequestResponseServlet</title></head>");        out.println("<body><h1>Request Information</h1>" + httpRequestTable);        out.println("<hr><h1>Response Information</h1>" + httpResponseTable);        out.println("</body></html>");        out.close();      } 

The getHttpRequestTable() method extracts data from the client Request object using HTTP-specific methods. We extract the request method used, the query string (if any) and some path information, and add them to the table:

      private StringBuffer getHttpRequestTable(HttpServletRequest request) {        HTMLTable table = new HTMLTable();        table.appendRow("HTTP Request Method", request.getMethod());        table.appendRow("Query String", request.getQueryString());        table.appendRow("Context Path", request.getContextPath());        table.appendRow("Servlet Path", request.getServletPath()); 

Next we extract all of the cookies associated with this request and add them to the table. If you run this example and do not see any cookies (assuming that you have cookies turned on in your browser) refresh the page and you will see cookies added to the request. This is because they are added to the Response object each time and sent back to the client:

        Cookie[] ourCookies = request.getCookies();        if (ourCookies == null || ourCookies.length == 0) {          table.appendRow("Cookies", "NONE");        } else {          for (int i = 0; i < ourCookies.length; i++) {            String cookieName = ourCookies[i].getName();            String cookieValue = ourCookies[i].getValue();            table.appendRow("Cookie: <code>" + cookieName + "</code>",                             cookieValue);          }        } 

Next we are going to extract the header information. If you know the specific header that you are interested in you can call the request.getHeader(String) method with the name, and receive the value of the header (or null if it doesn't exist). However, we can extract an Enumeration of all of the request headers and use a while loop to iterate through and extract all of the values of the headers and then process them, or in this case, include them in our table:

        Enumeration e = request.getHeaderNames();        while (e.hasMoreElements()) {          String headerName = (String)e.nextElement();          String headerValue = request.getHeader(headerName);          table.appendRow("Header: <code>" + headerName + "</code>",                           headerValue);        }        return table.toStringBuffer();      } 

The getHttpResponseTable() method adds a cookie to the response sent to the client and includes the details in the table. The cookie's name is the current number of times this servlet has been called, and the current date and time, provided by the Date object:

      private StringBuffer getHttpResponseTable(HttpServletResponse response) {        HTMLTable table = new HTMLTable();        int cookieCount = cookiesCreated++;        String name = Integer.toString(cookieCount);        String value = new Date(System.currentTimeMillis()).toString();        Cookie cookie = new Cookie(name, value);        response.addCookie(cookie);        table.appendRow("Cookie Added:<code>" + name + "</code>", value);        return table.toStringBuffer();      }    } 

Compiling and Running the Example

To run the examples we need to set up the web application. Create a web application in the webapp directory of Tomcat called httpServlet that has the following subdirectories:

    httpServlet/                WEB-INF/                        classes/                                httpExamples                        src/                           httpExamples 

Place the HttpRequestResponseServlet source code, along with the HTMLTable source code, into the src/httpExamples directory, and compile the code. Then move the classes to the classes/httpExamples directory.

Finally, to run your code, restart Tomcat and go to:

http://localhost:8080/httpServlet/servlet/httpExamples.HttpRequestResponseServlet

Implementing QuizServlet

This example presents the QuizForm.html form to the user and asks them to answer three questions. The QuizServlet retrieves the quiz parameters and calculates how well the user did. This example demonstrates using the HTTP doGet() and doPost() methods. It also shows how to extract and process parameters in order to prepare a return web page.

First, here's the QuizForm.html file that contains the Quiz questions:

    <html>    <head><title>Quiz</title></head>    <body>      <h2>The Quiz</h2>      <form method="post" action="servlet/httpExamples.QuizServlet">      <table>        <tr>          <td><b>Name:</b></td>          <td><input type="text" name="name" size=20></td>        </tr>        <tr>          <td><b>What is the capital of Australia?</b></td>          <td>&nbsp;<br>            <input type="radio" name="australia" value="Sydney"> Sydney <br>            <input type="radio" name="australia" value="Canberra">                                                        Canberra<br>&nbsp;          </td>        </tr>        <tr>          <td><b>What is the capital of Brazil?</b></td>          <td>&nbsp;<br>            <input type="radio" name="brazil" value="RioDeJaneiro">                                                     Rio de Janeiro<br>            <input type="radio" name="brazil" value="Brasilia">                                                     Brasilia<br>&nbsp;          </td>        </tr>        <tr>          <td><b>What is the capital of Ireland?</b></td>          <td>&nbsp;<br>            <input type="radio" name="ireland" value="Dublin"> Dublin<br>            <input type="radio" name="ireland" value="Galway"> Galway<br>&nbsp;          </td>        </tr>        <tr>          <td colspan=2 align="middle">            <input type="submit" value="Submit Answers">            <input type="reset" value="Reset Answers">          </td>        </tr>      </table>      </form>    </body>    </html> 

The page asks three questions regarding capital cities:

click to expand

Depending on the choice made, the correct (or incorrect) parameters get sent to the servlet.

The QuizServlet opens with a number of static Strings that contain information about the questions and answers:

    package httpExamples;    import javax.servlet.*;    import javax.servlet.http.*;    import java.io.*;    import java.util.*;    public class QuizServlet extends HttpServlet {      private static final String AUSTRALIA = "australia";      private static final String AUSTRALIA_CAPITAL = "Canberra";      private static final String BRAZIL = "brazil";      private static final String BRAZIL_CAPITAL = "Brasilia";      private static final String IRELAND = "ireland";      private static final String IRELAND_CAPITAL = "Dublin";      private static final String NAME = "name"; 

The doGet() method processes the form submission. First it prepares a count variable to count the correct answers, and then it extracts the parameters from the request:

      public void doGet(HttpServletRequest request,                        HttpServletResponse response)                        throws ServletException, IOException {        int count = 0;        String name = request.getParameter(NAME);        String answerAustralia = request.getParameter(AUSTRALIA);        String answerBrazil = request.getParameter(BRAZIL);        String answerIreland = request.getParameter(IRELAND); 

Here the doGet() method outputs the HTML page. If a name was supplied as a parameter, it is displayed on the page:

        response.setContentType("text/html");        PrintWriter out = response.getWriter();        out.println("<html>");        out.println("<head><title>QuizServlet</title></head>");        out.println("<body>");        if (name != null && name.trim().length() > 0) {          out.println("<h1>Welcome " + name + "</h1>");        } else {          out.println("<h1>Welcome</h1>");        } 

The doQuestion() method calls output and displays a response that depends on whether the question was correctly answered, and updates the count. The score is then printed out:

        count = count + doQuestion(out, 1, answerAustralia, AUSTRALIA_CAPITAL);        count = count + doQuestion(out, 2, answerBrazil, BRAZIL_CAPITAL);        count = count + doQuestion(out, 3, answerIreland, IRELAND_CAPITAL);        out.println("<hr width=\"25%\" align=\"left\">");        out.println("You scored " + count + " out of 3"); 

After the score, we identify the browser software being used by the client from the user-agent header. If this has "MSIE" in it then this is a Microsoft browser:

        String userAgent = request.getHeader("user-agent");        if (userAgent != null && userAgent.indexOf("MSIE") != -1) {          out.println(" using Microsoft browser.");        } else if (userAgent != null) {          out.println(" using Non-Microsoft browser.");        }        out.println("</body></html>");      } 

Here is an important point. The doPost() method forwards the request to doGet() to process the request. In fact the HTTP request is a POST request as the HTML form specifies a POST request. Here we can see that processing a GET or POST request has no programmatic differences. We can process both GET and POST requests in the same way:

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

Finally we have an auxiliary method to process the questions:

      private int doQuestion(PrintWriter out, int number,                             String answer, String solution) {        out.println("<h2>Question " + number + "</h2>");        if (answer != null &&            solution.equalsIgnoreCase(answer)) {          out.println("<b>Correct</b>");          return 1;        } else {          out.println("<b>Wrong:</b> The correct answer is " + solution);          return 0;        }      }    } 

Here's a typical response that the servlet will produce when the HTML form from QuizForm.html is submitted:

click to expand

Compiling and Running the Example

Place the QuizForm HTML page in the top level of the httpServlet directory. Place all of the Java source code in the src/httpExamples directory, compile them, and move the classes to the classes/httpExamples directory.

To run your code, go to http://localhost:8080/httpServlet/QuizForm.html to fill in the form. When you submit the form, the request will be passed to http://localhost:8080/httpServlet/servlet/httpExamples.QuizServlet.



 < Free Open Study > 



Professional Java Servlets 2.3
Professional Java Servlets 2.3
ISBN: 186100561X
EAN: 2147483647
Year: 2006
Pages: 130

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net