struts2封装客户端数据到Action
1.在Action中定义简单数据类型的属性
给Action定义简单类型的属性,封装客户端请求的数据
简单类型:String,基本类型和对应的引用类型
只要保证客户端请求的参数名称和Action的属性名称一样。
2.在Action中定义javabean对象封装客户端数据
2.1定义实体类
1 public class Users
2 {
3 private String uname;
4 private String upwd;
5 private Integer type;
6 public String getUname()
7 {
8 return uname;
9 }
10 public void setUname(String uname)
11 {
12 this.uname = uname;
13 }
14 public String getUpwd()
15 {
16 return upwd;
17 }
18 public void setUpwd(String upwd)
19 {
20 this.upwd = upwd;
21 }
22 public Integer getType()
23 {
24 return type;
25 }
26 public void setType(Integer type)
27 {
28 this.type = type;
29 }
30 }
2.2定义Action
Action中定义Javabean对象,作为属性
1 public class UserAction2
2 {
3 /***
4 * 使用javabean对象作为Action的属性,封装客户端请求的数据
5 * 如果Users类中存在一个属性为Score类型,Score类中存在一个属性Integer类型num
6
7 * 参数名称怎么写?user.score.num(属性链),struts2框架会自动的属性链上的每一个
8
9 * javabean类型进行实例化(ognl)
10
11 * **/
12 private Users user;
13 public Users getUser()
14 {
15 return user;
16 }
17 public void setUser(Users user)
18 {
19 this.user = user;
20 }
21 public String userReg2()
22 {
23 System.out.println(user.getUname()+" === "+user.getUpwd()+" === "+user.getType());
24 return Action.SUCCESS;
25 }
26 }
2.3注册Action
2.4定义UI页面
1 <!-- 使用javabean作为Action的属性 -->
2 <form action="userAction2_userReg2.action" method="post">
3 <div>
4 uname:
5 <input type="text" name="user.uname" />
6 </div>
7 <div>
8 upwd :
9 <input type="text" name="user.upwd " />
10 </div>
11 <div>
12 type :
13 <select name="user.type">
14 <option value="1">管理员</option>
15 <option value="2">用户</option>
16 </select>
17 </div>
18 <div>
19 <input type="submit" value="注册" />
20 </div>
21 </form>
总结:struts2框架会自动的获得客户端请求的参数,自动的类型转化,自动的封装为需要业务对象。
3 实现接口ModelDriven
ModelDriven:接口使用ognl表达式完成对象执行的封装,而getModel方法的返回值是被默认访问的对象。
3.1定义Action
1 public class UserAction3 implements ModelDriven<Users>
2 {
3 //定义Action的属性,同时进行实例化
4 private Users user=new Users();
5 /**
6 * 该方法会将客户端请求的参数,封装到users对象中,将users对象放入
7 * Action的值栈中.(ongl)
8 * 如果实现ModelDriven接口,
9 * 请求参数会被默认封装带getModel方法的返回值对象中
10 * 当获取需要的执行的是,默认由getModel方法的返回值对象中获得
11 * 好处:简化了参数的访问形式(客户端参数的命名,el表示的形式进行简化)
12 */
13 @Override
14 public Users getModel()
15 {
16 System.out.println("---------------"+user);
17 return user;
18 }
19 public String userReg3()
20 {
21 System.out.println(user.getUname()+" ------- "+user.getUpwd()+" ------- "+user.getType());
22 return Action.SUCCESS;
23 }
24 }
3.2定义UI页面
1 <!-- 通过实现ModelDirven接口,封装客户端数据 -->
2 <form action="userAction3_userReg3.action" method="post">
3 <div>
4 uname:
5 <input type="text" name="uname" />
6 </div>
7 <div>
8 upwd :
9 <input type="text" name="upwd" />
10 </div>
11 <div>
12 type :
13 <select name="type">
14 <option value="1">管理员</option>
15 <option value="2">用户</option>
16 </select>
17 </div>
18 <div>
19 <input type="submit" value="注册" />
20 </div>
21 </form>