WEBSERVLET ANNOTATIONS
Among many interesting features, Servlet 3.0 introduced annotations that make deploying Servlets, Filters and Listeners of all types easier. Most of the WebServlet annotations are packaged under javax.servlet.annotation. In this post we’ll see the following annotations.
- @WebServlet
- @WebFilter
- @WebListener
- @WebInitParam
WebListener, WebServlet and WebFilter annotations are placed on classes implementing respectively Listeners, Servlets and Filters. The WebInitParam annotation is used with WebServlet and WebFilter annotations specifying Servlet and Filter initialization parameters.
In order to provide support for these annotations, the mechanics of WebApp loading has to become a bit smarter.
Application Loading Phase
When an application loads, all classes comprising the application are examined for presence of the annotations. When these annotations are found on a particular class, the container registers instances of the classes as Listeners, Servlets, or Filters.
Registering a Listener using @WebListener
The WebListener annotation is used to register the following types of listeners
- Context Listener (javax.servlet.ServletContextListener)
- Context Attribute Listener (javax.servlet.ServletContextAttributeListener)
- Servlet Request Listener (javax.servlet.ServletRequestListener)
- Servlet Request Attribute Listener (javax.servlet.ServletRequestAttributeListener)
- Http Session Listener (javax.servlet.http.HttpSessionListener)
- Http Session Attribute Listener (javax.servlet.http.HttpSessionAttributeListener)
@WebListener is the easiest to use.
Example:
Registering ServletContextListeners.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
package com.j2eereference; import javax.servlet.annotation.WebListener; import javax.servlet.ServletContextEvent; import javax.servlet.ServletContextListener; @WebListener public class FooApplicationLifeCycleListener implements ServletContextListener { public void contextInitialized(ServletContextEvent event) { //do on application init } public void contextDestroyed(ServletContextEvent event) { //do on application destroy } } |
The type of listener is deduced from the list of interfaces that the class or its super class implements. If the class annotated with WebListener does not implement any of the listeners an error message will be logged.
Registering a Servlet using @WebServlet annotation
@WebServlet annotation is used to register a Servlet with a container. Below is the complete list of attributes that annotation encapsulates.
- name
- description
- value
- urlPatterns
- initParams
- loadOnStartup
- asyncSupported
- smallIcon
- largeIcon
The attributes are simply bits of data that prior to Servlet 3.0 would go into <servlet> or <servlet-mapping> tags of web.xml. Now they can be specified in java code.
Note: the spec mandates either value or urlPatterns attribute be specified.
Example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
package com.j2eereference; import java.io.IOException; import javax.servlet.*; import javax.servlet.annotation.*; @WebServlet(value="/hello", name="hello-servlet") public class HelloServlet extends GenericServlet { public void service(ServletRequest req, ServletResponse res) throws IOException, ServletException { res.getWriter().println("Hello World!"); } } |
After the successful build, a compile class will be created in WEB-INF/classes folder.Accessing http://localhost:8080/sample/hello should render the below text (‘sample’ is app name here).
1 |
Hello World! |
Using @WebInitParam with @WebServlet
The @WebInitParam annotation provides a means of specifying initialization parameters for servlets and filters.
The annotation defines the following attributes:
- name
- value
- description
Example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
package com.j2eereference; import java.io.IOException; import java.io.PrintWriter; import javax.servlet.*; import javax.servlet.annotation.*; @WebServlet(value="/hello", initParams = { @WebInitParam(name="param1", value="Hello "), @WebInitParam(name="param2", value=" World!") }) public class HelloServlet extends GenericServlet { public void service(ServletRequest req, ServletResponse res) throws IOException, ServletException { PrintWriter out = res.getWriter(); out.println(getInitParameter("param1")); out.println(getInitParameter("param2")); } } |
Accessing the servlet at http://locahost:8080/sample/hello will render (‘sample’ is the web-app name here)
1 |
Hello World! |
Registering a Filter with @WebFilter annotation
The @WebFilter annotation has the following attributes
- filterName
- description
- displayName
- initParams
- servletNames
- value
- urlPatterns
- dispatcherTypes
- asyncSupported
As mandated by the spec Resin expects that value, urlPatterns or servletNames will be specified.
Example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 |
package com.j2eereference; import java.io.*; import javax.servlet.*; import javax.servlet.annotation.*; @WebFilter(value="/hello", initParams = { @WebInitParam(name="message", value="Servlet says: Hello World!")}) public class TestFilter implements Filter { private FilterConfig _filterConfig; public void init(FilterConfig filterConfig) throws ServletException { _filterConfig = filterConfig; } public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws ServletException, IOException { PrintWriter out = res.getWriter(); out.print(_filterConfig.getInitParameter("message")); } public void destroy() { // destroy } } |
Metadata specified in WebFilter are available via FilterConfig object, so the output of http://localhost:8080/sample/hello will render the following output.
1 |
Servlet says: Hello World! |