【问题标题】:To get value from dropdown list in JSP in case the value is a member of another class从 JSP 中的下拉列表中获取值,以防该值是另一个类的成员
【发布时间】:2018-06-04 21:24:26
【问题描述】:

在这种情况下,从 JSP 的下拉列表中获取价值会更好吗?现在按下提交按钮后出现 400 状态错误。我试图在 Google 中搜索解决方案,但没有任何变体可以帮助我。

有一些代码片段,属于这个问题。 头等舱:

    public class Item1 {
    private int id;
    private Item2 item2; 

    //getters, setters
}

二等:

    public class Item2 {
    private int id;
    private String description; 

    //getters, setters
}

一级控制器:

@Controller
public class Item1Controller {
@Autowired
private Item1DAO item1DAO;
@RequestMapping(value = "/saveItem1", method = RequestMethod.POST)
public ModelAndView saveItem1 (@ModelAttribute Item1 item1) {
    item1DAO.addOrUpdateCourse(item1);
    return new ModelAndView("redirect:/item1List");
}
}

JSP 表单:

<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@page isELIgnored="false" %>
<html>
<head>
    <title>Add New Item1</title>
</head>
<body>
<form:form method="POST" action="/saveItem1" modelAttribute="item1">
    <table>
        <form:hidden path="id"/>
        <tr>
            <td><form:label path="Item2">Item2</form:label></td>
            <td>
    <form:select path="item2">
        <form:option value="null">No Item2</form:option>
        <form:options items="${item2List}"/>
    </form:select>
  </td>
</tr>
<tr>
  <td>
      <input type="submit" value="Save Item1"/>
  </td>
</tr>
</table>
</form:form>
</body>
</html>

【问题讨论】:

    标签: java spring-mvc jsp dropdown


    【解决方案1】:

    您应该将“get”和“set”方法(公共)放入 Item 类。公共构造函数将是一件好事。 我会尝试写相同的路径属性值:description

    【讨论】:

      【解决方案2】:

      paths 表单中有多个错误。每个都必须引用一个简单的字段,而不是一个复杂的对象。

      例如,你需要:

      <form:input path="item2.description"/> <!-- not path="description", no description in the Item1 model -->
      <form:label path="item2.id">           <!-- not "Item2" by itself, and wrong case -->
      <form:select path="item2.id">          <!-- not "item2" by itself -->
      

      【讨论】:

      • 非常抱歉,我在这个代码示例中犯了错误。 Item1 类没有名为 description 的字段。
      • 你仍然不能在任何地方使用path="item2",因为它是一个对象,而不是一个字段。您必须在 item2 中设置一个字段,例如 path="item2.id"
      • 非常感谢!它帮助了我。
      猜你喜欢
      • 1970-01-01
      • 2015-12-30
      • 1970-01-01
      • 1970-01-01
      • 2018-09-16
      • 2021-11-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多