【问题标题】:data-binding Spring数据绑定 Spring
【发布时间】:2012-02-06 22:00:19
【问题描述】:

我在请求中有一个联系人对象,该对象在 形成,然后得到修改后的对象。我希望返回的对象与您发送的对象相同,您保留表单中没有的属性的值。

class Contact{

     private String name;          // this attributes will be modified
     private String lastName;

     private Long id;
     private Date created;        // this atributes will not be modified

     // getters and setters ....

}


    @RequestMapping(value = "/{id}/edit", method = RequestMethod.GET)
    public String updateContact(@PathVariable("id") Long id, Model model) {

         Contact c = contactDao.get(id);
         model.addAttribute("contact", c);

         return "contact/form";

    }



     @RequestMapping(value = "/{id}/edit", method = RequestMethod.POST)
     public String update(@PathVariable("id") Long id, @Valid @ModelAttribute Contact contact, BindingResult result, Model model) {

        // The contact I get here I want to keep the original attributes of the
       // object sent, and have the changes in the fields shown on the form. is that possible?

        return "redirect:/contact";
  }


   <form:form action="${pageContext.servletContext.contextPath}/tags/create"            commandName="contact">

              <form:input path="name"/>
              <form:errors path="name" cssClass="formError"/>
              <form:input path="lastName"/>

   </form:form>

我不想使用隐藏字段来维护不会改变的属性的值

【问题讨论】:

    标签: java spring data-binding


    【解决方案1】:

    如果您只想在表单中处理某些字段,请创建一个新类 - ContactDTO 仅包含它们,然后手动(或通过反射)将它们复制到原始 Contact 对象(您加载通过数据库中的 id)

    【讨论】:

    • 这就是我正在做的,我没有
    【解决方案2】:

    我通过将联系人对象声明为存在于会话中的对象找到了问题的解决方案

    @Controller
    @RequestMapping("/contact")  
    @SessionAttributes("contact")
    public class ContactController {
    
    ....
    ....
    
    
        @RequestMapping(value = "/{id}/edit", method = RequestMethod.GET)
        public String updateContact(@PathVariable("id") Long id, Model model) {
    
            Contact c = contactDao.get(id);
            model.addAttribute("contact", c);
            return "contact/form";
    
        }
    
    
        @RequestMapping(value = "/{id}/edit", method = RequestMethod.POST)
        public String update(@PathVariable("id") Long id, @Valid @ModelAttribute Contact contact, BindingResult result, Model model) {
    
            contactDao.update(contact);
    
            return "redirect:/contact";
        }
    }
    

    【讨论】:

      【解决方案3】:

      您的持久性框架是什么?是 JPA 还是休眠?如果是这样,请使用 @Column(updatable=false)

      注释该字段

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2012-04-29
        • 2012-12-23
        • 2011-10-23
        • 1970-01-01
        • 1970-01-01
        • 2014-09-05
        • 2015-09-01
        相关资源
        最近更新 更多