繁体   English   中英

数据绑定弹簧

[英]data-binding Spring

我在请求中放入了一个Contact对象,该对象在表单中被修改,然后得到修改后的对象。 我希望返回的对象与您发送的对象相同,您可以保留不在表单中的属性的值。

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>

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

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

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

@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";
    }
}

您的持久性框架是什么? 是JPA还是Hibernate? 如果是这样,请使用@Column(updatable = false)对该字段进行注释。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM