Structs2 ModelDriven使用方法介绍

例子都为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"来取值。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值