還在為日期格式化的問題頭痛宪卿?趕緊閱覽文章尋找答案吧弊攘!
學(xué)習(xí)目標(biāo)
快速學(xué)會使用Jackson消息轉(zhuǎn)換器并實現(xiàn)日期的全局格式化哎榴。
快速查閱
專題閱讀:《SpringBoot 布道系列》
— Hey Man菇肃,Don't forget to Star or Fork . —
開始教程
一、全局日期格式化(基于自動配置)
關(guān)于日期格式化首量,很多人會想到使用Jackson的自動配置:
spring.jackson.date-format=yyyy-MM-dd HH:mm:ss
spring.jackson.timeZone: GMT+8
這種全局日期格式化固然方便,但在消息傳遞時只能解析特定的時間格式,在實際業(yè)務(wù)開展中并不那么方便加缘。例如某接口返回的是long
類型的時間戳鸭叙,顯然此時消息轉(zhuǎn)換器將拋出解析失敗的異常。
那么有沒更好的辦法拣宏,既支持返回默認(rèn)的日期格式沈贝,又支持解析復(fù)雜的日期字符串?
答案是有的勋乾,只需要重寫Jackson的消息轉(zhuǎn)換器來支持解析復(fù)雜的日期格式即可宋下。
二、全局日期格式化(基于消息轉(zhuǎn)換器)
首先在項目引入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ù)實際業(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類型的時間戳
} catch (ParseException e1) {
throw new RuntimeException("日期格式非法:" + e);
}
}
}
};
緊接著根據(jù)使用場景撩满,來介紹如何快速實現(xiàn)日期的格式化。
關(guān)于日期時間格式化的三種使用場景
(1)使用@ResponseBody
返回JSON
信息會用到MappingJackson2HttpMessageConverter
绅你。
@Bean
public MappingJackson2HttpMessageConverter mappingJackson2HttpMessageConverter() {
MappingJackson2HttpMessageConverter jsonConverter = new MappingJackson2HttpMessageConverter();
//設(shè)置解析JSON工具類
ObjectMapper objectMapper = new ObjectMapper();
//設(shè)置解析日期的工具類
objectMapper.setDateFormat(dateFormat);
//忽略未知屬性 防止解析報錯
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);
//忽略未知屬性 防止解析報錯
xmlMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
xmlConverter.setObjectMapper(xmlMapper);
return xmlConverter;
}
(3)使用ModelAndView
返回HTML
頁面信息。
值得注意的是忌锯,無論上面哪種消息轉(zhuǎn)換器均無法滿足頁面日期的全局格式化伪嫁,因為th:object
默認(rèn)調(diào)用的日期Date的toString方法,所以在Thymemleaf
頁面對日期格式化需要借助工具類#dates
偶垮。
例如:<input th:value="*{#dates.format(createTime,'yyyy-MM-dd HH:mm:ss')}">
三张咳、測試日期格式化
推薦大家下載源碼對照擼一遍,實踐是檢驗真理的唯一標(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="@{/}">1.在頁面中對日期格式化</a></h3>
<form th:object="${user}">
<input th:value="*{userId}" type="hidden">
賬號:<input th:value="*{username}">
密碼:<input th:value="*{password}" type="password">
時間:<input th:value="*{createTime}" type="text">
</form>
<form th:object="${user}">
賬號:<input th:value="*{username}">
密碼:<input th:value="*{password}" type="password">
時間:<input th:value="*{#dates.format(createTime,'yyyy-MM-dd HH:mm:ss')}">
</form>
<h3><a th:href="@{/user/json}">2.點擊獲取JSON信息</a></h3>
<h3><a th:href="@{/user/xml}">3.點擊獲取XML信息</a></h3>
</body>
</html>
啟動項目后訪問 http://localhost:8080 查看日期格式化效果:
四脚猾、小結(jié)
1、使用@ResponseBody
會根據(jù)請求頭信息來智能選擇JSON/XML
消息轉(zhuǎn)換器砚哗。
2龙助、通過重寫HttpMessageConverter
可以自定義消息轉(zhuǎn)換器來實現(xiàn)全局日期格式化。
3蛛芥、采用類似yyyy-MM-dd HH:mm:ss
的日期格式更符合國人的閱讀習(xí)慣提鸟,能夠提升用戶體驗。