The @WebServletannotation is used to declare a servlet. The annotated class must extend the javax.servlet.http.HttpServlet class.

 

Syntax of @WebServlet Annotation:

@WebServlet(
    attribute1=value1,
    attribute2=value2,
    ...
)
public class TheServlet extends javax.servlet.http.HttpServlet {
    // servlet code...
}
 

Attributes of @WebServlet Annotation:

Name

Type

Required

Description

value

or

urlPatterns

String[]

Required

Specify one or more URL patterns of the servlet. Either of attribute can be used, but not both.

name

String

Optional

Name of the servlet

displayName

String

Optional

Display name of the servlet

description

String

Optional

Description of the servlet

asyncSupported

boolean

Optional

Specify whether the servlet supports asynchronous operation mode. Default is false.

initParams

WebInitParam[]

Optional

Specify one or more initialization parameters of the servlet. Each parameter is specified by @WebInitParam annotation type.

loadOnStartup

int

Optional

Specify load-on-startup order of the servlet.

smallIcon

String

Optional

Specify name of the small icon of the servlet.

largeIcon

String

Optional

Specify name of the large icon of the servlet.

 

NOTE: the attributes displayName, description, smallIcon and largeIcon are primarily used by tools, IDEs or servlet containers, they do not affect operation of the servlet.

 

Some Examples with @WebServlet Annotation:

import javax.servlet.ServletConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;

@WebServlet(
		urlPatterns = "/myController",
		loadOnStartup = 1,
		asyncSupported = true
)
public class StartupServlet extends HttpServlet {
	
	public void init(ServletConfig config) {
		System.out.println("My servlet has been initialized");
	}
	
	// implement servlet doPost() and doGet()...
}


 

Here we declare the servlet StartupServlet with loadOnStartup = 1 which means that this servlet is initialized automatically by the servlet container when the server is being started (the message in the init() method will be printed). We also specify the servlet supports asynchronous mode.

 

Related Java Servlet Annotations:

 

Other Java Servlet Tutorials:


About the Author:

is certified Java programmer (SCJP and SCWCD). He started programming with Java in the time of Java 1.4 and has been falling in love with Java since then. Make friend with him on Facebook and watch his Java videos you YouTube.