作用:从页面读取数据时,简化bean的数据封装过程

用法:

1.添加两个jar

commons-beanutils-1.8.3.jar

commons-logging-1.1.1.jar

2.使用

/**
 * 实验beanUtils的Servlet 
 */
public class UserServlet03 extends HttpServlet {
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

		request.setCharacterEncoding(\"utf-8\");
		try {
			//注册自己的日期转换器
			ConvertUtils.register(new MyDateConverter(), Date.class);
			//转换
			Map map=request.getParameterMap();
			UserBean bean=new UserBean();
			//转换map数据,方法到bean上
			BeanUtils.populate(bean, map);
			//输出
			System.out.println(bean.toString());
			
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}
}

3.由于BeanUtils不能转换日期格式的数据,所以自定义 java.util.Date日期转换器

package it.cast.util;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import org.apache.commons.beanutils.Converter;

/**
 * 自定义 java.util.Date日期转换器
 */
public class MyDateConverter implements Converter {

	@Override
	// 将value 转换 c 对应类型
	// 存在Class参数目的编写通用转换器,如果转换目标类型是确定的,可以不使用c 参数
	public   convert(Class c,   value) {
		String strVal = (String) value;
		// 将String转换为Date --- 需要使用日期格式化
		DateFormat dateFormat = new SimpleDateFormat(\"yyyy-MM-dd\");
		try {
			Date date = dateFormat.parse(strVal);
			return date;
		} catch (ParseException e) {
			e.printStackTrace();
		}
		return null;
	}
}

示例bean:

public class UserBean {
	private String username;
	private String password;
	private String phone;
	private String mail;
	private Date 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 getPhone() {
		return phone;
	}
	public void setPhone(String phone) {
		this.phone = phone;
	}
	public String getMail() {
		return mail;
	}
	public void setMail(String mail) {
		this.mail = mail;
	}
	public Date getBirthday() {
		return birthday;
	}
	public void setBirthday(Date birthday) {
		this.birthday = birthday;
	}
	@Override
	public String toString() {
		return \"UserBean [username=\" + username + \", password=\" + password + \", phone=\" + phone + \", mail=\" + mail
				+ \", birthday=\" + birthday + \"]\";
	}
	
}

 

 

收藏 打印