The GenericServlet Class

 < Free Open Study > 



The GenericServlet class is an abstract class implementation of the Servlet interface. It implements the methods as defined by the Servlet interface, and servlets normally extend from this class. In addition to those methods defined in the Servlet interface, GenericServlet defines several other methods. Let's now take a tour of the methods of this class. We'll group these methods by functionality.

Lifecycle Methods

Servlet initialization is carried out by an init() method:

    public void init(ServletConfig config)    public void init() 

You should recognize the first form of the init(ServletConfig) method; it is required by the Servlet interface. When called by the container, the GenericServlet implementation of the init(ServletConfig) method stores a reference to the ServletConfig object in the servlet, and then calls the second init() method above. This version of the init() method is provided as a convenience, to eliminate the need to call the superclass method (via super.init(config)) in your code.

start sidebar

If you choose to override the init(ServletConfig) method, it is up to you to make sure that it calls the superclass method, otherwise the reference to the ServletConfig object will be lost:

end sidebar

As we saw in the previous section, the following method processes the client requests and is called by the servlet container:

    public abstract void service(ServletRequest req, ServletResponse res) 

It is declared abstract, because subclasses must implement a service() method to process their request (this is the purpose of the servlet!).

Called by the servlet container, the destroy() method is overridden if there is any persistence of data required, or if resources must be released:

    public void destroy() 

Servlet Environment Methods

Aside from getServletConfig() and getServletName(), the GenericServlet class provides a number of additional methods relating to the servlet and its environment.

With the ServletContext object that is contained in the ServletConfig object, we can access information about the servlet container in which the servlet is running. Calling the following method returns this ServletContext object:

    public ServletContext getServletContext() 

The getInitParameterNames() method returns an Enumeration of the names of the initialization parameters for the servlet:

    public java.util.Enumeration getInitParameterNames() 

This allows the servlet to access all initialization parameters without having to know their names in advance. When we have retrieved these names, we can use the following method to access their values:

    public String getInitParameter(String name) 

If the named parameter does not exist, null is returned.

Every servlet is known to the servlet container by a name. As we will learn in Chapter 4, this can be configured in the web application set-up. Calling the following method will retrieve the name of this servlet's instance:

    public String getServletName() 

Utility Methods

Two logging methods are also provided by GenericServlet to allow the servlet to write to the web application's log file:

    public void log(String msg)    public void log(String message, java.lang.Throwable t) 

This is for debugging and development information mainly, but anything can be written to this file if required. It is also preferable to writing to the console. Frequently programmers are required to support production applications where they only have limited access to the server on which the application runs. Access may be limited to shared directories, such as log files, so it is good practice to use the log files rather than the console.

The location and name of the log file is normally specified on the application configuration, but the exact method is dependent on the container implementation.

A word of warning: while in test and pre-production environments verbose logging may be useful, in practice there can be performance implications for frequent logging for active, high-load applications. In production environments we should only be logging important information such as web application errors, security information and other critical information.

If we use the log files excessively in busy production environments not only do we suffer the I/O costs of writing to the file excessively (with the overall implications for the server performance), but also we can lose sight of the important and useful information in the logs. Logging limited at most to the entry and exit of methods (and parameters/return values) is useful to identify the source of a problem, but this should be restricted only to important methods and points in the process.

Creating a Basic Servlet

So far we have learnt the basic concepts behind the servlet API that allow us to create basic servlets. At this point we are ready to use what we have learnt, by developing a BasicServlet that extends from the GenericServlet class to output a basic HTML web page. The servlet will output the following information:

  • The name of the servlet (as known to the container)

  • The number of times that the servlet has been executed

  • The date and time that the servlet instance was initialized

  • The current date and time on the server (for comparison)

  • The servlet information available to the container

