2012-02-06 98 views
1

我有一个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> 

我不想使用隐藏字段来维护不会改变

回答

0

我找到了解决问题的办法时指出接触对象为居住在会话对象

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

的属性值,如果你只想要一些字段的形式处理,使一个新的类 - 仅包含它们的ContactDTO,然后手动(或通过反射)将它们复制到原始的Contact对象(您通过数据库中的id加载)

+0

这就是我我在做,而我没有 – Jhonathan 2012-02-06 22:23:37

-1

什么是您的持久性框架?是JPA还是休眠?如果是这样,注释字段@Column(更新= FALSE)