I've been a zone leader with DZone since 2008, and I'm crazy about community. Every day I get to work with the best that JavaScript, HTML5, Android and iOS has to offer, creating apps that truly make at difference, as principal front-end architect at Avego. James is a DZone Zone Leader and has posted 639 posts at DZone. You can read more from them at their website. View Full User Profile

An Overview of Servlet 3.0

01.21.2009
| 42513 views |
  • submit to reddit

JSR 315 (Servlet 3.0) is an update to the existing Servlet 2.5 specification. Servlet 3.0 is focussed on extensibility and web framework pluggability, aligning with the goals of Java EE 6. Ease of Development (EoD) will be supported using newer language features. A reference implementation is available in the GlassFish v3 nightly build. The public review contains:

  • Pluggability
  • EoD
  • Async Support
  • Security Enhancements
  • Miscellaneous Changes

In this article we will bring you up to speed with what's happening with the Servlet 3.0 specification and give more detail on what is included.

Note: this article corresponds to the public review of the specification. As it is not yet final some things may change.

The Expert Group

Rajiv Mordani from Sun Microsystems is the specification lead with an expert group comprised of many of the most recognisable names in the Java community:

  • Adobe Systems Inc.
  • Apache Software Foundation
  • BEA Systems
  • Ericsson AB
  • Google Inc.
  • Hunter, Jason
  • IBM
  • Icesoft Technologies Inc
  • NCsoft Corporation
  • Oracle
  • Pramati Technologies
  • Prasanna, Dhanji R.
  • SAP AG
  • Ship, Howard M. Lewis
  • Suleiman, Hani
  • Sun Microsystems, Inc.
  • Tmax Soft, Inc.
  • Walker, Joe
  • Wilkins, Gregory John

Pluggability

Due to the popularity of so many various web frameworks, Servlet 3.0 will make it easier to use and configure the developer's framework of choice. So if you want to add in Struts, or Spring Web Flow it will be easy to do so.

  • Methods to add Servlets and Filters

    If a ServletContextListener is registered and wants to add a Servlet or Filter, then at the time of context initialization the event that is fired to the Listener can add Servlets and Filters to the context. The methods are addServlet and addFilter. For more details look for the javadocs at the JCP site at  http://jcp.org/aboutJava/communityprocess/pr/jsr315/index.html.

  • Web fragments

    Instead of having just one monolithic web.xml that is used by the developer to declare servlets, filters and other configuration for using the framework, the framework can now include a web-fragment.xml with all it's configuration.

    A web-fragment is almost identical to the web.xml and can contain all the configuration needed by the framework in the META-INF directory of the framework's jar file. The container will use the information to assembe the descriptor for the application and the application needn't have to use any of the boilerplate configuration in their app for the framework. There are rules that are defined int the specification for conflict resolution, overriding and disabling fragment scanning. Along with the annotations which also can be in libraries the feature is very compelling not only for the developers that use frameworks but also for framework authors to be self sufficient in defining the configuration needed.

    The great benefit to this is that library providers can supply their own web.xml fragment for use in your webapp.

Ease of Development

Several new annotations have been defined for ease of development in Servlet 3.0, allowing you to write a Servlet without requiring a descriptor. These annotations reside in the javax.servlet.annotation package. Thanks to the addition of annotations, it is now possible to have Servlet, Filter and ServletContextListener in a war file without a web.xml.

It's important to point out that this makes the web.xml optional, rather than redundant. The web.xml may be user to override metadata specified via annotations.

Following discussions in the expert group and the community, it was decided that method level annotations were not to be added, so you keep the doGet, doPost methods and need to extend HttpServlet to use them.

Let's take a closer look at the annotations present in the Servlet 3.0 specification:

Servlet Annotation

In Servlet 3.0, servlet metadata can be specified using @WebServlet

@WebServlet(name="mytest", 
urlPatterns={"/myurl"}, 
initParams={ @InitParam(name="n1", value="v1"), @InitParam(name="n2", value="v2") }) 
public class TestServlet extends javax.servlet.http.HttpServlet { 
.... 
} 

TestServlet extends HttpServlet, while the meta data provided corresponds with the web.xml as follows:

Parameter

Annotation Parameter

web.xml

Servlet name

name=

<servlet><servlet-name>

URL Pattern

urlPatterns={ }

<servlet-mapping>

Initialization parameters

