溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點(diǎn)擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

怎么在SpringBoot中利用HttpMessageConverter實(shí)現(xiàn)全局日期格式化

發(fā)布時(shí)間:2021-05-31 17:26:00 來源:億速云 閱讀:127 作者:Leah 欄目:編程語言

本篇文章給大家分享的是有關(guān)怎么在SpringBoot中利用HttpMessageConverter實(shí)現(xiàn)全局日期格式化,小編覺得挺實(shí)用的,因此分享給大家學(xué)習(xí),希望大家閱讀完這篇文章后可以有所收獲,話不多說,跟著小編一起來看看吧。

一、全局日期格式化(基于自動(dòng)配置)

關(guān)于日期格式化,很多人會想到使用Jackson的自動(dòng)配置:

spring.jackson.date-format=yyyy-MM-dd HH:mm:ss
spring.jackson.timeZone: GMT+8

這種全局日期格式化固然方便,但在消息傳遞時(shí)只能解析特定的時(shí)間格式,在實(shí)際業(yè)務(wù)開展中并不那么方便。例如某接口返回的是long類型的時(shí)間戳,顯然此時(shí)消息轉(zhuǎn)換器將拋出解析失敗的異常。

那么有沒更好的辦法,既支持返回默認(rèn)的日期格式,又支持解析復(fù)雜的日期字符串?

答案是有的,只需要重寫Jackson的消息轉(zhuǎn)換器來支持解析復(fù)雜的日期格式即可。

二、全局日期格式化(基于消息轉(zhuǎn)換器)

首先在項(xiàng)目引入Jackson、Thymeleaf等相關(guān)依賴:
 

   <dependency><!--Web相關(guān)依賴-->
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <dependency><!--Thymeleaf依賴-->
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-thymeleaf</artifactId>
    </dependency>
    <dependency><!--JSON 解析工具類-->
      <groupId>com.fasterxml.jackson.core</groupId>
      <artifactId>jackson-databind</artifactId>
    </dependency>
    <dependency><!--XML 解析工具類-->
      <groupId>com.fasterxml.jackson.dataformat</groupId>
      <artifactId>jackson-dataformat-xml</artifactId>
      <optional>true</optional>
    </dependency>

然后根據(jù) SimpleDateFormat 來定制支持復(fù)雜日期類型解析的工具類。

  private SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss") {
    //根據(jù)實(shí)際業(yè)務(wù)支持各種復(fù)雜格式的日期字符串。
    @Override
    public Date parse(String source) {
      try {
        return super.parse(source);//支持解析指定pattern類型。
      } catch (Exception e) {
        try {
          return new StdDateFormat().parse(source);//支持解析long類型的時(shí)間戳
        } catch (ParseException e1) {
          throw new RuntimeException("日期格式非法:" + e);
        }
      }
    }
  };

緊接著根據(jù)使用場景,來介紹如何快速實(shí)現(xiàn)日期的格式化。

關(guān)于日期時(shí)間格式化的三種使用場景

(1)使用@ResponseBody返回JSON信息會用到MappingJackson2HttpMessageConverter 。

 @Bean
  public MappingJackson2HttpMessageConverter mappingJackson2HttpMessageConverter() {
    MappingJackson2HttpMessageConverter jsonConverter = new MappingJackson2HttpMessageConverter();
    //設(shè)置解析JSON工具類
    ObjectMapper objectMapper = new ObjectMapper();
    //設(shè)置解析日期的工具類
    objectMapper.setDateFormat(dateFormat);
    //忽略未知屬性 防止解析報(bào)錯(cuò)
    objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    jsonConverter.setObjectMapper(objectMapper);
    List<MediaType> list = new ArrayList<>();
    list.add(MediaType.APPLICATION_JSON_UTF8);
    jsonConverter.setSupportedMediaTypes(list);
    return jsonConverter;
  }

