不同於上一篇文章,這裏我們可以通過註解方式來設置日期格式來進行格式化操作!
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";
}
然後我們輸入錯誤的格式:
添加還是能成功,但是生日就沒有了!
控制檯出現錯誤提示: