Home  >  Article  >  Java  >  What are the ways to handle dates in SpringBoot?

What are the ways to handle dates in SpringBoot?

PHPz
PHPzforward
2023-05-16 14:58:061467browse

In Spring Boot, we usually use Jackson to serialize and deserialize Java objects to JSON. When doing date serialization, we need to specify the date format, otherwise Jackson will use the default format, which may not be what we want. To specify the date format, there are two ways:

If there is no processing, the default result will be as shown below: So we need to use some means to process the date. Here are two ways to solve it.

What are the ways to handle dates in SpringBoot?

Method 1: Use annotations (not recommended)

We can add @JsonFormat() to the entity class date attribute and format our through the parameter pattern The desired format example is as follows:

@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
private LocalDateTime createTime;

@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
private LocalDateTime updateTime;

At this time, the front end will display according to the format we set

What are the ways to handle dates in SpringBoot?

For the above method, we need to The @JSONFormat annotation is added to the date displayed on the front end, so it is very troublesome, so there is method two. Through global exception handling.

Method two custom message converter

First Introducing the ObjectMapper in the Jackson package.

ObjectMapper is a class in the Jackson library. Its main function is:

  • Serialize Java objects into JSON/XML, etc. Format;

  • Deserialize data in JSON/XML and other formats into Java objects.

So, it is the key to convert objects into JSON/XML.

Then we can do something in this class,

(1) Customize the format of date conversion in the constructor. ----It is equivalent to changing its attributes. Initialization value.

(2) Configure SpringMVC to no longer call Jackson’s custom ObjectMapper when calling, and use our custom format

We will implement it in these two steps.

Step one: Inherit ObjectMapper, override the constructor, and customize the serialization method

public class JacksonObjectMapper extends ObjectMapper {

    public static final String DEFAULT_DATE_FORMAT = "yyyy-MM-dd";
    //public static final String DEFAULT_DATE_TIME_FORMAT = "yyyy-MM-dd HH:mm:ss";
    public static final String DEFAULT_DATE_TIME_FORMAT = "yyyy-MM-dd HH:mm";
    public static final String DEFAULT_TIME_FORMAT = "HH:mm:ss";

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

Step two: Let Spring use us Custom message converter

Here we have to think about it, how should we deal with it? Where to configure it? Configuration file? Configuration class?

First of all, we can think of it, it is indispensable in the system is an interceptor, and does the interceptor have a configuration class for configuring interception rules? So can we configure it here?

binggo, right here. When we configure the configuration class of the interceptor, we You will find that the WebMvcConfigurationSupport class has many methods,

including our commonly used protected void addInterceptors(InterceptorRegistry registry) { ... } Configure interception rules

public void addResourceHandlers(ResourceHandlerRegistry registry) {... } There are many configuration methods for configuring resource processing

and so on. And our Message converter is also among them

protected void extendMessageConverters(List<HttpMessageConverter<?>> converters) {...}

By configuring relevant information in this method, you can change the rules specified by Spring by default and use our own defined rules (components)

The code is as follows:

@Override
protected void extendMessageConverters(List<HttpMessageConverter<?>> converters) {
    log.info("扩展消息转换器...");
    //创建一个消息转换器对象,注意不要导错包是Jackson2Http
    MappingJackson2HttpMessageConverter converter =  new MappingJackson2HttpMessageConverter();
    //需要为消息转换器设置一个对象转换器,对象转换器可以将Java对象序列化为json数据
    converter.setObjectMapper(new JacksonObjectMapper());
    //将自己的消息转化器加入容器中
    converters.add(0, converter);
}
  • Created a MappingJackson2HttpMessageConverter, which is Spring MVC's integrated Jackson message converter, which can serialize/deserialize Java objects into JSON.

  • Specify the use of our JacksonObjectMapper for the message converter, which is used to serialize/deserialize Java objects into JSON.

  • Add the MappingJackson2HttpMessageConverter object just created to the message converter list converters, and add it to the first position so that it can be used first

Since we overridden the extendMessageConverters() method, Spring MVC will call this method and use the message converter we added. Therefore, the MappingJackson2HttpMessageConverter we added will take effect and use our custom JacksonObjectMapper() to handle the serialization and deserialization between objects and JSON.

Because our message converter is the first message converter, if the client requests to return JSON data Spring MVC will select our message converter for object serialization.

Thus, all dates in the system are serialized according to the format we require.

At this time, the front-end data is the format we set. It is no longer the default format of Jackson.

Since the date is mentioned, there is also a similar processing of sensitive information:

When we return the front-end data, we may not want the front-end to see the data due to the design of the entity class. Data, at this time, you need to process the data through some means, or two methods.

  • Replace the value of the data before returning, call the set method to set it to Spam information, such as setPassword(“******”)

  • is provided by Jackson in the entity class @JsonIgnore annotation can also be used The solution is to ignore the serialization and deserialization of fields.

The above is the detailed content of What are the ways to handle dates in SpringBoot?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:yisu.com. If there is any infringement, please contact admin@php.cn delete