首页 > 代码库 > struts中的模型驱动(ModelDriven)的使用
struts中的模型驱动(ModelDriven)的使用
模型驱动ModelDriven实际上是struts动作类所可以实现的一个接口,它可以直接把实体类当成页面数据的收集对象。
模型驱动的model有两个作用:1、获取表单中的数据。2、用于数据回显。
1、获取表单中数据:
实际上是一个名为modelDriver的拦截器来实现的。此拦截器在调用指定action方法(此处为add()方法)时候会先调用getModel()方法来初化model对象,接着将此模型压入valueStack栈顶中,接着对于表单中的属性的值,框架就会都调用栈顶对象的setter方法来保存。
实体类department.java如下:
public class Department implements Serializable{ private Long did; private String name; private String description; public Long getDid() { return did; } public void setDid(Long did) { this.did = did; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getDescription() { return description; } 动作类DepartmentAction.java
public class DepartmentAction extends ActionSupport implements ModelDriven<Department>{
//创建私有的模型驱动对象
private Department model = new Department();//对象一定要自己实例化(new 出来))
@Override
public Department getModel() {//调用action方法前会先调用此方法,但不会实例化相应对象。
return this.model;
}
private DepartmentService departmentService;
public void setDepartmentService(DepartmentService departmentService) {
this.departmentService = departmentService;
}
//页面的添加action方法
public String add(){
Department department = new Department();
//添加表单中的数据时,通过BeanUtils.copyProperties(source, target)方法,将表单中保存在栈顶的模型(表单中的department的数据)copy到新的department中保存进数据库
BeanUtils.copyProperties(this.model, department);
this.departmentService.saveDepartment(department);
return "chainAction";
}
}
2、对数据回显:
* 原理:回显是因为实现moderdriven接口的对象,会被struts2拦截器拦截封装,自动push到栈顶,然后前台页面取值时刚好是从栈顶取值,从而实现回显;
* 最好通过ActionContext.getContext().getValueStack().push(department)顶push方法,将moderdriven接口的对象放入内容栈(stack context)中,通过name=“xx”实现回显;
* 若通过ActionContext.getContext().put("department", department)方法放入valuestack中,则需要指定value="http://www.mamicode.com/%{#department.name}"回显;
public class DepartmentAction extends ActionSupport implements ModelDriven<Department>{
//创建私有的模型驱动对象
private Department model = new Department();//对象一定要自己实例化(new 出来)
@Override
public Department getModel() {//调用action方法前会先调用此方法,但不会实例化相应对象。
return this.model;
}
private DepartmentService departmentService;
public void setDepartmentService(DepartmentService departmentService) {
this.departmentService = departmentService;
}
public String updateUI(){
//得到要update的department,并将其放于内容栈(stack context)栈顶,内容栈栈顶的数据会根据对象的属性(如:name)回显在界面上,而放入valuestack中的数据需要在对象的前面加#回显。
Department department = this.departmentService.getDepartmentById(this.model.getDid());
ActionContext.getContext().getValueStack().push(department);//数据放进stack context栈顶
return "updateUI";
}
//更新用户数据方法:
public String update(){
//根据did找到要更新的department:
Department department = this.departmentService.getDepartmentById(this.model.getDid());
//将最新的department信息department中:
BeanUtils.copyProperties(this.model, department);
//将更新的department数据跟新到数据库中
this.departmentService.updateDepartment(department);
return "chainAction";
}
}
struts中的模型驱动(ModelDriven)的使用