欢迎您访问 最编程 本站为您分享编程语言代码,编程技术文章!
您现在的位置是: 首页

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

最编程 2024-04-30 11:32:26
...
动弹” 回归,赶紧下载 APP 愉快地摸鱼吧!”

简单介绍

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

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

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

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

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

  •  以JSON对象序列化传过来的值。在后端可以自动转成对应日期格式。对应的对象注解:@RequestBody
  •  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”, 
如果我前台不同页面过来的日期格式不一样就不好办了

三:非BOOT方式xml配置:

package com.spinach.boot.base;

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.annotation.InitBinder;
import org.springframework.web.bind.support.WebBindingInitializer;

public class CustomDateFormat implements WebBindingInitializer {

	/**
	 * 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));
	}

}

并在spingMVC配置文件进行配置

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

 

四:自定义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 wanghh
 * @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种和第二种,完美!

4.2 非boot项目

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.convert.converter.Converter;

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

public class CustomDateConverter implements Converter<String, Date> {

    Logger LOG = LoggerFactory.getLogger(this.getClass());

    private String datePattern;

    public void setDatePattern(String datePattern) {
        this.datePattern = datePattern;
    }

    @Override
    public Date convert(String s) {
        SimpleDateFormat dateFormat = new SimpleDateFormat(this.datePattern);
        try {
            Date date = dateFormat.parse(s);
            return date;
        }catch (ParseException e){
            LOG.error("convertError",e);
        }
        return null;
    }

}
<bean id="conversionService" class="org.springframework.format.support.FormattingConversionServiceFactoryBean">
<property name="converters">
	<list>
		<!-- 自定义转换器 -->
		<bean class="com.xxx.CustomDateConverter">
			<property name="datePattern" value="yyyy-MM-dd"></property>
		</bean>
	</list>
</property>
</bean>
<mvc:annotation-driven conversion-service="conversionService"></mvc:annotation-driven>

 

五:其它单独处理:

参考其它博客:

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

Spring Boot(四):利用注解自定义日期格式化