Servlets 简明教程

Servlets - Annotations

到目前为止,您已了解 Servlet 如何使用部署描述符(web.xml 文件)将您的应用程序部署到 Web 服务器中。Servlet API 3.0 引入了名为 javax.servlet.annotation 的新包。它提供可用于注释 Servlet 类的注释类型。如果您使用注释,则不需要部署描述符 (web.xml)。但您应该使用 tomcat7 或更高版本的 tomcat。

So far, you have learnt how Servlet uses the deployment descriptor (web.xml file) for deploying your application into a web server. Servlet API 3.0 has introduced a new package called javax.servlet.annotation. It provides annotation types which can be used for annotating a servlet class. If you use annotation, then the deployment descriptor (web.xml) is not required. But you should use tomcat7 or any later version of tomcat.

注释可替换 Web 部署描述符文件 (web.xml) 中等效的 XML 配置,如 Servlet 声明和 Servlet 映射。Servlet 容器将在部署时处理带注释的类。

Annotations can replace equivalent XML configuration in the web deployment descriptor file (web.xml) such as servlet declaration and servlet mapping. Servlet containers will process the annotated classes at deployment time.

Servlet 3.0 中引入的注释类型有:

The annotation types introduced in Servlet 3.0 are −

Sr.No.

Annotation & Description

1

@WebServlet To declare a servlet.

2

@WebInitParam To specify an initialization parameter.

3

@WebFilter To declare a servlet filter.

4

@WebListener To declare a WebListener

5

*@HandlesTypes * To declare the class types that a ServletContainerInitializer can handle.

6

@HttpConstraint This annotation is used within the ServletSecurity annotation to represent the security constraints to be applied to all HTTP protocol methods for which a corresponding HttpMethodConstraint element does NOT occur within the ServletSecurity annotation.

7

*@HttpMethodConstraint * This annotation is used within the ServletSecurity annotation to represent security constraints on specific HTTP protocol messages.

8

*@MultipartConfig * Annotation that may be specified on a Servlet class, indicating that instances of the Servlet expect requests that conform to the multipart/form-data MIME type.

9

@ServletSecurity This annotation is used on a Servlet implementation class to specify security constraints to be enforced by a Servlet container on HTTP protocol messages.

此处我们已详细讨论了一些注解。

Here we have discussed some of the Annotations in detail.

@WebServlet

@WebServlet用于使用容器声明Servlet的配置。下表包含用于WebServlet注解的属性列表。

The @WebServlet is used to declare the configuration of a Servlet with a container. The following table contains the list of attributes used for WebServlet annotation.

Sr.No.

Attribute & Description

1

String name Name of the Servlet

2

String[] value Array of URL patterns

3

String[] urlPatterns Array of URL patterns to which this Filter applies

4

Int loadOnStartup The integer value gives you the startup ordering hint

5

WebInitParam[] initParams Array of initialization parameters for this Servlet

6

Boolean asyncSupported Asynchronous operation supported by this Servlet

7

String smallIcon Small icon for this Servlet, if present

8

String largeIcon Large icon for this Servlet, if present

9

String description Description of this Servlet, if present

10

String displayName Display name of this Servlet, if present

注解的 valueurlPattern 属性中至少必须声明一个URL模式,但不能同时声明两个。

At least one URL pattern MUST be declared in either the value or urlPattern attribute of the annotation, but not both.

建议在URL模式是唯一要设置的属性时使用 value 属性,否则应使用 urlPattern 属性。

The value attribute is recommended for use when the URL pattern is the only attribute being set, otherwise the urlPattern attribute should be used.

Example

以下示例介绍如何使用@WebServlet注解。它是一个简单的servlet,用于显示文本 Hello Servlet

The following example describes how to use @WebServlet annotation. It is a simple servlet that displays the text Hello Servlet.

import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
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(value = "/Simple")
public class Simple extends HttpServlet {

   private static final long serialVersionUID = 1L;

   protected void doGet(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {

      response.setContentType("text/html");
      PrintWriter out = response.getWriter();
      out.print("<html><body>");
      out.print("<h3>Hello Servlet</h3>");
      out.print("</body></html>");
   }
}

以通常的方式编译 Simple.java ,并将你的类文件放入<Tomcat-installationdirectory>/webapps/ROOT/WEB-INF/classes。

Compile Simple.java in the usual way and put your class file in <Tomcat-installationdirectory>/webapps/ROOT/WEB-INF/classes.

现在只需运行 [role="bare"] [role="bare"]http://localhost:8080/Simple 即可尝试调用任何 servlet。您将在网页上看到以下输出。

Now try to call any servlet by just running [role="bare"]http://localhost:8080/Simple. You will see the following output on the web page.

Hello servlet

@WebInitParam

@WebInitParam 注解用于指定 Servlet 或 Filter 的初始化参数。它在 WebFilter 或 WebSevlet 注解中使用。下表包含用于 WebInitParam 注解的属性列表。

The @WebInitParam annotation is used for specifying an initialization parameter for a Servlet or a Filter. It is used within a WebFilter or WebSevlet annotations. The following table contains the list of attributes used for WebInitParam annotation.

Sr.No.

Attribute & Description

1

String name Name of the initialization parameter

2

String value Value of the initialization parameter

3

String description Description of the initialization parameter

Example

以下示例介绍如何将 @WeInitParam 注解与 @WebServlet 注解搭配使用。这是一个简单的 servlet,它显示文本 Hello Servlet 和字符串值 Hello World! ,它们取自 init 参数。

The following example describes how to use @WeInitParam annotation along with @WebServlet annotation. It is a simple servlet that displays the text Hello Servlet and the string value Hello World! which are taken from the init parameters.

import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
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(value = "/Simple", initParams = {
   @WebInitParam(name = "foo", value = "Hello "),
   @WebInitParam(name = "bar", value = " World!")
})
public class Simple extends HttpServlet {

   private static final long serialVersionUID = 1L;

   protected void doGet(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {

      response.setContentType("text/html");
      PrintWriter out = response.getWriter();
      out.print("<html><body>");
      out.print("<h3>Hello Servlet</h3>");
      out.println(getInitParameter("foo"));
      out.println(getInitParameter("bar"));
      out.print("</body></html>");
   }
}

以通常的方式编译 Simple.java ,然后将你的类文件放在 <Tomcat-installationdirectory>;/webapps/ROOT/WEB-INF/classes 中。

Compile Simple.java in the usual way and put your class file in <Tomcat-installationdirectory>;/webapps/ROOT/WEB-INF/classes.

现在只需运行 [role="bare"] [role="bare"]http://localhost:8080/Simple 即可尝试调用任何 servlet。您将在网页上看到以下输出。

Now try to call any servlet by just running [role="bare"]http://localhost:8080/Simple. You will see the following output on the web page.

Hello Servlet

Hello World!

@Webfilter

这是用于声明 servlet 过滤器的注释。它在部署时由容器处理,并向指定的 URL 模式、servlet 和分派器类型应用相应的过滤器。

This is the annotation used to declare a servlet filter. It is processed by the container at deployment time, and the corresponding filter applied to the specified URL patterns, servlets, and dispatcher types.

@WebFilter 注解在 Web 应用程序中定义了一个过滤器。此注释指定在类上,并包含有关声明的过滤器的元数据。带注释的过滤器必须至少指定一个 URL 模式。下表列出了用于 WebFilter 注解的属性。

The @WebFilter annotation defines a filter in a web application. This annotation is specified on a class and contains metadata about the filter being declared. The annotated filter must specify at least one URL pattern. The following table lists the attributes used for WebFilter annotation.

Sr.No.

Attribute & Description

1

String filterName Name of the filter

2

* String[] urlPatterns * Provides array of values or urlPatterns to which the filter applies

3

DispatcherType[] dispatcherTypes Specifies the types of dispatcher (Request/Response) to which the filter applies

4

String[] servletNames Provides an array of servlet names

5

String displayName Name of the filter

6

String description Description of the filter

7

WebInitParam[] initParams Array of initialization parameters for this filter

8

Boolean asyncSupported Asynchronous operation supported by this filter

9

String smallIcon Small icon for this filter, if present

10

String largeIcon Large icon for this filter, if present

Example

以下示例描述了如何使用 @WebFilter 注解。它是一个简单的 LogFilter,显示控制台上的 Init-param test-param 值和当前时间戳。这意味着过滤器在请求和响应之间发挥接口层的作用。这里我们为 urlPattern 使用了“/*”。这意味着此过滤器适用于所有 servlet。

The following example describes how to use @WebFilter annotation. It is a simple LogFilter that displays the value of Init-param test-param and the current time timestamp on the console. That means, the filter works like an interface layer between the request and the response. Here we use "/*" for urlPattern. It means, this filter is applicable for all the servlets.

import java.io.IOException;
import javax.servlet.annotation.WebFilter;
import javax.servlet.annotation.WebInitParam;
import javax.servlet.*;
import java.util.*;

// Implements Filter class

@WebFilter(urlPatterns = {"/*"}, initParams = {
   @WebInitParam(name = "test-param", value = "Initialization Paramter")})
public class LogFilter implements Filter {

   public void init(FilterConfig config) throws ServletException {
      // Get init parameter
      String testParam = config.getInitParameter("test-param");

      //Print the init parameter
      System.out.println("Test Param: " + testParam);
   }

   public void doFilter(ServletRequest request, ServletResponse response,
      FilterChain chain) throws IOException, ServletException {

      // Log the current timestamp.
      System.out.println("Time " + new Date().toString());

      // Pass request back down the filter chain
      chain.doFilter(request,response);
   }

   public void destroy( ) {
      /* Called before the Filter instance is removed
      from service by the web container*/
   }
}

以通常的方式编译 Simple.java ,并将你的类文件放入<Tomcat-installationdirectory>/webapps/ROOT/WEB-INF/classes。

Compile Simple.java in the usual way and put your class file in <Tomcat-installationdirectory>/webapps/ROOT/WEB-INF/classes.

现在只需运行 [role="bare"] [role="bare"]http://localhost:8080/Simple 即可尝试调用任何 servlet。您将在网页上看到以下输出。

Now try to call any servlet by just running [role="bare"]http://localhost:8080/Simple. You will see the following output on the web page.

Hello Servlet

Hello World!

现在,打开 servlet 控制台。在那里,您将看到 init 参数 testparamcurrent timestamp 的值以及 servlet 通知消息。

Now, open the servlet console. There, you will find the value of the init parameter testparam and the current timestamp along with servlet notification messages.