(2)使用@ResponseBody返回XML信息會用到MappingJackson2XmlHttpMessageConverter。

 @Bean
  public MappingJackson2XmlHttpMessageConverter mappingJackson2XmlHttpMessageConverter() {
    MappingJackson2XmlHttpMessageConverter xmlConverter = new MappingJackson2XmlHttpMessageConverter();
    //設(shè)置解析XML的工具類
    XmlMapper xmlMapper = new XmlMapper();
    //設(shè)置解析日期的工具類
    xmlMapper.setDateFormat(dateFormat);
    //忽略未知屬性 防止解析報(bào)錯(cuò)
    xmlMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    xmlConverter.setObjectMapper(xmlMapper);
    return xmlConverter;
  }

(3)使用ModelAndView返回HTML頁面信息。

值得注意的是,無論上面哪種消息轉(zhuǎn)換器均無法滿足頁面日期的全局格式化,因?yàn)閠h:object默認(rèn)調(diào)用的日期Date的toString方法,所以在Thymemleaf頁面對日期格式化需要借助工具類#dates。

例如:<input th:value="*{#dates.format(createTime,'yyyy-MM-dd HH:mm:ss')}">

三、測試日期格式化

推薦大家下載源碼對照擼一遍,實(shí)踐是檢驗(yàn)真理的唯一標(biāo)準(zhǔn)。

JAVA代碼:

/**
 * 用戶管理
 */
@RestController
public class UserController {

  /**
   * 打開主頁
   */
  @GetMapping("/")
  public ModelAndView index() {
    ModelAndView mv = new ModelAndView("user/user");
    mv.addObject("user", new User("1", "admin", "123456", new Date()));
    return mv;
  }

  /**
   * 自動(dòng)根據(jù)請求來判斷返回用戶JSON或XML
   */
  @GetMapping("/user")
  public User get() {
    return new User("1", "admin", "123456", new Date());
  }

  /**
   * 返回用戶JSON
   */
  @GetMapping(value = "/user/json", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
  public User getJson() {
    return new User("1", "admin", "123456", new Date());
  }

  /**
   * 返回用戶XML
   */
  @GetMapping(value = "/user/xml", produces = MediaType.APPLICATION_XML_VALUE)
  public User getXml() {
    return new User("1", "admin", "123456", new Date());
  }

}

頁面代碼:

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
  <meta charset="UTF-8">
  <title>日期格式化</title>
</head>
<body>
<h4><a th:href="@{/}" rel="external nofollow" >1.在頁面中對日期格式化</a></h4>
<form th:object="${user}">
  <input th:value="*{userId}" type="hidden">
  賬號:<input th:value="*{username}">
  密碼:<input th:value="*{password}" type="password">
  時(shí)間:<input th:value="*{createTime}" type="text">
</form>
<form th:object="${user}">
  賬號:<input th:value="*{username}">
  密碼:<input th:value="*{password}" type="password">
  時(shí)間:<input th:value="*{#dates.format(createTime,'yyyy-MM-dd HH:mm:ss')}">
</form>

<h4><a th:href="@{/user/json}" rel="external nofollow" >2.點(diǎn)擊獲取JSON信息</a></h4>
<h4><a th:href="@{/user/xml}" rel="external nofollow" >3.點(diǎn)擊獲取XML信息</a></h4>
</body>
</html>

啟動(dòng)項(xiàng)目后訪問 http://localhost:8080 查看日期格式化效果:

怎么在SpringBoot中利用HttpMessageConverter實(shí)現(xiàn)全局日期格式化

以上就是怎么在SpringBoot中利用HttpMessageConverter實(shí)現(xiàn)全局日期格式化,小編相信有部分知識點(diǎn)可能是我們?nèi)粘9ぷ鲿姷交蛴玫降?。希望你能通過這篇文章學(xué)到更多知識。更多詳情敬請關(guān)注億速云行業(yè)資訊頻道。

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI