技术开发 频道

Struts2 与 Struts1.x比较

二、 Action的区别

对于有着丰富的Struts1.x开发经验的朋友来说,都十分的清楚Action是整个Struts框架的核心内容,当然Struts2也不例外。不过,Struts1.x与Struts2的Action模型很大的区别。

Struts2和Struts1.x的差别,最明显的就是Struts2是一个pull-MVC架构。这是什么意思呢?从开发者角度看,就是说需要显示给用户的数据可以直接从Action中获取,而不像Struts1.x那样,必须把相应的Bean存到Page、Request或者Session中才能获取。Struts1.x 必须继承org.apache.struts.action.Action或者其子类,表单数据封装在FormBean中。Struts 2无须继承任何类型或实现任何接口,表单数据包含在Action中,通过Getter和Setter获取(如下面的ActionForStruts2的代码示例)。

虽然,在理论上Struts2的Action无须实现任何接口或者是继承任何的类,但是,在实际编程过程中,为了更加方便的实现Action,大多数情况下都会继承com.opensymphony.xwork2.ActionSupport类,并且重载(Override)此类里的String execute()方法。如下所示:

package ActionDiffer;
            
import java.text.DateFormat;
            
import java.util.Date;
            
import com.opensymphony.xwork2.ActionSupport;
            
public class ActionForStruts2 extends ActionSupport {
            
private String message;
            
public String getMessage() {
            
return message;
            }
            @Override
            
public String execute() {
            message 
= " This is hello from strtuts2. Now is: " +
            DateFormat.getInstance().format( 
new Date());
            
return SUCCESS;
            }
            }

首先,从ActionForStruts2可以看出,返回的对象不是ActionForward,而是String。如果你不喜欢以字符串的形式出现在你的代码中,有个Helper接口Action可以以常量方式提供常见结果,如“success”、“none”、“error”、“input”和“login”。

另外, 按照惯例,在Struts1.x中只有“execute”方法能调用Action, 但在Struts2中并非必要,任何声明为public String methodName() 方法,都能通过配置来调用Action。

最后,和Struts1.x最大的革命性的不同是,Struts2处理Action过程中调用的方法(“execute”方法)是不带参数的。那如何获取所需要的对象呢?答案是使用IoC(反转控制,Inversion of Control),也叫“依赖注入(Dependency Injection)”的模式(想更多地了解这方面信息请看Martin Fowler的文章http://www.martinfowler.com/articles/injection.html)。Spring框架使得这个模式流行起来,然而Struts2的前身(WebWork)也同时应用上了这个模式。

0
相关文章