Spring MVC的问题。如何从两个或多个对象创建视图?

时间:2011-02-13 18:43:45

标签: java spring jsp spring-mvc

[春季3.0.5] [jboss 5.1]

A有两个班级

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的返回类型是否与参数匹配二传手的类型?     org.springframework.beans.BeanWrapperImpl.getPropertyValue(BeanWrapperImpl.java:707)     org.springframework.be

有人可以向我解释为什么以及如何改进代码?

3 个答案:

答案 0 :(得分:3)

将对象包装在包装器表单类中,并将其传递给模型。

public class MyForm
{
   public user;
   public address;
   // getters, setters, etc.
}

然后

ModelAndView mav = new ModelAndView(); // ModelAndView
mav.addObject("myForm", new MyForm()); // e.g.

在您的模型中,是否应将地址附加到用户?换句话说,在我看来,UserAddress有一对多的关系,您应该让您的数据访问层处理这些问题。

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

答案 1 :(得分:2)

您还可以执行以下操作,这会阻止您严格用于显示新类。 Spring表单可以处理嵌套属性。

User user = new User();
Address adr = new Address();
user.setAddress(adr);
mav.addObject("user", user);

在你的.jsp中,你会以这种方式到达地址对象:

<form:form method="POST" commandName="user">
<form:label path="name" />
<form:input path="name" />
<form:label path="address.street" />
<form:input path="address.street" />
</form:form>

答案 2 :(得分:0)

对象用户的属性是地址(我想你有一个名为getAddress()的getter,所以在表单中你必须使用address而不是adr:

<form:label path="address.street" />
<form:input path="address.street" />

或创建一个名为getAdr()的getter(如你所愿)