Home Index Changes Prefs Log in »

Proposal for annotations and modularity of web.xml in the servlet specification.

The following annotations are being added to the Servlet 3.0 specification - @WebServlet, @ServletFilter, @InitParam and @WebServletContextListener

New annotations defined in the servlet 3.0 specification are shown below.

package javax.servlet.annotation;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
public @interface WebServlet {

    String servletName() default "";
    // url patterns. This will enable shorthand for @WebServlet("/foo")
    String [] value() default {};

    // For use when you have more than one param. Recommended when you have more than one attribute. 
    // Can only use one of the two - value or urlPatterns
    // Note that urlPatterns / values have default values. However at least one urlPattern MUST be specified (either by using the value or the urlPatterns field).
    String [] urlPatterns() default {};

    int loadOnStartup() default -1;

    InitParam [] initParams() default {};

    String icon() default "";

    String description() default "";
    
    boolean supportsAsync default false;
    
    long timeout default 0;

}

The default name of the Servlet if not specified is the fully qualified class name. The deployment descriptor elements may be used to override the name of the Servlet.

The annotated servlet MUST specify at least one url pattern to be deployed.

The WebServlet annotation can also be used on a web service being defined. So the @WebServlet annotation could also go on a JAX-RS / JAX-WS endpoint when deployed in the web container.

Classes annotated with @WebServlet class MUST extend javax.servlet.http.HttpServlet class except when applied on a JAX-RS / JAX-WS endpoint.

package javax.servlet.annotation;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
public @interface ServletFilter {

    String description() default "";

    String displayName() default "";

    InitParam [] initParams() default {};

    String filterName() default "";

    String icon() default "";

    String [] servletNames() default {};
    // url patterns. This will enable shorthand for @ServletFilter("/foo")
    String [] value();

    // For use when you have more than one param. Recommended when you have more than one attribute. 
    // Can only use one of the two - value or urlPatterns
    String [] urlPatterns();

    DispatcherType [] dispatcherTypes() default {DispatcherType.REQUEST};

    boolean supportsAsync default false;

}

Classes annotated with @ServletFilter MUST implement javax.servlet.Filter


package javax.servlet.annotation;

public @interface InitParam {

    String name();

    String value();

    String description() default "";
}

package javax.servlet.annotation;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
public @interface WebServletContextListener {
    String description() default "";

}


Classes annotated with @WebServletContextListener must implement javax.servlet.ServletContextListener


The following are 2 samples uses of the @WebServlet annotation

package samples;
import javax.servlet.annotation.*;
import javax.servlet.http.*;
import javax.servlet.*;

@WebServlet("/foo")
public class SimpleSample extends HttpServlet{
    public void service(ServletRequest req, ServletResponse res) {
        //...
    }
}

package samples;
import javax.servlet.http.*;
import javax.servlet.*;
import javax.servlet.annotation.*;

@WebServlet({"/foo", "/bar"})
public class SampleUsingAnnotationAttributes extends HttpServlet {

    public void doGet(HttpServletRequest req, HttpServletResponse res) {

    }
}

In addition to these annotations the current servlet spec already allows the use of RunAs, DeclareRoles, PersistenceContext, EJB, PersistenceUnit, PersistenceUnits, PostConstruct, PreDestroy, WebServiceRef, WebServiceRefs, Resource and Resources. All those will continue to work in the context of these new annotations. Issues -

There is an InitParam in javax.jws.soap from JSR 181 that has been deprecated and is slightly different than the one defined here. Should we look at aligning the two in anyway?

By default all applications will have index.htm(l) and index.jsp in the list of welcome-file-list. The descriptor may to be used to override these default settings. The relevant section (10.10) will be updated to reflect this change.

The order in which the listeners, Servlets etc are loaded from the various framework jars / classes in the WEB-INF/classes or WEB-INF/lib is unspecified when using annotations. If ordering is important then look at the section for modularity of web.xml below. The order can be specified in the deployment descriptor only.

Elements added to web.xml

The servlet element now has a child element that allows to enable / disable a servlet. The enable / disable controls whether a servlet is available at the url-pattern specified via an annotation or a web-fragment.

Modularity of web.xml


