struts2中的模型驱

action中的写法:
public class CategoryAction extends ActionSupport implements ModelDriven<Category>{

	private static final long serialVersionUID = 1L;
	private CategoryService cs = new CategoryService();
	public Category category = new Category(); //创建javabean实例
	
	public Category getCategory() {
		return category;
	}
	public void setCategory(Category category) {
		this.category = category;
	}
	
	@Override
	public Category getModel() {
		return category;
	}
	
	public String List(){
		java.util.List<Category> list = cs.getList();
		ActionContext.getContext().put("list", list);
		return "list";
	}

	public String add(){
		cs.add(category);
		return List();
	}
}
jsp中的写法:
</pre><pre name="code" class="java">
<span style="white-space:pre">	</span><s:form action="/category_add" method="post" theme="simple">
		<s:textfield name="cname"></s:textfield>
		<s:textfield name="cdate"></s:textfield>
		<s:submit value="提交"></s:submit>
	</s:form>


直接使用javabean的属性作为name可以取值与赋值。因为struts2是基于拦截器的,而模型驱动使用的拦截器是ModelDrivenInterceptor。其中的逻辑为:

@Override
    public String intercept(ActionInvocation invocation) throws Exception {
        Object action = invocation.getAction();

        if (action instanceof ModelDriven) {
            ModelDriven modelDriven = (ModelDriven) action;
            ValueStack stack = invocation.getStack();
            Object model = modelDriven.getModel();
            if (model !=  null) {
            	stack.push(model);//将对象置入值栈中
            }
            if (refreshModelBeforeResult) {
                invocation.addPreResultListener(new RefreshModelBeforeResult(modelDriven, model));
            }
        }
        return invocation.invoke();
    }



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值