代码改变世界

java内省,PropertyDescriptor和BeansUtil

2012-04-16 23:16  党飞  阅读(357)  评论(0)    收藏  举报

为了完成演示我们要有一个注册页面,主题部分如下:

  <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);