BeanUtils工具的使用

BeanUtils工具可以通过BeanUtils.populate(Object bean , map)方法将从request中接收到的数据封装到一个对象里面

首先我们写一个User类

public class UserInfo {


    String userId = null;
    String userName  = null;
    Date birthday;
    int age ;
    double salary;

    public double getSalary() {
        return salary;
    }
    public void setSalary(double salary) {
        this.salary = salary;
    }
    public int getAge() {
        return age;
    }
    public void setAge(int age) {
        this.age = age;
    }
    public Date getBirthday() {
        return birthday;
    }
    public void setBirthday(Date birthday) {
        this.birthday = birthday;
    }
    public String getUserId() {
        return userId;
    }
    public void setUserId(String userId) {
        this.userId = userId;
    }
    public String getUserName() {
        return userName;
    }
    public void setUserName(String userName) {
        this.userName = userName;
    }
    @Override
    public String toString() {
        return "UserInfo [userId=" + userId + ", userName=" + userName + ", birthday=" + birthday + ", age=" + age
                + ", salary=" + salary + "]";
    }



}

然后jsp代码如下

<form action="../user.do?handler=addUser" method="post">

    用户id:<input type="text" name="userId">
    <br>
    <br>
    用户名:<input type="text" name="userName">
    <br>
    <br>
    生日:<input type="text" name="birthday">
    <br>
    <br>
    年龄:<input type="text" name="age">
    <br>
    <br>
    薪水:<input type="text" name="salary">
    <br>
    <br>
    <input type="submit" value="提交">

form>

由于从request中接收的数据类型都是String类型,所以必须要注册一个类型转换器才能实现自动的转换,代码如下:

public class ToDate implements Converter{
    //写一个Converter接口的实现类,下边要用到
    public Date convert(Class type, Object value) {
        if(value != null){
            try {
                return (Date) new SimpleDateFormat("yyyy-MM-dd").parse(value.toString());
            } catch (ParseException e) {
                e.printStackTrace();
            }
        }
        return null;
    }
}

通过BeanUtils工具将数据封装到UserInfo对象,代码如下:

public void addUser(HttpServletRequest request , HttpServletResponse response) throws UnsupportedEncodingException{
        //实例化userinfo对象
        UserInfo user = new UserInfo();
        //把从jsp中接收到的数据放在map里
        Map map = request.getParameterMap();
        Converter converter = new ToDate();
        //注册类型转换器,其中converter是Converter接口的实现类,Date.class是需要转换成的类型
        ConvertUtils.register(converter , Date.class);
        try {
            //封装到user对象里
            BeanUtils.populate(user, map);
        } catch (IllegalAccessException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        System.out.println(user);
    }

你可能感兴趣的:(java)