java - Spring MVC - 从 JSP 中的列表访问表单中的对象

标签 java spring jsp spring-mvc

我正在尝试创建一个传递多个对象的表单。 我正在尝试创建一个表单,您可以在其中找到“产品”和“客户”并将它们添加到订单中。 我有 2 个模型类 CustomerProductCustomerphoneNo 变量,Productname 变量。 我发现传递多个对象的最简单方法是将它们添加到列表中并将 List 传递给 View。这就是我正在做的事情,但是访问这些模型对象是另一回事。

Controller 类:

 @Controller
    public class OrderController {

    @RequestMapping(value="/create_order", method= RequestMethod.GET)
    public ModelAndView create_order() {
        Map<String, Object> model = new HashMap<String, Object>();
        model.put("customer", new Customer());
        model.put("product", new Product());


        return new ModelAndView("create_order", "command", model);
    }
    }

页面:

<form:form method="POST" action="/Persistence_Web/order_confirmation" commandName="model">
<table>
<!-- I tried few different ways of writing it and all fail -->
    <tr><form:label path="model[0].phoneNo">Customer phone number</form:label></tr>
    <tr><form:input path="model[0].phoneNo"></form:input></tr>
....

最佳答案

引用属性Product.nameCustomer.phoneNo在你的模型中,你必须引用你在模型中给出的名称加上属性名称(类中必须有一个 getter!!!)

<tr><form:input path="${customer.phoneNo}"></form:input></tr>
<tr><form:input path="${product.name}"></form:input></tr>

*如果您想在 View 中操作类中的属性,则它们必须具有 getter 和 setter。命名必须是:

private int attributeName
public  int getAttributeName()

但是:只要类中的 getter 方法类似于 View 中的变量名称。您可以拥有getMyCalculation()方法没有 myCalculation属性,以便计算总计、平均值、格式化日期或需要在 View 中显示但不存储在模型中的任何内容。

此外,对于各种ProductsCustomers使用列表:

List<Customer> customers = // fill the list!!!
model.put("customers", customers);

并使用 <for:earch> 进行迭代

<c:forEach items="${customers}" var="customer">     
    <c:out value="${customer.phoneNo}"/>
</c:forEach>

关于java - Spring MVC - 从 JSP 中的列表访问表单中的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29912971/

相关文章:

java - BlueJ 中的编译错误- if else with return 语句

java - 无法在 Android Studio 2.3.1 中运行或模拟基本应用程序

spring - 通过 Class AbstractAnnotationConfigDispatcherServletInitializer 设置 "Active Profile"?

java - 使用 hibernate 编辑/更新用户角色关系

java - MySQLSyntaxErrorException - 准备好的语句中的参数无效

java - 在带有 URI 的 HTTP 请求中找不到映射 [springcodes/functions.jsp]

html - Struts验证错误后如何清除表格

java - 未在子资源方法上调用 Jersey NameBinding 过滤器

java - 如何在保存时识别 Spring Data JPA 中的更改?

java - 在运行时解析泛型变量时如何避免未经检查的强制转换?