SpringMVC自定义日期类型的数据绑定

目录:

  1. 应用场景
  2. 实现方法

[一]、应用场景

在实际应用中,经常会碰到表单中的日期 字符串和Javabean中的日期类型的属性自动转换,一般页面输入的日志格式为:yyyy-MM-dd ,而SpringMVC中默认不支持这样的格式转换,所以需要我们自定义数据类型的绑定才能实现这个功能。

[二]、实现方法

利用 WebBindingInitializer 注册自定义日期转换控制器。

自定义日期转换器:MyDataBinding.java

Timestamp 的实现:CustomTimestampEditor.java 

修改spring-mvc 的配置文件,添加 webBindingInitializer 属性的注入配置

这样就可以实现表单中的字符串自动转换为Date或者Timestamp 类型。

本文介绍到此结束@Michael Sun.

原创文章,转载请注明: 转载自micmiu – 软件开发+生活点滴[ http://www.micmiu.com/ ]

本文链接地址: http://www.micmiu.com/j2ee/spring/springmvc-binding-date/

发表评论?

5 条评论。

  1. 我他妈怎么没找到这个类:

    CustomTimestampEditor

    Spring 4.0.5

  2. 哥哥好:

    我已经解决了这个问题。使用了spring3.2提供的全局@ControllerAdvice,代码如下:

    @ControllerAdvice
    public class GlobalController {

    @InitBinder
    public void initBinder(WebDataBinder binder) {
    SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
    dateFormat.setLenient(false);

    SimpleDateFormat datetimeFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    datetimeFormat.setLenient(false);

    //自动转换日期类型的字段格式
    binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true));
    binder.registerCustomEditor(java.sql.Timestamp.class, new CustomTimestampEditor(datetimeFormat, true));

    //防止XSS攻击
    binder.registerCustomEditor(String.class, new StringEscapeEditor(true, false));
    }
    }

  3. 哥哥好:
    我按照你的demo配置了我的应用。启动正常,但保存表单时出问题。还是没绑定上。
    我若在Controller中自行用@InitBinder就没问题。
    我找了很多,是不是和mvc:annotation-driven配置有冲突呢。我的配置是


    如上配置,若只配置

    也不行。

    另外,我的项目默认引用的是fasterxml的jackson,为了引入

    引入了codehaus的jackson
    按理说不影响吧。或者去掉这个bean不引入codehaus的pom依赖也不行。

    请帮忙看看,是否落下了哪些呢? 我大概看了文档,也没看太明确。

    谢谢了哈。

回复给 杨光 ¬
取消回复


注意 - 你可以用以下 HTML tags and attributes:
<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code class="" title="" data-url=""> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong> <pre class="" title="" data-url=""> <span class="" title="" data-url="">