简体   繁体   中英

data-binding Spring

I have a Contact object that I put in the request, this object is modified in the form and then get the modified object. I would like the object that is back is the same object that you send, you keep the value of the attributes that were not in the form.

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>

I do not want to use hidden fields to maintain the value of the attributes that will not be changing

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

I found the solution to the problem by stating the contact object as an object that lives in the session

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

What is your persistence framework? is it JPA or Hibernate? If so, annotate the field with @Column(updatable=false)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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