问题描述
[春季3.0.5]
[jboss 5.1]
[spring 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中我有这个代码:
In Controller I have this code:
@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中的两个输入元素创建
And now I want to create from with two input element in 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>
当我运行一个像这样的例外时:
When I runing a got a exception like this one:
org.springframework.beans.NotReadablePropertyException:bean类[form.User]的属性'adr'无效:Bean属性'adr'不可读或getter方法无效:getter的返回类型是否匹配setter的参数类型?
org.springframework.beans.BeanWrapperImpl.getPropertyValue(BeanWrapperImpl.java:707)
org.springframework.be
org.springframework.beans.NotReadablePropertyException: Invalid property 'adr' of bean class [form.User]: Bean property 'adr' is not readable or has an invalid getter method: Does the return type of the getter match the parameter type of the setter? org.springframework.beans.BeanWrapperImpl.getPropertyValue(BeanWrapperImpl.java:707) org.springframework.be
有人可以向我解释为什么以及如何改进代码?
Can someone please explain to me why and how to improve the code?
推荐答案
将对象包装在包装器表单类中并将其传递给模型。
Wrap your objects in a wrapper form class and pass it in the model.
public class MyForm
{
public user;
public address;
// getters, setters, etc.
}
然后
ModelAndView mav = new ModelAndView(); // ModelAndView
mav.addObject("myForm", new MyForm()); // e.g.
在您的模型中,地址是否应附加给用户?换句话说,在我看来,像用户
与地址
有一对多的关系,你应该让您的数据访问层处理这些问题。
In your model, should address be attached to a user? In other words, it seems to me like a User
has a one to many relationship to Address
, and you should let your data access layer handle these concerns.
@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;
}
这篇关于Spring MVC的问题。如何从两个或多个对象创建视图?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!