1. 程式人生 > 其它 >Springmvc時間轉換+全域性異常捕獲

Springmvc時間轉換+全域性異常捕獲

註解@JsonFormat主要是後臺到前臺的時間格式的轉換

@JsonFormat(pattern="yyyy-MM-dd HH:mm:ss")

註解@DataFormAT主要是前後到後臺的時間格式的轉換

@DateTimeFormat(pattern ="yyyy-MM-dd HH:mm:ss")

spring mvc是通過jackson來序列化/反序列化json字串的;

jackson支援的日期格式:

"yyyy-MM-dd'T'HH:mm:ss.SSSZ";
"yyyy-MM-dd'T'HH:mm:ss.SSS'Z'";
"yyyy-MM-dd";
"EEE, dd MMM yyyy HH:mm:ss zzz";
long型別的時間戳;

資料庫的日期格式為yyyy-MM-dd HH:mm:ss

解決方案:

在spring boot配置檔案中加上如下程式碼:

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

@Slf4j
@ControllerAdvice
public class GlobalExceptionResolver extends DefaultHandlerExceptionResolver {

@ExceptionHandler(value = Exception.class)
public void defaultErrorHandler(HttpServletRequest request, HttpServletResponse response, Object handler, Exception e) throws Exception {
if (e!=null){
log.info(e.getMessage());
Map<String, Object> result = new HashMap<>();
result.put("code", 777);
result.put("msg", "請求資料格式錯誤");
String jsonStr = JSONUtils.toJSONString(result);
response.setCharacterEncoding("UTF-8");
response.setContentType("text/html;charset=UTF-8");
PrintWriter wirte = response.getWriter();
wirte.print(jsonStr);
wirte.flush();
wirte.close();
}
}
}