springmvc自定义数据类型转化器

目录:

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

[一]、应用场景

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

[二]、实现方法

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

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

1package com.micmiu.demo.web.v1.utils;
2 
3import java.text.SimpleDateFormat;
4 
5import org.springframework.beans.propertyeditors.CustomDateEditor;
6import org.springframework.web.bind.WebDataBinder;
7import org.springframework.web.bind.support.WebBindingInitializer;
8import org.springframework.web.context.request.WebRequest;
9 
10/**
11 * 自定义日期、时间的类型绑定
12 *
13 * @author <a href="http://www.micmiu.com">Michael Sun</a>
14 */
15public classMyDataBinding implements WebBindingInitializer {
16 
17    publicvoid initBinder(WebDataBinder binder, WebRequest request) {
18        SimpleDateFormat dateFormat =new SimpleDateFormat("yyyy-MM-dd");
19        dateFormat.setLenient(false);
20 
21        SimpleDateFormat datetimeFormat =new SimpleDateFormat(
22                "yyyy-MM-dd HH:mm:ss");
23        datetimeFormat.setLenient(false);
24 
25        binder.registerCustomEditor(java.util.Date.class,new CustomDateEditor(
26                dateFormat,true));
27        binder.registerCustomEditor(java.sql.Timestamp.class,
28                newCustomTimestampEditor(datetimeFormat, true));
29    }
30}

Timestamp 的实现:CustomTimestampEditor.java 

1package com.micmiu.demo.web.v1.utils;
2 
3import java.beans.PropertyEditorSupport;
4import java.sql.Timestamp;
5import java.text.SimpleDateFormat;
6import org.springframework.util.StringUtils;
7import java.text.ParseException;
8 
9/**
10 * Property editor for <code>java.sql.Timestamp</code>,<br>
11 * supporting a custom <code>java.text.DateFormat</code>.
12 *
13 * @author <a href="http://www.micmiu.com">Michael Sun</a>
14 */
15public classCustomTimestampEditor extendsPropertyEditorSupport {
16 
17    privatefinal SimpleDateFormat dateFormat;
18    privatefinal boolean allowEmpty;
19    privatefinal int exactDateLength;
20 
21    publicCustomTimestampEditor(SimpleDateFormat dateFormat, booleanallowEmpty) {
22        this.dateFormat = dateFormat;
23        this.allowEmpty = allowEmpty;
24        this.exactDateLength = -1;
25    }
26 
27    publicCustomTimestampEditor(SimpleDateFormat dateFormat,
28            booleanallowEmpty, int exactDateLength) {
29        this.dateFormat = dateFormat;
30        this.allowEmpty = allowEmpty;
31        this.exactDateLength = exactDateLength;
32    }
33 
34    publicvoid setAsText(String text) throws IllegalArgumentException {
35        if((this.allowEmpty) && (!(StringUtils.hasText(text)))) {
36            setValue(null);
37        } else {
38            if((text != null) && (this.exactDateLength >=0)
39                    && (text.length() !=this.exactDateLength)) {
40                thrownew IllegalArgumentException(
41                        "Could not parse date: it is not exactly"
42                                +this.exactDateLength + "characters long");
43            }
44            try{
45                setValue(newTimestamp(this.dateFormat.parse(text).getTime()));
46            }catch (ParseException ex) {
47                thrownew IllegalArgumentException("Could not parse date: "
48                        + ex.getMessage(), ex);
49            }
50        }
51    }
52 
53    publicString getAsText() {
54        Timestamp value = (Timestamp) getValue();
55        return((value != null) ?this.dateFormat.format(value) :"");
56    }
57}

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

1<!--Spring3.1 之后的自定义注解 HandlerAdapter -->
2<bean
3    class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter">
4    <propertyname="webBindingInitializer">
5        <beanclass="com.micmiu.demo.web.v1.utils.MyDataBinding"/>
6    </property>
7    <propertyname="messageConverters">
8        <list>
9            <bean
10                class="org.springframework.http.converter.ByteArrayHttpMessageConverter"/>
11            <bean
12                class="org.springframework.http.converter.StringHttpMessageConverter">
13                <propertyname="writeAcceptCharset"value="false"/>
14                <propertyname="supportedMediaTypes">
15                    <list>
16                        <value>text/plain;charset=UTF-8</value>
17                        <value>*/*;charset=UTF-8</value>
18                    </list>
19                </property>
20            </bean>
21            <bean
22                class="org.springframework.http.converter.xml.SourceHttpMessageConverter"/>
23            <bean
24                class="org.springframework.http.converter.support.AllEncompassingFormHttpMessageConverter"/>
25            <bean
26                class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter"></bean>
27        </list>
28    </property>
29</bean>

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值