使用Spring MVC它結果證明我可以用許多不同的方式系結我的表單,我真的覺得我迷路了。a的parseandprint方法Formatter等價于PropertyEditorSupport具有不同名稱的 a (getAsTextand setAsText)。同樣,我可以實作一個GenericConverter 或兩個Converter<S,T>s 來做完全相同的事情。
我在這里Formatters閱讀了替代的評論PropertyEditor,但我沒有找到任何支持它的檔案,它甚至都沒有被棄用。
我的問題是,在將資料從表單系結到物件時,正確的方法是什么spring-mvc?Spring和Spring 之間PropertyEditor的主要區別是什么?每個的用例是什么?對我來說,他們似乎肩負著同樣的責任。FormatterConverter
uj5u.com熱心網友回復:
為了幫助理解這些概念,我首先將 Spring 特定功能與 Java 公開的功能區分開來。
PropertyEditors 和相關的東西由JavaBeans Specification定義。
該規范定義了一個 API、機制和約定,用于處理物件、物件屬性以及與其更改相關的所有內容,作為事件。
PropertyEditors 通常在 GUI 中用于處理 UI 和底層物件模型之間的互動,通常處理屬性值與其String表示之間的轉換。
Spring 本身實際上PropertyEditor在許多不同的情況下使用不同的實作和 Java Beans 約定。例如,來自檔案:
在 Spring 中使用屬性編輯的幾個示例:
在 bean 上設定屬性是通過使用
PropertyEditor實作來完成的。當您使用 String 作為您在 XML 檔案中宣告的某個 bean 的屬性值時,Spring(如果相應屬性的設定器有Class引數)ClassEditor會嘗試將引數決議為Class物件。在 Spring 的 MVC 框架中決議 HTTP 請求引數是通過使用各種
PropertyEditor實作來完成的,您可以在CommandController.
總之,PropertyEditors 允許您使用更廣泛的用例。
現在,在 Spring 世界中,您還需要區分 Spring MVC 和 Spring Core。
請注意,Convert和Formatter都被定義為核心技術,與任何用例相關,并且不限于 Web 框架。
Spring 檔案在描述Spring Field Formatting時,對每個 API/SPI 的用途以及它們與PropertyEditors 的關系提供了很好的解釋:
正如上一節所討論的,
core.convert是一個通用的型別轉換系統。它提供了統一的ConversionServiceAPI 以及強型別的 Converter SPI,用于實作從一種型別到另一種型別的轉換邏輯。Spring 容器使用此系統系結 bean 屬性值。此外,Spring 運算式語言(SpEL)都DataBinder使用這個系統來系結欄位值。例如,當 SpEL 需要將 a 強制Short轉換為 aLong以完成一次expression.setValue(Object bean, Object value)嘗試時,core.convert系統會執行強制。現在考慮典型客戶端環境的型別轉換要求,例如 Web 或桌面應用程式。在這樣的環境中,您通常轉換 from
String以支持客戶端回發程序,以及轉換回String以支持視圖呈現程序。此外,您經常需要本地化String值。更通用的 core.convert Converter SPI 不直接解決此類格式要求。為了直接解決這些問題,Spring 3 引入了一個方便的 Formatter SPI,它PropertyEditor為客戶端環境的實作提供了一個簡單而健壯的替代方案。In general, you can use the Converter SPI when you need to implement general-purpose type conversion logic?—?for example, for converting between a
java.util.Dateand aLong. You can use the Formatter SPI when you work in a client environment (such as a web application) and need to parse and print localized field values. TheConversionServiceprovides a unified type conversion API for both SPIs.
In the specific use case of Spring MVC the framework itself is able to handle simple types when handling the HTTP requests.
Type conversion is automatically applied based on the configured set of converters, although that behavior can be tweaked using DataBinders and the aforementioned Formatting system. Please, see the relevant docs.
In a typical use case in which you deal with reading and writing the body of HTTP requests and responses, when using the @RequestBody, for example, Spring will use a bunch of different pre-configured HttpMessageConverter implementations: the actual ones registered will depend on your configuration and the libraries imported in your project - say Jackson, for example. I was unable to find that point in the documentation but here is the link to the actual source code.
Please, consider review this related SO question, it could be of help.
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/450855.html
