action类中属性驱动和模型驱动的区别

1.Struts2的属性驱动

 

在Action类中,属性××通过get××()和set××()方法,把参数在整个生命周期内进行传递,这就是属性驱动

代码如下:

 

package org.abu.csdn.action.user;

import com.opensymphony.xwork2.ActionSupport;

public class RegisterAction extends ActionSupport {  //首先类RegisterAction 必须继承ActionSupport 

    private String uname;


    public String getUname() {

        return uname;
    }

    public void setUname(String uname) {
        this.uname = uname;
    }

 

    @Override
    public String execute() throws Exception {    //重写execute() 方法执行Action动作
        return ActionSupport.SUCCESS;
    }

    public void validate(){  //重写validate()方法

if(uname==null || uname.trim().length()==0){

    this.addFieldError("uname","用户名不能为空");  //重写addFieldError()方法来进行错误处理

}

    }

}

 

2.Struts2的模型驱动

 

把用户请求参数封装到一个javabean中,Action中使用一个独立的modle实例来封装用户的请求参数和处理结果,action完成业务逻辑调度,使用2个类来分解action任务,这就是模型驱动。

 

注意:使用模型驱动时,在继承ActionSupport类或者实现action接口时,必须实现一个ModelDriver接口,该接口的作用建立一个Model对象来代替Action本身把数据存入ValueStack

 

 

代码如下:

 //把用户请求参数封装到User中

 

public class User { 

    private String uname;
    public String getUname() {

        return uname;
    }

    public void setUname(String uname) {
        this.uname = uname;
    } 

}

 

//Action中使用一个独立的RegisterAction(){}实例来封装用户的请求参数和处理结果
package org.abu.csdn.action.user;

import org.abu.csdn.dto.User;

import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;

public class RegisterAction extends ActionSupport implements ModelDriven<User> {//实现ModelDriver接口,该接口的作用建立一个Model对象来代替Action本身把数据存入ValueStackAc。

//<User>: 在这里引入student类

    private User user=new User();
    public User getModel() {// 模型驱动必须实现的方法,也是ModelDriven接口中唯一的方法       

        return user;
    }

   public RegisterAction(){

getModel() .setUname("Marry") ;

   }

   

   public String oneNewRegister(){

getModel() .setUname("Danny") ;

   }

    @Override
    public String execute() throws Exception {  //重写execute() 方法执行Action动作      
        return  SUCCESS;
    }

    public void validate(){  //重写validate()方法

 

if(user.getUname() ==null || user.getUname() .trim().length()==0){

    this.addFieldError("uname","用户名不能为空");  //重写addFieldError()方法来进行错误处理

}

    }

}

 

 
 
posted @ 2017-09-25 10:15  L伟铭  阅读(374)  评论(0编辑  收藏  举报