What's new in Java Servlet API 2.2?

A full update on the latest Java Servlet API

On August 23, Sun Microsystems published the first public release of the specification for Java Servlet API 2.2 (see the Resources section below for a link to the formal specification). Included in the specification are some very exciting enhancements to servlets. This article describes what's new in version 2.2 of the API, explains the decision-making process behind the changes, and demonstrates how to write servlets using API 2.2 features. To keep the article somewhere near a reasonable length, I'm going to assume that you're familiar with the classes and methods of previous versions of the Java Servlet API. If that's not the case, you can peruse Resources for links to sites that will help get you up to speed.

Java Servlet API 2.2 includes many enhancements that make servlets more powerful than ever:

  • Servlets are now part of the Java 2 Platform, Enterprise Edition specification

  • Servlets now embrace the notion of pluggable Web applications, which can be configured and deployed in a server-independent manner

  • Rules have been provided that define how servlets can be distributed across multiple back-end servers

  • Response output buffering has been added

  • Control over HTTP headers has been enhanced

  • New styles of request dispatching have been added

  • More advanced error handling can now be used

  • Several method signatures have been changed to keep the API consistent

Before we begin our examination of these enhancements, let me point out that version 2.2 has been released as a specification only; no Web server yet supports it. Even Sun's official reference implementation is still perhaps a couple months away; it is expected to be released with source code as part of the Jakarta Project (see Resources for information on Jakarta). So be careful, boys and girls; don't try these code examples at home!

Java 2 Platform, Enterprise Edition

One of the first things one notices when reading the Java Servlet API 2.2 specification is that the term servlet engine has been replaced by servlet container. This minor change is indicative of a larger one: the Java Servlet API is now a required API of the Java 2 Platform, Enterprise Edition (J2EE) specification and, throughout J2EE's terminology, container is preferred over engine. The addition of servlets to J2EE has no real effect on pure servlet developers (except for the fact that we have to stop saying "engine"). But it does guarantee that enterprise developers using J2EE will always have support for servlets. (Lucky developers!)

Web applications

Java Servlet API 2.2 includes one new feature so significant it may change the way the Web works. That feature: Web applications.

A Web application, as defined in the servlet specification, is a collection of servlets, JavaServer Pages (JSPs), HTML documents, images, and other Web resources that are set up in such a way as to be portably deployed across any servlet-enabled Web server. Installing a Web app is simple. Gone are the days of detailed instruction sheets telling you how to install third-party Web components, with different instructions for each type of Web server. With Web apps, the entire application can be contained in a single archive file and deployed by placing the file into a specific directory.

War: What is it good for?

Web app archive files have the extension .war, which stands for Web application archive. War files are actually jar files (created using the jar utility) saved with an alternate extension. Using the jar format allows jar files to be stored in compressed form and have their contents digitally signed. The .war file extension was chosen over .jar to let people and tools know to treat them differently.

Inside a war file you might find a file listing like this:


On install, a war file can be mapped to any URI prefix path on the server. The war file then handles all requests beginning with that prefix. For example, if the war file above were installed under the prefix /demo, the server would use it to handle all requests beginning with /demo. A request for /demo/index.html would serve the index.html file from the war file. A request for /demo/howto.jsp or /demo/images/banner.gif would also serve content from the war file.

About the WEB-INF directory

The WEB-INF directory is special. The files there are not served directly to the client; instead, they contain Java classes and configuration information for the Web app. The directory behaves like a jar file's META-INF directory; it contains metainformation about the archive contents.

The WEB-INF/classes directory contains the class files for this Web app's servlets and support classes. WEB-INF/lib contains classes stored in jar files. For convenience, Web server class loaders automatically look to WEB-INF/classes and WEB-INF/lib for their classes -- no extra install steps are necessary.

The servlets under WEB-INF in this Web app can be invoked using URIs like /demo/servlet/MyServlet and /demo/servlet/com.mycorp.frontend.CorpServlet. Notice how every request for this app begins with /demo, even requests for servlets.

The web.xml file in the WEB-INF directory is known as a deployment descriptor. This file contains configuration information about the Web app in which it resides. It's an XML file with a DTD (set of tags and structure) specified in detail as part of the Java Servlet API. The DTD contains over 50 tags, allowing you to specify any of the following:

Graphical icon files for the application

Useful for GUI manipulation.

A description of the app

Information on what the app does, who wrote it, where it can be found, and so on.

A flag indicating whether or not the app can be distributed

Distributed apps can be spread across multiple back-end servers to improve performance and add fail-over support, but such apps must be written according to stricter rules than their nondistributed counterparts. For example, objects placed into sessions for a distributed app should be serializable. This flag indicates whether the app has been written in accordance with the stricter rules.

Parameter information for the app

Essentially, these are init parameters for the application.

Registered servlet names

A place to register servlets and give them names. Previously, each server had a different process for registering servlets, making deployment difficult.

Servlet init parameters

Pass servlets parameters at initialization time. A new standard way to accomplish what used to be a server dependent process.

Servlet load order

