struts2之3--Action类的包装

来源:岁月联盟 编辑:exp 时间:2012-07-29

1  :直接让上面的Action去实现Struts2框架Action接口。里面会提供几个常量和一个抽象的execute方法。以下就是struts2提供的Action接口。
//定义5个字符串常量,统一返回值。主要的作用是 规范返回值。
public abstract interface com.opensymphony.xwork2.Action {
 
  // Field descriptor #4 Ljava/lang/String;
  public static final java.lang.String SUCCESS = "success";
 
  // Field descriptor #4 Ljava/lang/String;
  public static final java.lang.String NONE = "none";
 
  // Field descriptor #4 Ljava/lang/String;
  public static final java.lang.String ERROR = "error";
 
  // Field descriptor #4 Ljava/lang/String;
  public static final java.lang.String INPUT = "input";
 
  // Field descriptor #4 Ljava/lang/String;
  public static final java.lang.String LOGIN = "login";
 
  // Method descriptor #16 ()Ljava/lang/String;
  public abstract java.lang.String execute() throws java.lang.Exception;
}


2: 让上面的Action去继承Struts2框架的ActionSupport(com.opensymphony.xwork2.ActionSupport)这个类提供了Struts2的很多特殊的功能。
  让Action类继承这个ActionSupport类,就会时Action类可以提供数据校验,国际化,对象序列化等功能 。而且这个ActionSupport是实现Action接口的。

以下就是这个ActionSupport类要实现的接口声明。

public class com.opensymphony.xwork2.ActionSupport
implements com.opensymphony.xwork2.Action,
com.opensymphony.xwork2.Validateable,
com.opensymphony.xwork2.ValidationAware,
com.opensymphony.xwork2.TextProvider,
com.opensymphony.xwork2.LocaleProvider,
java.io.Serializable {

。。。 相关的处理方法
}

 

需要注意的地方

Actionsupport这个工具类在实现了Action接口的基础上还定义了一个validate()方法,重写该方法,它会在execute()方法之前执行,如校验失败,会转入input处,必须在配置该Action时配置input属性。
如果检验出错误可以调用this.addFieldError的方法给框架添加错误信息。然后在页面中可以直接显示出来。
如下示例:

@Override
public void validate() {
   if(null == this.getPasswd() || "".equals(this.getPasswd().trim())){
    this.addFieldError(passwd, "passwd is required");
   }
   if(null== this.getUsername() || "".equals(this.getUsername().trim())){
    this.addFieldError(username, "username is required");
   }
}

 

另外,Actionsupport还提供了一个getText(String key)方法还实现国际化,该方法从资源文件上获取国际化信息,这是非常有用的。

 


 


作者:weiguolee