Spring MVC 类型转换 @InitBinder使用 转
1:代码实例
@InitBinder public void initBinder(WebDataBinder binder) { SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd"); dateFormat.setLenient(false); binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true)); binder.registerCustomEditor(SystemInfo.class, new PropertyEditorSupport() { @Override public void setAsText(String text) throws IllegalArgumentException { if (!StringUtils.hasText(text)) { return; } { Long systemInfoId = Long.valueOf(text); SystemInfo systemInfo = systemInfoService.findById(systemInfoId); setValue(systemInfo); } } }); binder.registerCustomEditor(Category.class, new PropertyEditorSupport() { @Override public void setAsText(String text) throws IllegalArgumentException { if (!StringUtils.hasText(text)) { return; } else { Long categoryId = Long.valueOf(text); Category category = categoryService.findById(categoryId); setValue(category); } } }); }?
?
?
1publicclassUserimplementsSerializable{2????privateDate birth;3????privatebyte[] icon;4}?
注册这两种属性编辑器只需在Controller中定义如下这样一个initBinder方法:
01@Controller("userController")02@RequestMapping(value ="/user")03publicclassUserController {04????@RequestMapping(value ="create", method = RequestMethod.POST)05????publicString create(@ModelAttribute("user") User user,06????????????RedirectAttributes redirectAttributes) {07????????userService.createUser(user);08????????redirectAttributes.addFlashAttribute("message","create success!");09?10????????returnSUCCESS;11????}12?????13????@InitBinder14????protectedvoidinitBinder(15????????????WebDataBinder binder)throwsServletException {16????????binder.registerCustomEditor(byte[].class,17????????????????newByteArrayMultipartFileEditor());18?????????19????????SimpleDateFormat dateFormat =newSimpleDateFormat("yyyy-MM-dd");20??????????? ????dateFormat.setLenient(false);21?????????? ????binder.registerCustomEditor(Date.class,newCustomDateEditor(dateFormat,false));22????}23}?
ByteArrayMultipartFileEditor和CustomDateEditor都是spring直接提供的。可以参考这两个类的源码,
高级的自定义的还没用过,等用到的时候再补充到这里(2012-11-04补充)
今天终于用到了自定义的Editor,我现在有一个User对象,它有一个Set<Role> roles集合。
1publicclassUserimplementsSerializable{2????publicSet<Role> roles =newHashSet<Role>();Role有id和name属性,?
1publicclassRoleimplementsSerializable {2????privateLong id;//3????privateString name;//?
UserController如下
1@RequestMapping(value ="create", method = RequestMethod.GET)2publicString createForm(ModelMap model) {3????model.addAttribute("roleList", roleService.findAllRoles());4????User user =newUser();5????model.addAttribute(user);6????return"user/user_new";7}我的user_new.jsp如下:1<divclass="control-group">2????<labelclass="control-label"for="roles">角色:</label>3????<divclass="controls">4????????<sf:checkboxespath="roles"items="${roleList }"itemValue="id"itemLabel="name"/>5????</div>6</div>用户在页面上check一个或多个角色,提交form,这时我们期望user对象中的roles集合能自动绑定用户选择的值,但是提交到服务器上的数据其实是一组roleId,我们需要在自定义的PropertyEditor中将其转成Role对象.?
可以像这样定义RoleEditor.java
01publicclassRoleEditorextendsPropertyEditorSupport {02????privateRoleService roleService;03?04????publicRoleEditor(RoleService roleService) {05????????this.roleService = roleService;06????}07?08????@Override09????publicvoidsetAsText(String text)throwsIllegalArgumentException {10????????if(text !=null) {11????????????Role role = roleService.findRoleById(Long.valueOf(text));12????????????setValue(role);13????????}else{14????????????setValue(null);15????????}16????}17}并在UserController中的initBinder方法中注册该编辑器1@InitBinder2protectedvoidinitBinder(3????????WebDataBinder binder)throwsServletException {4????//@see http://forum.springsource.org/showthread.php?59612-Service-injection-amp-PropertyEditor5????binder.registerCustomEditor(Role.class,newRoleEditor(roleService));6}这时在UserController的create方法中取得的User对象就是已经绑定了roles的了1@RequestMapping(value ="create", method = RequestMethod.POST)2publicString create(@ModelAttribute("user") User user,3????????RedirectAttributes redirectAttributes) {4????userService.createUser(user);5????redirectAttributes.addFlashAttribute("message","create success!");6?7????returnSUCCESS;8}?
值得注意的是,你必须要覆写Role的equals和hashCode方法,不然当你进入修改页面时,user的role属性不会自动的check上。
?
?
?
?
RoleEditor可以简化成
public class RoleEditor extends PropertyEditorSupport {
??@Override
??public void setAsText(String text) throws IllegalArgumentException {
????if (text != null) {
??????Role role = new Role();
??????role.setId(Long.valueOf(text));
??????setValue(role);
????} else {
??????setValue(null);
????}
??}
}
保存时只用了id值,没有必要去数据库再查找一次