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

标签 java spring jsp spring-mvc

[ 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/

相关文章:

Java-如何链接 AWT 矩形?

java - 如何让这个二维数组向右旋转 90 度?

Java将Hashmap放入Treemap

spring - 找不到 io.projectreactor :reactor-bom:pom:Bismuth-M1

eclipse - eclipse、jsp、tomcat 和 mysql 资源不可用错误

java - 需要可靠/持久的出站套接字,选项?

java - 使用 Spring 注释将值注入(inject) map

java - Spring配置问题

eclipse - 如何在 Eclipse 中的 JSP/JSP 标签中获取 EL(表达式语言)内容辅助(自动完成)?

java.lang.ClassNotFoundException : javax. servlet.jsp.jSTL.sql.SQLExecutionTag