SpringMVC或SpringBoot请求时间参数报错处理方法

一:先亮出最好的,全局性参数处理

新建一个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


觉得还可以请您打赏,您的十分满意是小编的无限动力。

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值