前后台日期交互总结(Spring MVC)
前后台日期交互总结(Spring MVC)
前后台日期转换的工具Jackson、FastJson等
我使用的是FastJson,SpringBoot默认集成了Jackson,
因为之前一直用的FastJson也没碰到过什么bug,就记录FastJson使用
后台 -------> 前台(序列化)
@ResponseBody
自动返回值序列化,需要配置
@Configuration
public class FastJsonResultConfig {
@Bean
public HttpMessageConverters fastJson() {
FastJsonHttpMessageConverter fastConverter = new FastJsonHttpMessageConverter();
FastJsonConfig fastJsonConfig = new FastJsonConfig();
//fastJsonConfig.setDateFormat("yyyy-MM-dd HH:mm:ss");
fastJsonConfig.setSerializerFeatures(
//时间处理
SerializerFeature.PrettyFormat,
SerializerFeature.WriteDateUseDateFormat,
SerializerFeature.WriteNullNumberAsZero,
SerializerFeature.WriteNullListAsEmpty,
SerializerFeature.WriteNullStringAsEmpty,
SerializerFeature.WriteNullBooleanAsFalse);
//处理中文乱码问题
List<MediaType> fastMediaTypes = new ArrayList<>();
fastMediaTypes.add(MediaType.APPLICATION_JSON_UTF8);
fastConverter.setSupportedMediaTypes(fastMediaTypes);
fastConverter.setFastJsonConfig(fastJsonConfig);
return new HttpMessageConverters(fastConverter);
}
}
默认返回的是 yyyy-MM-dd HH:mm:ss
格式
定制样式使用注解@JSONField(format = "yyyy-MM-dd")
前台 -------> 后台(反序列化)
后台接收有两种方式
方式一
定义baseController
@InitBinder
public void initBinder(ServletRequestDataBinder binder) {
binder.registerCustomEditor(Date.class, new DateConvertEditor());
}
public class DateConvertEditor extends PropertyEditorSupport {
private SimpleDateFormat datetimeFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
private SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
private SimpleDateFormat monthFormat = new SimpleDateFormat("yyyy-MM");
private SimpleDateFormat timeFormat = new SimpleDateFormat("HH:mm:ss");
@Override
public void setAsText(String text) throws IllegalArgumentException {
System.out.println(text);
if (StringUtils.hasText(text)) {
char temp = ':';
try {
if (text.indexOf(temp) == -1 && text.length() == 10) {
setValue(this.dateFormat.parse(text));
} else if (text.indexOf(temp) > 0 && text.length() == 19) {
setValue(this.datetimeFormat.parse(text));
} else if (text.indexOf(temp) > 0 && text.length() == 21) {
text = text.replace(".0", "");
setValue(this.datetimeFormat.parse(text));
} else if (text.length() == 8) {
setValue(this.timeFormat.parse(text));
} else if (text.length() == 7) {
setValue(this.monthFormat.parse(text));
}
else {
throw new IllegalArgumentException("Could not parse date, date format is error ");
}
} catch (ParseException ex) {
IllegalArgumentException iae = new IllegalArgumentException("Could not parse date: " + ex.getMessage());
iae.initCause(ex);
throw iae;
}
} else {
setValue(null);
}
}
}
方式二
@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;
}
}
对于特殊的可以使用@DateTimeFormat(pattern = "yyyy-MM-dd")
来指定接收日期格式
补充
对于使用model绑定的日期要前端展示需要使用相应模板引擎提供的方式
jsp:
<fmt:formatDate value="${date}" pattern="yyyy-MM-dd HH:mm:ss"/>
thymleaf:
<td th:text="${#dates.format(date,'yyyy-MM-dd')}"></td>
后面再看Jackson,毕竟是Spring默认集成的查看了Springboot的依赖包如下
推荐使用Jackson