struts2之3--Action类的包装

从上一篇文章中我们可以看到LoginAction 这个普通的类就可以实现方法处理。但为了更好,更规范,更简单的开发Action类,struts2提供了Action接口,也提供了一个类ActionSupport。

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)方法还实现国际化,该方法从资源文件上获取国际化信息,这是非常有用的。







  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值