ServletContext
The javax.servlet.ServletContext interface represents a Servlet's view of the Web Application it belongs to. Through the ServletContext interface, a Servlet can access raw input streams to Web Application resources, virtual directory translation, a common mechanism for logging information, and an application scope for binding objects. Individual container vendors provide specific implementations of ServletContext objects, but they all provide the same functionality defined by the ServletContext interface.
Initial Web Application Parameters
Previously in this chapter initial parameters for use with individual Servlets were demonstrated. The same functionality can be used on an application-wide basis to provide initial configuration that all Servlets have access to. Each Servlet has a ServletConfig object accessible by the getServletConfig() method of the Servlet. A ServletConfig object includes methods for getting initial parameters for the particular Servlet, but it also includes the getServletContext() method for accessing the appropriate ServletContext instance. A ServletContext object implements similar getInitParam() and getInitParamNames() methods demonstrated for ServletConfig. The difference is that these methods do not access initial parameters for a particular Servlet, but rather parameters specified for the entire Web Application.
Specifying application-wide initial parameters is done in a similar method as with individual Servlets, but requires replacement of the init-param element with the context-param element of Web.xml, and requires the tag be placed outside any specific servlet tag. Occurrences of context-param tags should appear before any Servlet tags. A helpful use of application context parameters is specifying contact information for an application's administration. Using the current jspbook web.xml, an entry for this would be placed as follows.
... <web-app> <context-param> <param-name>admin email</param-name> <param-value>admin@jspbook.com</param-value> </context-param> <servlet> <servlet-name>helloworld</servlet-name> <servlet-class>com.jspbook.HelloWorld</servlet-class> ...
We have yet to see how to properly handle errors and exceptions thrown from Servlets, but this initial parameter is ideal for error handling Servlets. For now, create a Servlet that assumes it will be responsible for handling errors that might arise with the Web Application. In Chapter 4 we will show how to enhance this Servlet to properly handle thrown exceptions, but for now pretend a mock error was thrown. Save the code in Listing 2-18 as MockError.java in the /WEB-INF/classes/com/jspbook directory of the jspbook Web Application.
Listing 2-18. MockError.java
package com.jspbook; import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class MockError extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { response.setContentType("text/html"); PrintWriter out = response.getWriter(); out.println("<html>"); out.println("<head>"); out.println("<title>An Error Has Occurred!</title>"); out.println("</head>"); out.println("<body>"); ServletContext sc = getServletConfig().getServletContext(); String adminEmail = sc.getInitParameter("admin email"); out.println("<h1>Error Page</h1>"); out.print("Sorry! An unexpected error has occurred."); out.print("Please send an error report to "+adminEmail+"."); out.println("</body>"); out.println("</html>"); } }
Reload the jspbook Web Application and browse to http://127.0.0.1/jspbook/MockError to see the page with the context parameter information included. Figure 2-19 shows what the MockError Servlet looks like when rendered by a Web browser.
Figure 2-19. Browser Rendering of the MockError Servlet
Notice the correct context parameter value was inserted in the error message. This same parameter might also be used in other various Servlets as part of a header or footer information. The point to understand is that this parameter can be used throughout the entire Web Application while still being easily changed when needed.
Application Scope
Complementing the request scope, a ServletContext instance allows for server-side objects to be placed in an application-wide scope34. This type of scope is ideal for placing resources that need to be used by many different parts of a Web Application during any given time. The functionality is identical to that as described for the HttpRequest object and relies on binding objects to a ServletContext instance. For brevity this functionality will not be iterated over again, but will be left for demonstration in later examples of the book.
It is important to note that an application scope should be used sparingly. Objects bound to a ServletContext object will not be garbage collected until the ServletContext is removed from use, usually when the Web Application is turned off or restarted. Placing large amounts of unused objects in application scope does tax a server's resources and is not good practice. Another issue (that will be gone into in more detail later) is that the ServletContext is not truly application-wide. If the Web Application is running on multiple servers (say, a Web farm), then there will be multiple ServletContext objects; any updates to one ServletContext on one server in the farmer will not be replicated to the other ServletContext instances.
Virtual Directory Translation
All the resources of a Web Application are abstracted to a virtual directory. This directory starts with a root, "/", and continues on with a virtual path to sub-directories and resources. A client on the World Wide Web can access resources of a Web Application by appending a specific path onto the end of the HTTP address for the server the Web Application runs on. The address for reaching the jspbook Web Application on your local computer is http://127.0.0.1. Combining this address with any virtual path to a Web Application resource provides a valid URL for accessing the resource via HTTP.
A Web Application's virtual directory is helpful because it allows fictitious paths to link to real resources located in the Web Application. The only downside to the functionality is that Web Application developers cannot directly use virtual paths to obtain the location of a physical resource. To solve this problem, the ServletContext object provides the following method:
getRealPath(java.lang.String path)35
The getRealPath() method returns a String containing the real path for a given virtual path. The real path represents the location of the resource on the computer running the Web Application.
To compliment the getRealPath() method, the ServletContext object also defines methods for obtaining a listing of resources in a Web Application or for an InputStream or URL connection to a particular resource:
-
getResourcePaths(java.lang.String path): The getResourcePaths() method returns a java.util.Set of all the resources in the directory specified by the path. The path must start from the root of the Web Application, "/".
-
getResourceAsStream(java.lang.String path): The getResourceAsStream() method returns an instance of an InputStream to the physical resource of a Web Application. This method should be used when a resource needs to be read verbatim rather than processed by a Web Application.
-
getResource(java.lang.String path): The getResource() method returns a URL to the resource that is mapped to a specified path. This method should be used when a resource needs to be read as it would be displayed to a client.
It is important to remember that a Web Application is designed to be portable. Hard coding file locations in Servlet code is not good practice because it usually causes the Servlet not to work when deployed on a different server or if the Web Application is run directly from a compressed WAR file. The correct method for reading a resource from a Web Application is by using either the getResource() or getResourceAsStream() methods. These two methods ensure the Servlet will always obtain access to the desired resource even if the Web Application is deployed on multiple servers or as a compressed WAR.
The most common and practical use for virtual directory translation is for accessing important flat files packaged with a Web Application. This primarily includes configuration files but is also used for miscellaneous purposes such as simple flat file databases. An ideal example would be one involving a complex Servlet using a custom configuration file; however, a complex Servlet like this has yet to appear in this book. For a demonstration, a simple Servlet will be created that reads raw files and resources from a Web Application (Listing 2-19). While not necessary for most real-world uses, this Servlet is ideal for learning as it effectively shows the source code of an entire Web Application.
Listing 2-19. ShowSource.java
package com.jspbook; import java.io.*; import javax.servlet.*; import javax.servlet.http.*; import java.util.*; public class ShowSource extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { PrintWriter out = response.getWriter(); // Get the ServletContext ServletConfig config = getServletConfig(); ServletContext sc = config.getServletContext(); // Check to see if a resource was requested String resource = request.getParameter("resource"); if (resource != null && !resource.equals("")) { // Use getResourceAsStream() to properly get the file. InputStream is = sc.getResourceAsStream(resource); if (is != null) { response.setContentType("text/plain"); StringWriter sw = new StringWriter(); for (int c = is.read(); c != -1; c = is.read()) { sw.write(c); } out.print(sw.toString()); } } // Show the HTML form. else { response.setContentType("text/html"); out.println("<html>"); out.println("<head>"); out.println("<title>Source-Code Servlet</title>"); out.println("</head>"); out.println("<body>"); out.println("<form>"); out.println("Choose a resource to see the source.<br>"); out.println("<select name=\"resource\">"); // List all the resources in this Web Application listFiles(sc, out, "/"); out.println("</select><br>"); out.print("<input type=\"submit\" "); out.println("value=\"Show Source\">"); out.println("</body>"); out.println("</html>"); } } // Recursively list all resources in Web App void listFiles(ServletContext sc, PrintWriter out, String base){ Set set = sc.getResourcePaths(base); Iterator i = set.iterator(); while (i.hasNext()) { String s = (String)i.next(); if (s.endsWith("/")) { listFiles(sc, out, s); } else { out.print("<option value=\""+s); out.println("\">"+s+"</option>"); } } } }
Save Listing 2-15 as ShowSource.java in the /WEB-INF/classes/com/jspbook directory of the jspbook Web Application. Compile the code and deploy the Servlet to the /ShowSource path extension of the jspbook Web Application, and after reloading the Web Application, browse to http://127.0.0.1/jspbook/ShowSource. Figure 2-20 shows what a browser rendering of the Servlet's output looks like.
Figure 2-20. Browser Rendering of the ShowSource Servlet
The Servlet uses the getResourcePaths() method to obtain a listing of all the files in the Web Application. After selecting a file, the Servlet uses the getResourceAsStream() method to obtain an InputStream object for reading and displaying the source code of the resource.
Application-Wide Logging
A nice but not commonly used feature of Servlets is Web Application-wide logging. A ServletContext object provides a common place all Servlets in a Web Application can use to log arbitrary information and stack traces for thrown exceptions. The advantage of this functionality is that it consolidates the often odd mix of custom code that gets used for logging errors and debugging information. The following two methods are available for logging information via a Web Application's ServletContext:
-
log(java.lang.String msg): The log() method writes the specified string to a Servlet log file or log repository. The Servlet API only specifies a ServletContext object implement these methods. No specific direction is given as to where the logging information is to be saved and or displayed. Logged information is sent to System.out or to a log file for the container.
-
log(java.lang.String message, java.lang.Throwable throwable): This method writes both the given message and the stack trace for the Throwable exception passed in as parameters. The message is intended to be a short explanation of the exception.
With J2SDK 1.4 the Servlet logging feature is not as helpful as it has previously been. The main advantage of the two log() methods is that they provided a common place to send information regarding the Web Application. Most often, as is with Tomcat, a container also allowed for a Servlet developer to write a custom class to handle information logged by a Web Application. This functionality makes it easy to customize how and where Servlet logging information goes. The downside to using the ServletContext log() methods is that only code that has access to a ServletContext object can easily log information. Non-Servlet classes require a creative hack to log information in the same manner. A better and more commonly used solution for Web Application logging is to create a custom set of API that any class can access and use. The idea is nothing new and can be found in popularized projects such as Log4j, http://jakarta.apache.org/log4j or with the J2SDK 1.4 standard logging API, the java.util.logging package. Both of these solutions should be preferred versus the Servlet API logging mechanism when robust logging is required.
In lieu of demonstrating the two ServletContext log() methods, a brief explanation and example of the java.util.logging package is given in Chapter 4. A flexible and consolidated mechanism for logging information is needed in any serious project. The Servlet API logging mechanism does work for simple cases, but this book encourages the use of a more robust logging API.
Distributed Environments
In most cases a ServletContext object can be considered as a reference to the entire Web Application. This holds true for single machine servers running one JVM for the Web Application. However, J2EE is not designed to be restricted for use on a single server. A full J2EE server, not just a container supporting Servlets and JSP, allows for multiple servers to manage and share the burden of a large-scale Web Application. These types of applications are largely outside the scope of this book, but it should be noted that application scope and initial parameters will not be the same in a distributed environment. Different servers and JVM instances usually do not share direct access to each other's information. If developing for a group of servers, do not assume that the ServletContext object will be the same for every request. This topic is discussed further in later chapters of the book.
Temporary Directory
One subtle but incredibly helpful feature of the Servlet specification is the requirement of a temporary work directory that Servlets and other classes in a Web Application can use to store information. The exact location of the temporary directory is not specified, but all containers are responsible for creating a temporary directory and setting a java.io.File object, which describes that directory as the javax.servlet.context.tempdir ServletContext attribute. Information stored in this directory is only required to persist while the Web Application is running, and information stored in the temporary directory will always be hidden from other Web Applications running on the same server.
The container-defined temporary directory is helpful for one really important reason: Web Applications can be run directly from a WAR; there is no guarantee that you can rely on using ServletContext getRealPath() to always work. To solve the problem, all Web Applications have access to at least one convenient place where temporary information can be stored, and that place is provided using the javax.servlet.context.tempdir attribute. There are a few good use cases where the javax.servlet.context.tempdir attribute is needed. In any situation where a Web Application is caching content locally (not in memory), the javax.servlet.context.tempdir attribute temporary directory is the ideal place to store the cache. Additionally, the temporary directory provides a place to temporarily store file uploads or any other information a Web Application is working with.
In practice, it is usually safe to assume your Web Application will be deployed outside of a WAR, especially when you have control over the deployment; however, in cases where a Web Application is intended for general use, the provided temporary directory should always be used to ensure maximum portability of your code. Later on in the book some use cases that deal with the temporary directory are provided; if you took a look at either of the previously mentioned file-upload API, you would have noticed they both take advantage of the temporary directory.