SpringMVCを使用する場合、フォームの日付文字列間とJavabeanの日付タイプ間の変換に遭遇することがよくありますが、SpringMVCはデフォルトでこの形式の変換をサポートしていないため、この問題を解決するためにデータバインディングを手動で構成およびカスタマイズする必要があります。
SpringMVC Annotation @initbinderとSpringのWebdateBinderクラスを使用して、日付変換が必要なコントローラーで動作します。
WebDataBinderは、指定されたプロパティエディターにリクエストパラメーターをバインドするために使用されます。フォアグラウンドのコントローラーに渡される値は、モデルのセット値の場合、セットのプロパティがオブジェクトの場合、Springはコンバージョンの対応するエディターを見つけてセットします。
コードは次のとおりです。
@initbinder public void initbinder(webdatabinder binder){simpledateformat dateformat = new simpledateFormat( "yyyy-mm-dd"); dateformat.setlenient(false); Binder.registerCustomeditor(date.class、new CustomDateEditor(dateFormat、true)); }SpringMVCに構成ファイルを追加する必要があります
<! - パーサー登録 - > <bean> <プロパティ名= "messageconverters"> <list> <ref bean = "stringhttpmessageconverter"/> </list> </list> </property> </bean> <! - 文字列タイプパーサー、文字列ID = <> <bean id = "stringhttpmessageconverter"/>>>>>
ライティングの変更
<MVC:annotation-driven> <MVC:message-converters> <bean> <constructor-arg value = "utf-8"/> </bean> </mvc:message-converters> </mvc:annotation-driven>
拡大する:
Spring MVCは、フォームをバインドする前にこれらの編集者を登録します。 Spring自体は、CustomDateEditor、CustomBooleAneditor、CustomNumberEditorなど、基本的に十分な多くの実装クラスを提供します。
使用時にWebDataBinderのRegisterCustomeditorメソッドを呼び出します
RegisterCustomeditorソースコード:
public void RegisterCustomeditor(class <?> rebulictype、PropertyEditor PropertyEditor){getPropertyEditorRegistry()。RegisterCustomEditor(rebulictype、propertyeditor);}最初のパラメーターexpectTypeは、変換する必要があるタイプです。
2番目のパラメータープロパティエディターは、インターフェイスであるプロパティエディターです。 CustomDateEditorなどの上記の例はすべて、このインターフェイスを実装するPropertyEditorsupportクラスを継承します。
また、これらのエディタークラスを使用することもできません。
私たちは自分自身を構築することができます:
Import org.springframework.beans.propertyeditors.propertieseditor; public class double -editorは、propertyeditorsupportを拡張します{@override public void setastext(string text)throws Illegalargumentexception {if(text == null || text.equals( "" "){text =" 0 "; } setValue(double.parsedouble(text)); } @Override public string getastext(){retun getValue()。toString(); }}上記はこの記事のすべての内容です。みんなの学習に役立つことを願っています。誰もがwulin.comをもっとサポートすることを願っています。