SpringMVC: Getting Started with Data Binding (2)

1. How to match the input data format with the required one? For example: http://localhost:8080/date1.do?date1=2018-01-01, where the data type of the input date1 is A String type data in the format "yyyy-MM-dd", how to ensure that it is converted into the data in the Date format we need. Spring introduces the Formatter interface

public interface Formatter<T> extends Printer<T>, Parser<T> { 

}
Parse the data of type String to Date type, note: Only String type is allowed here. You can write a class below to implement this interface

In this way, the String type format of "yyyy-MM-dd" can be parsed into Date format data. Next, it needs to be bound,

After the binding is complete, you can enter the browser for testing.

2. In addition to the formatter that can parse data of type String, Spring also provides Converter, which converts data of type S into data of type T. Its implementation method is similar to that of Formatter:

3. If the above two methods are not used, is there any other way to achieve it? You can use WebDateBinder, first register an editor,

This can also achieve the purpose.

3.String property editor: PropertyEditor, this interface has many implementation classes, for example, the more important methods under PropertyEditorSupport are getSource, setSource, getValue, setValue, getAsText, setAsText,

 

 4. Summary: Regarding the difference between the three, Property is built-in and can be extended by overriding methods, but it can only be used locally with WebDateBinder, Formatter is built-in, you can also write classes to implement interfaces and override methods To extend it, it can be used locally and globally. Converter is built-in and has no extensibility. The built-in classes are all final modified, not extensible, and can be used locally and globally.

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325282142&siteId=291194637