SpringMVC或SpringBoot請求時間引數報錯處理方法
阿新 • • 發佈:2019-01-04
一:先亮出最好的,全域性性引數處理
新建一個GlobalHandler類,同時也可以在這裡做全域性異常處理(類要加上Spring的ControllerAdvice註解);類中加入:
@InitBinder public void initBinder(WebDataBinder binder) { // System.out.println("============處理所有@RequestMapping註解方法,在其執行之前初始化資料繫結器"); SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss"這是我的GlobalHandler類:); // dateFormat.setLenient(false);//這句一個不要存在,不然還是處理不了時間轉換 binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true)); }
@ControllerAdvice public class GlobalHandler { @ExceptionHandler(RuntimeException.class) @ResponseBody //表示攔截json public Map<String,Object> exceptionHandler(){ Map<String,Object> result = new HashMap<>(); result.put(BaseController.JSON_SUCCESS,0); result.put(BaseController.JSON_MSG,"code = 500"); return result; } @InitBinder public void initBinder(WebDataBinder binder) { // System.out.println("============處理所有@RequestMapping註解方法,在其執行之前初始化資料繫結器");SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss"); // dateFormat.setLenient(false);//這句一個不要存在,不然還是處理不了時間轉換 binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true)); } }
二:在controller需要日期轉換的類中加入下面這個方法:
@InitBinder protected void initBinder(ServletRequestDataBinder binder) { DateFormat fmt = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss"); CustomDateEditor dateEditor = new CustomDateEditor(fmt, true); binder.registerCustomEditor(Date.class, dateEditor); }
三:在需要轉換的實體類的屬性上增加 @DateTimeFormat(pattern = "yyyy-MM-dd hh:mm:ss")
@DateTimeFormat(pattern = "yyyy-MM-dd hh:mm:ss") private Date gdDate;
如果您在編寫java過程中有出現問題,如果不嫌棄小編我學歷淺薄,歡迎新增我的微信一共討論,感謝您的支援!微訊號:atgeretg
覺得還可以請您打賞,您的十分滿意是小編的無限動力。