Using the annotations defined above the need of web.xml is optional. However for incremental upgrade / overriding either the default values or the values set via annotations the deployment descriptor is used. As before, if the metadata-complete element is set to true in the web.xml descriptor, annotations in the class files need not be processed. It implies that all the metadata for the application is specified via descriptor(s). For better pluggability and less configuration for developers in this version of the specification we are introducing the notion of web-fragments. A web-fragment is a part or all of the web.xml that can be specified and included in a library / framework jar's META-INF directory. The container will pick up and use the configuration as per the rules defined below.


A web fragment is a logical partitioning of the web app in such a way that the frameworks being used within the web app can define all the artifacts without asking devlopers to go and edit / add information in the web.xml deployment descriptor. It can include the Servlets, filters bundled in the framework.
This proposal defines the addition of a new xml descriptor - web-fragment.xml that can be used by frameworks / libraries.
A web-fragment can contain the defintion of a servlet, filters, listeners basically the whole web.xml but with a different top level element - web-fragment as opposed to web-app.
If the fragment is packaged as a jar file and has metadata information in the form of deployment descriptor then the web-fragment.xml descriptor must be in the META-INF/ directory of the jar file.
If a framework wants its META-INF/web-fragment.xml honored in such a way that it augments a web application's web.xml, the framework must be bundled within the web application's WEB-INF/lib directory. In order for any other types of resources (e.g., class files) of the framework to be made available to a web application, it is sufficient for the framework to be present anywhere in the classloader delegation chain of the web application.In other words, only JAR files bundled in a web application's WEB-INF/lib directory, but not those higher up in the classloading delegation chain, need to be scanned for web-fragment.xml
During deployment the container is responsible for scanning the location specified above and discovering the web-fragment.xml and processing them. The requirements about name uniqueness that exist currently for a single web.xml also apply to the union of a web.xml and all applicable web-fragment.xml files.

Attached below are the new schema for web.xml and web-fragment.xml -

web-fragment Schema (info)
web-common Schema (info)
Updated web.xml schema (info)


Ordering for listeners / servlet mappings

