您当前的位置: 首页 > 文章详情 网站首页 文章详情
Spring MVC 映射Date类型参数的解决方案
发布时间:2017-1-23 17:30:39 作者:Jastar · Wang 浏览:738
在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"; }
原创声明:
1.本文章系原创,版权归本站所有。
2.本站所有文章允许转载,开放分享,但严禁用于任何商业用途。
3.转载文章请务必保留以下信息:
原文作者:Jastar·Wang(或“代码与酒博客频道”)
原文链接: