Newsletter sign-up
View all newsletters

Enterprise Java Newsletter
Stay up to date on the latest tutorials and Java community news posted on JavaWorld

Sponsored Links

Optimize with a SATA RAID Storage Solution
Range of capacities as low as $1250 per TB. Ideal if you currently rely on servers/disks/JBODs

Servlet 2.3: New features exposed

A full update on the latest Servlet API spec

  • Print
  • Feedback

Page 4 of 5

public class MyConnectionManager implements ServletContextListener {
  public void contextInitialized(ServletContextEvent e) {
    Connection con = // create connection
    e.getServletContext().setAttribute("con", con);
  }
  public void contextDestroyed(ServletContextEvent e) {
    Connection con = (Connection) e.getServletContext().getAttribute("con");
    try { con.close(); } catch (SQLException ignored) { } // close connection
  }
}


This listener ensures that a database connection is available in every new servlet context, and that all connections are closed when the context shuts down.

The HttpSessionActivationListener interface, another new listener interface in API 2.3, is designed to handle sessions that migrate from one server to another. A listener implementing HttpSessionActivationListener is notified when any session is about to passivate (move) and when the session is about to activate (become live) on the second host. These methods give an application the chance to persist nonserializable data across JVMs, or to glue or unglue serialized objects back into some kind of object model before or after migration. The interface has two methods:

  • void sessionWillPassivate(HttpSessionEvent e): The session is about to passivate. The session will already be out of service when this call is made.
  • void sessionDidActivate(HttpSessionEvent e): The session has been activated. The session will not yet be in service when this call is made.


You register this listener just like the others. However, unlike the others, the passivate and activate calls here will most likely occur on two different servers!

Select a character encoding

API 2.3 provides much-needed support for handling foreign language form submittals. There's a new method, request.setCharacterEncoding(String encoding), that lets you tell the server a request's character encoding. A character encoding, also known as a charset, is a way to map bytes to characters. The server can use the specified charset to correctly parse the parameters and POST data. By default, a server parses parameters using the common Latin-1 (ISO 8859-1) charset. Unfortunately, that only works for Western European languages. When a browser uses another charset, it is supposed to send the encoding information in the Content-Type header of the request, but almost no browsers do. This method lets a servlet tell the server what charset is in use (it is typically the charset of the page that contains the form); the server takes care of the rest. For example, a servlet receiving Japanese parameters from a Shift_JIS encoded form could read the parameters like this:

  // Set the charset as Shift_JIS
  req.setCharacterEncoding("Shift_JIS");
  // Read a parameter using that charset
  String name = req.getParameter("name");


Remember to set the encoding before calling getParameter() or getReader(). The setCharacterEncoding() call may throw java.io.UnsupportedEncodingException if the encoding is not supported. This functionality is also available for users of API 2.2 and earlier, as part of the com.oreilly.servlet.ParameterParser class. (See Resources.)

JAR dependencies

Often, a WAR file (Web application archive file, added in API 2.2) requires various other JAR libraries to exist on the server and operate correctly. For example, a Web application using the ParameterParser class needs cos.jar in the classpath. A Web application using WebMacro needs webmacro.jar. Before API 2.3, either those dependencies had to be documented (as if anyone actually reads documentation!) or each Web application had to include all its required jar files in its own WEB-INF/lib directory (unnecessarily bloating each Web application).

Servlet API 2.3 lets you express JAR dependencies within the WAR using the WAR's META-INF/MANIFEST.MF entry. That is the standard way for jar files to declare dependencies, but with API 2.3, WAR files must officially support the same mechanism. If a dependency can't be satisfied, a server can politely reject the Web application at deployment time instead of causing an obscure error message at runtime. The mechanism allows a high degree of granularity. For example, you can express a dependency on a particular version of an optional package, and the server has to find the right one with a search algorithm. (See Resources for a link to documentation that explains in detail how the manifest versioning model works.)

Class loaders

Here's a small change with a big impact: In API 2.3, a servlet container (a.k.a. the server) will ensure that classes in a Web application not be allowed to see the server's implementation classes. In other words, the class loaders should be kept separate.

That doesn't sound like much, but it eliminates the possibility of a collision between Web application classes and server classes. That had become a serious problem because of XML parser conflicts. Each server needs an XML parser to parse web.xml files, and many Web applications these days also use an XML parser to handle reading, manipulation, and writing of XML data. If the parsers supported different DOM or SAX versions, that could cause an irreparable conflict. The separation of class scope solves this issue nicely.

New error attributes

The previous API version, Servlet API 2.2, introduced several request attributes that could be used by servlets and JSPs acting as targets of an <error-page> rule. If you don't remember <error-page> rules, they let you configure a Web application so that certain error status codes or exception types cause specific pages to be displayed:

<web-app>
    <!-- ..... -->
    <error-page>
        <error-code>
            404
        </error-code>
        <location>
            /404.html
        </location>
    </error-page>
    <error-page>
        <exception-type>
            javax.servlet.ServletException
        </exception-type>
        <location>
            /servlet/ErrorDisplay
        </location>
    </error-page>
    <!-- ..... -->
</web-app>


A servlet in the <location> for an <error-page> rule could receive the following three attributes:

  • javax.servlet.error.status_code: An Integer telling the error status code, if any
  • javax.servlet.error.exception_type: A Class instance indicating the type of exception that caused the error, if any
  • javax.servlet.error.message: A String telling the exception message, passed to the exception constructor


Using those attributes, a servlet could generate an error page customized to the error, as shown below:

  • Print
  • Feedback

Resources