A Guide to Java EE Web-Related Annotations – Java EE网络相关的注释指南

最后修改: 2017年 4月 20日

中文/混合/英文(键盘快捷键:t)

1. Overview

1.概述

Java EE annotations make developers’ life easier by allowing them to specify how application components should behave in a container. These are modern alternatives for XML descriptors and basically, make it possible to avoid boilerplate code.

Java EE注解使开发者的生活更轻松,因为他们可以指定应用程序组件在容器中的行为方式。这些是XML描述符的现代替代品,基本上可以避免模板代码。

In this article, we’ll focus on annotations introduced with Servlet API 3.1 in Java EE 7. We will examine their purpose and look at their usage.

在这篇文章中,我们将重点讨论Java EE 7中Servlet API 3.1引入的注解。我们将研究它们的目的并看看它们的用法。

2. Web Annotations

2.网络注释

Servlet API 3.1 introduced a new set of annotation types that can be used in Servlet classes:

Servlet API 3.1引入了一组新的注解类型,可以在Servlet类中使用。

  • @WebServlet
  • @WebInitParam
  • @WebFilter
  • @WebListener
  • @ServletSecurity
  • @HttpConstraint
  • @HttpMethodConstraint
  • @MultipartConfig

We’ll examine them in detail in next sections.

我们将在接下来的章节中详细研究它们。

3. @WebServlet

3.@WebServlet

Simply put, this annotation allows us to declare Java classes as servlets:

简单地说,这个注解允许我们将Java类声明为servlets

@WebServlet("/account")
public class AccountServlet extends javax.servlet.http.HttpServlet {
    
    public void doGet(HttpServletRequest request, HttpServletResponse response) 
      throws IOException {
        // ...
    }
 
    public void doPost(HttpServletRequest request, HttpServletResponse response) 
      throws IOException {
        // ...
    }
}

3.1. Using Attributes of @WebServlet Annotation

3.1.使用@WebServlet注释的属性

@WebServlet has a set of attributes that allow us to customize the servlet:

@WebServlet有一组属性,允许我们定制Servlet。

  • name
  • description
  • urlPatterns
  • initParams

We can use these as shown in the example below:

我们可以使用这些,如下面的例子所示。

@WebServlet(
  name = "BankAccountServlet", 
  description = "Represents a Bank Account and it's transactions", 
  urlPatterns = {"/account", "/bankAccount" }, 
  initParams = { @WebInitParam(name = "type", value = "savings")})
public class AccountServlet extends javax.servlet.http.HttpServlet {

    String accountType = null;

    public void init(ServletConfig config) throws ServletException {
        // ...
    }

    public void doGet(HttpServletRequest request, HttpServletResponse response) 
      throws IOException {
        // ... 
    }

    public void doPost(HttpServletRequest request, HttpServletResponse response) 
      throws IOException {
        // ...  
    }
}

The name attribute overrides the default servlet name which is the fully qualified class name by default. If we want to provide a description of what the servlet does, we can use the description attribute.

name属性覆盖了默认的servlet名称,该名称默认为完全合格的类名称。如果我们想对servlet的功能进行描述,我们可以使用description属性。

The urlPatterns attribute is used to specify the URL(s) at which the servlet is available (multiple values can be provided to this attribute as shown in the code example).

urlPatterns属性用于指定servlet可用的URL(如代码示例中所示,可以为该属性提供多个值)。

4. @WebInitParam

4.@WebInitParam

This annotation is used with the initParams attribute of the @WebServlet annotation and the servlet’s initialization parameters.

该注解与@WebServlet注解的initParams属性以及Servlet的初始化参数一起使用。

In this example, we set a servlet initialization parameter type, to the value of ‘savings’:

在这个例子中,我们设置了一个servlet初始化参数type,数值为’savings’。

@WebServlet(
  name = "BankAccountServlet", 
  description = "Represents a Bank Account and it's transactions", 
  urlPatterns = {"/account", "/bankAccount" }, 
  initParams = { @WebInitParam(name = "type", value = "savings")})
public class AccountServlet extends javax.servlet.http.HttpServlet {

    String accountType = null;

    public void init(ServletConfig config) throws ServletException {
        accountType = config.getInitParameter("type");
    }

    public void doPost(HttpServletRequest request, HttpServletResponse response) 
      throws IOException {
        // ...
    }
}

5. @WebFilter

5.@WebFilter

If we want to alter the request and response of a servlet without touching its internal logic, we can use the WebFilter annotation. We can associate filters with a servlet or with a group of servlets and static content by specifying an URL pattern.

如果我们想改变一个servlet的请求和响应而不触及其内部逻辑,我们可以使用WebFilter注解。我们可以通过指定一个URL模式,将过滤器与一个servlet或一组servlet和静态内容联系起来。

In the example below we are using the @WebFilter annotation to redirect any unauthorized access to the login page:

在下面的例子中,我们使用 @WebFilter注解来重定向任何未经授权的访问到登录页面。

@WebFilter(
  urlPatterns = "/account/*",
  filterName = "LoggingFilter",
  description = "Filter all account transaction URLs")
public class LogInFilter implements javax.servlet.Filter {
    
    public void init(FilterConfig filterConfig) throws ServletException {
    }

    public void doFilter(
        ServletRequest request, ServletResponse response, FilterChain chain) 
          throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse res = (HttpServletResponse) response;

        res.sendRedirect(req.getContextPath() + "/login.jsp");
        chain.doFilter(request, response);
    }

    public void destroy() {
    }

}

6. @WebListener

6.@WebListener

Should we want knowledge or control over how and when a servlet and its requests are initialized or changed, we can use the @WebListener annotation.

如果我们想了解或控制Servlet及其请求如何以及何时被初始化或改变,我们可以使用@WebListener注解。

To write a web listener we need to extend one or more of the following interfaces:

要写一个网络监听器,我们需要扩展以下一个或多个接口。

  • ServletContextListener – for notifications about the ServletContext lifecycle
  • ServletContextAttributeListener – for notifications when a ServletContext attribute is changed
  • ServletRequestListener – for notifications whenever a request for a resource is made
  • ServletRequestAttributeListener – for notifications when an attribute is added, removed or changed in a ServletRequest
  • HttpSessionListener – for notifications when a new session is created and destroyed
  • HttpSessionAttributeListener – for notifications when a new attribute is being added to or removed from a session

Below is an example of how we can use a ServletContextListener to configured a web application:

下面是一个例子,说明我们如何使用ServletContextListener来配置一个Web应用程序。

@WebListener
public class BankAppServletContextListener 
  implements ServletContextListener {

    public void contextInitialized(ServletContextEvent sce) { 
        sce.getServletContext().setAttribute("ATTR_DEFAULT_LANGUAGE", "english"); 
    } 
    
    public void contextDestroyed(ServletContextEvent sce) { 
        // ... 
    } 
}

7. @ServletSecurity

7.@ServletSecurity

When we want to specify the security model for our servlet, including roles, access control and authentication requirements we use the annotation @ServletSecurity.

当我们想为我们的Servlet指定安全模型,包括角色、访问控制和认证要求时,我们使用注解@ServletSecurity

In this example we will restrict access to our AccountServlet using the @ServletSecurity annotation:

在这个例子中,我们将使用@ServletSecurity 注释来限制对我们的AccountServlet 的访问。

@WebServlet(
  name = "BankAccountServlet", 
  description = "Represents a Bank Account and it's transactions", 
  urlPatterns = {"/account", "/bankAccount" }, 
  initParams = { @WebInitParam(name = "type", value = "savings")})
@ServletSecurity(
  value = @HttpConstraint(rolesAllowed = {"Member"}),
  httpMethodConstraints = {@HttpMethodConstraint(value = "POST", rolesAllowed = {"Admin"})})
public class AccountServlet extends javax.servlet.http.HttpServlet {

    String accountType = null;

    public void init(ServletConfig config) throws ServletException {
        // ...
    }

    public void doGet(HttpServletRequest request, HttpServletResponse response) 
      throws IOException {
       // ...
    }

    public void doPost(HttpServletRequest request, HttpServletResponse response) 
      throws IOException {        
        double accountBalance = 1000d;

        String paramDepositAmt = request.getParameter("dep");
        double depositAmt = Double.parseDouble(paramDepositAmt);
        accountBalance = accountBalance + depositAmt;

        PrintWriter writer = response.getWriter();
        writer.println("<html> Balance of " + accountType + " account is: " + accountBalance 
        + "</html>");
        writer.flush();
    }
}

In this case, when invoking the AccountServlet, the browser pops up a login screen for the user to enter a valid username and password.

在这种情况下,当调用AccountServlet时,浏览器会弹出一个登录屏幕,让用户输入一个有效的用户名和密码。

We can use @HttpConstraint and @HttpMethodConstraint annotations to specify values for the attributes value and httpMethodConstraints, of @ServletSecurity annotation.

我们可以使用@HttpConstraint@HttpMethodConstraint注解来指定valuehttpMethodConstraints,的属性值@ServletSecurity注解。

@HttpConstraint annotation applies to all HTTP methods. In other words, it specifies the default security constraint.

@HttpConstraint 注解适用于所有的HTTP方法。换句话说,它指定了默认的安全约束。

@HttpConstraint has three attributes:

@HttpConstraint有三个属性。

  • value
  • rolesAllowed
  • transportGuarantee

Out of these attributes, the most commonly used attribute is rolesAllowed. In the example code snippet above, users who belong to the role Member are allowed to invoke all HTTP methods.

在这些属性中,最常用的属性是rolesAllowed。在上面的示例代码片段中,属于角色Member的用户被允许调用所有的HTTP方法。

@HttpMethodConstraint annotation allows us to specify the security constraints of a particular HTTP method.

@HttpMethodConstraint注解允许我们指定特定HTTP方法的安全约束。

@HttpMethodConstraint has the following attributes:

@HttpMethodConstraint具有以下属性。

  • value
  • emptyRoleSemantic
  • rolesAllowed
  • transportGuarantee

In the example code snippet above, it shows how the doPost method is restricted only for users who belong to the Admin role, allowing the deposit function to be done only by an Admin user.

在上面的示例代码片断中,显示了doPost方法是如何只对属于Admin角色的用户进行限制的,允许存款功能只由Admin用户完成。

8. @MultipartConfig

8.@MultipartConfig

This annotation is used when we need to annotate a servlet to handle multipart/form-data requests (typically used for a File Upload servlet).

当我们需要注释一个servlet来处理multipart/form-data请求(通常用于文件上传servlet)时,就可以使用这个注释。

This will expose the getParts() and getPart(name) methods of the HttpServletRequest can be used to access all parts as well as an individual part.

这将暴露出getParts()getPart(name)方法的HttpServletRequest可用于访问所有部分以及单个部分。

The uploaded file can be written to the disk by calling the write(fileName) of the Part object.

通过调用部件对象的write(fileName),可以将上传的文件写到磁盘。

Now we will look at an example servlet UploadCustomerDocumentsServlet that demonstrates its usage:

现在我们来看看一个示范性的Servlet UploadCustomerDocumentsServlet ,它演示了它的用法。

@WebServlet(urlPatterns = { "/uploadCustDocs" })
@MultipartConfig(
  fileSizeThreshold = 1024 * 1024 * 20,
  maxFileSize = 1024 * 1024 * 20,
  maxRequestSize = 1024 * 1024 * 25,
  location = "./custDocs")
public class UploadCustomerDocumentsServlet extends HttpServlet {

    protected void doPost(HttpServletRequest request, HttpServletResponse response) 
      throws ServletException, IOException {
        for (Part part : request.getParts()) {
            part.write("myFile");
        }
    }

}

@MultipartConfig has four attributes:

@MultipartConfig有四个属性。

  • fileSizeThreshold – This is the size threshold when saving the uploaded file temporarily. If the uploaded file’s size is greater than this threshold, it will be stored on the disk. Otherwise, the file is stored in memory (size in bytes)
  • maxFileSize – This is the maximum size of the uploaded file (size in bytes)
  • maxRequestSize – This is the highest size of the request, including both uploaded files and other form data (size in bytes)
  • location – The is the directory where uploaded files are stored

9. Conclusion

9.结论

In this article, we looked at some Java EE annotations introduced with the Servlet API 3.1 and their purpose and their usage.

在这篇文章中,我们看了一些随Servlet API 3.1引入的Java EE注解,以及它们的目的和用法。

Source code related to this article can be found over on GitHub.

与本文有关的源代码可以在GitHub上找到over