`

Spring MVC 类型转换 @InitBinder使用 转

    博客分类:
  • SSH
阅读更多

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);
                }
            }
        });
    }

 

 

Html代码 复制代码 收藏代码
  1.             <form:form modelAttribute="categoryEditForm" id="categoryForm" method="post" action="saveOrUpdate.do">  
  2.                
  3.             <form:hidden path="category.objectId" />  
  4.             <input type="hidden" name="category.parent" value="${categoryEditForm.category.parent.objectId}"/>  
  5.             <input type="hidden" name="category.systemInfo" value="${categoryEditForm.category.systemInfo.objectId }"/>  
  6.                
  7.             <div class="area">  
  8.                 <div class="areaTitle">  
  9.                     <div class="inner">  
  10.                         <label>Category Information Form</label>  
  11.                         <div class="clear"></div>  
  12.                     </div>  
  13.                 </div>  
  14.             </div>  
  15.                
  16.             <div class="areaBody">  
  17.     <table class="formTable">  
  18.                     <tbody>  
  19.                         <tr>  
  20.                 <td colspan="4">  
  21.                     <span class="button"><span><a href="javascript:sumbit();" class="btnSave">Submit</a></span></span>  
  22.                 </td>  
  23.             </tr>    
  24.             <tr>  
  25.                 <td colspan="4">&nbsp;</td>  
  26.             </tr>  
  27.             <tr>  
  28.                 <td align="right">Parent Category Name:</td>  
  29.                 <td colspan="3"><form:input path="category.parent.name.fullName" readonly="true" id="parentCategory" cssClass="input readOnly" /></td>                                           
  30.             </tr>  
  31.             <tr>  
  32.                 <td align="right">Current Category Name:</td>  
  33.                 <td><form:input path="category.name.fullName" id="categoryName" cssClass="input"/></td>  
  34.                 <td align="right">description:</td>  
  35.                 <td><form:input path="category.description" id="description" cssClass="input"/></td>  
  36.             </tr>  
  37.                     </tbody>  
  38.                         </table>  
  39.             </div>  
  40.                
  41. </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 Date birth;
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 String create(@ModelAttribute("user") User user,
06             RedirectAttributes redirectAttributes) {
07         userService.createUser(user);
08         redirectAttributes.addFlashAttribute("message", "create success!");
09  
10         return SUCCESS;
11     }
12      
13     @InitBinder
14     protected void initBinder(
15             WebDataBinder binder) throws ServletException {
16         binder.registerCustomEditor(byte[].class,
17                 new ByteArrayMultipartFileEditor());
18          
19         SimpleDateFormat dateFormat = 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 Long id;//
3     private String name;//

 

UserController如下

1 @RequestMapping(value = "create", method = RequestMethod.GET)
2 public String createForm(ModelMap model) {
3     model.addAttribute("roleList", roleService.findAllRoles());
4     User user = 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 RoleService roleService;
03  
04     public RoleEditor(RoleService roleService) {
05         this.roleService = roleService;
06     }
07  
08     @Override
09     public void setAsText(String text) throws IllegalArgumentException {
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 @InitBinder
2 protected void initBinder(
3         WebDataBinder binder) throws ServletException {
4     //@see http://forum.springsource.org/showthread.php?59612-Service-injection-amp-PropertyEditor
5     binder.registerCustomEditor(Role.class, new RoleEditor(roleService));
6 }
这时在UserController的create方法中取得的User对象就是已经绑定了roles的了
1 @RequestMapping(value = "create", method = RequestMethod.POST)
2 public String create(@ModelAttribute("user") User user,
3         RedirectAttributes redirectAttributes) {
4     userService.createUser(user);
5     redirectAttributes.addFlashAttribute("message", "create success!");
6  
7     return SUCCESS;
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值,没有必要去数据库再查找一次

分享到:
评论
1 楼 wxynxyo 2013-12-16  
非常感谢,解决了一个问题

相关推荐

    详解SpringMVC注解@initbinder解决类型转换问题

    本篇文章主要介绍了详解SpringMVC注解@initbinder解决类型转换问题,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧

    spring mvc使用@InitBinder标签对表单数据绑定的方法

    主要介绍了spring mvc使用@InitBinder标签对表单数据绑定的方法,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧

    精通Spring MVC 4

    Spring MVC属于SpringFrameWork的后续产品,已经融合在Spring Web Flow里面。Spring 框架提供了构建 Web 应用程序的全功能 MVC 模块。Spring MVC4是当前zuixin的版本,在众多特性上有了进一步的提升。, 在精通Spring...

    SpringMVC的@InitBinder参数转换代码实例

    主要介绍了SpringMVC的@InitBinder参数转换代码实例,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下

    Spring MVC 之@ModelAttribute使用.rar

    Spring MVC 之@ModelAttribute使用.rar

    spring mvc中的@ModelAttribute注解示例介绍

    在Spring mvc中,注解@ModelAttribute是一个非常常用的注解,下面这篇文章主要给大家介绍了关于spring mvc中@ModelAttribute注解的相关资料,文中通过示例代码介绍的非常详细,需要的朋友可以参考下。

    spring mvc中注解@ModelAttribute的妙用分享

    主要给大家介绍了关于spring mvc中注解@ModelAttribute妙用的相关资料,文中通过示例代码介绍的非常详细,对大家学习或者使用Android具有一定的参考学习价值,需要的朋友们下面来一起看看吧。

    spring mvc 官方文档

    本文详细介绍spring MVC的原理和开发心得体会。

    精通Spring MVC 4 中文

    精通Spring MVC 4 中文

    Spring MVC 基于注解实例

    Spring MVC 基于注解实例Spring MVC 基于注解实例Spring MVC 基于注解实例Spring MVC 基于注解实例Spring MVC 基于注解实例Spring MVC 基于注解实例Spring MVC 基于注解实例Spring MVC 基于注解实例Spring MVC 基于...

    SpringMVCDemo:Spring MVC 框架知识案例

    1.创建第一个 Spring MVC 程序案例 2.Spring MVC @RequestMapping 注解案例 3.Spring MVC 请求参数的获取案例 4.Spring MVC 域对象共享数据案例 5.Spring MVC @ModelAttribute 注解案例 6.Spring MVC 国际化案例 7....

    Spring MVC 入门实例

    这篇文章将教你快速地上手使用 Spring 框架. 如果你手上有一本《Spring in Action》, 那么你最好从第三部分"Spring 在 Web 层的应用--建立 Web 层"开始看, 否则那将是一场恶梦! 首先, 我需要在你心里建立起 Spring...

    [免费]Spring MVC学习指南(高清)

    Spring MVC是Spring框架中用于Web应用快速开发的一个模块,其中的MVC是Model-View-Controller的缩写。作为当今业界最主流的Web开发框架,Spring MVC已经成为当前最热门的开发技能,同时也广泛用于桌面开发领域。 ...

    spring mvc中的@PathVariable获得请求url中的动态参数

    本文主要介绍了spring mvc中的@PathVariable获得请求url中的动态参数的代码。具有很好的参考价值,下面跟着小编一起来看下吧

    Spring MVC所需jar包

    Spring MVC所需jar包,包含java开发中 Spring MVC架构中最常用的jar包

    Spring MVC+MyBatis开发从入门到项目实战

    《Spring MVC+MyBatis开发从入门到项目实战》适用于拥有Java基础的软件开发人员学习框架开发,也适用于大中专院校在校师生学习开发技术,以及软件从业实习生提升框架开发技术水平,也可作为高等院校计算机及相关专业...

Global site tag (gtag.js) - Google Analytics