struts2继承ActionSupport类
1.struts2框架搭建流程,请看上一个博客。
2.在src目录下新建一个包,即com.hnpi.action,在包下建一个class类,即HelloWordAction,
注意:使用继承ActionSupport类来实现Action的方式,如下所示:
import com.opensymphony.xwork2.ActionSupport;
public class HelloWorldAction extends ActionSupport {
//省略了
}
ActionSupport类本身实现了Action接口,所以继承ActionSupport类就相当于实现了Action接口。除此之外,ActionSupport类还实现了其它几个接口,来为程序员提供更多使用的功能,这些接口和Struts2的一些其他特性相结合,可以实现基本的数据验证功能和国际化。接口如下所示:
com.opensymphony.xwork2.Validateable; //提供validate()方法来为Action增加验证的功能
com.opensymphony.xwork2.Validateaware; //提供方法来保存和恢复action或field级的错误信息
com.opensymphony.xwork2.TextProvider; //提供获取本地信息文本的功能
com.opensymphony.xwork2.LocaleProvider;//提供getLocale()方法来获取本地消息
3.要实现数据验证的功能,只需要在Action类中覆盖实现validate方法即可;在validate方法内部,对请求传递过来的数据进行校验,如果不满足要求,那么添加例外信息到父类用于存放例外的集合中。示例代码如下:
package com.hnpi.action;
import com.opensymphony.xwork2.ActionSupport;
public class HelloWorldAction extends ActionSupport {
private String account;
private String password;
private String submitFlag;
public String execute() throws Exception {
this.businessExecute();
return "toWelcome";
}
public void validate(){
if(account==null || account.trim().length()==0){
this.addFieldError("account", "账号不可以为空");