1. Action 实现 ModelDriven 接口后的运行流程

本文解析了Struts2框架中ModelDriven拦截器的工作原理。首先通过ModelDrivenInterceptor的intercept方法获取并检查Action对象,确保其实现了ModelDriven接口。接着,通过调用getModel方法将对象压入值栈,并将请求参数赋值给栈顶对象。最后强调了getModel方法的正确实现方式。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1). 先会执行 ModelDrivenInterceptor 的 intercept 方法.

public String intercept(ActionInvocation invocation) throws Exception {
//获取 Action 对象: EmployeeAction 对象, 此时该 Action 已经实现了 ModelDriven 接口
//public class EmployeeAction implements RequestAware, ModelDriven<Employee>---这里就是我Action类实现的ModelDriven接口

 

Object action = invocation.getAction();

 

//判断 action 是否是 ModelDriven 的实例
if (action instanceof ModelDriven) {
//强制转换为 ModelDriven 类型
ModelDriven modelDriven = (ModelDriven) action;
//获取值栈
ValueStack stack = invocation.getStack();
//调用 ModelDriven 接口的 getModel() 方法
//即调用 EmployeeAction 的 getModel() 方法
/*自己在Action类中实现ModelDriven接口时重写了getModel()方法
public Employee getModel() {
employee = new Employee();
return employee;
}
*/
//实际就是为了获取到我们返回的对象
Object model = modelDriven.getModel();
if (model != null) {
//把 getModel() 方法的返回值(也就是我想压入栈顶的对象)压入到值栈的栈顶. 实际压入的是 EmployeeAction 的 employee 成员变量
stack.push(model);
}
if (refreshModelBeforeResult) {
invocation.addPreResultListener(new RefreshModelBeforeResult(modelDriven, model));
}
}
return invocation.invoke();
}

2).压入栈顶后, 执行到 ParametersInterceptor 的 intercept 方法: 把请求参数的值赋给栈顶对象对应的属性. 若栈顶对象没有对应的属性, 则查询
值栈中下一个对象对应的属性...

3). 注意: getModel 方法不能提供以下实现. 的确会返回一个 Employee 对象到值栈的栈顶. 但当前 Action
的 employee 成员变量却是 null.

public Employee getModel() {
return new Employee();
}

转载于:https://www.cnblogs.com/jeremy-blog/p/3992020.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值