SPRINGMVC Accept Date type parameter processing
The problem, that is, how to springmvc the conversion of parameter types
Scenario 1 Initbinder
Adding data bindings to the controller
1 @InitBinder
2 public void Initbinder (Webdatabinder binder) {
3 SimpleDateFormat dateformat = new Simpledateform at ("Yyyy-mm-dd");
4 dateformat.setlenient (false);
5 Binder.registercustomeditor (Date.class, New Customdateeditor (DateFormat, True)); True: Allow null value to be entered, false: cannot be null
Scenario 2 Converter
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
* Resolution
* 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
class Dateconvert implements Converter<string, date> {
@Override public
Date Convert (String stringdate) {
SimpleDateFormat SimpleDateFormat = new SimpleDateFormat ("Yyyy-mm-dd");
try {
return Simpledateformat.parse (stringdate),
} catch (ParseException e) {
e.printstacktrace ();
}
return null;
}
}
3. Registering the custom type conversion class
<!--step Three: Register the processor Mapper/processor adapter, add Conversion-service Properties--
<mvc:annotation-driven conversion-service= " Conversionservice "/>
<!--Step Two: Create Convertion-service and inject dateconvert-->
<bean id=" Conversionservice "class=" Org.springframework.format.support.FormattingConversionServiceFactoryBean ">
<property name= "Converters" >
<set>
<ref bean= "Dateconvert"/>
</set>
< /property>
</bean>
<!--first step: Create a custom date conversion rule--
<bean id= "Dateconvert" class= " Zpark.convert.DateConvert "/>