提交 e6fd1ee7 authored 作者: Matrix's avatar Matrix

[全局配置] 修正了时间类的问题

上级 db360dfe
package com.tykj.dev.config;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.*;
import com.fasterxml.jackson.databind.ser.std.DateSerializer;
import com.fasterxml.jackson.datatype.jdk8.Jdk8Module;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateTimeSerializer;
import com.fasterxml.jackson.module.paramnames.ParameterNamesModule;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.Date;
/**
* 描述:使jackson能够正确的接收时间格式
*
* @author HuangXiahao
* @version V1.0
* @class Java8TimeConfig
* @data 2020/5/20
**/
@Configuration
public class Java8TimeConfig {
@Value("${spring.jackson.date-format}")
private String formatValue;
@Bean(name = "format")
DateTimeFormatter format() {
return DateTimeFormatter.ofPattern(formatValue);
}
@Bean
public ObjectMapper serializingObjectMapper(@Qualifier("format") DateTimeFormatter format) {
JavaTimeModule javaTimeModule = new JavaTimeModule();
javaTimeModule.addSerializer(LocalDateTime.class, new LocalDateTimeSerializer(format));
javaTimeModule.addSerializer(Instant.class, new InstantCustomSerializer(format));
javaTimeModule.addSerializer(Date.class, new DateSerializer(false, new SimpleDateFormat(formatValue)));
javaTimeModule.addDeserializer(Instant.class, new InstantCustomDeserializer());
javaTimeModule.addDeserializer(Date.class, new DateCustomDeserializer());
return new ObjectMapper()
.registerModule(new ParameterNamesModule())
.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false)
.registerModule(javaTimeModule)
.disable(SerializationFeature.FAIL_ON_EMPTY_BEANS);
}
/**
* Support for Java date and time API.
*
* @return the corresponding Jackson module.
*/
@Bean
public JavaTimeModule javaTimeModule() {
return new JavaTimeModule();
}
@Bean
public Jdk8Module jdk8TimeModule() {
return new Jdk8Module();
}
static class InstantCustomSerializer extends JsonSerializer<Instant> {
private final DateTimeFormatter format;
private InstantCustomSerializer(DateTimeFormatter formatter) {
this.format = formatter;
}
@Override
public void serialize(Instant instant, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException {
if (instant == null) {
return;
}
String jsonValue = format.format(instant.atZone(ZoneId.systemDefault()));
jsonGenerator.writeString(jsonValue);
}
}
static class InstantCustomDeserializer extends JsonDeserializer<Instant> {
@Override
public Instant deserialize(JsonParser p, DeserializationContext ctxt)
throws IOException {
String dateString = p.getText().trim();
if (StringUtils.isNotBlank(dateString)) {
Date pareDate;
try {
pareDate = DateFormatUtil.pareDate(dateString);
if (null != pareDate) {
return pareDate.toInstant();
}
} catch (ParseException e) {
e.printStackTrace();
}
}
return null;
}
}
static class DateCustomDeserializer extends JsonDeserializer<Date> {
@Override
public Date deserialize(JsonParser p, DeserializationContext ctxt)
throws IOException {
String dateString = p.getText().trim();
if (StringUtils.isNotBlank(dateString)) {
try {
return DateFormatUtil.pareDate(dateString);
} catch (ParseException e) {
e.printStackTrace();
}
}
return null;
}
}
}
\ No newline at end of file
package com.tykj.dev.config;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.*;
import com.fasterxml.jackson.databind.ser.std.DateSerializer;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateSerializer;
import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateTimeSerializer;
import com.fasterxml.jackson.module.paramnames.ParameterNamesModule;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
......@@ -8,12 +17,22 @@ import org.springframework.format.datetime.DateFormatterRegistrar;
import org.springframework.format.datetime.standard.DateTimeFormatterRegistrar;
import org.springframework.format.support.DefaultFormattingConversionService;
import org.springframework.format.support.FormattingConversionService;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.security.web.method.annotation.AuthenticationPrincipalArgumentResolver;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.Instant;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.util.List;
/**
......@@ -30,6 +49,17 @@ public class WebMvcConfigConfig extends WebMvcConfigurationSupport {
@Value("${file.path}")
private String path;
@Value("${spring.jackson.date-format}")
private String formatValue;
@Value("${spring.jackson.local-date-format:yyyy-MM-dd}")
private String localDatePattern;
@Bean(name = "format")
DateTimeFormatter format() {
return DateTimeFormatter.ofPattern(formatValue);
}
/**
* 发现如果继承了WebMvcConfigurationSupport,则需要在这里重新指定静态资源
*/
......@@ -63,8 +93,97 @@ public class WebMvcConfigConfig extends WebMvcConfigurationSupport {
return conversionService;
}
@Override
protected void addArgumentResolvers(List<HandlerMethodArgumentResolver> argumentResolvers) {
argumentResolvers.add(new AuthenticationPrincipalArgumentResolver());
}
/**
* Override this method to extend or modify the list of converters after it has
* been configured. This may be useful for example to allow default converters
* to be registered and then insert a custom converter through this method.
*
* @param converters the list of configured converters to extend
* @since 4.1.3
*/
@Override
protected void extendMessageConverters(List<HttpMessageConverter<?>> converters) {
DateTimeFormatter format = DateTimeFormatter.ofPattern(formatValue);
MappingJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter();
JavaTimeModule javaTimeModule = new JavaTimeModule();
javaTimeModule.addSerializer(LocalDateTime.class, new LocalDateTimeSerializer(format));
javaTimeModule.addSerializer(LocalDate.class, new LocalDateSerializer(DateTimeFormatter.ofPattern(localDatePattern)));
javaTimeModule.addSerializer(Instant.class, new InstantCustomSerializer(format));
javaTimeModule.addSerializer(Date.class, new DateSerializer(false, new SimpleDateFormat(formatValue)));
javaTimeModule.addDeserializer(Instant.class, new InstantCustomDeserializer());
javaTimeModule.addDeserializer(Date.class, new DateCustomDeserializer());
ObjectMapper mapper = new ObjectMapper()
.registerModule(new ParameterNamesModule())
.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false)
.registerModule(javaTimeModule)
.disable(SerializationFeature.FAIL_ON_EMPTY_BEANS);
converter.setObjectMapper(mapper);
converters.add(0, converter);
super.extendMessageConverters(converters);
}
static class InstantCustomSerializer extends JsonSerializer<Instant> {
private final DateTimeFormatter format;
private InstantCustomSerializer(DateTimeFormatter formatter) {
this.format = formatter;
}
@Override
public void serialize(Instant instant, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException {
if (instant == null) {
return;
}
String jsonValue = format.format(instant.atZone(ZoneId.systemDefault()));
jsonGenerator.writeString(jsonValue);
}
}
static class InstantCustomDeserializer extends JsonDeserializer<Instant> {
@Override
public Instant deserialize(JsonParser p, DeserializationContext ctxt)
throws IOException {
String dateString = p.getText().trim();
if (StringUtils.isNotBlank(dateString)) {
Date pareDate;
try {
pareDate = DateFormatUtil.pareDate(dateString);
if (null != pareDate) {
return pareDate.toInstant();
}
} catch (ParseException e) {
e.printStackTrace();
}
}
return null;
}
}
static class DateCustomDeserializer extends JsonDeserializer<Date> {
@Override
public Date deserialize(JsonParser p, DeserializationContext ctxt)
throws IOException {
String dateString = p.getText().trim();
if (StringUtils.isNotBlank(dateString)) {
try {
return DateFormatUtil.pareDate(dateString);
} catch (ParseException e) {
e.printStackTrace();
}
}
return null;
}
}
}
......@@ -37,7 +37,6 @@ public class CheckStatTableVo {
private List<String> checkUserNames;
@ApiModelProperty("创建时间")
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
private LocalDateTime createTime;
@ApiModelProperty("完成情况")
......
......@@ -52,13 +52,11 @@ public class CheckStatVo {
/**
* 开始时间
*/
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
private LocalDateTime startTime;
/**
* 结束时间
*/
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
private LocalDateTime endTime;
private LocalDateTime createTime;
......
......@@ -51,35 +51,6 @@ public class FinalCheckController {
@Autowired
private FinalCheckService fcService;
public static void downloadExcel(HttpServletRequest request, HttpServletResponse response, Workbook wb, String excelName) {
// 判断数据
if (wb == null) {
throw new ApiException("workbook can not be null!");
}
// 重置响应对象
response.reset();
// 当前日期,用于导出文件名称
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
String dateStr = excelName + sdf.format(new Date()) + ".xls";
// 指定下载的文件名--设置响应头
response.addHeader("Content-Disposition", "attachment;filename=" + dateStr);
response.setContentType("application/octet-stream;charset=UTF-8");
response.setHeader("Pragma", "no-cache");
response.setDateHeader("Expires", 0);
// 写出数据输出流到页面
try {
OutputStream output = response.getOutputStream();
BufferedOutputStream bufferedOutPut = new BufferedOutputStream(output);
wb.write(bufferedOutPut);
bufferedOutPut.flush();
bufferedOutPut.close();
output.close();
} catch (IOException e) {
e.printStackTrace();
}
}
@GetMapping("/reports")
@ApiOperation(value = "查询所有决算报告(不附带详情数据)")
public Page<FinalReportVo> findAllReports(
......
......@@ -13,6 +13,7 @@ import org.springframework.data.jpa.domain.support.AuditingEntityListener;
import javax.persistence.*;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
/**
......@@ -160,7 +161,7 @@ public class DeviceLibrary {
*/
@CreatedDate
@ApiModelProperty(value = "创建时间")
private java.util.Date createTime;
private Date createTime;
/**
* 更新用户id
*/
......@@ -172,7 +173,7 @@ public class DeviceLibrary {
*/
@LastModifiedDate
@ApiModelProperty(value = "更新时间")
private java.util.Date updateTime;
private Date updateTime;
/**
* 删除标记(0:未删除,1:已删除)
*/
......
Markdown 格式
0%
您添加了 0 到此讨论。请谨慎行事。
请先完成此评论的编辑!
注册 或者 后发表评论