在Spring MVC中,无法直接将Date类型的数据映射绑定到Controller方法的参数中,因为Spring本身不支持这种类型的转换,所以这里有两种解决方案供小伙伴儿们参考一下下。
1.自定义格式转换(荐)
在Controller中使用InitBinder(该注解在Spring2.5之后才有)注解来定义如下方法,即可解决Date类型转换问题:
/**
* 自定义方法绑定请求参数的Date类型
*
* @param request
* @param binder
* @throws Exception
*/
@InitBinder
protected void initBinder(HttpServletRequest request, ServletRequestDataBinder binder) throws Exception {
DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
CustomDateEditor editor = new CustomDateEditor(df, true);//true表示允许为空,false反之
binder.registerCustomEditor(Date.class, editor);
}
2.单独映射该参数(土)
当然了,最土的方法莫过于把这个Date类型的参数单独映射为String类型,然后自己再通过程序将其转换为Date类型:
@RequestMapping(value = "test")
public String test(ModelMap model, String date) throws ParseException {
Date d = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(date);
// ...接下来怎么做咯
return "test";
}
更多推荐
Spring MVC 映射Date类型参数的解决方案
发布评论