InitParams={ @InitParam{name=””, value=””}

<servlet>

<init-param>

<param-name>.. </param-name>

<param-value>.. </param-value>

<init-param>

 

Servlet Filter Annotation

ServletFilter meta data is specified using the @ServletFilter annotation

public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException { 
.... 
} 

public void destroy() { 
.... 
} 
} 

Parameter

Annotation Parameter

web.xml

URL Pattern

urlPatterns={ }

<servlet-mapping>

Initialization parameters

InitParams={ @InitParam{name=””, value=””}

<servlet>

<init-param>

<param-name>.. </param-name>

<param-value>.. </param-value>

<init-param>

 

Servlet Context Listener Annotation

A ServletContextListener is simply marked with the @WebServletContextListener rather than needing to list it the web.xml file.

@WebServletContextListener 
public class TestServletContextListener implements javax.servlet.ServletContextListener { 
.... 
public void contextInitialized(ServletContextEvent sce) { 
.... 
} 

public void contextDestroyed(ServletContextEvent sce) { 
.... 
} 
} 

Async Support

The biggest change made in the specification is the addition of asynchronous processing. The main cases to cover were:

  • Waiting for a resource to become available, such as JDBC or a call to a Web Service.

  • Generating response asynchronously

  • Using exisiting frameworks to generate responses after waiting the for asychronous operation to complete.

While the early draft had suspend and resume, the latest specification has two variations of the startAsync() method on ServletRequest.

One (startAsync() ) takes no parameters and initialises an AsyncContext with the original request and response. The ( startAsync() ) other takes a request and response as a parameter to initialise the AsyncContext with.

Servlets (@WebServlet) and Filters (@ServletFilter) that support asynchronous processing need to be annotated with the supportAsync attribute set. It is illegal to call startAsync if you have a Servlet or Filter that doesn't support asynchronous processing anywhere in the request processing chain.

The is also an AsyncListener that can be registered to get notification on timeout and completion of asynchronous processing of the request. This listener can be used to clean up resources if the wrapped request and response were used to create it's AsyncContext.

You can forward requests back to the container using the AsyncContext.forward(path) and AsyncContext.forward() methods so frameworks like JSP can create a response.

Security Enhancements

HTTPServletRequest will be enhanced with methods allowing programmatic login and logout, while ServletRequest will be able to force a login.The logout method will allow an application to reset the authentication state of a request without requiring the authentication to be bound to a HTTPSession.

Conclusion

The draft is just beginning to be implemented within Glassfish v3. The specification will be a required piece of Java EE 6 and hence all the features described above will be available in all Java EE 6 compatible containers. The presence of the various features described above will make developing Java web appications much easier.

Thanks to Rajiv Mordani for his input into this article, and to Shing Wai and Jan Luehe for the code snippets.

Comments

Cody A_ replied on Wed, 2009/01/21 - 8:45am

Any idea when the projected release is for JEE 6?

I'm really anxious to test some of these features.

Thanks for the update.

Zemian Deng replied on Wed, 2009/01/21 - 10:09am

Cool, thanks for the intro.

Ronald Miura replied on Wed, 2009/01/21 - 10:35am

And how can I disable this automatic discovery of both xml fragments and annotated classes?

This may cause security issues if any jar in the classpath exposes something (like a debug console) without explicit declaration in the application.

I know it is optional, but is it disabled or enabled by default?

Hantsy Bai replied on Thu, 2009/01/22 - 2:12am

 Why not remove "extends javax.servlet.http.HttpServlet" code fragments and make is true POJO's

Tarik Filali Ansary replied on Thu, 2009/01/22 - 3:51am

Is it possible to load and remove servlets and servlets filters dynamically?

Will it be possible to change at during runtime which WebServlet reply for the a url (Ex: urlPatterns={"/myurl"} ?

Thanx in advance

 

 

 

 

Ronald Miura replied on Thu, 2009/01/22 - 6:45am in response to: Hantsy Bai

'POJOs' are overrated. What is the advantage of making Servlet a POJO?

This is not the same as, say, EJBs or Spring beans, which you really want to take advantage of inheritance when modeling your domain.

Servlets are infrastructure. Even the annotation thing is kinda useless. Who writes servlets these days, besides when doing some really low level stuff? If you want Controllers, you should use a MVC framework (one from the hundreds), which will be a lot more flexible and powerful.

Bhavani Sankar replied on Wed, 2009/01/28 - 5:09am

 

Very helpful for knowing new things coming in Servlet 3.0 ! Thanks to James !

Comment viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.