SpringMVC uses @ InitBinder to parse and binder page data. springmvcinitbinder
Synchronous publishing: http://www.yuanrengu.com/index.php/springmvc-user-initbinder.html
In projects using the SpingMVC framework, some data types on the page, such as Date, Integer, and Double, are usually bound to the Controller entity, or the controller needs to accept the data, if this type of data is not processed, it cannot be bound.
Here we can use annotation @ InitBinder to solve these problems, so that SpingMVC will register these editors before binding the form. Generally, these methods are used in BaseController. The controllers that need to perform such conversions only need to inherit the BaseController. In fact, Spring provides many implementation classes, such as CustomDateEditor, CustomBooleanEditor, and CustomNumberEditor, which are basically enough.
The demo is as follows:
public class BaseController { @InitBinder protected void initBinder(WebDataBinder binder) { binder.registerCustomEditor(Date.class, new MyDateEditor()); binder.registerCustomEditor(Double.class, new DoubleEditor()); binder.registerCustomEditor(Integer.class, new IntegerEditor()); } private class MyDateEditor extends PropertyEditorSupport { @Override public void setAsText(String text) throws IllegalArgumentException { SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); Date date = null; try { date = format.parse(text); } catch (ParseException e) { format = new SimpleDateFormat("yyyy-MM-dd"); try { date = format.parse(text); } catch (ParseException e1) { } } setValue(date); } } public class DoubleEditor extends PropertiesEditor { @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(); } } public class IntegerEditor extends PropertiesEditor { @Override public void setAsText(String text) throws IllegalArgumentException { if (text == null || text.equals("")) { text = "0"; } setValue(Integer.parseInt(text)); } @Override public String getAsText() { return getValue().toString(); } } }