Section 18.4. How to Write a Servlet


18.4. How to Write a Servlet

So how do you write a servlet? You may already have figured it out, from what we've described so far. You need to:

  • Write a Java class that extends HttpServlet

  • In that class, write the following methods:

    • init()

    • destroy()

    • doGet() and/or doPost()

That's the basic idea. There are lots of details about what arguments are supplied, what other resources are available, what methods can be used to get at parameters, and so on. We'll discuss some of those in our example servlet.

Let's start with a simplistic servlet, one that will dynamically generate the "Hello, world" string as a Web page (Example 18.1).

Example 18.1. A "Hello, world" servlet
 /*  * HiServlet.java  */ package net.multitool.servlet; import javax.servlet.*; import javax.servlet.http.*; /**  * Simple Servlet that generates a page of HTML  */ public class HiServlet   extends HttpServlet {   /**    * Think of this as the constructor for the servlet.    * We need do nothing for our example,    * but we should call our parent object.    */   public void   init(ServletConfig config)     throws ServletException   {     super.init(config);   } // init   /**    * Called when the Web server is shutting down    * or wants to shut down this particular servlet.    * We need do nothing.    */   public void   destroy()   {   } // destroy   /**    * Handles the HTTP GET method.    * @param request servlet request    * @param response servlet response    */    protected void    doGet(HttpServletRequest request, HttpServletResponse response)      throws ServletException, java.io.IOException    {    doBoth(request, response);    } // doGet    /**     * Handles the HTTP POST method.     * @param request servlet request     * @param response servlet response     */    protected void    doPost(HttpServletRequest request, HttpServletResponse response)      throws ServletException, java.io.IOException    {      doBoth(request, response);    } // doPost    /**     * Requests for both HTTP GET and POST methods come here,     * because we're not doing anything different     * between the two request types. This way we need only one     * version of the code that does the real work.     * @param request servlet request     * @param response servlet response     */    protected void    doBoth(HttpServletRequest request, HttpServletResponse response)      throws ServletException, java.io.IOException    {      java.io.PrintWriter out = response.getWriter();      response.setContentType("text/html");      /* output our page of html */      out.println("<html>");      out.println("<head>");      out.println("<title>A Java Servlet</title>");      out.println("</head>");      out.println("<body>");      out.println("Hello, world.");      out.println("</body>");      out.println("</html>");      out.close();    } // doBoth    /**     * Returns a short description of the servlet.     */    public String    getServletInfo()    {      return "Very Simple Servlet";    } // getServletInfo() } // class HiServlet 

Whew! That is a lot of code for only a simple "Hello, world," but remember that this is not just a run-on-your-desktop application. This is a network-based servlet that can respond to concurrent requests from across the network and talk to Web browsers. There's a lot of plumbing that needs to be connected to a Web server for the servlet to run, and that's what most of this code isjust the connections. The other verbose part is all of the HTML that we spit out around our message. You can make it even more elaborate, with background colors and other HTML decorations if you want to try it yourself.

Once you've written a servlet, though, you can't just run it from the command line like any Java class. [1] Much of the work of a servlet is done behind the scenes by the Web server (e.g., Tomcat). The tougher question is, "How do you run a servlet?" That involves issues of configuring the Web server, setting up directory locations, and so forth. It's the subject of the next chapter.

[1] Well, actually, you could if it had a main() method defined. Our example doesn't, but a servlet class is still a Java class, and you might define a public static void main() method that would allow you to run it from the command line as a way to drive the rest of the class for simple testing. Of course, such a simple test harness wouldn't be driving a Web browser, and so on but technically it is possible. We didn't want to lie to you.

Once you've deployed this servlet (by reading the next chapter and/or with help from your IDE), you can run the servlet and talk to it via your browser. We've pointed a browser window at one such deployment to get a highly uninteresting Web page (Figure 18.2) whose HTML source (in your browser menu, select View> Page Source) is shown in Figure 18.3.

Figure 18.2. A very simple page from our servlet


Figure 18.3. The servlet-generated source of our simple page




    Java Application Development with Linux
    Java Application Development on Linux
    ISBN: 013143697X
    EAN: 2147483647
    Year: 2004
    Pages: 292

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