Once we have walked through the code, we will look at what we need to do to get this example running on the Catalina servlet container provided by the Tomcat web server.

    package basicServlets;    import javax.servlet.GenericServlet;    import javax.servlet.ServletConfig;    import javax.servlet.ServletRequest;    import javax.servlet.ServletResponse;    import javax.servlet.ServletException;    import java.io.IOException;    import java.io.PrintWriter;    import java.util.Date;    public class BasicServlet extends GenericServlet { 

The BasicServlet class extends from GenericServlet and implements the three Servlet lifecycle methods. The service() method is required, but overriding the initialization and destruction methods are optional. Additionally, we will also override the getServletInfo() method:

      private static int count = 0;      private static final Date initialDate = new Date();      private Date thisDate; 

We have three variables in this servlet. The first two are static. The integer count is used to monitor how many times the servlet has been run since the servlet was originally loaded (note that if the current servlet instance is unloaded it still maintains the count). Similarly, the initialDate object is designed to store the exact date and time the first instance was created. The thisDate object holds the exact date and time that the current instance was created. Realistically both the initialDate object and the thisDate object will be equal (or almost) as they are created on the first call. However, if this servlet instance was unloaded, or more than one instance was created, then these Date objects would differ.

In the init() method, we call the superclass init() method first to ensure this is processed and that the ServletConfig object reference is stored. We also initialise the thisDate variable here. Finally we also log the time the servlet instance was initialised. Also included is a (commented out) println() statement to the console so that you can see the initialization happening as you execute it:

      public void init(ServletConfig config) throws ServletException {        super.init(config);        thisDate = new Date();        //System.out.println("BasicServlet initialized at:" + thisDate);        log("BasicServlet initialized at:" + thisDate);      } 

The service() method will process the requests. In this case we output a simple HTML page using the PrintWriter object of the ServletResponse object:

      public void service(ServletRequest request, ServletResponse response)                                         throws ServletException, IOException { 

We first set the type of the data that we are going to send back to the client ("text/html") and then call the getWriter() method on the Response object. In the next section we will look at the ServletResponse interface in more detail:

       response.setContentType("text/html");       PrintWriter out = response.getWriter(); 

The HTML page itself is simply output as text, sent to the PrintWriter object's println() method:

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

We include the getServletName() method so we can see what the servlet container knows this servlet instance as:

       out.println("<body><h2>" + getServletName() + "</h2>");       out.println("This is a basic servlet.<br>");       out.println("<table><tr>"); 

We then output a small table with values that include the count of how many times the servlet has been executed since startup:

       out.println("<tr><td><b>BasicServlet executed:</b></td><td>" +                     (++count) + " time(s)</td></tr>"); 

We also output the time the first instance of the servlet was initialized, the time the current instance was initialized, and the current time for comparison:

       out.println("<tr><td><b>BasicServlet initialized at:</b></td><td>" +                     initialDate + "</td></tr>");       out.println("<tr><td><b>This instance initialized at:</b></td><td>" +                     thisDate + "</td></tr>");       out.println("<tr><td><b>Current Time:</b></td><td>" +                     new Date() + "</td></tr>"); 

Finally we call the getServletInfo() method to see what this information is, and close the page:

       out.println("<tr><td><b>Servlet Information:</b></td><td>" +                     getServletInfo() + "</td></tr></body></html>");       out.close();     } 

We have implemented the getServletInfo() method with information about the servlet version and date:

      public String getServletInfo() {        return "basicServlets.BasicServlet; Version: 1.0; (C) 2002.";      } 

Finally we implement a destroy() method. It's not really necessary here (we haven't opened or created any resources that need to be explicitly released), but in this case, for illustrative purposes, it prints to the log when it is destroyed. Again there is a System.out.println() statement you can uncomment, in case you want to see this process on the console:

      public void destroy() {        //System.out.println("BasicServlet: destroy method called");        log("destroy method called");      }    } 

We have just created a basic servlet extending from the GenericServlet, which is our first step towards building full web applications. Throughout the chapter we will build on this to enhance our understanding of the Servlet API classes and interfaces. First we will have a look at how to compile this servlet and execute it on Tomcat.

Compiling and Running Servlets on Tomcat

In this section we will explain how to get your servlet running on Tomcat.

Appendix A contains instructions on how to acquire, install and setup Tomcat on your computer. This section assumes that you have a basic installation of Tomcat running on your system.

To get the servlet running, we need to create a directory structure to house the servlets. First locate your web applications directory in Tomcat, which will be located in the %CATALINA_HOME%\webapps directory (here %CATALINA_HOME% is the root directory of your Tomcat installation).

We need to create the application directory structure as shown below in the webapps directory:

     servletAPI\                WEB-INF                classes\                        basicServlets\                        personalPortal\                src\                    basicServlets\                    personalPortal\ 

Make sure the names of the folders are exactly as written above (including the same case). Place the BasicServlet.java file in the basicServlets subfolder of the source code directory (src), ready for compilation. Then compile it from the src directory using the javac compiler, including %CATALINA_HOME%\common\lib\servlet.jar in your classpath. Finally, move the resulting class file into the classes\basicServlets directory, and restart Tomcat.

When the server is restarted, you can access the servlet on the following URL:

http://localhost:8080/servletAPI/servlet/basicServlets.BasicServlet

If you have successfully deployed your servlet, you should see the following page, which shows the information we wanted to know about the servlet:

click to expand

We are now going to expand our servlet horizons. We will start by considering the request-response cycle of the servlet model, how the Servlet API wraps up the client request information, and our servlet's response in the provided interfaces.



 < 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