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();
}