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

spring 3.2 自定义参数绑定--日期格式转换器

2015-12-28 20:16 405 查看
springmvc配置文件
<!-- 代替org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping
和org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter -->

<mvc:annotation-driven conversion-service="conversionService"></mvc:annotation-driven>

<!-- 自定义参数绑定 -->

<bean id="conversionService" class="org.springframework.format.support.FormattingConversionServiceFactoryBean">
<property name="converters">
<list>
<!-- 日期类型转换 -->
<bean class="converter.CustomDateConverter"></bean>
</list>
</property>
</bean>
org.springframework.format.support.FormattingConversionServiceFactoryBean

spring提供的converter的对外接口,可以注入自己写的converter转换器

需要向处理器适配器中注入自定义的参数绑定组件,本例接口在注解驱动
conversion-service="conversionService"


自定义的日期转换器
package converter;

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

import org.springframework.core.convert.converter.Converter;

public class CustomDateConverter implements Converter<String, Date> {

@Override
public Date convert(String source) {
//实现将日期串转换成日期类型,格式是yyyy-MM-dd HH:mm:ss
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
try {

return simpleDateFormat.parse(source);
} catch (ParseException e) {

e.printStackTrace();
}
return null;
}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  日期参数转换