Struts 2 简明教程

Struts 2 - Annotations

如前所述,Struts 提供两种形式的配置。传统方法是为所有配置使用 struts.xml 文件。到目前为止,我们在教程中已经看到了很多这样的例子。配置 Struts 的另一种方法是使用 Java 5 注释特性。使用 Struts 注释,我们可以实现 Zero Configuration

As mentioned previously, Struts provides two forms of configuration. The traditional way is to use the struts.xml file for all the configurations. We have seen so many examples of that in the tutorial so far. The other way of configuring Struts is by using the Java 5 Annotations feature. Using the struts annotations, we can achieve Zero Configuration.

要在您的项目中开始使用注释,请确保您已将以下 jar 文件包含在 WebContent/WEB-INF/lib 文件夹中 -

To start using annotations in your project, make sure you have included the following jar files in your WebContent/WEB-INF/lib folder −

  1. struts2-convention-plugin-x.y.z.jar

  2. asm-x.y.jar

  3. antlr-x.y.z.jar

  4. commons-fileupload-x.y.z.jar

  5. commons-io-x.y.z.jar

  6. commons-lang-x.y.jar

  7. commons-logging-x.y.z.jar

  8. commons-logging-api-x.y.jar

  9. freemarker-x.y.z.jar

  10. javassist-.xy.z.GA

  11. ognl-x.y.z.jar

  12. struts2-core-x.y.z.jar

  13. xwork-core.x.y.z.jar

现在,让我们来看看如何清除 struts.xml 文件中可用的配置并用注释替换它。

Now, let us see how you can do away with the configuration available in the struts.xml file and replace it with annotaions.

要解释 Struts2 中注释的概念,我们必须重新考虑 Struts2 Validations 章节中解释的验证示例。

To explain the concept of Annotation in Struts2, we would have to reconsider our validation example explained in Struts2 Validations chapter.

在这里,我们以一个员工为例,他的姓名和年龄将使用一个简单的页面进行捕获,并且我们将放置两个验证以确保“USER”始终输入一个姓名,并且年龄应介于 28 到 65 之间。

Here, we shall take an example of an Employee whose name, age would be captured using a simple page, and we will put two validations to make sure that ÜSER always enters a name and age should be in between 28 and 65.

让我们从示例的主要 JSP 页面开始。

Let us start with the main JSP page of the example.

Create Main Page

让我们编写主页面 JSP 文件 index.jsp ,用于收集上述与员工相关的的信息。

Let us write main page JSP file index.jsp, which is used to collect Employee related information mentioned above.

<%@ page language = "java" contentType = "text/html; charset = ISO-8859-1"
   pageEncoding = "ISO-8859-1"%>
<%@ taglib prefix = "s" uri = "/struts-tags"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
   "http://www.w3.org/TR/html4/loose.dtd">

<html>
   <head>
      <title>Employee Form</title>
   </head>

   <body>

      <s:form action = "empinfo" method = "post">
         <s:textfield name = "name" label = "Name" size = "20" />
         <s:textfield name = "age" label = "Age" size = "20" />
         <s:submit name = "submit" label = "Submit" align="center" />
      </s:form>

   </body>
</html>

index.jsp 利用了 Struts 标记,我们尚未介绍它,但我们将在与标记相关的章节中研究它。但就目前而言,假设 s:textfield 标记打印一个输入字段,而 s:submit 打印一个提交按钮。我们在每个标记中使用了 label 属性,为每个标记创建标签。

The index.jsp makes use of Struts tag, which we have not covered yet but we will study them in tags related chapters. But for now, just assume that the s:textfield tag prints a input field, and the s:submit prints a submit button. We have used label property for each tag which creates label for each tag.

Create Views

我们将使用 JSP 文件 success.jsp ,该文件在已定义的操作返回 SUCCESS 的情况下调用。

We will use JSP file success.jsp which will be invoked in case the defined action returns SUCCESS.

<%@ page language = "java" contentType = "text/html; charset = ISO-8859-1"
	pageEncoding = "ISO-8859-1"%>
<%@ taglib prefix = "s" uri = "/struts-tags"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
   "http://www.w3.org/TR/html4/loose.dtd">

<html>
   <head>
      <title>Success</title>
   </head>

   <body>
      Employee Information is captured successfully.
   </body>
</html>

Create Action

这是使用注释的地方。让我们在 Employee.java 文件中使用注释重新定义操作类 Employee ,然后添加一个名为 validate () 的方法,如下所示。确保您的操作类扩展 ActionSupport 类,否则您的 validate 方法将不会执行。

This is the place where annotation is used. Let us re-define action class Employee with annotation, and then add a method called validate () as shown below in Employee.java file. Make sure that your action class extends the ActionSupport class, otherwise your validate method will not be executed.

package com.tutorialspoint.struts2;

import com.opensymphony.xwork2.ActionSupport;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Result;
import org.apache.struts2.convention.annotation.Results;
import com.opensymphony.xwork2.validator.annotations.*;

@Results({
   @Result(name = "success", Location = "/success.jsp"),
   @Result(name = "input", Location = "/index.jsp")
})
public class Employee extends ActionSupport {
   private String name;
   private int age;

   @Action(value = "/empinfo")

   public String execute() {
      return SUCCESS;
   }

   @RequiredFieldValidator( message = "The name is required" )

   public String getName() {
      return name;
   }

   public void setName(String name) {
      this.name = name;
   }

   @IntRangeFieldValidator(message = "Age must be in between 28 and 65", min = "29", max = "65")

   public int getAge() {
      return age;
   }

   public void setAge(int age) {
      this.age = age;
   }
}

我们在本示例中使用了几个注释。让我逐一解释一下 -

We have used few annotations in this example. Let me go through them one by one −

  1. First, we have included the Results annotation. A Results annotation is a collection of results.

  2. Under the results annotation, we have two result annotations. The result annotations have the name that correspond to the outcome of the execute method. They also contain a location as to which view should be served corresponding to return value from execute()

  3. The next annotation is the Action annotation. This is used to decorate the execute() method. The Action method also takes in a value which is the URL on which the action is invoked.

  4. Finally, I have used two validation annotations. I have configured the required field validator on name field and the integer range validator on the age field. I have also specified a custom message for the validations.

Configuration Files

我们确实不需要 struts.xml 配置文件,所以让我们删除此文件,并查看 web.xml 文件的内容 −

We really do not need struts.xml configuration file, so let us remove this file and let us check the content of web.xml file −

<?xml version = "1.0" Encoding = "UTF-8"?>
<web-app xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance"
   xmlns = "http://java.sun.com/xml/ns/javaee"
   xmlns:web = "http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
   xsi:schemaLocation = "http://java.sun.com/xml/ns/javaee
   http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
   id = "WebApp_ID" version = "3.0">

   <display-name>Struts 2</display-name>

   <welcome-file-list>
      <welcome-file>index.jsp</welcome-file>
   </welcome-file-list>

   <filter>
      <filter-name>struts2</filter-name>

      <filter-class>
         org.apache.struts2.dispatcher.FilterDispatcher
      </filter-class>

      <init-param>
         <param-name>struts.devMode</param-name>
         <param-value>true</param-value>
      </init-param>
   </filter>

   <filter-mapping>
      <filter-name>struts2</filter-name>
      <url-pattern>/*</url-pattern>
   </filter-mapping>
</web-app>

现在,右键单击项目名称并单击 Export > WAR File 以创建 War 文件。然后将此 WAR 部署在 Tomcat 的 webapps 目录中。最后,启动 Tomcat 服务器并尝试访问 URL http://localhost:8080/HelloWorldStruts2/index.jsp 。这将生成以下屏幕:

Now, right click on the project name and click Export > WAR File to create a War file. Then deploy this WAR in the Tomcat’s webapps directory. Finally, start Tomcat server and try to access URL http://localhost:8080/HelloWorldStruts2/index.jsp. This will produce the following screen −

helloworldstruts12

现在不要输入任何必需信息,只需点击 Submit 按钮即可。您将看到以下结果 -

Now do not enter any required information, just click on Submit button. You will see the following result −

helloworldstruts121

输入必需信息,但输入一个错误的 From 域,假设名称为“测试”,年龄为 30,最后点击 Submit 按钮。您将看到以下结果 -

Enter the required information but enter a wrong From field, let us say name as "test" and age as 30, and finally click on Submit button. You will see the following result −

helloworldstruts122

Struts 2 Annotations Types

Struts 2 应用程序可以使用 Java 5 注释,作为 XML 和 Java 属性配置的替代方案。您可以查看与不同类别相关的最重要注释的列表 −

Struts 2 applications can use Java 5 annotations as an alternative to XML and Java properties configuration. You can check the list of most important annotations related to different categories −