If the order in which the listeners are invoked is important to an application or the order in which the servlets, filters etc are invoked is important then a deployment descriptor must be used. As described above - when using annotations to define the listeners, servlets and filters the order in which they are invoked is unspecified. Same is the case for the order in which web-fragment.xml files are scanned in jars. Below are a set of rules that apply for ordering of servlets, filters and listeners:

  1. The order for listeners, servlets, filters if relevant must be specified in either the web-fragment.xml or the web.xml.
  2. The ordering will be based on the order in which they are defined in the descriptor.
    1. Filters that match a request are chained in the order in which they are declared in the web.xml.
    2. Servlets are initialized either lazily at request processing time, or eagerly during deployment. In the latter case, they are initialized in the order indicated by their load-on-startup elements.
    3. Currently, context listeners are invoked in random order. We would like to change invoking them in the order in which they are declared in the web.xml
  3. The order in the web.xml of the web application overrides what is specified in the web-fragment.xml.
  4. If a servlet is disabled using the enable / disable element introduced in the web.xml then the servlet will not be available at the url-pattern specified for the servlet.
  5. The web.xml of the web application has the highest precedence when resolving conflicts between the web.xml and web-fragment.xml.
  6. If metadata-complete is not specified in the descriptors then the effective metadata for the application is derived by combining the metadata present in the annnotations and the descriptor. The descriptor always overrides any metadata specified via annotations.
  7. A descriptor (web.xml or web-fragment.xml) may have a top level element of type javaee:java-identifierType. If a element is present, it must be considered for the ordering of artifacts.
  8. A deployment descriptor may have an element. If so, this element must contain zero or one element and zero or one element. If either element is present, it must contain one or more elements. These constraints are enforced by the schema. These elements can be specified either in the main web.xml or in the fragments (if a fragment knows it has dependencies of it's own for example). Below is an example demonstrating some of the new elements

web-fragment.xml (Fragment 1)

<web-fragment>
  <name>MyFragment1</name>
  <ordering><before><name>MyFragment2</name></before></ordering>
  ..
</web-fragment>
web-fragment.xml (Fragment 2)
<web-fragment>
  <name>MyFragment2</name>
  <ordering><after><name>MyFragment1</name></after></ordering>
  ..
</web-fragment>
web.xml
<web-app>
  <name>MyApp</name>
  <ordering>
  <before><name>Fragment1</name></before></name>
  ...
</web-app>

The preceding example illustrates some, but not all, of the following principles.

  • means the document must be ordered before the document with the name matching the name specified within the nested element.
  • means the document must be ordered after the document with the name matching the name specified within the nested element.
  • There is a special element that may be included within the or element. The element must be handled as follows.
    • If the element contains a nested , the document will be moved to the beginning of the list of sorted documents. If there are multiple documents requiring before , they will all be at the beginning of the list of sorted documents, but the ordering within the group of such documents is unspecified.
    • If the element contains a nested , the document will be moved to the end of the list of sorted documents. If there are multiple documents requiring after , they will all be at the end of the list of sorted documents, but the ordering within the group of such documents is unspecified.
    • Within a or element, if an element is present, but is not the only element within its parent element, the other elements within that parent must be considered in the ordering process.
  • If a web.xml or web-fragment.xml file does not have an section the artifacts are assumed to not have any ordering dependency.
  • If the runtime discovers circular references, an informative message must be logged, and the section of all parties of the circular reference must be ignored.

Below are some examples of showing how the rules apply to the various descriptors.

web.xml (with no name and ordering elements)

<web-app>
  <servlet>
    <servlet-name>MyServlet</servlet-name>
    <servlet-class>com.foo.wombat.MyAppServlet</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>MyServlet</servlet-name>
    <url-pattern>/wombats</url-pattern>
  </servlet-mapping>
  <listener>
    <listener-class>
     com.foo.wombat.MyContextListener2
    </listener-class>
  </listener>
  <listener>
    <listener-class>
     com.foo.wombat.MyContextListener1
    </listener-class>
  </listener>


</web-app>

web-fragment.xml (with no name or ordering elements)

<web-fragment>
  <servlet>
    <servlet-name>MyServlet</servlet-name>
    <servlet-class>com.foo.wombat.MyAppServlet</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>MyServlet</servlet-name>
    <url-pattern>/MyServlet</url-pattern>
  </servlet-mapping>
  <listener>
    <listener-class>
     com.foo.wombat.MyContextListener1
    </listener-class>
  </listener>
  <listener>
    <listener-class>
     com.foo.wombat.MyContextListener2
    </listener-class>
  </listener>

</web-fragment>

The mapping defined in the web.xml takes precedence and the order in which the listeners are invoked will also be based on the web.xml as opposed to the fragment.


Methods for declaring Servlet and Filters and the corresponding mappings programatically


The following method are added to the ServletContext and can be called during the initilization of the application only. It is illegal to call these methods from outside the contextInitialized event of the webapp.

Index: ServletContext.java
===================================================================
RCS file: /cvs/glassfish/servlet-api/src/jakarta-servletapi-5/jsr154/src/share/javax/servlet/ServletContext.java,v
retrieving revision 1.7
diff -u -r1.7 ServletContext.java
--- ServletContext.java	5 May 2007 05:34:19 -0000	1.7
+++ ServletContext.java	18 Mar 2008 00:37:34 -0000
@@ -44,6 +44,8 @@
 import java.net.MalformedURLException;
 import java.net.URL;
 import java.util.Enumeration;
+import java.util.EnumSet;
+import java.util.Map;
 import java.util.Set;
 
 
@@ -688,6 +690,128 @@
      */
     
     public String getServletContextName();
+
+    /**
+     * Adds the servlet with the given name, description, class name,
+     * init parameters, and loadOnStartup, to this servlet context.
+     *
+     * <p>If <tt>loadOnStartup</tt> is a positive integer or zero, it
+     * indicates to the container the initialization priority of the
+     * servlet. In this case, the container must instantiate and initialize
+     * the servlet during the initialization phase of this servlet context,
+     * that is, after it has invoked all of the ServletContextListeners
+     * configured for this servlet context at their
+     * {@link ServletContextListener#contextInitialized} method.
+     *
+     * <p>If <tt>loadOnStartup</tt> is a negative integer, the container
+     * is free to instantiate and initialize the servlet lazily.
+     *
+     * @param servletName the name of the servlet
+     * @param description the description of the servlet
+     * @param className the fully qualified class name of the servlet
+     * @param initParameters the initialization parameters of the servlet,
+     * or null if the servlet does not need any
+     * @param loadOnStartup the initialization priority of the servlet
+     *
+     * @throws IllegalArgumentException if a servlet with the given
+     * <tt>servletName</tt> already exists in this servlet context
+     * @throws IllegalStateException if this servlet context has already
+     * been initialized
+     *
+     * @since 3.0
+     */
+    public void addServlet(String servletName,
+                           String description,
+                           String className,
+                           Map<String, String> initParameters,
+                           int loadOnStartup);
+
+    /**
+     * Adds servlet mappings from the given url patterns to the servlet
+     * with the given servlet name to this servlet context.
+     *
+     * <p>The servlet with the given name may have been declared in the
+     * deployment descriptor or one of the web fragments of this servlet
+     * context, or may be added using {@link #addServlet addServlet}. It is
+     * legal to add a servlet mapping for a servlet that has not yet been
+     * added.
+     *
+     * @param servletName the name of the servlet for which the servlet
+     * mapping is added
+     * @param urlPatterns the url patterns of the servlet mapping
+     *
+     * @throws IllegalArgumentException if <tt>urlPatterns</tt> is null
+     * or empty
+     * @throws IllegalStateException if this servlet context has already
+     * been initialized
+     *
+     * @since 3.0
+     */
+    public void addServletMapping(String servletName,
+                                  String... urlPatterns);
+
+    /**
+     * Adds the filter with the given name, description, and class name to
+     * this servlet context.
+     *
+     * @param filterName the name of the filter
+     * @param description the description of the filter
+     * @param className the fully qualified class name of the filter
+     * @param initParameters the initialization parameters of the filter,
+     * or null if the filter does not need any
+     *
+     * @throws IllegalArgumentException if a filter with the given
+     * <tt>filterName</tt> already exists in this servlet context
+     * @throws IllegalStateException if this servlet context has already
+     * been initialized
+     *
+     * @since 3.0
+     */
+    public void addFilter(String filterName,
+                          String description,
+                          String className,
+                          Map<String, String> initParameters);
+
+    /**
+     * Adds a filter mapping with the given servlet names, and
+     * dispatcher types for the filter with the given filter name to this
+     * servlet context.
+     *
+     * <p>The filter with the given name may have been declared in the
+     * deployment descriptor or one of the web fragments of this servlet
+     * context, or may be added using {@link #addFilter addFilter}. It is
+     * legal to add a filter mapping for a filter that has not yet been added.
+     *
+     * <p>Filter mappings added via this method will be matched against 
+     * requests in the same order in which they were added.
+     * 
+     * <p>Depending on the value of the <tt>isMatchAfter</tt> parameter, the
+     * given filter mapping will be considered after or before any
+     * <i>declared</i> filter mappings of this servlet context.
+     *
+     * @param filterName the name of the filter for which the filter
+     * mapping is added
+     * @param dispatcherTypes the dispatcher types of the filter mapping,
+     * or null if the default <tt>DispatcherType.REQUEST</tt> is to be used
+     * @param isMatchAfter true if the given filter mapping should be matched
+     * against requests after any declared filter mappings of this servlet
+     * context, and false if it is supposed to be matched before any declared
+     * filter mappings of this servlet context
+     * @param servletNames the servlet names of the filter mapping
+     *
+     * @throws IllegalArgumentException if <tt>servletNames</tt> is both null or empty
+     * @throws IllegalStateException if this servlet context has already
+     * been initialized
+     *
+     * @since 3.0
+     */
+
+    public void addFilterMappingForServletNames(String filterName,
+                                EnumSet<DispatcherType> dispatcherTypes,
+                                 boolean isMatchAfter,
+                                 String... servletNames);
+
+    /**
+     * Adds a filter mapping with the given url patterns, and
+     * dispatcher types for the filter with the given filter name to this
+     * servlet context.
+     *
+     * <p>The filter with the given name may have been declared in the
+     * deployment descriptor or one of the web fragments of this servlet
+     * context, or may be added using {@link #addFilter addFilter}. It is
+     * legal to add a filter mapping for a filter that has not yet been added.
+     *
+     * <p>Filter mappings added via this method will be matched against 
+     * requests in the same order in which they were added.
+     * 
+     * <p>Depending on the value of the <tt>isMatchAfter</tt> parameter, the
+     * given filter mapping will be considered after or before any
+     * <i>declared</i> filter mappings of this servlet context.
+     *
+     * @param filterName the name of the filter for which the filter
+     * mapping is added
+     * @param dispatcherTypes the dispatcher types of the filter mapping,
+     * or null if the default <tt>DispatcherType.REQUEST</tt> is to be used
+     * @param isMatchAfter true if the given filter mapping should be matched
+     * against requests after any declared filter mappings of this servlet
+     * context, and false if it is supposed to be matched before any declared
+     * filter mappings of this servlet context
+     * @param urlPatterns the url patterns of the filter mapping
+     *
+     * @throws IllegalArgumentException if <tt>urlPatterns</tt> is null or empty
+     * @throws IllegalStateException if this servlet context has already
+     * been initialized
+     *
+     * @since 3.0
+     */
+    public void addFilterMappingForUrlPatterns(String filterName,
+                                 EnumSet<DispatcherType> dispatcherTypes,
+                                 boolean isMatchAfter,
+                                 String... urlPatterns); }
+
}

