• (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错误,所以这时候需把两边的格式改为一致才行。

  • 相关阅读:
    .netcore返回HellowWorld四种方式(管道配置,管道扩展方法,中间件,IStartupFilter 使用中间件的升级扩展)
    Mysql分页大数据量查询优化
    swagger发布本地的调试的时候没事,发布服务器提示500 : {"Message":"出现错误。"}
    DBeaver的使用(impala和数据库)
    mysql远程连接问题
    java+thymeleaf-layout-dialect+thymeleaf的使用
    springboot+thyemeleaf+swagger项目的创建和问题的解决
    ffmpeg实践
    Camera.main
    python双曲线拟合
  • 原文地址:https://www.cnblogs.com/ITzhangda/p/9889582.html
Copyright © 2020-2023  润新知