Converter实现Date类型转换

Posted 王醒燕

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Converter实现Date类型转换相关的知识,希望对你有一定的参考价值。

1.springmvc-config.xml配置

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
       http://www.springframework.org/schema/beans/spring-beans-4.3.xsd
       http://www.springframework.org/schema/context
       http://www.springframework.org/schema/context/spring-context-4.3.xsd
       http://www.springframework.org/schema/mvc  http://www.springframework.org/schema/mvc/spring-mvc.xsd">
    <context:annotation-config/>
    <context:component-scan base-package="com.wxy.controller"/>
    <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/jsp/"></property>
        <property name="suffix" value=".jsp"></property>
    </bean>
    <mvc:annotation-driven conversion-service="conversionService" />
    <bean id="conversionService" class="org.springframework.context.support.ConversionServiceFactoryBean">
        <property name="converters">
            <set>
                <bean class="com.wxy.convert.DateConverter" />
            </set>
        </property>
    </bean>
</beans>

2.日期转换类DateConverter.java

 1 package com.wxy.convert;
 2 
 3 import org.springframework.core.convert.converter.Converter;
 4 import java.text.ParseException;
 5 import java.text.SimpleDateFormat;
 6 import java.util.Date;
 7 
 8 public class DateConverter implements Converter<String,Date> {
 9     private String datePattern = "yyyy-MM-dd HH:mm:ss";
10     @Override
11     public Date convert(String source){
12         SimpleDateFormat simpleDateFormat = new SimpleDateFormat(datePattern);
13         try{
14             return simpleDateFormat.parse(source);
15         }catch (ParseException e){
16             throw new IllegalArgumentException(
17                     "无效的日期格式,请使用这种格式:"+datePattern
18             );
19         }
20     }
21 }

3.日期控制器类DateController

package com.wxy.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import java.util.Date;
@Controller
public class DateController {
    @RequestMapping("/customDate")
    public String CustomDate(Date date){
        System.out.println("date="+date);
        return "success";
    }
}

目前是不完善版本,只能控制台输出,等完善jsp页面,再修改。

以上是关于Converter实现Date类型转换的主要内容,如果未能解决你的问题,请参考以下文章

SpringMVC 获得请求数据 -- 自定义类型转换器(Date)

JAVA_Converter_字符串类型转Date类型

Spring MVC Converter 啥时候执行转换

Spring类型转换 ConversionSerivce Convertor

SpringBoot开源项目学习总结

spring jpa之实体属性类型转换器AttributeConverter,自定义Converter,通用Converter