SpringMVC学习笔记16-----数据格式化操作和格式化错误的显示
程序员文章站
2024-01-03 11:11:52
...
不同于上一篇文章,这里我们可以通过注解方式来设置日期格式来进行格式化操作!
1.代码:
把之前@InitBinder注解的方法注释掉,然后再在JavaBean中的要添加格式的类属性上面加上:
@DateTimeFormat(pattern = "yyyy-MM-dd")
private Date birth;
springmvc.xml文件(将之前的ConversionServiceFactoryBean改成了现在的FormattingConversionServiceFactoryBean,不影响此前的任何功能):
<!--For @DateTimeFormat annotation to change configuration
from ConversionServiceFactoryBean to FormattingConversionServiceFactoryBean,
And this change will affect other function previous!-->
<bean id="conversionService" class="org.springframework.format.support.FormattingConversionServiceFactoryBean">
<property name="converters">
<set>
<ref bean="studentConverter"/>
</set>
</property>
</bean>
2.源码分析:
我们在Student类中的birth的setter方法打个断点:
然后调试程序到这一步,在函数栈中往前翻找到:
在variables中找到binder里的ConversionService,发现其类型是DefaultFormattingConversionService,可以同时进行数据格式化和校验,然后我们看下其内容:
可以看到好多注解工厂类:注解就是这么来的!
3.出现错误怎么办:
之前说数据绑定的时候已经说过,SpringMVC会把绑定和校验出现的错误结果放在BindingResult中,所以我们就可以在我们的目标方法中加上BindingResult入参!将之前的添加的目标方法改成这样:
/* add one student information*/
@RequestMapping(value = "/stu", method = RequestMethod.POST)
public String saveStu(Student student, BindingResult result) {
/*if something goes wrong during the project running*/
if (result.hasErrors()) {
System.out.println("there is some thing wrong!");
for (FieldError error : result.getFieldErrors()) {
System.out.println(error.getField() + " has problem:" + error.getDefaultMessage());
}
}
/* it is the solution of the question that input.jsp only give student'school id value but no name value */
School school = schoolDao.getSchoolById(student.getSchool().getId());
student.setSchool(school);
studentDao.saveStudent(student);
return "redirect:/stus";
}
然后我们输入错误的格式:
添加还是能成功,但是生日就没有了!
控制台出现错误提示: