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:

 

Other Java Servlet Tutorials:


About the Author:

is certified Java programmer (SCJP and SCWCD). He began programming with Java back in the days of Java 1.4 and has been passionate about it ever since. You can connect with him on Facebook and watch his Java videos on YouTube.



Add comment