The problem, that is, how to springmvc the conversion of parameter types
To pass the client over. A string type, converted to a date type, for example:
1.controller
/** * Receive date type parameter * NOTE: * SPRINGMVC when receiving date type parameter, if do not do special processing will appear 400 syntax format error * Workaround * 1. Global Date processing * * /@RequestMapping ("/test" )public String Test (Date birthday) { System.out.println (birthday); return "Index"; }
2. Custom type conversion rules
SPRINGMVC provides the converter interface, which supports converting from one object to another object
/*** Global Date Processing class * convert<t,s> * generic T: Parameter submitted on behalf of the client String * Generic S: type converted by convert
*/ Public classDateconvertImplementsConverter<string, date>{@Override PublicDate Convert (String stringdate) {SimpleDateFormat SimpleDateFormat=NewSimpleDateFormat ("Yyyy-mm-dd"); Try { returnSimpledateformat.parse (stringdate); } Catch(ParseException e) {e.printstacktrace (); } return NULL; }}
3. Registering the custom type conversion class
<!--Step Three: Register the processor Mapper/processor adapter and add the Conversion-service property - <Mvc:annotation-drivenConversion-service= "Conversionservice"/> <!--Step Two: Create a convertion-service and inject Dateconvert - <BeanID= "Conversionservice"class= "Org.springframework.format.support.FormattingConversionServiceFactoryBean"> < Propertyname= "Converters"> <Set> <refBean= "Dateconvert"/> </Set> </ Property> </Bean> <!--First step: Create a custom date conversion rule - <BeanID= "Dateconvert"class= "Zpark.convert.DateConvert"/>
4. Address Bar Access
http://localhost:9999/date/test2?birthday=1990-01-02
Reference: http://blog.csdn.net/renhui999/article/details/9837897
PS: Test for a long time to succeed, the number of failures too much will not be recorded, here just recorded the correct steps to test
Package Zpark.convert;
Import Java.text.parseexception;import Java.text.simpledateformat;import java.util.Date;
Import org.springframework.core.convert.converter.converter;/** * Global Date Processing class * convert<t,s> * generic T: Arguments submitted on behalf of the client String * Generics s: type converted by convert */public class Dateconvert implements Converter<string, date> {
@Overridepublic Date Convert (String stringdate) {SimpleDateFormat SimpleDateFormat = new SimpleDateFormat ("Yyyy-mm-dd" ), try {return simpledateformat.parse (stringdate),} catch (ParseException e) {e.printstacktrace ();} return null;}
}
SPRINGMVC Accept Date Type parameter processing