模型驱动

1.概述

模型驱动又称为ModelDriven。在实现过程中,Action需要去实现ModelDriven接口。

2.实现步骤

  • 第一步:创建类并实现ModelDriven接口
  • 第二步:定义属性(成员字段)并编写get/set访问器
  • 第三步:编写请求处理方法
  • 第四步:配置Action

3.示例

[Action]

 1 /**
 2  * 模型驱动
 3  *     必须实现ModelDriven接口
 4  *     成员字段必须进行实例化
 5  *     必须完成get访问器
 6  * @author Terry
 7  *
 8  */
 9 public class UserAction3 implements ModelDriven<User>{
10     //必须进行实例化
11     private User user = new User();
12     
13     //只有get(没有set)
14     @Override
15     public User getModel() {
16         return user;
17     }
18 
19     
20     public String execute(){
21         System.out.println(user);
22         return "success";
23     }
24 }

[配置Action]

1         <action name="add3" class="cn.hl.action.UserAction3">
2             <result>/update3.jsp</result>
3         </action>

[Jsp]

 1     <form action="user/add3.action" method="post">
 2         <table>
 3             <caption>
 4                 用户注册(实体类方式--模型驱动)
 5             </caption>
 6             <tr>
 7                 <th>姓名:</th>
 8                 <td>
 9                     <input type="text" name="userName" /> 
10                 </td>
11             </tr>
12             <tr>
13                 <th>帐号:</th>
14                 <td>
15                     <input type="text" name="account" /> 
16                 </td>
17             </tr> 
18             <tr>
19                 <th>密码:</th>
20                 <td>
21                     <input type="text" name="pwd" /> 
22                 </td>
23             </tr>   
24             <tr>
25                 <td>
26                     <input type="submit" value="保存" />
27                 </td>
28             </tr>        
29         </table>
30     </form>

【注意事项】

Ø 成员字段必须进行实例化

Ø Jsp使用字段的属性时,不需要加字段名(前缀)

Ø 不需要定义set访问器

    <form action="user/add3.action" method="post">

    <table>

    <caption>

    用户注册(实体类方式--模型驱动)

    </caption>

    <tr>

    <th>姓名:</th>

    <td>

    <input type="text" name="userName" /> 

    </td>

    </tr>

    <tr>

    <th>帐号:</th>

    <td>

    <input type="text" name="account" /> 

    </td>

    </tr> 

<tr>

    <th>密码:</th>

    <td>

    <input type="text" name="pwd" /> 

    </td>

    </tr>   

    <tr>

    <td>

    <input type="submit" value="保存" />

    </td>

    </tr>

    </table>

    </form>

原文地址:https://www.cnblogs.com/zhzcode/p/9941954.html