springmvc请求时间参数报错

本文介绍在SpringBoot项目中如何解决表单提交Date类型参数时出现的问题,提供了三种有效解决方案,包括使用@DateTimeFormat注解、Controller上的initBinder方法及@ControllerAdvice全局配置。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

其实之前就遇到过这个问题,只是之前并没有做记录,现在学习springboot,看到一种比较好的处理方式就记录下来。

问题:

在提交表单到Controller的时候,如果实体中存在Date类型的参数或者参数就是Date类型的,那么在提交表单的时候会遇到提交失败的错误,通过debug发现连controller都没有进入。

解决方法:

之前在网上搜索过处理方法,现在了解的由三种。全局处理推荐第三章方法。

  1. 在实体的属性上增加@DateTimeFormat(pattern = “yyyy-MM-dd”),如下:

     public class User {
        private Integer id;
        private String name;
        @DateTimeFormat(pattern = "yyyy-MM-dd")
        private Date birthday;
        //省略get--set方法
    }
    
  2. 在Controller上加入initBinder方法,如下:

         @InitBinder
        public void initBinder(WebDataBinder binder) {
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
            dateFormat.setLenient(false);
            binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true));
        }
    
  3. 这个是我最新发现的,用了@ControllerAdvice,此注解注解的类内注解的方法应用到所有的 @RequestMapping注解的方法。读起来绕口,直接看例子:

    @ControllerAdvice
    public class GlobalExceptionHandler {
        @InitBinder
        public void initBinder(WebDataBinder binder) {
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
            dateFormat.setLenient(false);
            binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true));
        }
    }
    

这个会应用到你系统中所有的请求。是不是很简单,当然这个类其实更好的用处是异常处理,详见开涛大神的博客点击进入

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值