今日 ,写一个springboot项目时,进行添加操作时,报错 ,报错提示如下所示:
而我的表单提交信息如下:
查看错误状态码,400 表示 语法格式有错误 ,于是仔细排查。发现:Birth在javaBean对象中定义的类型为Date类型,在页面上的输入如下:
<div class="from-group">
<label>Birth</label>
<input name="birth" type="text" class="form-control" placeholder="zhangsan">
</div>
于是大概就明白了报错的原因,传入的birth的格式不对,springmvc在自动封装请求参数时,无法进行类型转换,由此引发报400错,为了验证该原因, 我输入 2017.12.21 仍旧报该错,在输入 2017/12/21 ,成功完成添加,这就说明确实是格式不对造成的。
为什么是这样呢?
我接着去看springboot自动配置类 -WebMvcAutoConfiguration ,查找 WebMvcProperties.class 有如下配置:
/**
* Date format to use. For instance, `dd/MM/yyyy`.
*/
private String dateFormat;
原来这里采用默认配置 ,格式类似 dd/MM/yyyy ,不能支持 dd-MM-yyyy形式,所以这就好办了, 我们可以在application.yml/application.properties中将默认日期格式化改为 dd-mm-yyyy形式:
#spring.mvc.date-format=yyyy-MM-dd HH:mm
spring.mvc.date-format=yyyy-MM-dd
重新启动springboot项目,然后提交表单就会发现,dd-mm-yyyy形式可以正常提交了,但是注意:默认的dd/MM/yyyy就无法提交。以上就是我解决问题的过程。
总结: 遇到报错,状态码为400时,不要慌,说明是语法格式错误,一般都是数据格式不对,springmvc无法封装绑定到实体类中,或者无法绑定到某个字段,要仔细查看传入的数据的格式。
另外看到的帖子说,在参数的后面加一个, BindingResult bindingResult ,也可以解决报错的问题,即
public String addEmp(Employee employee, BindingResult bindingResult){
// todo
}
经过测试 ,确实可以解决,但是,绑定的实体类中,该项没有具体值,也就是说表单输入的值,并没有绑定到实体类的该字段上。 打印 bindingResult.getModel()
{employee=Employee{id=1006, lastName='zhangsan', email='zh@163.com', gender=1, department=Department [id=102, departmentName=D-BB], birth=null}, org.springframework.validation.BindingResult.employee=org.springframework.validation.BeanPropertyBindingResult: 1 errors
Field error in object 'employee' on field 'birth': rejected value [2017/12/12]; codes [typeMismatch.employee.birth,typeMismatch.birth,typeMismatch.java.util.Date,typeMismatch]; arguments [org.springframework.context.support.DefaultMessageSourceResolvable: codes [employee.birth,birth]; arguments []; default message [birth]]; default message [Failed to convert property value of type 'java.lang.String' to required type 'java.util.Date' for property 'birth'; nested exception is org.springframework.core.convert.ConversionFailedException: Failed to convert from type [java.lang.String] to type [java.util.Date] for value '2017/12/12'; nested exception is java.lang.IllegalArgumentException: Parse attempt failed for value [2017/12/12]]}
大概是捕捉并处理了异常,这明显不是我们想要的结果,因为并没有去解决异常, 并且数据也没有被封装,实质上并没有解决问题,因此不建议采用该方式。