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

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

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

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

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

public class User implements Serializable{
	private Date birth;
	private byte[] icon;
}


註冊這兩種屬性編輯器只需在Controller中定義以下這樣一個initBinder方法: spring-mvc

@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直接提供的。能夠參考這兩個類的源碼, 服務器

高級的自定義的還沒用過,等用到的時候再補充到這裏(2012-11-04補充) mvc

今天終於用到了自定義的Editor,我如今有一個User對象,它有一個Set<Role> roles集合。 app

public class User implements Serializable{
    public Set<Role> roles = new HashSet<Role>();
Role有id和name屬性,


public class Role implements Serializable {
	private Long id;//
	private String name;//


UserController以下 jsp

@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";
	}
個人user_new.jsp以下:
<div class="control-group">
		<label class="control-label" for="roles">角色:</label>
		<div class="controls">
			<sf:checkboxes path="roles" items="${roleList }" itemValue="id" itemLabel="name"/>
		</div>
	</div>
用戶在頁面上check一個或多個角色,提交form,這時咱們指望user對象中的roles集合能自動綁定用戶選擇的值,可是提交到服務器上的數據實際上是一組roleId,咱們須要在自定義的PropertyEditor中將其轉成Role對象.


能夠像這樣定義RoleEditor.java 編輯器

public class RoleEditor extends PropertyEditorSupport {
	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上。

這裏有人提相同的問題:

http://stackoverflow.com/questions/7421346/spring-binding-listobject-to-formcheckboxes

還有這裏

http://stackoverflow.com/questions/8700339/spring-mvc-usage-of-formcheckbox-to-bind-data


參考:

http://www.mkyong.com/spring-mvc/spring-mvc-failed-to-convert-property-value-in-file-upload-form/

http://linkedjava.blogspot.com/2011/06/spring-controller-with-date-object.html(須要FQ)

http://forum.springsource.org/showthread.php?59612-Service-injection-amp-PropertyEditor

相關文章
相關標籤/搜索