为实现字符串转换成特定的类型,也可以自定义编辑器,进行帮@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{
.................
}
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
文章由极客之音整理,本文链接:https://www.bmabk.com/index.php/post/71219.html