Specifies which servlets are preloaded, and in what order.

URL mapping rules

Standardized mappings from URLs to servlets. For example, allow /lite/* to be handled by LiteServer and *.jsp to be handled by JspServlet (a mapping needed to support JSPs). Note that a /lite/* mapping for this Web app would handle requests beginning with /demo/lite/.

Session timeout defaults

Specify how many minutes of client inactivity can go by before a session times out.

File extension to MIME type mappings

Override server defaults or add mappings not known to the server.

A welcome file list

An ordered list of files to look for when a request comes in for a directory without specifying the file. Often index.jsp, index.html, index.htm.

Error-handling rules

Specify Web pages to handle various kinds of errors. Pages can be registered based on error code (for example, 404 errors serve some specific page) or based on exception type (for example, if a servlet throws javax.servlet.UnavailableException, display some explanatory page).

References to external data sources, such as JNDI

Add resources into the JNDI lookup table, like database connections. Allow the resources to be located by servlets using a simple name lookup.

Security constraints

Dictate which pages must be protected, and by what mechanism. Include built-in form-based authentication.

For those interested, the Web app DTD and a simple example web.xml file can be found in the Resources section. A full description of all the elements in the DTD would extend this article beyond a reasonable length, and may be of little interest in the long run, as these files are likely to be generated by graphical tools; thus, I will not describe the elements here.

The structure of the web.xml file is not in itself important; what interests us is the fact that having a deployment descriptor file allows configuration information to be specified in a server-independent manner, greatly simplifying the deployment process. Because of deployment descriptors, not only are simple servlets portable, but you can now transfer whole self-contained subsections of your site between servers.

As Java Servlet API 2.2 gains in popularity, it's likely that a commercial market for war files will develop. War files will become pluggable Web components, capable of being downloaded and installed and put to work right away -- no matter what your operating system or Web server. 9.95 for a site search engine, anyone?

Deployment descriptors also provide Web-hosting companies with a convenient way to support multiple customers on the same server. Customers can be given control over their individual domains. They can individually manage servlet registration, URL mappings, MIME types, and page-level security constraints -- without needing general access to the Web server.

Now let's take a look at how Web apps are implemented.

Web apps: A programmer's view

From a programmer's point of view, a Web app corresponds to one ServletContext object. All servlets inside a Web app share the same ServletContext instance. All Web servers have at least one context, called the default context. It handles requests whose URI paths match no other context prefix. (So, for example, it would handle requests for /index.html or /images/tile.gif.)

Parameter information for the Web app (specified in the deployment descriptor) is available using two new methods in ServletContext: getInitParameter() and getInitParameterNames(). These methods are modeled after their counterparts in GenericServlet. getInitParameter(String name) returns the string value of the specified parameter. getInitParameterNames() returns an enumeration containing the names of all the init parameters available to the app.

A servlet can determine the URI prefix of the context in which it's running using the new getContextPath() method in ServletRequest. This method returns a string representing the URI prefix of the context handling the request. The value starts with /, has no ending /, and, for the default context, is empty. For a request to /catalog/books/servlet/BuyNow, for example, the getContextPath() would return /catalog/books.

When using the context object to request resources, it's important to remember not to include the context path in the request. After all, the context knows its own path, and by not specifying the path in code, you ensure that the application can be moved to a different path prefix without recompiling. For example, when getting a RequestDispatcher to a servlet, use context.getRequestDispatcher("/servlet/BuyNow"). A request for /catalog/books/servlet/BuyNow would fail because the request is interpreted relative to the context root. The same goes for context.getResource() and context.getResourceAsStream().

The following servlet doGet() method demonstrates these context methods in action. Remember, this code won't compile against today's servers.

public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {

res.setContentType("text/plain"); PrintWriter out = res.getWriter();

out.println("My context path is: " + req.getContextPath());

ServletContext context = getServletContext(); out.println("My context instance is: " + context);

out.println("My context parameters are:"); Enumeration e = context.getInitParameterNames(); while (e.hasMoreElements()) { String name = (String) e.nextElement(); Object value = context.getAttribute(name); out.println(name + ": " + value); }

// Now let's dispatch RequestDispatcher dispatcher = context.getRequestDispatcher("/servlet/BuyNow"); dispatcher.include(req, res); }

This code first prints the current context path, the context reference, the init parameters, and finally includes output from the BuyNow servlet.

Lifecycle clarifications

Some additional clarifications have been made in the Java Servlet API 2.2 specification pertaining to Web apps and the servlet lifecycle.

It's now defined that, for servlets that don't implement SingleThreadModel, there's exactly one instance of a servlet per definition (that is, registered name) per context. Previously, the server could optionally create multiple instances. This new, stricter rule allows servlets to use instance variables to hold state associated with a particular servlet definition. For example, counter servlets can store their count in instance variables, and each registered name for the counter can maintain its own count. (This was how nearly everyone wrote servlets with versions 2.0 and 2.1 of the API; the difference is that now this technique is guaranteed to work.)

1 2 3 Page 1
Page 1 of 3