Configure the Spring configuration file:
1 <BeanID= "Conversionservice"2 class= "Org.springframework.context.support.ConversionServiceFactoryBean">3 < Propertyname= "Converters">4 <List>5 <Beanclass= "App06a.converter.StringToDateConverter">6 <Constructor-argtype= "Java.lang.String"value= "Mm-dd-yyyy"/>7 </Bean>8 </List>9 </ Property>Ten </Bean> One <Mvc:annotation-drivenConversion-service= "Conversionservice"/>
Once this is configured, you can create a converter loader class to write the implementation of a converter. Here we write a converter that converts a string type to a date type. The date format is after value.
1 Public classStringtodateconverterImplementsConverter<string,date>{2 PrivateString Datepattern;3 PublicStringtodateconverter (String datepattern) {4 This. datepattern=Datepattern;5System.out.println ("instiating" +datepattern);6 }7 @Override8 PublicDate Convert (String s) {9SimpleDateFormat dateformat=NewSimpleDateFormat ();TenDateformat.setlenient (false); One Try { A returnDateformat.parse (s); -}Catch(ParseException e) { - Throw NewIllegalArgumentException ("invailed date" +datepattern+ "\" "); the } - } -}
The Converer<s,t> interface is then implemented.
Thus, if the date is entered incorrectly, the previously entered page will be returned, and a prompt will appear on the page:
1@RequestMapping (value= "/employee_input")2 PublicString Inputemployee (model model) {3Model.addattribute ("Employee",NewEmployee ());4 return"Employeeform";5 }6 7@RequestMapping (value= "/employee_save")8 PublicString saveemployee (@ModelAttribute Employee employee,bindingresult Bindresult,model Model) {9 if(Bindresult.haserrors ()) {TenFielderror fielderror=bindresult.getfielderror (); One return"Employeeform"; A } -Model.addattribute ("Employee", employee); - return"Employeedetails"; the}
==========================================================
Converter in spring: Converter