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:

  • A servlet is annotated with only the URL pattern:
    import java.io.IOException;
    
    import javax.servlet.annotation.WebServlet;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    
    @WebServlet("/processForm")
    public class MyServlet extends HttpServlet {
    	public void doGet(HttpServletRequest request, HttpServletResponse response)
    			throws IOException {
    		response.getWriter().println("Hello");
    	}
    }
    Here the servlet MyServlet is mapped to the URL pattern /processForm. When accessing this servlet, it will return a “Hello” message.

  • A servlet is annotated with multiple URL patterns:
    import javax.servlet.annotation.WebServlet;
    import javax.servlet.http.HttpServlet;
    
    @WebServlet(urlPatterns = {"/sendFile", "/uploadFile"})
    public class UploadServlet extends HttpServlet {
    	// implement servlet doPost() and doGet()...
    }
    Here the servlet UploadServlet can be accessed through two URL patterns: /sendFile and /uploadFile.

  • Declare a servlet with additional information:
    import javax.servlet.annotation.WebServlet;
    import javax.servlet.http.HttpServlet;
    
    @WebServlet(
    		name = "MyOwnServlet",
    		description = "This is my first annotated servlet",
    		urlPatterns = "/processServlet"
    )
    public class MyServlet extends HttpServlet {
    	// implement servlet doPost() and doGet()...
    }
     

    Here we specify name and description for the servlet class MyServlet. 

  • Declare a servlet with some init parameters:
    import java.io.IOException;
    import java.io.PrintWriter;
    
    import javax.servlet.annotation.WebInitParam;
    import javax.servlet.annotation.WebServlet;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    
    @WebServlet(
    		urlPatterns = "/imageUpload",
    		initParams =
    		{
    			@WebInitParam(name = "saveDir", value = "D:/FileUpload"),
    			@WebInitParam(name = "allowedTypes", value = "jpg,jpeg,gif,png")
    		}
    )
    public class ImageUploadServlet extends HttpServlet {
    
    	public void doGet(HttpServletRequest request, HttpServletResponse response)
    			throws IOException {
    		String saveDir = getInitParameter("saveDir");
    		String fileTypes = getInitParameter("allowedTypes");
    
    		PrintWriter writer = response.getWriter();
    
    		writer.println("saveDir = " + saveDir);
    		writer.println("fileTypes = " + fileTypes);
    	}
    }
     

    Here we declare the ImageUploadServletmapped by the URL pattern /imageUpload and specify two init parameters saveDir and allowedTypes. The doGet() method retrieves values of these parameters and prints them out to the client.

  • Declare a servlet with asynchronous operation mode and load-on-startup order:
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.



Add comment

   


Comments 

#14BABY SAROJA2023-01-24 01:50
i have coming 404 error in springboot
Quote
#13Sanyasi Karree2022-09-28 05:22
HTTP Status 404 – Not Found
Type Status Report


Description The origin server did not find a current representation for the target resource or is not willing to disclose that one exists.
Quote
#12Shalini2021-12-21 10:11
HTTP Status 404 – Not Found
Type Status Report

Message Whiteboard not found

Description The origin server did not find a current representation for the target resource or is not willing to disclose that one exists.

Apache Tomcat/8.5.39 (Ubuntu)
Quote
#11Yesre2020-12-09 21:25
what jar file should I import because I got the error "The attribute name is undefined for the annotation type WebServlet".
Quote
#10Alisher2020-11-11 05:11
Thank you . Very useful
Quote