一:先亮出最好的,全局性参数处理
新建一个GlobalHandler类,同时也可以在这里做全局异常处理(类要加上Spring的ControllerAdvice注解);类中加入:
@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));
}
这是我的GlobalHandler类:
@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
觉得还可以请您打赏,您的十分满意是小编的无限动力。