feat(修改): 日期格式化只能在实体类中定义,没有别的办法了

This commit is contained in:
bunny 2024-03-23 21:29:38 +08:00
parent 8d13f48c70
commit 163b6fd373
27 changed files with 73 additions and 131 deletions

7
.gitignore vendored Normal file
View File

@ -0,0 +1,7 @@
**/target/
.idea
*.iml
*.class
*Test.java
**/test/
logs

View File

@ -26,7 +26,7 @@
<maven.compiler.target>17</maven.compiler.target>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<mysql.verison>8.0.32</mysql.verison>
<fastjson.version>2.0.21</fastjson.version>
<fastjson.version>2.0.47</fastjson.version>
<lombok.version>1.18.20</lombok.version>
<mybatis.version>3.0.1</mybatis.version>
<pagehelper.version>2.1.0</pagehelper.version>

View File

@ -24,6 +24,11 @@
<artifactId>spzx-model</artifactId>
<version>1.0-SNAPSHOT</version>
</dependency>
<dependency>
<groupId>com.atguigu</groupId>
<artifactId>common-util</artifactId>
<version>1.0-SNAPSHOT</version>
</dependency>
<!-- spring boot web开发所需要的起步依赖 -->
<dependency>
<groupId>org.springframework.boot</groupId>
@ -34,11 +39,10 @@
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<!--支持配置属性类yml文件中可以提示配置项-->
<dependency>
<groupId>com.atguigu</groupId>
<artifactId>common-util</artifactId>
<version>1.0-SNAPSHOT</version>
<scope>compile</scope>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
</dependency>
</dependencies>
</project>

View File

