后端的日期类型赋值前端表单_Spring Boot实践--前端字符串日期自动转换成后台date类型。...

简单介绍

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

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配置文件进行配置

四:自定义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 {

private static final List 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 {

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;

}

}

五:其它单独处理:

参考其它博客:

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值