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();
}
}
}
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持毛票票。
热门推荐
1 训练狗狗憋尿
2 狗狗追踪训练
3 狗狗训练要多少钱
5 深圳狗狗训练
6 训练狗狗唤回
7 狗狗叫怎么训练
8 狗狗训练班
10 狗狗社会化训练
11 狗狗叫回训练
12 广州狗狗训练学校
13 狗狗训练躺下
14 狗狗随行训练
15 训练狗狗巡回
16 狗狗要怎么训练
17 狗狗喂食训练
18 训练狗狗躺下