[spring3.0.5] [jboss 5.1]
一个有两个班
public class User { private String name; private String surname; private Address address; ... sets and gets setters and getters } public class Address { private String street; ... setters and getters }
在Controller中,我有以下代码:
@Controller public class MyController { @RequestMapping(value = "/index") public ModelAndView showForm() { ModelAndView mav = new ModelAndView(); mav.setViewName("index"); User user = new User(); Address adr = new Address(); mav.addObject("user", user); mav.addObject("adr", adr); }
现在我想在JSP中使用两个输入元素来创建
<%@taglib uri="http://www.springframework.org/tags" prefix="spring"%> <%@taglib uri="http://www.springframework.org/tags/form" prefix="form"%> <html><head><body> <form:form method="POST" commandName="user"> <form:label path="name" /> <form:input path="name" /> <form:label path="adr.street" /> <form:input path="adr.street" /> </form:form> </body> </html>
当我运行一个类似这样的异常:
org.springframework.beans.NotReadablePropertyException:Bean类[form.User]的无效属性’adr’:Bean属性’adr’不可读或具有无效的getter方法:getter的返回类型是否与getter方法的参数类型匹配。二传手?org.springframework.beans.BeanWrapperImpl.getPropertyValue(BeanWrapperImpl.java:707)org.springframework.be
有人可以向我解释为什么以及如何改进代码吗?
将对象包装在包装器表单类中,然后将其传递给模型。
public class MyForm { public user; public address; // getters, setters, etc. }
然后
ModelAndView mav = new ModelAndView(); // ModelAndView mav.addObject("myForm", new MyForm()); // e.g.
在您的模型中,地址应该附加到用户吗?换句话说,在我看来,与User有着一对多的关系Address,您应该让数据访问层处理这些问题。
User
Address
@Entity @Table(name = "user") public class User { @Id @Column(name="user_id") public Long id; @OneToMany @JoinColumn(name = "user_id") // so the address table would have a user_id foreign key public Address address; }