@WebServlet annotation (Servlet annotation)

Posted by a2bardeals on Tue, 08 Feb 2022 11:30:13 +0100


@Properties of WebServlet annotation

@Use of WebServlet annotations

In Servlet, web XML plays a very important role. It can centrally manage the configuration of all servlets, but if there are a large number of servlets in the project, web The configuration of XML will become very lengthy. In this case, Annotation is a better choice.

Unlike XML, annotations do not need to rely on configuration files. They can be used directly in classes. Their configuration is only valid for the current class, which avoids the problem of lengthy configuration caused by centralized management.

In order to simplify the configuration of Servlet, annotation support is added in Servlet 3.0, such as @ WebServlet, @ WebInitParm, @ WebFilter and @ WebLitener, which makes web XML is no longer required since Servlet 3.0. Let's introduce @ WebServlet.

@Properties of WebServlet annotation

@WebServlet is used to declare a class as a Servlet. The annotation will be processed by the container during deployment. The container deploys the corresponding class as a Servlet according to its specific attribute configuration. This annotation has some common attributes given in the table below.

Attribute nametypelabeldescribeRequired
nameString<servlet-name>Specifies the name attribute of the Servlet.
If not explicitly specified, the value is the fully qualified name of the Servlet, that is, package name + class name.
valueString[ ]<url-pattern>This attribute is equivalent to the urlPatterns attribute and cannot be specified at the same time.
If specified at the same time, the value of value is usually ignored.
urlPatternsString[ ]<url-pattern>Specifies the URL matching pattern for a set of servlets.yes
loadOnStartupint<load-on-startup>Specifies the loading order of the Servlet.no
initParamsWebInitParam[ ]<init-param>Specify a set of Servlet initialization parameters.no
asyncSupportedboolean<async-supported>Declare whether the Servlet supports asynchronous operation mode.no
descriptionString<description>Specify the description of the Servlet.no
displayNameString<display-name>Specify the display name of the Servlet.no

@Use of WebServlet annotations

1. Enable annotation support

web. The top-level tag < web app > of XML has an attribute: metadata complete, which is used to specify the current web Whether XML is complete. If this property is set to true, the container will only rely on the web when deployed XML, ignoring all annotations. If this property is not configured or set to false, annotation support is enabled.

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
    id="WebApp_ID" metadata-complete="false" version="4.0">
    <!-- metadata-complete Value is true´╝îIndicates that annotation support is turned off -->
    <!-- metadata-complete Value is false´╝îIndicates that annotation support is enabled -->

Note: since the default value of the metadata complete attribute is false, that is, Servlet annotation support is enabled by default, it is not necessary to create a web annotation when using this annotation by default XML file.

2. Use @ WebServlet annotation

@WebServlet belongs to class level annotation, which is marked on the class that inherits HttpServlet. The common writing method is to write the relative request path (i.e. value) of the Servlet directly in the annotation, as shown below.


This writing method omits the urlPatterns attribute name, and its complete writing method is as follows.

@WebServlet(urlPatterns = "/myHttpServlet")

If you need to set multiple attributes in @ WebServlet, the attributes must be separated by commas, as shown below.

@WebServlet(asyncSupported = true, name = "MyHttpServlet", description = "name describe", loadOnStartup = 1, urlPatterns = {
        "/myHttpServlet", "/*"}, initParams = {
        @WebInitParam(name = "Hello", value = "MyHttpServlet!", description = "init Parameter 1"),
        @WebInitParam(name = "Hi", value = "World!", description = "init Parameter 2")})
public class MyHttpServlet extends HttpServlet {

    public void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //Get Servlet initialization parameters
        ServletConfig config = this.getServletConfig();
        String hello = config.getInitParameter("Hello");
        String Hi = config.getInitParameter("Hi");
        PrintWriter writer = resp.getWriter();
        writer.write("Hello:" + hello + " Hi:" + Hi);

    public void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {


matters needing attention:

  • Servlet classes created by implementing the servlet interface or inheriting GenericServlet cannot use @ WebServlet annotation.
  • Use the @ WebServlet annotation to configure the Servlet class, not in the web Configure the Servlet related attributes in the XML file again. If you use web XML and @ WebServlet configure the same Servlet class, then web The value of < Servlet name > in XML cannot be the same as the value of name in the annotation, otherwise the container will ignore the configuration in the annotation.

Topics: Java servlet