@ -35,15 +35,16 @@ public class RedisConfiguration {
* 使用StringRedisSerializer序列化为字符串
*/
@Bean
public RedisTemplate<String, Object> redisTemplate(LettuceConnectionFactory factory) {
public RedisTemplate<String, Object> redisTemplate(LettuceConnectionFactory connectionFactory) {
RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>();
redisTemplate.setConnectionFactory(factory);
// 设置key序列化为String
redisTemplate.setConnectionFactory(connectionFactory);
// 设置key序列化为string
redisTemplate.setKeySerializer(new StringRedisSerializer());
redisTemplate.setHashKeySerializer(new StringRedisSerializer());
// 设置value序列化为JSON使用GenericJackson2JsonRedisSerializer替换默认的序列化
// 设置value序列化为JSON使用GenericJackson2JsonRedisSerializer替换默认序列化
redisTemplate.setValueSerializer(new GenericJackson2JsonRedisSerializer());
redisTemplate.setHashKeySerializer(new StringRedisSerializer());
redisTemplate.setHashValueSerializer(new GenericJackson2JsonRedisSerializer());
return redisTemplate;
}
@ -62,29 +63,31 @@ public class RedisConfiguration {
.serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(redisSerializer))
.serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(serializer));
return RedisCacheManager.builder(factory).cacheDefaults(redisCacheConfiguration).build();
RedisCacheManager cacheManager = RedisCacheManager.builder(factory)
.cacheDefaults(redisCacheConfiguration).build();
return cacheManager;
}
/**
* 指定的日期模式
*/
public Jackson2JsonRedisSerializer<Object> jsonRedisSerializer() {
// LocalDatetime序列化默认不兼容jdk8日期序列化
JavaTimeModule javaTimeModule = new JavaTimeModule();
javaTimeModule.addDeserializer(LocalDate.class, new LocalDateDeserializer(DateTimeFormatter.ofPattern("yyyy-MM-dd")));
javaTimeModule.addSerializer(LocalDate.class, new LocalDateSerializer(DateTimeFormatter.ofPattern("yyyy-MM-dd")));
javaTimeModule.addDeserializer(LocalDateTime.class, new LocalDateTimeDeserializer(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
javaTimeModule.addSerializer(LocalDateTime.class, new LocalDateTimeSerializer(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
ObjectMapper mapper = new ObjectMapper();
// 设置Object访问权限
// 设置ObjectMapper访问权限
mapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
// 记录序列化之后的数据类型方便反序列化
mapper.activateDefaultTyping(LaissezFaireSubTypeValidator.instance, ObjectMapper.DefaultTyping.NON_FINAL);
// 关闭默认的日期格式化方式默认UTC日期格式 yyyy-MM-ddTHH:mm:ss.SSS
mapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
mapper.registerModule(javaTimeModule);
// LocalDatetime序列化默认不兼容jdk8日期序列化
JavaTimeModule timeModule = new JavaTimeModule();
timeModule.addDeserializer(LocalDate.class, new LocalDateDeserializer(DateTimeFormatter.ofPattern("yyyy-MM-dd")));
timeModule.addSerializer(LocalDate.class, new LocalDateSerializer(DateTimeFormatter.ofPattern("yyyy-MM-dd")));
timeModule.addDeserializer(LocalDateTime.class, new LocalDateTimeDeserializer(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
timeModule.addSerializer(LocalDateTime.class, new LocalDateTimeSerializer(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
mapper.registerModule(timeModule);
return new Jackson2JsonRedisSerializer<>(mapper, Object.class);
}
}

View File

@ -7,8 +7,8 @@ import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry
@Configuration
@Slf4j
public class ResourceConfiguration extends WebMvcConfiguration {
protected void addResourceHandlers(ResourceHandlerRegistry registry) {
log.info("ResourceConfiguration===>设置静态资源映射...");
public void addResourceHandlers(ResourceHandlerRegistry registry) {
log.info("设置静态资源映射");
registry.addResourceHandler("/doc.html").addResourceLocations("classpath:/META-INF/resources/");
registry.addResourceHandler("/webjars/**").addResourceLocations("classpath:/META-INF/resources/webjars/");
}

View File

@ -1,21 +1,14 @@
package com.atguigu.config;
import com.atguigu.constant.LocalDateTimeConstant;
import com.atguigu.interceptor.LoginAuthInterceptor;
import com.atguigu.json.JacksonObjectMapper;
import com.atguigu.properties.InterceptorsProperties;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;
import java.text.SimpleDateFormat;
import java.util.List;
@Component
@Slf4j
public class WebMvcConfiguration extends WebMvcConfigurationSupport {
@ -48,22 +41,4 @@ public class WebMvcConfiguration extends WebMvcConfigurationSupport {
registry.addInterceptor(loginAuthInterceptor).addPathPatterns("/**")
.excludePathPatterns(interceptorsProperties.getNoAuthUrls());
}
/**
* 扩展Spring MVC框架的消息转化器
*
* @param converters 转换器
*/
public void extendMessageConverters(List<HttpMessageConverter<?>> converters) {
log.info("WebMvcConfiguration===>扩展消息转换器...");
// 创建一个消息转换器对象
MappingJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter();
// 需要为消息转换器设置一个对象转换器对象转换器可以将Java对象序列化为json数据
converter.setObjectMapper(new JacksonObjectMapper());
// 添加条件判断只应用于特定的请求路径
converter.getObjectMapper().setDateFormat(new SimpleDateFormat(LocalDateTimeConstant.DEFAULT_DATE_TIME_SECOND_FORMAT));
// 将自己的消息转化器加入容器中
converters.add(converter);
}
}

View File

@ -67,7 +67,7 @@ public class GlobalExceptionHandler {
String username = message.split(" ")[2];
// 错误信息
String errorMessage = username + MessageConstant.ALREADY_EXISTS;
return Result.error(exception.getMessage());
return Result.error(errorMessage);
} else {
return Result.error(MessageConstant.UNKNOWN_ERROR);
}

View File

@ -39,15 +39,15 @@ public class LoginAuthInterceptor implements HandlerInterceptor {
}
// 获取用户信息不存在
String userinfoString = (String) redisTemplate.opsForValue().get(token);
if (StringUtils.isEmpty(userinfoString)) {
Object sysUserObject = redisTemplate.opsForValue().get(token);
String sysUserString = JSON.toJSONString(sysUserObject);
if (sysUserObject == null) {
InterceptorUtil.unLoginInterceptor(response);
return false;
}
// 将用户信息放到ThreadLocal中
SysUser sysUser = JSON.parseObject(userinfoString, SysUser.class);
BaseContext.setSysUser(sysUser);
BaseContext.setSysUser(JSON.parseObject(sysUserString, SysUser.class));
// 更新Redis过期时间
redisTemplate.expire(token, 7, TimeUnit.DAYS);

View File

@ -1,46 +0,0 @@
package com.atguigu.json;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.module.SimpleModule;
import com.fasterxml.jackson.datatype.jsr310.deser.LocalDateDeserializer;
import com.fasterxml.jackson.datatype.jsr310.deser.LocalDateTimeDeserializer;
import com.fasterxml.jackson.datatype.jsr310.deser.LocalTimeDeserializer;
import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateSerializer;
import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateTimeSerializer;
import com.fasterxml.jackson.datatype.jsr310.ser.LocalTimeSerializer;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import static com.atguigu.constant.LocalDateTimeConstant.*;
import static com.fasterxml.jackson.databind.DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES;
/**
* 对象映射器:基于jackson将Java对象转为json或者将json转为Java对象
* 将JSON解析为Java对象的过程称为 [从JSON反序列化Java对象]
* 从Java对象生成JSON的过程称为 [序列化Java对象到JSON]
*/
public class JacksonObjectMapper extends ObjectMapper {
public JacksonObjectMapper() {
super();
// 收到未知属性时不报异常
this.configure(FAIL_ON_UNKNOWN_PROPERTIES, false);
// 反序列化时属性不存在的兼容处理
this.getDeserializationConfig().withoutFeatures(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
SimpleModule simpleModule = new SimpleModule()
.addDeserializer(LocalDateTime.class, new LocalDateTimeDeserializer(DateTimeFormatter.ofPattern(DEFAULT_DATE_TIME_FORMAT)))
.addDeserializer(LocalDate.class, new LocalDateDeserializer(DateTimeFormatter.ofPattern(DEFAULT_DATE_FORMAT)))
.addDeserializer(LocalTime.class, new LocalTimeDeserializer(DateTimeFormatter.ofPattern(DEFAULT_TIME_FORMAT)))
.addSerializer(LocalDateTime.class, new LocalDateTimeSerializer(DateTimeFormatter.ofPattern(DEFAULT_DATE_TIME_FORMAT)))
.addSerializer(LocalDate.class, new LocalDateSerializer(DateTimeFormatter.ofPattern(DEFAULT_DATE_FORMAT)))
.addSerializer(LocalTime.class, new LocalTimeSerializer(DateTimeFormatter.ofPattern(DEFAULT_TIME_FORMAT)));
// 注册功能模块 例如可以添加自定义序列化器和反序列化器
this.registerModule(simpleModule);
}
}

View File

@ -1,15 +1,21 @@
package com.atguigu.spzx.manger;
import lombok.extern.slf4j.Slf4j;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.transaction.annotation.EnableTransactionManagement;
@SpringBootApplication
@EnableCaching
@EnableTransactionManagement // 开启注解方式的事务管理
@EnableCaching// 开启缓存注解
@EnableScheduling
@ComponentScan("com.atguigu")
@MapperScan("com.atguigu.spzx.manger.mapper")
@Slf4j
public class MangerApplication {
public static void main(String[] args) {
SpringApplication.run(MangerApplication.class, args);

View File

@ -1,6 +1,5 @@
package com.atguigu.spzx.manger.service.impl;
import com.alibaba.fastjson.JSON;
import com.atguigu.constant.ExceptionConstant;
import com.atguigu.exception.BunnyException;
import com.atguigu.lib.MD5;
@ -66,7 +65,7 @@ public class SysUserServiceImpl implements SysUserService {
}
// 登录成功
String token = UUID.randomUUID().toString().replaceAll("-", "");
redisTemplate.opsForValue().set(token, JSON.toJSONString(sysUser), 7, TimeUnit.DAYS);
redisTemplate.opsForValue().set(token, sysUser, 7, TimeUnit.DAYS);
// 返回loginVo对象
return LoginVo.builder().token(token).build();
}

View File

@ -11,12 +11,8 @@ bunny:
port: 6379
database: 2
spzx:
noAuthUrls:
- /admin/system/index/login
- /admin/system/index/generateValidateCode
- /v3/**
# jackson:
# date-format: yyyy-MM-dd HH:mm:ss
# time-zone: GMT+8

View File

@ -14,6 +14,7 @@ spring:
url: jdbc:mysql://${bunny.datasource.host}:${bunny.datasource.port}/${bunny.datasource.sqlData}?serverTimezone=GMT%2B8&useSSL=false&characterEncoding=utf-8&allowPublicKeyRetrieval=true
username: ${bunny.datasource.username}
password: "${bunny.datasource.password}"
data:
redis:
host: ${bunny.redis.host}
@ -33,7 +34,6 @@ logging:
mybatis:
type-aliases-package: com.atguigu.spzx.model
mapper-locations: classpath:mapper/*.xml
# config-location: classpath:mybatis-config.xml
configuration:
log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
map-underscore-to-camel-case: true

View File

@ -4,7 +4,7 @@
<contextName>logback</contextName>
<!-- 日志的输出目录 -->
<property name="log.path" value="D://logs//spzx-manager//logs" />
<property name="log.path" value="logs//spzx-manager//logs"/>
<!--控制台日志格式:彩色日志-->
<!-- magenta:洋红 -->
@ -12,7 +12,8 @@
<!-- cyan:青色 -->
<!-- white:白色 -->
<!-- magenta:洋红 -->
<property name="CONSOLE_LOG_PATTERN" value="%yellow(%date{yyyy-MM-dd HH:mm:ss}) %highlight([%-5level]) %green(%logger) %msg%n"/>
<property name="CONSOLE_LOG_PATTERN"
value="%yellow(%date{yyyy-MM-dd HH:mm:ss}) %highlight([%-5level]) %green(%logger) %msg%n"/>
<!--文件日志格式-->
<property name="FILE_LOG_PATTERN" value="%date{yyyy-MM-dd HH:mm:ss} [%-5level] %thread %file:%line %logger %msg%n"/>

View File

@ -11,12 +11,8 @@ bunny:
port: 6379
database: 2
spzx:
noAuthUrls:
- /admin/system/index/login
- /admin/system/index/generateValidateCode
- /v3/**
# jackson:
# date-format: yyyy-MM-dd HH:mm:ss
# time-zone: GMT+8

View File

@ -14,6 +14,7 @@ spring:
url: jdbc:mysql://${bunny.datasource.host}:${bunny.datasource.port}/${bunny.datasource.sqlData}?serverTimezone=GMT%2B8&useSSL=false&characterEncoding=utf-8&allowPublicKeyRetrieval=true
username: ${bunny.datasource.username}
password: "${bunny.datasource.password}"
data:
redis:
host: ${bunny.redis.host}
@ -33,7 +34,6 @@ logging:
mybatis:
type-aliases-package: com.atguigu.spzx.model
mapper-locations: classpath:mapper/*.xml
# config-location: classpath:mybatis-config.xml
configuration:
log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
map-underscore-to-camel-case: true

View File

@ -4,7 +4,7 @@
<contextName>logback</contextName>
<!-- 日志的输出目录 -->
<property name="log.path" value="D://logs//spzx-manager//logs" />
<property name="log.path" value="logs//spzx-manager//logs"/>
<!--控制台日志格式:彩色日志-->
<!-- magenta:洋红 -->
@ -12,7 +12,8 @@
<!-- cyan:青色 -->
<!-- white:白色 -->
<!-- magenta:洋红 -->
<property name="CONSOLE_LOG_PATTERN" value="%yellow(%date{yyyy-MM-dd HH:mm:ss}) %highlight([%-5level]) %green(%logger) %msg%n"/>
<property name="CONSOLE_LOG_PATTERN"
value="%yellow(%date{yyyy-MM-dd HH:mm:ss}) %highlight([%-5level]) %green(%logger) %msg%n"/>
<!--文件日志格式-->
<property name="FILE_LOG_PATTERN" value="%date{yyyy-MM-dd HH:mm:ss} [%-5level] %thread %file:%line %logger %msg%n"/>

View File

@ -1,5 +1,6 @@
package com.atguigu.spzx.model.entity.base;
import com.fasterxml.jackson.annotation.JsonFormat;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Data;
@ -8,15 +9,14 @@ import java.util.Date;
@Data
public class BaseEntity implements Serializable {
@Schema(description = "唯一标识")
private Long id;
// @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
@Schema(description = "创建时间")
private Date createTime;
// @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
@Schema(description = "修改时间")
private Date updateTime;