0%

Struts2 Action模型驱动

模型驱动,与之前的属性驱动区别在于把所有的属性封装在一个JavaBean(模型)中,当用户提交数据时,自动调用模型属性的setter方法设置属性值,缺点在于没有属性驱动灵活。 User.java(模型):

package com.bean;

public class User {
    private String username;
    private String password;
    public String getUsername() {
        return username;
    }
    public void setUsername(String username) {
        this.username = username;
    }
    public String getPassword() {
        return password;
    }
    public void setPassword(String password) {
        this.password = password;
    }
    @Override
    public String toString() {
        // TODO Auto-generated method stub
        return this.username+" "+this.password;
    }
}

Action除了继承ActionSupport还要实现ModelDriven接口,该接口定义了一个getModel()方法,返回经过赋值的模型实例:

package com.struts2;

import com.bean.User;
import com.impl.LoginServiceImpl;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;
import com.service.LoginService;

public class LoginAction extends ActionSupport implements ModelDriven {

    public User user=new User();
    private LoginService loginService=new LoginServiceImpl();
    //LoginService是登录的
    /**
     * getModel方法自动将提交的数据给user属性赋值
     */
    @Override
    public User getModel() {
        // TODO Auto-generated method stub
        return user;
    }
    
    public String execute() throws Exception
    {
        if(loginService.isLogin(user))
        {
            return SUCCESS;
        }
        this.addActionError("用户名或密码错误");
        return INPUT;
    }
}

struts.xml配置与原属性驱动无异。