zoukankan      html  css  js  c++  java
  • (ssm框架)springMVC form表单提交---包含时间(date)类型的数据报错400

    •   用户中有日期(Date)属性,提交表单的时候,SpringMVC报错,意思是不能把字符串转为日期类型的,浏览器报400。如果是strtus的话,压根不是问题,这事因为sprongMVC识别不了Data类型解决方式有如下几种
    • 第一种方法:实体类加注解
        @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")  
        private Date birthday;  
     
     
        @JsonFormat(pattern = "yyyy-MM-dd", timezone = "GMT+8")
        public Date getBirthday(){

    在对应的字段属性上加注解。

    • 第二种方法:控制器中加入一段数据绑定的代码
       //将字符串转换为Date类
        @InitBinder
        public void initBinder(WebDataBinder binder, WebRequest request) {
            //转换日期格式
            DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            //注册自定义的编辑器
            binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true));
            
        }
    • 第三种方法:实现一个全局日期类型转换器进行配置
    package com.xueqing.demo;
     
    import java.text.DateFormat;
    import java.text.SimpleDateFormat;
    import java.util.Date;
     
    import org.springframework.beans.propertyeditors.CustomDateEditor;
    import org.springframework.web.bind.WebDataBinder;
    import org.springframework.web.bind.support.WebBindingInitializer;
    import org.springframework.web.context.request.WebRequest;
     
    public class CustomDateEdtor implements WebBindingInitializer {   
        public void initBinder(WebDataBinder binder, WebRequest request) {
            // TODO Auto-generated method stub
            //转换日期格式
            DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");        
            binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true));
        }
    }

    然后在springMvc配置文件进行配

    <!-- 配置全局日期转换器 -->
        <bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
            <property name="webBindingInitializer">    
                <bean class="nuc.ss.wlb.core.web.CustomDateEdtor"/>
            </property>
        </bean>
    • 第四种方法:更改日期输入框格式

    马虎造成输入框日期格式与数据库格式不一致造成,比如我数据库是这样的格式:

     

    而你输入框的格式是这样的

    也会导致因为Date类型不对应造成的400错误,所以这时候需把两边的格式改为一致才行。

  • 相关阅读:
    ubuntu 18.04 搭建flask服务器(大合集,个人实操)
    Ubuntu18.04下Git安装及使用
    c#随机打乱数组
    c#递归获取目录下所有文件名称
    授人以渔:Keil配色界面较为详细的解释
    k8s存储资源之持久化存储资源存储卷PV与PVC理解与应用(七)
    Servlet总结
    Linux 系统目录结构
    make 编译笔记
    【Linux】Linux网络编程
  • 原文地址:https://www.cnblogs.com/ITzhangda/p/9889582.html
Copyright © 2011-2022 走看看