When using SpringMVC, you often encounter conversions between date strings in the form and JavaBean's Date type, while SpringMVC does not support conversions in this format by default, so you need to manually configure and customize data binding to solve this problem.
Use SpringMVC annotation @initbinder and Spring's WebDateBinder class to operate in Controllers that require date conversion.
WebDataBinder is used to bind request parameters to the specified property editor. Since the value passed to the controller in the foreground is of String type, when Set value in Model, if the property of set is an object, Spring will find the corresponding editor for conversion, and then SET it in.
The code is as follows:
@InitBinder public void initBinder(WebDataBinder binder) { SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd"); dateFormat.setLenient(false); binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true)); }Need to add the configuration file in SpringMVC
<!-- parser registration--> <bean> <property name="messageConverters"> <list> <ref bean="stringHttpMessageConverter"/> </list> </property> </bean> <!-- String type parser, allowing direct return of String---> <bean id="stringHttpMessageConverter"/>
Change of writing
<mvc:annotation-driven> <mvc:message-converters> <bean> <constructor-arg value="UTF-8"/> </bean> </mvc:message-converters></mvc:annotation-driven>
expand:
Spring mvc will register these editors before binding the form. Spring itself provides a large number of implementation classes, such as CustomDateEditor, CustomBooleanEditor, CustomNumberEditor, etc., which are basically enough.
Call the registerCustomEditor method of WebDataBinder when using
registerCustomEditor source code:
public void registerCustomEditor(Class<?> requiredType, PropertyEditor propertyEditor) { getPropertyEditorRegistry().registerCustomEditor(requiredType, propertyEditor);} The first parameter requiredType is the type that needs to be converted.
The second parameter PropertyEditor is the property editor, which is an interface. The above mentioned examples such as CustomDateEditor, all inherit the PropertyEditorSupport class that implements this interface.
We can also not use these editor classes that come with them.
We can construct ourselves:
import org.springframework.beans.propertyeditors.PropertiesEditor;public class DoubleEditor extends PropertyEditorSupport { @Override public void setAsText(String text) throws IllegalArgumentException { if (text == null || text.equals("")) { text = "0"; } setValue(Double.parseDouble(text)); } @Override public String getAsText() { return getValue().toString(); }}The above is all the content of this article. I hope it will be helpful to everyone's learning and I hope everyone will support Wulin.com more.