Example:

package samples;

import javax.servlet.ServletContext;
import javax.servlet.ServletContextListener;
import javax.servlet.ServletContextEvent;

@WebServletContextListener
public class MyListener implements ServletContextListener {
    public void contextInitialized(ServletContextEvent sce) {
        ServletContext sc = sce.getServletContext();

        sc.addServlet("myServlet", "Sample servlet", "foo.bar.MyServlet", null, -1);
        sc.addServletMapping("myServlet", new String[] { "/urlpattern/*" });
    }

    public void contextDestroyed(ServletContextEvent sce) {
        // Do nothing
    }
}

Additional convenience methods:

Index: ServletRequest.java
===================================================================
RCS file: /cvs/glassfish/servlet-api/src/jakarta-servletapi-5/jsr154/src/share/javax/servlet/ServletRequest.java,v
retrieving revision 1.6
diff -u -r1.6 ServletRequest.java
--- ServletRequest.java	5 May 2007 05:34:19 -0000	1.6
+++ ServletRequest.java	18 Mar 2008 00:37:34 -0000
@@ -619,5 +619,26 @@
      */
     public int getLocalPort();
 
+    /**
+     * Gets the servlet context to which this servlet request was last
+     * dispatched.
+     *
+     * @return the servlet context to which this servlet request was last
+     * dispatched
+     *
+     * @since 3.0
+     */
+    public ServletContext getServletContext();
+
+    /**
+     * Gets the servlet response with which this servlet request has been
+     * associated.
+     *
+     * @return the servlet response with which this servlet request has been
+     * associated
+     *
+     * @since 3.0
+     */
+    public ServletResponse getServletResponse();
 }
 
