Struts 2 简明教程
Struts 2 - Actions
Actions 是 Struts2 框架的核心,它们对任何 MVC(模型视图控制器)框架来说都是如此。每个 URL 都会映射到一个特定的操作,该操作提供处理逻辑,这是为用户提供服务请求所必需的。
Actions are the core of the Struts2 framework, as they are for any MVC (Model View Controller) framework. Each URL is mapped to a specific action, which provides the processing logic which is necessary to service the request from the user.
但是,该操作还可以在两个其他重要能力中发挥作用。首先,无论它是一个 JSP 还是其他类型的结果,该操作在从请求传输到视图的数据传输中扮演着重要的角色。其次,该操作必须协助框架确定哪个结果应呈现将在响应中返回给请求的视图。
But the action also serves in two other important capacities. Firstly, the action plays an important role in the transfer of data from the request through to the view, whether its a JSP or other type of result. Secondly, the action must assist the framework in determining which result should render the view that will be returned in the response to the request.
Create Action
Struts2 中操作的唯一要求是必须有一个不带参数的方法,该方法返回一个 String 或 Result 对象,并且必须是一个 POJO。如果未指定不带参数的方法,则默认行为是使用 execute() 方法。
The only requirement for actions in Struts2 is that there must be one noargument method that returns either a String or Result object and must be a POJO. If the no-argument method is not specified, the default behavior is to use the execute() method.
另外,你可以扩展实现六个接口的 ActionSupport 类,包括 Action 接口。Action 接口如下:
Optionally you can extend the ActionSupport class which implements six interfaces including Action interface. The Action interface is as follows −
public interface Action {
public static final String SUCCESS = "success";
public static final String NONE = "none";
public static final String ERROR = "error";
public static final String INPUT = "input";
public static final String LOGIN = "login";
public String execute() throws Exception;
}
让我们看看 Hello World 示例中的操作方法:
Let us take a look at the action method in the Hello World example −
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;
}
}
为了说明操作方法控制视图的观点,让我们对 execute 方法进行以下更改并按如下方式扩展类 ActionSupport:
To illustrate the point that the action method controls the view, let us make the following change to the execute method and extend the class ActionSupport as follows −
package com.tutorialspoint.struts2;
import com.opensymphony.xwork2.ActionSupport;
public class HelloWorldAction extends ActionSupport {
private String name;
public String execute() throws Exception {
if ("SECRET".equals(name)) {
return SUCCESS;
} else {
return ERROR;
}
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
在此示例中,我们在 execute 方法中有一些逻辑来查看 name 属性。如果该属性等于字符串 "SECRET" ,我们返回 SUCCESS 作为结果,否则返回 ERROR 作为结果。因为我们扩展了 ActionSupport,所以我们可以使用 String 常量 SUCCESS 和 ERROR。现在,让我们按如下方式修改我们的 struts.xml 文件:
In this example, we have some logic in the execute method to look at the name attribute. If the attribute equals to the string "SECRET", we return SUCCESS as the result otherwise we return ERROR as the result. Because we have extended ActionSupport, so we can use String constants SUCCESS and ERROR. Now, let us modify our struts.xml file as follows −
<?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>
<result name = "error">/AccessDenied.jsp</result>
</action>
</package>
</struts>
Create a View
让我们在 Eclipse 项目的 WebContent 文件夹中创建以下 jsp 文件 HelloWorld.jsp 。为此,右键单击项目资源管理器中的 WebContent 文件夹,然后选择 New >JSP File 。如果返回结果是 SUCCESS(这是在 Action 接口中定义的一个 String 常量“success”),则会调用该文件:
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. This file will be called in case return result is SUCCESS which is a String constant "success" as defined in Action interface −
<%@ 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>
以下是如果操作结果是 ERROR(等于 String 常量“error”)的情况下框架调用的文件。以下是 AccessDenied.jsp 的内容:
Following is the file which will be invoked by the framework in case action result is ERROR which is equal to String constant "error". Following is the content of AccessDenied.jsp
<%@ page contentType = "text/html; charset = UTF-8" %>
<%@ taglib prefix = "s" uri = "/struts-tags" %>
<html>
<head>
<title>Access Denied</title>
</head>
<body>
You are not authorized to view this page.
</body>
</html>
我们还需要在 WebContent 文件夹中创建一个 index.jsp 。该文件将作为初始操作 URL,用户可以单击此 URL 告知 Struts 2 框架调用 HelloWorldAction 类的 execute 方法并呈现 HelloWorld.jsp 视图。
We also need to create index.jsp in the WebContent folder. This file will serve as the initial action URL where the user can click to tell the Struts 2 framework to call the *execute*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>
就是这样,不需要更改 web.xml 文件,因此让我们使用我们在 Examples 章节中创建的相同的 web.xml。现在,我们可以使用 Struts 2 框架运行我们的 Hello World 应用程序了。
That’s it, there is no change required for web.xml file, so let us use the same web.xml which we had created in Examples chapter. Now, we are ready to run our Hello World application using Struts 2 framework.
Execute the Application
右键单击项目名称并单击 Export > WAR 文件来创建一个 War 文件。然后将此 WAR 部署到 Tomcat 的 webapps 目录中。最后,启动 Tomcat 服务器并尝试访问 URL http://localhost:8080/HelloWorldStruts2/index.jsp 。这将为您提供以下屏幕:
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 give you following screen −
让我们输入一个单词“SECRET”,你将看到以下页面:
Let us enter a word as "SECRET" and you should see the following page −
现在输入除了“SECRET”之外的任何单词,你将看到以下页面:
Now enter any word other than "SECRET" and you should see the following page −
Create Multiple Actions
你将经常定义多个操作来处理不同的请求并向用户提供不同的 URL,你要按如下所示定义不同的类:
You will frequently define more than one actions to handle different requests and to provide different URLs to the users, accordingly you will define different classes as defined below −
package com.tutorialspoint.struts2;
import com.opensymphony.xwork2.ActionSupport;
class MyAction extends ActionSupport {
public static String GOOD = SUCCESS;
public static String BAD = ERROR;
}
public class HelloWorld extends ActionSupport {
...
public String execute() {
if ("SECRET".equals(name)) return MyAction.GOOD;
return MyAction.BAD;
}
...
}
public class SomeOtherClass extends ActionSupport {
...
public String execute() {
return MyAction.GOOD;
}
...
}
你将按如下方式在 struts.xml 文件中配置这些操作:
You will configure these actions in struts.xml file as follows −
<?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.HelloWorld"
method = "execute">
<result name = "success">/HelloWorld.jsp</result>
<result name = "error">/AccessDenied.jsp</result>
</action>
<action name = "something"
class = "com.tutorialspoint.struts2.SomeOtherClass"
method = "execute">
<result name = "success">/Something.jsp</result>
<result name = "error">/AccessDenied.jsp</result>
</action>
</package>
</struts>
正如你在上面假设的示例中看到的那样,操作结果 SUCCESS 和 ERROR’s 是重复的。
As you can see in the above hypothetical example, the action results SUCCESS and ERROR’s are duplicated.
为了解决此问题,建议你创建一个包含结果结果的类。
To get around this issue, it is suggested that you create a class which contains the result outcomes.