gpt4 book ai didi

java - Spring MVC 的问题。如何从两个或多个对象创建 View ?

转载 作者:行者123 更新时间:2023-11-29 08:15:49 24 4
gpt4 key购买 nike

[ 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 中我有这段代码:

@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: 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 匹配参数二传手的类型? 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.

在您的模型中,地址应该附加到用户吗?换句话说,在我看来,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;
}

关于java - Spring MVC 的问题。如何从两个或多个对象创建 View ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4986082/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com