有Struts 1.x经验的朋友都知道Action是Struts的核心内容,当然Struts 2.0也不例外。不过,Struts 1.x与Struts 2.0的Action模型很大的区别。
| Struts 1.x | Stuts 2.0 |
接口 | 必须继承org.apache.struts.action.Action或者其子类 | 无须继承任何类型或实现任何接口 |
表单数据 | 表单数据封装在FormBean中 | 表单数据包含在Action中,通过Getter和Setter获取 |
虽然,理论上Struts 2.0的Action无须实现任何接口或继承任何类型,但是,我们为了方便实现Action,大多数情况下都会继承com.opensymphony.xwork2.ActionSupport类,并重载(Override)此类里的String execute()方法。具体的实现,如例1所示:
<% @ page contentType = " text/html; charset=UTF-8 " %>
<% @ taglib prefix = " s " uri = " /struts-tags " %>
< html >
< head >
< title > Hello World! </ title >
</ head >
< body >
< h2 >< s:property value ="message" /></ h2 >
</ body >
</ html >
例1 HelloWorld.jsp
package tutorial;
import java.text.DateFormat;
import java.util.Date;
import com.opensymphony.xwork2.ActionSupport;
public class HelloWorld extends ActionSupport {
private String message;
public String getMessage() {
return message;
}
@Override
public String execute() {
message = " Hello World, Now is " + DateFormat.getInstance().format( new Date());
return SUCCESS;
}
}
例1 classes/tutorial/HelloWorld.java
< package name ="ActionDemo" extends ="struts-default" >
< action name ="HelloWorld" class ="tutorial.HelloWorld" >
< result > /HelloWorld.jsp </ result >
</ action >
</ package >
例1 classes/struts.xml中HelloWorld Action的配置
在浏览器地址栏中键入http://localhost:8080/Struts2_Action/HelloWorld.action。