您的位置:首页 > 编程语言 > Java开发

springMVC类型转换,@initBinder使用

2014-12-17 20:55 429 查看
http://jwlsky.iteye.com/blog/18906761:代码实例Java代码@InitBinderpublic 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() {@Overridepublic 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() {@Overridepublic void setAsText(String text)throws IllegalArgumentException {if (!StringUtils.hasText(text)) {return;} else {Long categoryId = Long.valueOf(text);Category category = categoryService.findById(categoryId);setValue(category);}}});}
@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);
}
}
});
}
Html代码<form:formmodelAttribute="categoryEditForm"id="categoryForm"method="post"action="saveOrUpdate.do"><form:hiddenpath="category.objectId"/><inputtype="hidden"name="category.parent"value="${categoryEditForm.category.parent.objectId}"/><inputtype="hidden"name="category.systemInfo"value="${categoryEditForm.category.systemInfo.objectId }"/><divclass="area"><divclass="areaTitle"><divclass="inner"><label>Category Information Form</label><divclass="clear"></div></div></div></div><divclass="areaBody"><tableclass="formTable"><tbody><tr><tdcolspan="4"><spanclass="button"><span><ahref="javascript:sumbit();"class="btnSave">Submit</a></span></span></td></tr><tr><tdcolspan="4"> </td></tr><tr><tdalign="right">Parent Category Name:</td><tdcolspan="3"><form:inputpath="category.parent.name.fullName"readonly="true"id="parentCategory"cssClass="input readOnly"/></td></tr><tr><tdalign="right">Current Category Name:</td><td><form:inputpath="category.name.fullName"id="categoryName"cssClass="input"/></td><tdalign="right">description:</td><td><form:inputpath="category.description"id="description"cssClass="input"/></td></tr></tbody></table></div></form:form>2、实例2

spring mvc的表单类型转换(custom property editor)

9人收藏此文章,我要收藏发表于7个月前(2012-10-28 14:14) , 已有329次阅读,共1个评论spring mvc的表单类型转换太强大了,目前用到了两个简单的,一个是将表单中的file自动映射成byte[],这样文件上传(如果使用blob)就无需写任何代码了。另一个是将表单中的yyyy-MM-dd格式映射成java.util.Date,假设User.java中有如下这两种特殊的属性:
1
public
class
User
implements
Serializable{
2
private
Datebirth;
3
private
byte
[]icon;
4
}
注册这两种属性编辑器只需在Controller中定义如下这样一个
initBinder
方法:
01
@Controller
(
"userController"
)
02
@RequestMapping
(value= 
"/user"
)
03
public
class
UserController{
04
@RequestMapping
(value= 
"create"
,method = RequestMethod.POST)
05
public
Stringcreate(
@ModelAttribute
(
"user"
)User user,
06
RedirectAttributesredirectAttributes) {
07
userService.createUser(user);
08
redirectAttributes.addFlashAttribute(
"message"
,
"createsuccess!"
);
09
10
return
SUCCESS;
11
}
12
13
@InitBinder
14
protected
void
initBinder(
15
WebDataBinderbinder) 
throws
ServletException{
16
binder.registerCustomEditor(
byte
[].
class
,
17
new
ByteArrayMultipartFileEditor());
18
19
SimpleDateFormatdateFormat = 
new
SimpleDateFormat(
"yyyy-MM-dd"
);
20
dateFormat.setLenient(
false
);
21
binder.registerCustomEditor(Date.
class
,
new
CustomDateEditor(dateFormat,
false
));
22
}
23
}
ByteArrayMultipartFileEditor和CustomDateEditor都是spring直接提供的。可以参考这两个类的源码,高级的自定义的还没用过,等用到的时候再补充到这里(2012-11-04补充)今天终于用到了自定义的Editor,我现在有一个User对象,它有一个Set<Role> roles集合。
1
public
class
User
implements
Serializable{
2
public
Set<Role>roles = 
new
HashSet<Role>();
Role有id和name属性,
1
public
class
Role
implements
Serializable{
2
private
Longid;
//
3
private
Stringname;
//
UserController如下
1
@RequestMapping
(value= 
"create"
,method = RequestMethod.GET)
2
public
StringcreateForm(ModelMap model) {
3
model.addAttribute(
"roleList"
,roleService.findAllRoles());
4
Useruser = 
new
User();
5
model.addAttribute(user);
6
return
"user/user_new"
;
7
}
我的user_new.jsp如下:
1
<
div
class
=
"control-group"
>
2
<
label
class
=
"control-label"
for
=
"roles"
>角色:</
label
>
3
<
div
class
=
"controls"
>
4
<
sf:checkboxes
path
=
"roles"
items
=
"${roleList}"
itemValue
=
"id"
itemLabel
=
"name"
/>
5
</
div
>
6
</
div
>
用户在页面上check一个或多个角色,提交form,这时我们期望user对象中的roles集合能自动绑定用户选择的值,但是提交到服务器上的数据其实是一组roleId,我们需要在自定义的PropertyEditor中将其转成Role对象.可以像这样定义RoleEditor.java
01
public
class
RoleEditor
extends
PropertyEditorSupport{
02
private
RoleServiceroleService;
03
04
public
RoleEditor(RoleServiceroleService) {
05
this
.roleService= roleService;
06
}
07
08
@Override
09
public
void
setAsText(Stringtext) 
throws
IllegalArgumentException{
10
if
(text!= 
null
){
11
Rolerole = roleService.findRoleById(Long.valueOf(text));
12
setValue(role);
13
}
else
{
14
setValue(
null
);
15
}
16
}
17
}
并在UserController中的initBinder方法中注册该编辑器
1
@InitBinder
2
protected
void
initBinder(
3
WebDataBinderbinder) 
throws
ServletException{
4
//@see http://forum.springsource.org/showthread.php?59612-Service-injection-amp-PropertyEditor[/code]
5
binder.registerCustomEditor(Role.
class
,
new
RoleEditor(roleService));
6
}
这时在UserController的create方法中取得的User对象就是已经绑定了roles的了
1
@RequestMapping
(value= 
"create"
,method = RequestMethod.POST)
2
public
Stringcreate(
@ModelAttribute
(
"user"
)User user,
3
RedirectAttributesredirectAttributes) {
4
userService.createUser(user);
5
redirectAttributes.addFlashAttribute(
"message"
,
"createsuccess!"
);
6
7
return
SUCCESS;
8
}
值得注意的是,你必须要覆写Role的equals和hashCode方法,不然当你进入修改页面时,user的role属性不会自动的check上。RoleEditor可以简化成public class RoleEditor extends PropertyEditorSupport {@Overridepublic void setAsText(String text) throws IllegalArgumentException {if (text != null) {Role role = new Role();role.setId(Long.valueOf(text));setValue(role);} else {setValue(null);}}}保存时只用了id值,没有必要去数据库再查找一次
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: