zoukankan      html  css  js  c++  java
  • Struts2属性驱动与模型驱动

    为什么要使用属性驱动和模型驱动

    struts2与struts很大的不同点在于,struts的execute方法提供了HttpServletRequest和HttpServletResponse方法在获取客户端提交的数据信息的时候需要使用HttpServletRequest的getParameter()方法,并且还需要进行必要的数据类型转换。如何客户端提交的数据量大的时候,我们则需要写很多的getParameter方法。这样代码量就相应的增加不少。但是struts2为我们提供了属性驱动和模型驱动,它不需要我们写很多的获取值的方法。而只需要我们在Action中定义相应的getter方法,在界面上以Action中的变量名作为表单元素的name属性值即可。

    二、属性驱动和模型驱动有什么异同?

    1.属性驱动

    对于属性驱动,我们需要在Action中定义与表单元素对应的所有的属性,因而在Action中会出现很多的getter和setter方法

    2.模型驱动

    对于模型驱动,使用的Action对象需要实现ModelDriven接口并给定所需要的类型.而在Action中我们只需要定义一个封装所有数据信息的javabean

    3.属性和模型驱动的相同点

    当我们使用属性驱动和模型驱动的时候,必须将表单的元素中的name属性值与我们定义接收数据信息的变量名对应起来。

    模型驱动具体实例

    模型驱动,与之前的属性驱动区别在于把所有的属性封装在一个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<User> {
     
    	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;
    	}
    }
  • 相关阅读:
    使用 Spring data redis 结合 Spring cache 缓存数据配置
    Spring Web Flow 笔记
    Linux 定时实行一次任务命令
    css js 优化工具
    arch Failed to load module "intel"
    go 冒泡排序
    go (break goto continue)
    VirtualBox,Kernel driver not installed (rc=-1908)
    go运算符
    go iota
  • 原文地址:https://www.cnblogs.com/chengJAVA/p/3628804.html
Copyright © 2011-2022 走看看