Home > Articles

Java Servlets

This chapter is from the book

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.

02fig19.gifFigure 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.

02fig20.gifFigure 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.

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.

Overview


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information


To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.

Surveys

Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.

Newsletters

If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information


Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.

Security


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.

Children


This site is not directed to children under the age of 13.

Marketing


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information


If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.

Choice/Opt-out


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information


Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents


California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure


Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.

Links


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact


Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice


We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020