spring Boot实践--前端字符串日期自动转换成后台date类型。

简单介绍

在前后台开发的时候:日期格式会转来转去,很麻烦。大致总结如下:

1:后端返回对象:可以使用spring提供的:HttpMessageConverter来自动转换,有很多实现。

比如:AbstractJackson2HttpMessageConverter的两种实现:下面前两种

  • MappingJackson2XmlHttpMessageConverter:xml解析器
  • MappingJackson2HttpMessageConverter:JSON解析器。系统默认。
  • GsonHttpMessageConverter  JSON解析器 
  • FastHttpMessageConverter JSON解析器

2:后端接接收对象:有两种:

  •  以JSON对象序列化传过来的值。在后端可以自动转成对应日期格式。
  •  Form日期字符串:就不能自动识别了,就是本博客解决的问题了。

问题还原:当前台提交日期格式数据到后台保存时,已办以字符串的形式传输,如果后台是data类型接受的话会报400格式错误。参考网上的博客加自己实践记录一下。这时候就需要处理一下: 有以下四种方式:

一:字段String类型转换

第0种(最low的方式):后台用String类型字段接收,如果需要使用再换成date。

二:@DateTimeFormat

第1种:使用@DateTimeFormat(pattern = “yyyy-MM-dd HH:mm:ss”)注解在实体字段上, 
这种方式的优点是:可以灵活的定义接收的类型 
缺点很明显:不能全局统一处理,需要为每个需要转换字段都加注解太麻烦

三:基类@InitBinder写一个全局转换日期

第2种:写一个BaseController,每一个需要处理的controller继承这个BaseController,在BaseController里使用@InitBinder写一个全局转换日期方法:

/**
	 * form表单提交 Date类型数据绑定
	 * <功能详细描述>
	 * @param binder
	 * @see [类、类#方法、类#成员]
	 */
@InitBinder  
public void initBinder(WebDataBinder binder) {  
	    SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");  
	    dateFormat.setLenient(false);  
	    binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true));  
}

@InitBinder
public void initBinder(ServletRequestDataBinder binder,WebRequest request) {
	//转换日期格式
    DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    //注册自定义的编辑器
    binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true));        
}

这种方式的优点是:可以全局统一处理,不用再关注具体需要转换的日期字段 
缺点就是:只能定义一种日期类型,我定义了”yyyy-MM-dd”就没法定义”yyyy-MM-dd HH:mm:ss”, 
如果我前台不同页面过来的日期格式不一样就不好办了

四:自定义DateConverterConfig重写convert方法

实现一下spring提供的Converter,重写里面的convert方法:

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

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

/**
 * 全局handler前日期统一处理
 * @author zhanghang
 * @date 2018/1/11
 */
@Component
public class DateConverterConfig implements Converter<String, Date> {

    private static final List<String> formarts = new ArrayList<>(4);
    static{
        formarts.add("yyyy-MM");
        formarts.add("yyyy-MM-dd");
        formarts.add("yyyy-MM-dd hh:mm");
        formarts.add("yyyy-MM-dd hh:mm:ss");
    }

    @Override
    public Date convert(String source) {
        String value = source.trim();
        if ("".equals(value)) {
            return null;
        }
        if(source.matches("^\\d{4}-\\d{1,2}$")){
            return parseDate(source, formarts.get(0));
        }else if(source.matches("^\\d{4}-\\d{1,2}-\\d{1,2}$")){
            return parseDate(source, formarts.get(1));
        }else if(source.matches("^\\d{4}-\\d{1,2}-\\d{1,2} {1}\\d{1,2}:\\d{1,2}$")){
            return parseDate(source, formarts.get(2));
        }else if(source.matches("^\\d{4}-\\d{1,2}-\\d{1,2} {1}\\d{1,2}:\\d{1,2}:\\d{1,2}$")){
            return parseDate(source, formarts.get(3));
        }else {
            throw new IllegalArgumentException("Invalid boolean value '" + source + "'");
        }
    }

    /**
     * 格式化日期
     * @param dateStr String 字符型日期
     * @param format String 格式
     * @return Date 日期
     */
    public  Date parseDate(String dateStr, String format) {
        Date date=null;
        try {
            DateFormat dateFormat = new SimpleDateFormat(format);
            date = dateFormat.parse(dateStr);
        } catch (Exception e) {

        }
        return date;
    }

}

我这里是springboot项目通过@Component注解将这个类交给spring容器托管的,如果springmvc项目还需要到xml配置文件注册这个类 
优点很明显了:足够灵活,在静态代码块里自定义任意格式日期,在重写的方法里在配上对应的正则表达式就行,也可以做到全局统一处理,兼顾了第1种和第二种,完美!

四:非BOOT方式:全局日期类型转换器并进行配置

package com.spinach.core.web;

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

import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.support.WebBindingInitializer;
import org.springframework.web.context.request.WebRequest;

public class CustomDateEdtor implements WebBindingInitializer {

    
    public void initBinder(WebDataBinder binder, WebRequest request) {
        // TODO Auto-generated method stub
        //转换日期格式
        DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        
        binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true));
    }

}


并在spingMVC配置文件进行配置

<bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
      <property name="webBindingInitializer">    
          <bean class="com.spinach.core.web.CustomDateEdtor"/>
      </property>
</bean>

   

猜你喜欢

转载自my.oschina.net/spinachgit/blog/1806459