In projects using the SpringMVC framework, you often encounter data whose data types are Date, Integer, Double, etc. must be bound to the controller's entity, or the controller needs to accept this data. If this type of data type is not processed, it will not be bound.
Here we can use the annotation @InitBinder to solve these problems, so that SpringMVC will register these editors before binding the form. Generally, these methods are included in the BaseController. The controller that needs to perform such conversion only needs to inherit the BaseController. In fact, Spring provides many implementation classes, such as CustomDateEditor, CustomBooleanEditor, CustomNumberEditor, etc., which are basically sufficient.
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(); } } }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.