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 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;
}
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) {
}
}
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.
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
web-common Schema
Updated web.xml schema
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:
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.
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.
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();
+ }
}