springMVC之form表单同名数据绑定

前几天在论坛中看到有很多人说springmvc中,如果前台form表单有相同的属性名,比如

<input name="student.name"/>

<input name="class.name"/>

如果在struts2中提供对应javabean的Get/set方法就可以解决

在springmvc 的@Controller中不行,当然你可以提供一个formBean,比如 class FormBean {

Student student;

Classes classes;

}

,可以解决这个问题。

其实springmvc本身也提供对这种方式的绑定(参考一个朋友的回答)

springmvc 源码中有一个WebDataBinder类,属性fieldDefaultPrefix就是解决上面问题的,取之注释

扫描二维码关注公众号,回复: 790063 查看本文章

/**
     * Specify a prefix that can be used for parameters that indicate default
     * value fields, having "prefix + field" as name. The value of the default
     * field is used when the field is not provided.*/

因此可以在springMVC的Controller中如下使用:

@InitBinder("user") 
    public void initBinder(WebDataBinder binder) { 
           // binder.registerCustomEditor(Date.class, new CustomDateEditor(new SimpleDateFormat("yyyy-MM-dd"), true));
            binder.setFieldDefaultPrefix("user.");//别名前缀
    }


   
    @InitBinder("student") 
    public void initBinder1(WebDataBinder binder) { 
          // binder.registerCustomEditor(Date.class, new CustomDateEditor(new SimpleDateFormat("yyyy-MM-dd"), true));
            binder.setFieldDefaultPrefix("student.");//别名前缀
    }

@RequestMapping(value="/new")
    public String _new(ModelMap model, Student student,@ModelAttribute("bb")User user) throws Exception {
        //model.addAttribute("student",);
        System.out.println(user.getId());
        System.out.println(student.getName());
        System.out.println(user.getName());
        return "/user/form_include";
    }

代码说明:在initBinder和initBinder1中进行数据前缀的绑定,和form表单中前缀名的相同,比如student.

然后在_new方法中springmvc会进行绑定,详细见WebDataBinder源码

protected void checkFieldDefaults(MutablePropertyValues mpvs) {
        if (getFieldDefaultPrefix() != null) {此处得到的是前缀比如student.
            String fieldDefaultPrefix = getFieldDefaultPrefix();
            PropertyValue[] pvArray = mpvs.getPropertyValues();此处得到的是form表单的参数,比如student.name之类的
            for (PropertyValue pv : pvArray) {
                if (pv.getName().startsWith(fieldDefaultPrefix)) {
                    String field = pv.getName().substring(fieldDefaultPrefix.length());此处的得到具体属性名
                    if (getPropertyAccessor().isWritableProperty(field) && !mpvs.contains(field)) {
                        mpvs.add(field, pv.getValue());得到的属性名放假map
                    }
                    mpvs.removePropertyValue(pv);//移除掉,比如student移除掉
                }
            }
        }
    }

猜你喜欢

转载自goodluck-wgw.iteye.com/blog/1726103
今日推荐