spring cloud系列-04.定义全局日期转换器,springboot同样适用

近日遇到了前台请求参数中日期格式传入到后台controller接收自动转换date失败的问题,查找部分资料后决定定义一个全局的日期转换器,代码亲自验证通过。

1.自定义日期格式转换器

/**
 * 
 */
package com.xxxx.log.config;

import java.text.FieldPosition;
import java.text.ParsePosition;
import java.text.SimpleDateFormat;
import java.util.Date;
import com.xxxx.common.utils.StringUtils;

import com.fasterxml.jackson.databind.util.StdDateFormat;

/**
 * @ClassName: CustomDateFormat
 * @date 2018年01月23日 下午4:28:57
 */
public class CustomDateFormat extends StdDateFormat {

    private static final long serialVersionUID = -3201781773655300201L;

    public static final CustomDateFormat instance = new CustomDateFormat();

    @Override
    /**
     * @ClassName: CustomDateFormat
     * 这个方法可不写,jckson主要使用的是parse(String)这个方法用来转换日期格式的,
     * 只要覆盖parse(String)这个方法即可
     * @date 2018年01月23日 下午4:28:57
     */
    public Date parse(String dateStr, ParsePosition pos) {
        SimpleDateFormat sdf  = null;
        if(StringUtils.isBlank(dateStr)){
            return null;
        }
        if (dateStr.length() == 10) {
            sdf = new SimpleDateFormat("yyyy-MM-dd");
            return sdf.parse(dateStr, pos);
        }
        if (dateStr.length() == 16) {
            sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
            return sdf.parse(dateStr, pos);
        }
        if (dateStr.length() == 19) {
            sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            return sdf.parse(dateStr, pos);
        }
        if (dateStr.length() == 23) {
            sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
            return sdf.parse(dateStr, pos);
        }
        return super.parse(dateStr, pos);
    }

    @Override
    public Date parse(String dateStr) {
        ParsePosition pos = new ParsePosition(0);
        SimpleDateFormat sdf  = null;
        if(StringUtils.isBlank(dateStr)){
            return null;
        }
        if (dateStr.length() == 10) {
            sdf = new SimpleDateFormat("yyyy-MM-dd");
            return sdf.parse(dateStr, pos);
        }
        if (dateStr.length() == 16) {
            sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
            return sdf.parse(dateStr, pos);
        }
        if (dateStr.length() == 19) {
            sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            return sdf.parse(dateStr, pos);
        }
        if (dateStr.length() == 23) {
            sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
            return sdf.parse(dateStr, pos);
        }
        return super.parse(dateStr, pos);
    }

    public StringBuffer format(Date date, StringBuffer toAppendTo, FieldPosition fieldPosition){
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        return sdf.format(date, toAppendTo, fieldPosition);
    }

    public CustomDateFormat clone() {
        return new CustomDateFormat();
    }
}

2.启动类继承【WebMvcConfigurerAdapter】,并覆盖其configureMessageConverters方法,将我们自定义的消息转换器加入到spring的上下文中。

package com.xxxx.log;

import java.util.ArrayList;
import java.util.List;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.cloud.netflix.feign.EnableFeignClients;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.xxxx.log.config.CustomDateFormat;

/**
 * 程序启动
 */
@EnableDiscoveryClient
@EnableFeignClients
@SpringBootApplication
@RefreshScope
@ComponentScan("com.xxxx")
public class LogServerApplication extends WebMvcConfigurerAdapter{

    public static void main( String[] args ){
        SpringApplication.run(LogServerApplication.class, args);
    }

    @Bean  
    public MappingJackson2HttpMessageConverter getMappingJackson2HttpMessageConverter() {
        MappingJackson2HttpMessageConverter mappingJackson2HttpMessageConverter = new MappingJackson2HttpMessageConverter();  
        //设置日期格式  
        ObjectMapper objectMapper = new ObjectMapper(); 
        objectMapper.setDateFormat(CustomDateFormat.instance);  
        objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
        mappingJackson2HttpMessageConverter.setObjectMapper(objectMapper);  
        //设置中文编码格式  
        List list = new ArrayList();  
        list.add(MediaType.APPLICATION_JSON_UTF8);
        mappingJackson2HttpMessageConverter.setSupportedMediaTypes(list);
        return mappingJackson2HttpMessageConverter;
    }  

    @Override
    public void configureMessageConverters(List> converters){
        converters.add(getMappingJackson2HttpMessageConverter());
    }

}

启动后controller即可接收【yyyy-MM-dd】,【yyyy-MM-dd HH:mm】,【yyyy-MM-dd HH:mm:ss】,【yyyy-MM-dd HH:mm:ss.SSS】格式的参数并且可以正确自动转换成date类型了。
转换还可以使用正则表达式继续扩展,可支持带斜杠之类的格式,有兴趣的自己试试吧。

你可能感兴趣的:(spring,spring-cloud)