SpringMVC中利用@InitBinder来对页面数据进行解析绑定的方法
在使用SpingMVC框架的项目中,经常会遇到页面某些数据类型是Date、Integer、Double等的数据要绑定到控制器的实体,或者控制器需要接受这些数据,如果这类数据类型不做处理的话将无法绑定。
这里我们可以使用注解@InitBinder来解决这些问题,这样SpingMVC在绑定表单之前,都会先注册这些编辑器。一般会将这些方法些在BaseController中,需要进行这类转换的控制器只需继承BaseController即可。其实Spring提供了很多的实现类,如CustomDateEditor、CustomBooleanEditor、CustomNumberEditor等,基本上是够用的。
demo如下:
publicclassBaseController{
@InitBinder
protectedvoidinitBinder(WebDataBinderbinder){
binder.registerCustomEditor(Date.class,newMyDateEditor());
binder.registerCustomEditor(Double.class,newDoubleEditor());
binder.registerCustomEditor(Integer.class,newIntegerEditor());
}
privateclassMyDateEditorextendsPropertyEditorSupport{
@Override
publicvoidsetAsText(Stringtext)throwsIllegalArgumentException{
SimpleDateFormatformat=newSimpleDateFormat("yyyy-MM-ddHH:mm:ss");
Datedate=null;
try{
date=format.parse(text);
}catch(ParseExceptione){
format=newSimpleDateFormat("yyyy-MM-dd");
try{
date=format.parse(text);
}catch(ParseExceptione1){
}
}
setValue(date);
}
}
publicclassDoubleEditorextendsPropertiesEditor{
@Override
publicvoidsetAsText(Stringtext)throwsIllegalArgumentException{
if(text==null||text.equals("")){
text="0";
}
setValue(Double.parseDouble(text));
}
@Override
publicStringgetAsText(){
returngetValue().toString();
}
}
publicclassIntegerEditorextendsPropertiesEditor{
@Override
publicvoidsetAsText(Stringtext)throwsIllegalArgumentException{
if(text==null||text.equals("")){
text="0";
}
setValue(Integer.parseInt(text));
}
@Override
publicStringgetAsText(){
returngetValue().toString();
}
}
}
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持毛票票。