为实现字符串转换成特定的类型,也可以自定义编辑器,进行帮@InitBinder进行绑定
1、写一个类继承PropertyEditorSupport类,然后重写setAsText方法,下面以Double类型转换为例
public class MyDoubleEditor extends PropertyEditorSupport {
@Override
/* 重写setAsText方法 */
public void setAsText(String text) throws IllegalArgumentException {
if(text ==null || "".equals(text))
text="0";
setValue(Double.parseDouble(text));
}
}
2、写一个BaseController,在里面绑定,给需要的controller继承
@ControllerAdvice
public class BaseController {
@InitBinder
public void initBinder(WebDataBinder binder) {
System.out.println("bider----------------");
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
sdf.setLenient(false);// 让日期格式严格遵定日期格式
binder.registerCustomEditor(Date.class, new CustomDateEditor(sdf, true));
binder.registerCustomEditor(Double.class, new MyDoubleEditor());
}
}
3、需要数据转换的类继承BaseController
@Controller
public class UserController extends BaseController{
.................
}