SpringMVCフレームワークを使用したプロジェクトでは、データ型が日付、整数、ダブルなどであるデータがコントローラーのエンティティに拘束される必要があるか、コントローラーがこのデータを受け入れる必要があるデータが発生することがよくあります。このタイプのデータ型が処理されない場合、バインドされません。
ここでは、Annotation @initbinderを使用してこれらの問題を解決できるため、SpringMVCがフォームをバインドする前にこれらのエディターを登録します。一般に、これらの方法はBasecontrollerに含まれています。このような変換を実行する必要があるコントローラーは、Basecontrollerを継承するだけです。実際、Springは、カスタムデートエディター、CustomBooleAneditor、CustomNumberEditorなど、基本的に十分な多くの実装クラスを提供します。
デモは次のとおりです。
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はPropertyEditorSupportを拡張します{@Override public void setastext(string text)throws legalarargumentexception {simpledateFormat format = new SimpledateFormat( "yyyy-mm-dd hh:mm:ss");日付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(){retun 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(){retun getValue()。toString(); }}}上記はこの記事のすべての内容です。みんなの学習に役立つことを願っています。誰もがwulin.comをもっとサポートすることを願っています。