struts2中的ModelDriven

2014-11-24 10:10:33 · 作者: · 浏览: 2
在使用struts2的时候,我们在 jsp中经常写这样的代码片段:
  


其中studentScores.student.stuName是对应后台action的熟悉,action是这样写的

public class StudentExamAction extends ActionSupport {


	// 学生实体
	private Student studentScores;

	//查询学生的分数
	public String queryScores(){
	
		.....
		.....
	}
	

	public Student getStudentScores() {
		return studentScores;
	}

	public void setStudentScores(Student studentScores) {
		this.studentScores = studentScores;
	}

	
}

在action中设置了studentScores的getter/setter的属性,前台就可以使用对象名.属性名的方式设置或获取值了,studentScores.student.stuName当中,studentScores对象导航了两次,导航次数还比较少,当导航次数多了,造成了要写的字串很长,这是可以使用struts2的ModelDriven机制。


首先让action类继承ModelDriven接口,并实现getModel接口:

/**
 * 
 * 
 * @author : xqf
 * @group : tgb8
 * @Date : 2013-12-31 14:07:29
 * @Version : 1.0.0
 */
public class StudentExamAction extends ModelDriven {


	// 学生实体
	private Student studentScores;

	//实现getModel方法
	 @Override
    public Object getModel() {

       if(studentScores == null){
           studentScores = new studentScores();
       }
       return studentScores;

    }

	
	//查询学生的分数
	public String queryScores(){
	
		.....
		.....
	}
	

	public Student getStudentScores() {
		return studentScores;
	}

	public void setStudentScores(Student studentScores) {
		this.studentScores = studentScores;
	}

	
}

然后写上面的jsp页代码的时候就可以像下面一样了,代码少了一些:

  

背后的原理涉及到了在struts2传值中非常重要的valueStack,以后用一篇专门的博客来讲一讲,大家也可以参照下面这篇博客来帮助理解:

Struts2数据传输的背后机制

Struts2中ModelDriven机制及其运用