SpringBoot基于HttpMessageConverter實(shí)現(xiàn)全局日期格式化
還在為日期格式化的問題頭痛?趕緊閱覽文章尋找答案吧!
學(xué)習(xí)目標(biāo)
快速學(xué)會使用Jackson消息轉(zhuǎn)換器并實(shí)現(xiàn)日期的全局格式化。
快速查閱
開始教程
一、全局日期格式化(基于自動配置)
關(guān)于日期格式化,很多人會想到使用Jackson的自動配置:
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; } /** * 自動根據(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> <h3><a th:href="@{/}" rel="external nofollow" >1.在頁面中對日期格式化</a></h3> <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> <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>
啟動項(xiàng)目后訪問 http://localhost:8080 查看日期格式化效果:
四、小結(jié)
1、使用@ResponseBody會根據(jù)請求頭信息來智能選擇JSON/XML消息轉(zhuǎn)換器。
2、通過重寫HttpMessageConverter可以自定義消息轉(zhuǎn)換器來實(shí)現(xiàn)全局日期格式化。
3、采用類似yyyy-MM-dd HH:mm:ss的日期格式更符合國人的閱讀習(xí)慣,能夠提升用戶體驗(yàn)。
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
Kotlin + Retrofit + RxJava簡單封裝使用詳解
這篇文章主要介紹了Kotlin + Retrofit + RxJava簡單封裝使用詳解,小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧2018-07-07Spring Security基本架構(gòu)與初始化操作流程詳解
這篇文章主要介紹了Spring Security基本架構(gòu)與初始化操作流程,Spring Security是一個(gè)能夠?yàn)榛赟pring的企業(yè)應(yīng)用系統(tǒng)提供聲明式的安全訪問控制解決方案的安全框架2023-03-03SpringBoot利用validation實(shí)現(xiàn)優(yōu)雅的校驗(yàn)參數(shù)
數(shù)據(jù)的校驗(yàn)是交互式網(wǎng)站一個(gè)不可或缺的功能,如果數(shù)據(jù)庫中出現(xiàn)一個(gè)非法的郵箱格式,會讓運(yùn)維人員頭疼不已。本文將介紹如何利用validation來對數(shù)據(jù)進(jìn)行校驗(yàn),感興趣的可以跟隨小編一起學(xué)習(xí)一下2022-06-06springboot關(guān)閉druid監(jiān)控 druid2改配置文件無效的解決
這篇文章主要介紹了springboot關(guān)閉druid監(jiān)控 druid2改配置文件無效的解決方案,具有很好的參考價(jià)值,希望對大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2024-05-05struts2中實(shí)現(xiàn)多個(gè)文件同時(shí)上傳代碼
struts2中實(shí)現(xiàn)多個(gè)文件同時(shí)上傳代碼,需要的朋友可以參考一下2013-04-04深入理解JSON及其在Java中的應(yīng)用小結(jié)
json它是一種輕量級的數(shù)據(jù)交換格式,由于其易于閱讀和編寫,同時(shí)也易于機(jī)器解析和生成,因此廣泛應(yīng)用于網(wǎng)絡(luò)數(shù)據(jù)交換和配置文件,這篇文章主要介紹了深入理解JSON及其在Java中的應(yīng)用,需要的朋友可以參考下2023-12-12攔截器獲取request的值之后,Controller拿不到值的解決
這篇文章主要介紹了攔截器獲取request的值之后,Controller拿不到值的解決方案,具有很好的參考價(jià)值,希望對大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2021-10-10