配置spring的配置文件:
1 <bean id="conversionService" 2 class="org.springframework.context.support.ConversionServiceFactoryBean"> 3 <property name="converters"> 4 <list> 5 <bean class="app06a.converter.StringToDateConverter"> 6 <constructor-arg type="java.lang.String" value="MM-dd-yyyy"/> 7 </bean> 8 </list> 9 </property> 10 </bean> 11 <mvc:annotation-driven conversion-service="conversionService"/>
这样配置好了之后,就可以创建一个Converter的装换器类来写一个转换器的实现。这里我们写的转换器是把String类型转换为Date类型的。日期格式为value后面的。
1 public class StringToDateConverter implements Converter<String,Date>{ 2 private String datePattern; 3 public StringToDateConverter(String datePattern){ 4 this.datePattern=datePattern; 5 System.out.println("instiating"+datePattern); 6 } 7 @Override 8 public Date convert(String s) { 9 SimpleDateFormat dateformat=new SimpleDateFormat(); 10 dateformat.setLenient(false); 11 try { 12 return dateformat.parse(s); 13 } catch (ParseException e) { 14 throw new IllegalArgumentException("invailed date"+datePattern+"""); 15 } 16 } 17 }
然后实现了Converer<S,T>接口。
这样,若是日期输入错误,则会返回之前输入的页面,页面上也会出现提示:
1 @RequestMapping(value="/employee_input") 2 public String inputEmployee(Model model){ 3 model.addAttribute("employee",new Employee()); 4 return "EmployeeForm"; 5 } 6 7 @RequestMapping(value="/employee_save") 8 public String saveEmployee(@ModelAttribute Employee employee,BindingResult bindresult,Model model){ 9 if(bindresult.hasErrors()){ 10 FieldError fielderror=bindresult.getFieldError(); 11 return "EmployeeForm"; 12 } 13 model.addAttribute("employee",employee); 14 return "EmployeeDetails"; 15 }
==========================================================