Struts 2 简明教程

Struts 2 - Hello World Example

您已从 Struts 2 架构中了解到,在 Struts 2 Web 应用程序中单击超链接或提交 HTML 表单时,输入由控制器收集,该控制器将输入发送到名为 Actions 的 Java 类。在执行 Action 后,结果选择资源以呈现响应。该资源通常是 JSP,但它也可以是 PDF 文件、Excel 电子表格或 Java 小程序窗口。

As you have already learnt from the Struts 2 architecture, when you click on a hyperlink or submit an HTML form in a Struts 2 web-application, the input is collected by the Controller which is sent to a Java class called Actions. After the Action is executed, a result selects a resource to render the response. The resource is generally a JSP, but it can also be a PDF file, an Excel spreadsheet, or a Java applet window.

假设您已经构建了开发环境。现在,让我们继续构建我们的第一个 Hello World Struts2 项目。该项目的目标是构建一个收集用户姓名并在用户姓名后显示“Hello World”的 Web 应用程序。

Assuming that you already have built your development environment. Now, let us proceed for building our first Hello World Struts2 project. The aim of this project is to build a web application that collects the user’s name and displays "Hello World" followed by the user name.

对于任何 Struts 2 项目,我们必须创建以下四个组件 −

We would have to create following four components for any Struts 2 project −

Sr.No

Components & Description

1

Action Create an action class which will contain complete business logic and control the interaction between the user, the model, and the view.

2

Interceptors Create interceptors if required, or use existing interceptors. This is part of Controller.

3

View Create a JSPs to interact with the user to take input and to present the final messages.

4

Configuration Files Create configuration files to couple the Action, View and Controllers. These files are struts.xml, web.xml, struts.properties.

我打算使用 Eclipse IDE,这样所有必需的组件都将创建在动态 Web 项目下。让我们现在开始创建动态 Web 项目。

I am going to use Eclipse IDE, so that all the required components will be created under a Dynamic Web Project. Let us now start with creating Dynamic Web Project.

Create a Dynamic Web Project

启动 Eclipse,然后使用 File > New > Dynamic Web Project 执行,输入项目名称为 HelloWorldStruts2 ,并设置其选项的其余部分,如下一个界面中所示 −

Start your Eclipse and then go with File > New > Dynamic Web Project and enter project name as HelloWorldStruts2 and set rest of the options as given in the following screen −

helloworldstruts1

在下一个界面中选择所有默认选项,最后选中 Generate Web.xml deployment descriptor 选项。这将在 Eclipse 中为您创建一个动态 Web 项目。现在使用 Windows > Show View > Project Explorer ,您会看到您的项目窗口如下所示 −

Select all the default options in the next screens and finally check Generate Web.xml deployment descriptor option. This will create a dynamic web project for you in Eclipse. Now go with Windows > Show View > Project Explorer, and you will see your project window something as below −

helloworldstruts2

现在,将 struts 2 库文件夹 C:\struts-2.2.3\lib 中的以下文件复制到我们的项目的 WEB-INF\lib 文件夹。为此,您可以简单地将以下所有文件拖放到 WEB-INF\lib 文件夹中。

Now copy following files from struts 2 lib folder C:\struts-2.2.3\lib to our project’s WEB-INF\lib folder. To do this, you can simply drag and drop all the following files into WEB-INF\lib folder.

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

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

  3. commons-lang-x.y.jar

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

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

  6. freemarker-x.y.z.jar

  7. javassist-.xy.z.GA

  8. ognl-x.y.z.jar

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

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

Create Action Class

Action 类是 Struts 2 应用程序的关键,我们大多数在 action 类中实现业务逻辑。因此,让我们在 Java Resources > src 下创建一个 Java 文件 HelloWorldAction.java,其中含有 com.tutorialspoint.struts2 包的名称,并在其中包含如下内容。

Action class is the key to Struts 2 application and we implement most of the business logic in action class. So let us create a java file HelloWorldAction.java under Java Resources > src with a package name com.tutorialspoint.struts2 with the contents given below.

Action 类在用户单击 URL 时响应用户操作。将执行一个或多个 Action 类的,并将返回一个字符串结果。特定 JSP 页面将基于结果中含有的值进行呈现。

The Action class responds to a user action when user clicks a URL. One or more of the Action class’s methods are executed and a String result is returned. Based on the value of the result, a specific JSP page is rendered.

package com.tutorialspoint.struts2;

public class HelloWorldAction {
   private String name;

   public String execute() throws Exception {
      return "success";
   }

   public String getName() {
      return name;
   }

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

这是一个非常简单的类,其中一个属性称为“name”。我们为“name”属性有标准的 getter 和 setter 方法,并有一个返回字符串“success”的 execute 方法。

This is a very simple class with one property called "name". We have standard getters and setter methods for the "name" property and an execute method that returns the string "success".

Struts 2 框架将为此 HelloWorldAction 类创建一个对象,并在响应用户的操作时调用 execute 方法。您将业务逻辑放入该方法,该方法最终返回 String 常量。换句话说,对于每个 URL,您必须实现一个 action 类,并可以使用类名作为您的 action 名称,或者使用 struts.xml 文件进行映射,如下所示。

The Struts 2 framework will create an object of the HelloWorldAction class and call the executed method in response to a user’s action. You put your business logic inside this method which finally returns the String constant. In other words, for each URL, you would have to implement one action class and either you can use that class name directly as your action name or you can map to some other name using struts.xml file as shown below.

Create a View

我们还需要一个 JSP 来显示最终信息,当发生预定义的操作时,此页面将由 Struts 2 框架调用,且此映射将定义在 struts.xml 文件中。因此,让我们在 Eclipse 项目中的 WebContent 文件夹中创建以下 jsp 文件 HelloWorld.jsp 。为此,在 Project Explorer 文件夹中右键单击 WebContent 文件夹,并选择 New >JSP File

We need a JSP to present the final message, this page will be called by Struts 2 framework when a predefined action will happen and this mapping will be defined in struts.xml file. So let us create the below jsp file HelloWorld.jsp in the WebContent folder in your eclipse project. To do this, right click on the WebContent folder in the project explorer and select New >JSP File.

<%@ page contentType = "text/html; charset = UTF-8" %>
<%@ taglib prefix = "s" uri = "/struts-tags" %>

<html>
   <head>
      <title>Hello World</title>
   </head>

   <body>
      Hello World, <s:property value = "name"/>
   </body>
</html>

taglib 指令告诉 Servlet 容器本页面将使用 Struts 2 标记,且这些标记将 s

The taglib directive tells the Servlet container that this page will be using the Struts 2 tags and that these tags will be preceded by s.

s:property 将显示 action 类属性“name”的值,后者由 HelloWorldAction 类中的 getName() 方法返回。

The s:property tag displays the value of action class property "name> which is returned by the method getName() of the HelloWorldAction class.

Create Main Page

我们还需要在 WebContent 中创建 index.jsp 。此文件将作为初始 action URL,用户可以单击此 URL 通知 Struts 2 框架调用 HelloWorldAction 类的确定方法并呈现 HelloWorld.jsp 视图。

We also need to create index.jsp in the WebContent folder. This file will serve as the initial action URL where a user can click to tell the Struts 2 framework to call a defined method of the HelloWorldAction class and render the HelloWorld.jsp view.

<%@ 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>Hello World</title>
   </head>

   <body>
      <h1>Hello World From Struts2</h1>
      <form action = "hello">
         <label for = "name">Please enter your name</label><br/>
         <input type = "text" name = "name"/>
         <input type = "submit" value = "Say Hello"/>
      </form>
   </body>
</html>

上面视图文件中定义的 hello action 将使用 struts.xml 文件映射到 HelloWorldAction 类及其 execute 方法。当用户点击“提交”按钮时,这将导致 Struts 2 框架运行 HelloWorldAction 类中定义的 execute 方法,且基于该方法返回的一个值,将选择一个合适的视图并将其呈现为响应。

The hello action defined in the above view file will be mapped to the HelloWorldAction class and its execute method using struts.xml file. When a user clicks on the Submit button it will cause the Struts 2 framework to run the execute method defined in the HelloWorldAction class and based on the returned value of the method, an appropriate view will be selected and rendered as a response.

Configuration Files

我们需要一个映射来关联 URL、HelloWorldAction 类(模型)和 HelloWorld.jsp(视图)。该映射将告诉 Struts 2 框架哪些类将响应用户的操作(URL)、将执行该类的哪些方法,以及将基于该方法返回的字符串结果呈现哪些视图。

We need a mapping to tie the URL, the HelloWorldAction class (Model), and the HelloWorld.jsp (the view) together. The mapping tells the Struts 2 framework which class will respond to the user’s action (the URL), which method of that class will be executed, and what view to render based on the String result that method returns.

因此,让我们创建一个名为 struts.xml 的文件。因为 Struts 2 要求将 struts.xml 放在 classes 文件夹中。因此,在 WebContent/WEB-INF/classes 文件夹下创建 struts.xml 文件。Eclipse 默认不会创建“classes”文件夹,因此您需要自己创建。为此,在 Project Explorer 中右键单击 WEB-INF 文件夹,并选择 New > Folder 。您的 struts.xml 应如下所示:

So let us create a file called struts.xml. Since Struts 2 requires struts.xml to be present in the classes folder. Hence, create struts.xml file under the WebContent/WEB-INF/classes folder. Eclipse does not create the "classes" folder by default, so you need to do this yourself. To do this, right click on the WEB-INF folder in the project explorer and select New > Folder. Your struts.xml should look like −

<?xml version = "1.0" Encoding = "UTF-8"?>
<!DOCTYPE struts PUBLIC
   "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
   "http://struts.apache.org/dtds/struts-2.0.dtd">

<struts>
   <constant name = "struts.devMode" value = "true" />

   <package name = "helloworld" extends = "struts-default">
     <action name = "hello"
         class = "com.tutorialspoint.struts2.HelloWorldAction"
         method = "execute">
         <result name = "success">/HelloWorld.jsp</result>
      </action>
   </package>
</struts>

需要对上述配置文件作一点说明。在此,我们将 constants struts.devMode 设为 true ,因为我们正在开发环境中工作并且我们需要看到一些有用的日志消息。然后,我们定义了一个名为 helloworld 的包。

Few words which need to be understood regarding the above configuration file. Here, we set the constant struts.devMode to true, because we are working in development environment and we need to see some useful log messages. Then, we define a package called helloworld.

当您想要将 action 放在一起时,创建包非常有用。在我们的示例中,我们将其 action 命名为“hello”,它对应于 URL /hello.action ,并且由 HelloWorldAction.class 支持。当调用 URL /hello.action 时, HelloWorldAction.classexecute 方法就是要运行的方法。如果 execute 方法返回的结果为“success”,那么我们就会将用户带到 HelloWorld.jsp

Creating a package is useful when you want to group your actions together. In our example, we named our action as "hello" which is corresponding to the URL /hello.action and is backed up by the*HelloWorldAction.class*. The execute method of HelloWorldAction.class is the method that is run when the URL /hello.action is invoked. If the outcome of the execute method returns "success", then we take the user to HelloWorld.jsp.

下一步是创建 web.xml 文件,该文件是 Struts 2 任何请求的入口点。Struts2 应用程序的入口点将是部署描述符 (web.xml) 中定义的一个过滤器。因此,我们会在 web.xml 中定义 org.apache.struts2.dispatcher.FilterDispatcher 类的入口。需要在 WebContent 下的 WEB-INF 文件夹下创建 web.xml 文件。当您创建该项目时,Eclipse 已经为您创建了一个空的 web.xml 文件。因此,我们只需按如下所示对其进行修改:

Next step is to create a web.xml file which is an entry point for any request to Struts 2. The entry point of Struts2 application will be a filter defined in deployment descriptor (web.xml). Hence, we will define an entry of org.apache.struts2.dispatcher.FilterDispatcher class in web.xml. The web.xml file needs to be created under the WEB-INF folder under WebContent. Eclipse had already created a skeleton web.xml file for you when you created the project. So, lets just modify it as follows −

<?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>
   </filter>

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

我们已经将 index.jsp 指定为我们的欢迎文件。然后,我们已经将 Struts2 过滤器配置为在所有 url 上运行(即与 /* 模式匹配的任何 url)。

We have specified index.jsp to be our welcome file. Then we have configured the Struts2 filter to run on all urls (i.e, any url that match the pattern /*)

To Enable Detailed Log

您可以在 WEB-INF/classes 文件夹下创建 logging.properties 文件,从而在使用 Struts 2 时启用完整的日志功能。在您的属性文件中保留以下两行内容:

You can enable complete logging functionality while working with Struts 2 by creating logging.properties file under WEB-INF/classes folder. Keep the following two lines in your property file −

org.apache.catalina.core.ContainerBase.[Catalina].level = INFO
org.apache.catalina.core.ContainerBase.[Catalina].handlers = \
   java.util.logging.ConsoleHandler

默认的 logging.properties 指定了一个 ConsoleHandler,用于将日志转到 stdout 以及一个 FileHandler。可以使用 SEVERE、WARNING、INFO、CONFIG、FINE、FINER、FINEST 或 ALL 设置处理器的日志级别阈值。

The default logging.properties specifies a ConsoleHandler for routing logging to stdout and also a FileHandler. A handler’s log level threshold can be set using SEVERE, WARNING, INFO, CONFIG, FINE, FINER, FINEST or ALL.

这就完成了。我们已经准备好使用 Struts 2 框架运行我们的 Hello World 应用程序。

That’s it. We are ready to run our Hello World application using Struts 2 framework.

Procedure for Executing the Application

右键点击项目名称,然后点击 Export > WAR File 创建一个 War 文件。

Right click on the project name and click Export > WAR File to create a War file.

然后将这个 WAR 部署在 Tomcat 的 webapps 目录中。

Then deploy this WAR in the Tomcat’s webapps directory.

最后,启动 Tomcat 服务器,然后尝试访问 URL http://localhost:8080/HelloWorldStruts2/index.jsp 。这将给你提供以下屏幕 −

Finally, start Tomcat server and try to access URL http://localhost:8080/HelloWorldStruts2/index.jsp. This will give you following screen −

helloworldstruts4

输入一个值“Struts2”并提交页面。你应该能看到下一页

Enter a value "Struts2" and submit the page. You should see the next page

helloworldstruts5

注意,你可以在 struts.xml 文件中定义一个 index 为一个动作,而在那种情况下,你就可以像 http://localhost:8080/HelloWorldStruts2/index.action 一样调用 index 页面。检查下面如何定义 index 为一个动作 −

Note that you can define index as an action in struts.xml file and in that case you can call index page as http://localhost:8080/HelloWorldStruts2/index.action. Check below how you can define index as an action −

<?xml version = "1.0" Encoding = "UTF-8"?>
<!DOCTYPE struts PUBLIC
   "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
   "http://struts.apache.org/dtds/struts-2.0.dtd">
<struts>
   <constant name = "struts.devMode" value = "true" />
   <package name = "helloworld" extends = "struts-default">

      <action name = "index">
         <result >/index.jsp</result>
      </action>

      <action name = "hello"
         class = "com.tutorialspoint.struts2.HelloWorldAction"
         method = "execute">
         <result name = "success">/HelloWorld.jsp</result>
      </action>

   </package>
</struts>