spring mvc的表單類型轉換(custom property editor)

spring mvc的表單類型轉換太強大了,目前用到了兩個簡單的,

一個是將表單中的file自動映射成byte[],這樣文件上傳(如果使用blob)就無需寫任何代碼了。

另一個是將表單中的yyyy-MM-dd格式映射成java.util.Date,

假設User.java中有如下這兩種特殊的屬性:

public class User implements Serializable{
    private Date birth;
    private byte[] icon;
}
```註冊這兩種屬性編輯器只需在Controller中定義如下這樣一個initBinder方法:





<div class="se-preview-section-delimiter"></div>

這裏寫代碼片
“`

@Controller("userController")
@RequestMapping(value = "/user")
public class UserController {
    @RequestMapping(value = "create", method = RequestMethod.POST)

    public String create(@ModelAttribute("user") User user,

            RedirectAttributes redirectAttributes) {

        userService.createUser(user);

        redirectAttributes.addFlashAttribute("message", "create success!");

        return SUCCESS;

    }    

    @InitBinder
    protected void initBinder(
            WebDataBinder binder) throws ServletException {
        binder.registerCustomEditor(byte[].class,
                new ByteArrayMultipartFileEditor());         

        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
                dateFormat.setLenient(false);
                binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, false));
    }
}

ByteArrayMultipartFileEditor和CustomDateEditor都是spring直接提供的。
自定義的:

  public class User implements Serializable{
    public Set<Role> roles = new HashSet<Role>();
    }
public class Role implements Serializable {
    private Long id;
    private String name;

UserController如下:

@RequestMapping(value = "create", method = RequestMethod.GET)
public String createForm(ModelMap model) {
    model.addAttribute("roleList", roleService.findAllRoles());
    User user = new User();
    model.addAttribute(user);
    return "user/user_new";
}
public class RoleEditor extends PropertyEditorSupport {2
    private RoleService roleService;
    public RoleEditor(RoleService roleService) {
        this.roleService = roleService;
    }
    @Override
    public void setAsText(String text) throws IllegalArgumentException {
        if (text != null) {
            Role role = roleService.findRoleById(Long.valueOf(text));
            setValue(role);
        } else {
            setValue(null);
        }
    }
}

並在UserController中的initBinder方法中註冊該編輯器

@InitBinder
protected void initBinder(
        WebDataBinder binder) throws ServletException {
    //@see http://forum.springsource.org/showthread.php?59612-Service-injection-amp-PropertyEditor
    binder.registerCustomEditor(Role.class, new RoleEditor(roleService));
}

這時在UserController的create方法中取得的User對象就是已經綁定了roles的了

@RequestMapping(value = "create", method = RequestMethod.POST)
public String create(@ModelAttribute("user") User user,
        RedirectAttributes redirectAttributes) {
    userService.createUser(user);
    redirectAttributes.addFlashAttribute("message", "create success!");
    return SUCCESS;
}

值得注意的是,你必須要覆寫Role的equals和hashCode方法,不然當你進入修改頁面時,user的role屬性不會自動的check上。

發佈了95 篇原創文章 · 獲贊 28 · 訪問量 10萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章