例子都为struts2中的文档例子
JSP提交数据:
<s:form action=
"modelDrivenResult"
method=
"POST"
namespace=
"/modelDriven"
>
<s:textfield label=
"Gangster Name"
name=
"name"
/>
<s:textfield label=
"Gangster Age"
name=
"age"
/>
<s:checkbox label=
"Gangster Busted Before"
name=
"bustedBefore"
/>
<s:textarea cols=
"30"
rows=
"5"
label=
"Gangster Description"
name=
"description"
/>
<s:submit />
</s:form>
|
根据数据提交的action,和namespace,修改struts.xml的内容
添加下面配置到struts.xml
<
package
name=
"base2"
namespace=
"/modelDriven"
extends
=
"struts-default"
>
<action name=
"modelDrivenResult"
class
=
"ModelDrivenAction"
>
<result>/Hello.jsp</result>
</action>
</
package
>
|
然后添加处理数据的action,这里使用ModelDriven的方式。该action继承ModelDriven接口,实现getModel()方法,方法只返回一个模型对象,默认转换Object。只要改模型对象提供的方法和提交数据的name属性对应,struts2就能自动把数据赋给模型对象,最后对象提供各种get方法把数据存放在值栈,传递到Hello.jsp。
处理的action,返回模型对象Gangster。
public
class
ModelDrivenAction
extends
ActionSupport
implements
ModelDriven {
public
String execute()
throws
Exception {
return
SUCCESS;
}
public
Object getModel() {
return
new
Gangster();
}
}
|
模型类
public
class
Gangster
implements
Serializable {
private
String name;
private
int
age;
private
String description;
private
boolean
bustedBefore;
public
int
getAge() {
return
age;
}
public
void
setAge(
int
age) {
this
.age = age;
}
public
boolean
isBustedBefore() {
return
bustedBefore;
}
public
void
setBustedBefore(
boolean
bustedBefore) {
this
.bustedBefore = bustedBefore;
}
public
String getDescription() {
return
description;
}
public
void
setDescription(String description) {
this
.description = description;
}
public
String getName() {
return
name;
}
public
void
setName(String name) {
this
.name = name;
}
}
|
最后Hello.jsp中可以使用<s:property value=".."/>取值,value直接使用相应的age,name等。而action虽然提供的getModel()方法,但因为转为了Object,而Object不能提供取值的方法,所以无法使用value="model.xxx"来取值。