美文网首页
Spring MVC接收参数为日期类型

Spring MVC接收参数为日期类型

作者: else05 | 来源:发表于2017-07-21 14:56 被阅读588次

    问题:

    在Spring Boot的Controller中接收日期类型,格式是yyyy-MM-dd HH:mm:ss , 结果报异常

    public String batchUpload(@RequestParam  LocalDateTime startTime){
    // do something
    }
    

    报的异常
    Failed to convert value of type 'java.lang.String' to required type 'java.time.LocalDateTime'
    如果是Date类型则为
    Failed to convert value of type 'java.lang.String' to required type 'java.util.Date'

    解决方法:

    先加上maven依赖:

    <dependency>
         <groupId>com.fasterxml.jackson.datatype</groupId>
         <artifactId>jackson-datatype-jsr310</artifactId>
    </dependency>
    
    • 第一种:在controller中加入如下方法
    @InitBinder  
    private void initBinder(WebDataBinder binder) {  
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");  
        binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true));  
    }  
    
    注:这种方式只能处理Date类型,如果是LocalDateTime则要自己新建类,继承PropertyEditorSupport ,可以参考org.springframework.beans.propertyeditors.CustomDateEditor的实现方式
    • 第二种:使用注解
    public String batchUpload(@RequestParam @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")  LocalDateTime startTime){
    // do something
    }
    
    注:前端传的日期格式为“2017-07-03 12:23:12” 。如果“2017-7-3 12:23:12”则会异常,因为匹配规则为“yyyy-MM-dd HH:mm:ss” , 除了年份,都要为两位数才行

    参考:

    相关文章

      网友评论

          本文标题:Spring MVC接收参数为日期类型

          本文链接:https://www.haomeiwen.com/subject/thcekxtx.html