public class User {
private String nickname;
private String message;
private double sale;
private Date birthday;
....
省略getter setter
public class MyDateConverter implements Converter {
@Override
public Object convert(Class clazz, Object obj) {
//obj强制类型转换为String
String str = (String) obj;
//定义日期格式化工具
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Date date = null;
try {
date = sdf.parse(str);
} catch (ParseException e) {
e.printStackTrace();
}
return date;
}
}
@WebServlet("/beanutils")
public class BeanUtilsServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
public BeanUtilsServlet() {
super();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("utf-8");
response.setCharacterEncoding("utf-8");
response.setContentType("text/html;charset=UTF-8");
//获取数据
Map<String, String[]> map = request.getParameterMap();
//创建对象
User user = new User();
//注册自定义转换器
ConvertUtils.register(new MyDateConverter(), Date.class);
//完成封装
try {
BeanUtils.populate(user, map);
} catch (IllegalAccessException | InvocationTargetException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//打印
System.out.println(user.getNickname());
System.out.println(user.getMessage());
System.out.println(user.getSale());
System.out.println(user.getBirthday());
}
...省略doPost
}
注意到这一行, Map<String, String[]> map = request.getParameterMap(); 我们使用了getParameterMap进行参数的获取,得到一个K为String(参数名),V为String[](参数值数组)的Map。
ConvertUtils.register(new MyDateConverter(), Date.class);
这里是在调用BeanUtils之前进行了自定转换器的注册。这样之后遇到满足日期定义模式的字符串时就会调用该转换器转换为日期类型。 BeanUtils.populate(user, map); 该方法接受两个参数,待封装的对象,要封装的参数map。
在前台输入如下参数
昵称 asdad
发言asdad
价格1111.333
日期1993-12-02
后台输出如下
asdad
asdad
1111.333
Thu Dec 02 00:00:00 CST 1993