Java Servlet @HandlesTypes Annotation Example
- Details
- Written by Nam Ha Minh
- Last Updated on 26 June 2019   |   Print Email
This post helps you understand how to use the @HandlesTypes annotation in the Java Servlet API.
You know, the @HandlesTypes annotation is used to annotate a class that implements javax.servlet.ServletContainerInitializer interface. It declares the class types in which an implementation of ServletContainerInitializer is interested.
Syntax of @HandlesTypes annotation:
@HandlesTypes({Class1, Class2, Class3, ...}) public class AnInitializer implements ServletContainerInitializer { public void onStartup(Set<Class<?>> classes, ServletContext context) throws ServletException { // initialization code... } }
The Servlet container will find and pass a Set of application classes that extend, implement, or have been annotated with the class types listed by the @HandlesTypes annotation as the first argument of the onStartup() method. If the container did not find any matching classes, it will pass null.
Attributes of @HandlesTypes annotation:
Name | Type | Required | Description |
value | java.lang.Class[] | Required | An array of class types in which the implementation of ServletContainerInitializer is interested. |
Examples of @HandlesTypes annotation:
The following code example shows a typical usage of the @HandlesTypes annotation:
@HandlesTypes({ javax.servlet.http.HttpServlet.class, javax.servlet.Filter.class }) public class AppInitializer implements ServletContainerInitializer { @Override public void onStartup(Set<Class<?>> classes, ServletContext context) throws ServletException { // initialization code... } }
In the above code, we specify two class types: javax.servlet.http.HttpServlet and javax.servlet.Filter. The Servlet container will pass a Set containing implementation classes of the listed types to the method onStartup().
Related Java Servlet Annotations:
- @WebServlet annotation
- @WebFilter annotation
- @WebListener annotation
- @WebInitParam annotation
- @MultipartConfig annotation
- @ServletSecurity, @HttpMethodContraint and @HttpConstraint annotations
Other Java Servlet Tutorials:
- Java Servlet Quick Start for beginners (XML)
- Java Servlet for beginners (annotations)
- Java Servlet and JSP Hello World Tutorial with Eclipse, Maven and Apache Tomcat
- Handling HTML form data with Java Servlet
- Java File Download Servlet Example
Comments