其实模型驱动这个名字听起来挺大气的 说实话乍看起来看不明白。
先举例:一个model类:Department类,就是一个简单的类。
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 public class Department implements Serializable{ 2 3 private Long did; 4 private String dname; 5 private String description; 6 7 private Set<User> users; 8 9 public Long getDid() { 10 return did; 11 } 12 13 public void setDid(Long did) { 14 this.did = did; 15 } 16 17 public String getDname() { 18 return dname; 19 } 20 21 public void setDname(String dname) { 22 this.dname = dname; 23 } 24 25 public String getDescription() { 26 return description; 27 } 28 29 public void setDescription(String description) { 30 this.description = description; 31 } 32 33 public Set<User> getUsers() { 34 return users; 35 } 36 37 public void setUsers(Set<User> users) { 38 this.users = users; 39 } 40 41 }
既然是说明struts2的模型驱动,当然得再建一个action类DepartmentAction.class
1 public class DepartmentAction extends ActionSupport implements ModelDriven<Department>{ 2 3 private IDepartmentService departmentService; 4 5 private Department department = new Department(); 6 public void setDepartmentService(IDepartmentService departmentService) { 7 this.departmentService = departmentService; 8 } 9 public Department getModel() { 10 return department; 11 } 12 13 }
该类继承了ActionSupport类,实现了接口ModelDriven,这个接口定义了一个方法叫做getModel(),它是用来返回实体的对象,像上面的department。
到底getModel方法谁来调用,那就是拦截器来调用。模型驱动拦截器ModelDrivenInterceptor中的部分源码
1 @Override 2 public String intercept(ActionInvocation invocation) throws Exception { 3 Object action = invocation.getAction(); 4 5 if (action instanceof ModelDriven) {//判断当前的action是否实现了ModelDriven接口 6 ModelDriven modelDriven = (ModelDriven) action; 7 ValueStack stack = invocation.getStack();//把ValueStack值栈取出来 8 Object model = modelDriven.getModel(); 9 if (model != null) { 10 stack.push(model);//把模型驱动的对象加入到栈顶 11 } 12 if (refreshModelBeforeResult) { 13 invocation.addPreResultListener(new RefreshModelBeforeResult(modelDriven, model)); 14 } 15 } 16 return invocation.invoke(); 17 }