黑马程序员---PropertyDescriptor和BeansUtil

来源:互联网 发布:python可以做什么 编辑:程序博客网 时间:2024/05/17 21:44

---------------------- android培训、java培训、期待与您交流! ----------------------

我们有一个注册页面,主题部分如下:

  <body>
    <form action="servlet/MyServlet" method="post">
    用户名:<input type="text" name="username"/><br/>
    密码:<input type="password" name="password"/><br/>
    年龄:<input type="text" name="age"/><br/>
    出生日期:<input type="text" name="birthday"/><br/>     
     <input type="submit" value="登陆"/>
    </form>   
  </body>

针对此注册页面,我们见一个javaBean

public class Student {

 private String username;
 private String password;
 private String age;
 private String birthday;
 public String getUsername() {
  return username;
 }
 public void setUsername(String username) {
  this.username = username;
 }
 public String getPassword() {
  return password;
 }
 
 public void setPassword(String password) {
  this.password = password;
 }
 public String getAge() {
  return age;
 }
 public void setAge(String age) {
  this.age = age;
 }
 public String getBirthday() {
  return birthday;
 }
 public void setBirthday(String birthday) {
  this.birthday = birthday;
 }
 @Override
 public String toString() {
  return "Student [age=" + age + ", birthday=" + birthday + ", password="
    + password + ", username=" + username + "]";
 }
}

用PropertyDescriptor完成填充javaBean

 Student student = new Student();
  Map<String,String[]> map = request.getParameterMap();//得到页面参数组成的的map
  for(Map.Entry<String, String[]> o: map.entrySet())
  {
   String key = o.getKey();
   try {
    PropertyDescriptor pd = new PropertyDescriptor(key, Student.class);//用参数名和javaBean实例化PropertyDescriptor

    Method m = pd.getWriteMethod();//通过对参数名的反射得到setter方法
    m.invoke(student, o.getValue());
   } catch (Exception e) {
    throw new RuntimeException(e);
   }
  }
  System.out.println(student);

这样就把页面的数据存入了javaBean中,不过页面参数名一定要和javaBean中的一致。

BeanUtils把这些封装到了populate(...)中。

  Student student = new Student();
  Map<String,String[]> map = request.getParameterMap();  
  try {
   BeanUtils.populate(student, map);
  } catch (Exception e) {
   throw new RuntimeException(e);
  }
  System.out.println(student);

 

 

---------------------- android培训、java培训、期待与您交流! ---------------------- 

详细请查看:http://edu.csdn.net/heima 

原创粉丝点击
热门问题 老师的惩罚 人脸识别 我在镇武司摸鱼那些年 重生之率土为王 我在大康的咸鱼生活 盘龙之生命进化 天生仙种 凡人之先天五行 春回大明朝 姑娘不必设防,我是瞎子 金毛眼睛打肿了怎么办 金毛的眼睛红怎么办 眼睛干涩有红血丝怎么办 小孩子眼睛红有眼屎怎么办 狗狗的肉垫粗糙怎么办 狗狗眼睛变蓝色怎么办 脸被太阳晒伤了怎么办 皮肤晒伤红肿痒怎么办 3岁儿童频繁眨眼怎么办 狗狗的眼睛红肿怎么办 脸过敏发红怎么办不痒 上眼皮红肿痒是怎么办 眼睛痒了几天了怎么办 眼睛肿了还痒怎么办 孩子脸上有红血丝怎么办 脸上长了红血丝怎么办 指甲受创出血了怎么办 手指被挤压紫了怎么办 眼睛撞了有淤血怎么办 下眼底有小白点怎么办 狗的白眼球充血怎么办 眼球有出血点是怎么办 吃阿胶上火了该怎么办 胎儿胼胝体发育不良怎么办 鸡眼看到硬芯了怎么办 小脚趾起茧子疼怎么办 脚起老茧很痛怎么办 化疗后骨髓抑制严重怎么办 胃炎引起的胃胀怎么办 胃病胀肚子很鼓怎么办 小孩淋巴结发炎肚子疼痛怎么办 顺产后子宫脱垂怎么办 顺产完子宫脱垂怎么办 额头长了个鱼鳞怎么办 脸上长了很多痣怎么办 做过狐臭的疤痕怎么办 痤疮留下的红印怎么办 脸上疤掉了黑印怎么办 脸上有黑色的疤怎么办 一只眼睛外斜视怎么办 残币银行不给换怎么办