An Example Servlet





An Example Servlet

Now let's examine the code for a complete servlet. As we mentioned, a single URL presents a servlet to the outside world, exactly as a CGI script is represented to the Web browser. However, unlike a CGI script, information about the request made of the servlet is not passed as environment variables that must be parsed. It is instead given to the servlet as a set of well-defined Java objects. To illustrate this point, let's examine the simplest possible servlet, the Hello World example.





/**

 * This class is a simple sample servlet

 */

import java.io.*;

import javax.servlet.*;

import javax.servlet.http.*;



public class HelloServlet extends HttpServlet {

/**

 * This method handles an HTTP GET request and outputs

 * HTML to print "Hello IBM WebSphere World" to a browser.

 */

public void doGet (HttpServletRequest req, HttpServletResponse res) res)

throws ServletException, IOException{

     PrintWriter out = null;

    res.setContentType("text/html");

    out = res.getWriter ();

    out.println("<html>");

    out.println("<head><title>Sample</title></head>");

    out.println("<body>");

    out.println("Hello IBM WebSphere World!");

    out.println("</body>");

    out.println("</html>");

}

} To run this servlet, assuming the host localhost is defined, the Web and application server are appropriately configured to have a context root of helloctx, and that the HelloServlet.class file is placed in the appropriate location. You would enter the URL http://localhost/helloctx/HelloServlet on the URL line of a Web browser. The words Hello IBM WebSphere World would then be shown in your Web browser.

Our simple servlet class extends the class javax.servlet.http.HttpServlet. Think about HttpServlet and its descendents as being servlets that speak HTTP as their native language. The key thing to understand about HttpServlet is that they typically handle GET and POST requests. HttpServlet subclasses handle one or both of these methods by overriding either doGet() or doPost()respectively. In our case we're overriding doGet(), so the information sent back will be displayed on a client's browser if she types in the URL corresponding to our servlet (e.g., send a GET request).

Which Servlet Methods Do I Override?

The HttpServlet class defines a special do [Request Type] method (or a service handler) for each of the HTTP Request types that were previously discussed. These methods are simply defined as protected void methods—they are not declared abstract. The service() method defined in HttpServlet is written to automatically call the appropriate service handler based on the type of request that is received. In your servlets, you will generally choose to override only a small subset of these methods—generally doGet() or doPost().

Sometimes, the same servlet will need to handle both GET and POST requests. If the code in each of these methods is different (e.g., you want to do something different for each request type) you should override both doGet() and doPost(). On the other hand, if you need to implement the same logic for both request types, then you should probably override service() instead.


Now, exactly how is the reply Hello IBM WebSphere World sent back to the browser? As you can see from the example, the route we use is an object that implements the interface HttpServletResponse. HttpServletResponse allows you to do several things:

  • Set the MIME type (or content-type) of the HTTP response header. This can be any valid MIME type (like image/jpeg or audio/wav. Most of the time the response type will be text/html, which means you are sending back HTML to be interpreted and displayed by the browser. The method setContentType(String) sets the content type.

  • Set the HTTP header values with setHeader(String, String). This is useful if you want to disable browser and server page caching for a response page. Note that all headers must be sent before any output is written to the servlet output stream. This is because HTTP specifies that headers appear before the message body in the response. The headers are implicitly written to the servlet output stream the first time the servlet explicitly writes to the stream.

  • Obtain a PrintWriter for output with getWriter(). When you are sending HTML as your content type, you want to make it human-readable. PrintWriter facilitates this by adding CR/LF on the end of your text lines with the println() method . Additionally, other writers allow for National Language support and translation of Unicode characters to UTF. In all other respects, PrintWriter acts like an output stream. You can also obtain an OutputStream with getOutputStream().

  • Redirect the browser to a different page with sendRedirect(String)

In our example we're simply setting the content type of the response, opening a PrintWriter for output, and sending several lines of HTML text back to the browser. This is what most servlets end up doing for output. They may obtain part of the information they display from an outside source (say, from a socket to another server, or a JDBC query). However, the mechanics of sending HTML to the client is the same regardless of the source.

Those of you with keen attention to detail will have noticed that doGet()also takes a second parameter, HTTPServletRequest, which we did not use. Servlets that need to process input from the browser use this interface. The code in a doGet() or doPost() method typically use the HttpServletRequest methods getParameterNames(), getParameter(), and getParameterValues() to read in the HTTP parameters sent as part of a POST request or of a query string.

The servlet then makes decisions based on those parameters, or records them to persistent storage. If we make a small modification to the HelloServlet servlet, we can send a message parameter to the servlet and have it display that message instead of the common "Hello IBM WebSphere World!" message. Examine the new code and note the lines in bold type.





        /**

         * This class is a simple sample servlet, which takes a message parameter

         */

        import java.io.*;

        import javax.servlet.*;

        import javax.servlet.http.*;



        public class HelloServlet extends HttpServlet {

        /**

         * This method handles an HTTP GET request and outputs

         * HTML to print "Hello IBM WebSphere World" to a browser.

         */

        public void doGet (HttpServletRequest req, HttpServletResponse res)



        throws ServletException, IOException{

        PrintWriter out = null;

        res.setContentType("text/html");

        out = res.getWriter ();



        // Changed Code

        String theMessage = req.getParameter("mymessage");

        if (theMessage == null) {

        theMessage = "Hello IBM WebSphere World!";

        }

           out.println("<html>");

           out.println("<head><title>Sample</title></head>");

           out.println("<body>");

           out.println(theMessage);

           out.println("</body>");

           out.println("</html>");

        }

}

To run this servlet you would use the same URL as before with an additional Query-String. An example URL of this type might be: http://localhost/servlet/HelloServlet?mymessage=Hello+Parameter. The words Hello Parameter would then be shown in your Web browser. Without the + sign in the URL the space and Parameter portion of the URL would be lost. The + can be used for spaces to ensure that the full message will survive the network send. You could use %20 to represent the space as well.

If you examine the code changes, you can see that the difference is the use of the req.getParameter("mymessage") to obtain the data passed on the URL. The getParameter() method takes one argument which must be a String and is the case-sensitive identifier of the parameter in the request. The name of this parameter key must match exactly the name used on the Query-String. If it does not match, getParameter()will return a null. If null is returned, then the method will set the variable theMessage to "Hello WebSphere World!" The last thing done to the code was to change the out.println() to use the newly created variable, theMessage.

Some Comments about HelloServlet

One of the things that makes it difficult to explain the servlet API is that the simplest examples, like the one we have shown here, are not truly representative of the way in which servlets are used in practice. In particular, you should avoid hard-coding HTML into your servlets. Remember from our overview discussion of the J2EE APIs and the MVC design pattern that servlets will act as mediators that will tie together domain logic and display logic in the form of JSPs. In general, you should avoid placing HTML in your servlet code; if you place HTML in your servlets, it becomes more difficult to change the look of your Web sites since you must change your Java code even if all that changes is the HTML that is returned.



     Python   SQL   Java   php   Perl 
     game development   web development   internet   *nix   graphics   hardware 
     telecommunications   C++ 
     Flash   Active Directory   Windows