Index: ServletRequestWrapper.java
===================================================================
RCS file: /cvs/glassfish/servlet-api/src/jakarta-servletapi-5/jsr154/src/share/javax/servlet/ServletRequestWrapper.java,v
retrieving revision 1.3
diff -u -r1.3 ServletRequestWrapper.java
--- ServletRequestWrapper.java	5 May 2007 05:34:19 -0000	1.3
+++ ServletRequestWrapper.java	18 Mar 2008 00:37:34 -0000
@@ -420,6 +420,31 @@
     public int getLocalPort(){
         return this.request.getLocalPort();
     }
-    
+
+    /**
+     * Gets the servlet context to which this servlet request was last
+     * dispatched.
+     *
+     * @return the servlet context to which this servlet request was last
+     * dispatched
+     *
+     * @since 3.0
+     */
+    public ServletContext getServletContext() {
+        return request.getServletContext();
+    }
+
+    /**
+     * Gets the servlet response with which this servlet request has been
+     * associated.
+     *
+     * @return the servlet response with which this servlet request has been
+     * associated
+     *
+     * @since 3.0
+     */
+    public ServletResponse getServletResponse() {
+        return request.getServletResponse();
+    }
 }
« Home Attachments Info Index Changes Prefs
This page (revision-82) was last changed on 22-Dec-08 13:52 PM, -0800 by RajivMordani