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

posted @ 2018-11-01 15:36  程序员张达  阅读(6746)  评论(2编辑  收藏  举报