作用:从页面读取数据时,简化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 + \"]\";
}
}
继续阅读与本文标签相同的文章
上一篇 :
权威发布:中国人工智能学会自动驾驶入门秘籍
-
专线网络与家庭宽带区别(基础篇)
2026-05-18栏目: 教程
-
还不会用 K8s 集群控制器?那你会用冰箱吗?(多图详解)
2026-05-18栏目: 教程
-
Java 12 与Java 13 新特性预览:Switch表达式、GC新垃圾回收算法、低延时GC、ZGC改进等
2026-05-18栏目: 教程
-
Apache Flink 在同程艺龙实时计算平台的研发与应用实践
2026-05-18栏目: 教程
-
Apache Flink 进阶(一):Runtime 核心机制剖析
2026-05-18栏目: 教程
