您的位置:首页 > 编程语言 > Java开发

SpringMVC中绑定日期类型的几种方式总结

2018-06-13 09:54 501 查看
版权声明:转载请申明原创地址 https://blog.csdn.net/pw191410147/article/details/80674569

1,在bean实体中使用@DateTimeFormat(pattern="yyyy-MM-dd")


2,自定义一个全局类型转换器

package com.itpengwei.bos.converters;

import java.text.SimpleDateFormat;
import java.util.Date;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.convert.converter.Converter;

/**
* S:需要转换的资源 T:target目标资源
*
* @author pengwei
*
*/
public class GloabDateConverters implements Converter<String, Date> {

@Override
public Date convert(String source) {
try {
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
Date target = dateFormat.parse(source);
// 转换完成返回出去
return target;
} catch (Exception e) {
e.printStackTrace();
// 转换异常,返回null
return null;
}
}

}

然后在springmvc.xml中配置自定义类型转换器

<mvc:annotation-driven
conversion-service="converService" />
<!-- 配置转换器工厂 -->
<bean id="converService"
class="org.springframework.format.support.FormattingConversionServiceFactoryBean">
<property name="converters">
<list>
<!-- 配置自定义日期转换器 -->
<bean class="com.itpengwei.bos.converters.GloabDateConverters" />
</list>
</property>
</bean>

阅读更多
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: