SpringBoot基于HttpMessageConverter實(shí)現(xiàn)全局日期格式化
還在為日期格式化的問(wèn)題頭痛?趕緊閱覽文章尋找答案吧!
學(xué)習(xí)目標(biāo)
快速學(xué)會(huì)使用Jackson消息轉(zhuǎn)換器并實(shí)現(xiàn)日期的全局格式化。
快速查閱
開始教程
一、全局日期格式化(基于自動(dòng)配置)
關(guān)于日期格式化,很多人會(huì)想到使用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)換器將拋出解析失敗的異常。
那么有沒(méi)更好的辦法,既支持返回默認(rèn)的日期格式,又支持解析復(fù)雜的日期字符串?
答案是有的,只需要重寫Jackson的消息轉(zhuǎn)換器來(lái)支持解析復(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 來(lái)定制支持復(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ù)使用場(chǎng)景,來(lái)介紹如何快速實(shí)現(xiàn)日期的格式化。
關(guān)于日期時(shí)間格式化的三種使用場(chǎng)景
(1)使用@ResponseBody返回JSON信息會(huì)用到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信息會(huì)用到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頁(yè)面信息。
值得注意的是,無(wú)論上面哪種消息轉(zhuǎn)換器均無(wú)法滿足頁(yè)面日期的全局格式化,因?yàn)閠h:object默認(rèn)調(diào)用的日期Date的toString方法,所以在Thymemleaf頁(yè)面對(duì)日期格式化需要借助工具類#dates。
例如:<input th:value="*{#dates.format(createTime,'yyyy-MM-dd HH:mm:ss')}">
三、測(cè)試日期格式化
推薦大家下載源碼對(duì)照擼一遍,實(shí)踐是檢驗(yàn)真理的唯一標(biāo)準(zhǔn)。
JAVA代碼:
/**
* 用戶管理
*/
@RestController
public class UserController {
/**
* 打開主頁(yè)
*/
@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ù)請(qǐng)求來(lái)判斷返回用戶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());
}
}
頁(yè)面代碼:
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>日期格式化</title>
</head>
<body>
<h3><a th:href="@{/}" rel="external nofollow" >1.在頁(yè)面中對(duì)日期格式化</a></h3>
<form th:object="${user}">
<input th:value="*{userId}" type="hidden">
賬號(hào):<input th:value="*{username}">
密碼:<input th:value="*{password}" type="password">
時(shí)間:<input th:value="*{createTime}" type="text">
</form>
<form th:object="${user}">
賬號(hào):<input th:value="*{username}">
密碼:<input th:value="*{password}" type="password">
時(shí)間:<input th:value="*{#dates.format(createTime,'yyyy-MM-dd HH:mm:ss')}">
</form>
<h3><a th:href="@{/user/json}" rel="external nofollow" >2.點(diǎn)擊獲取JSON信息</a></h3>
<h3><a th:href="@{/user/xml}" rel="external nofollow" >3.點(diǎn)擊獲取XML信息</a></h3>
</body>
</html>
啟動(dòng)項(xiàng)目后訪問(wèn) http://localhost:8080 查看日期格式化效果:

四、小結(jié)
1、使用@ResponseBody會(huì)根據(jù)請(qǐng)求頭信息來(lái)智能選擇JSON/XML消息轉(zhuǎn)換器。
2、通過(guò)重寫HttpMessageConverter可以自定義消息轉(zhuǎn)換器來(lái)實(shí)現(xiàn)全局日期格式化。
3、采用類似yyyy-MM-dd HH:mm:ss的日期格式更符合國(guó)人的閱讀習(xí)慣,能夠提升用戶體驗(yàn)。
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
SpringMVC?HttpMessageConverter報(bào)文信息轉(zhuǎn)換器
這篇文章主要為大家介紹了SpringMVC?HttpMessageConverter報(bào)文信息轉(zhuǎn)換器,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2022-05-05
Spring Boot下如何自定義Repository中的DAO方法
這篇文章主要介紹了Spring Boot下如何自定義Repository中的DAO方法,需要的朋友可以參考下2017-06-06
Spring整合WebSocket應(yīng)用示例(上)
以下教程是小編在參與開發(fā)公司的一個(gè)crm系統(tǒng),整理些相關(guān)資料,在該系統(tǒng)中有很多消息推送功能,在其中用到了websocket技術(shù)。下面小編整理分享到腳本之家平臺(tái)供大家參考2016-04-04
springboot整合mybatis的超詳細(xì)過(guò)程(配置模式+注解模式)
這篇文章主要介紹了springboot整合mybatis的詳細(xì)過(guò)程(配置模式+注解模式),這里我使用的是配置模式+注解模式所以需要配置全局文件,本文通過(guò)實(shí)例代碼給大家介紹的非常詳細(xì),需要的朋友可以參考下2022-04-04

