【问题标题】:Java spring post form one to many relationshipJava spring post形成一对多关系
【发布时间】:2017-04-26 09:39:45
【问题描述】:

我正在尝试获取对象控制器上的 POST 表单数据具有一对多关系。就像下面的代码

我的通知模型

private long id;
@NotBlank(message = ERROR.NOT_EMPTY)
private String title;
@NotBlank(message = ERROR.NOT_EMPTY)
private String content;
// One Notification has many User
private List<NotificationUser> listNotificationUser;;

// Getter and setter method

我的控制器

@RequestMapping(value = "notification/add", method = RequestMethod.GET)
public String create(ModelMap model) {
    ArrayList<User> listUser = userService.getAllUsername();
    model.put("user", listUser);
    model.addAttribute("notification", new Notification());

    return "notification/add";

}
@RequestMapping(value = "notification/add", method = RequestMethod.POST)
public String create(ModelMap model, HttpServletRequest request,
        @Valid @ModelAttribute(value = "notification") Notification notification, BindingResult bindingResult) {
    ....
}

我的.jsp

<form:form method="POST" action="add" name="addForm" commandName="notification">
        <!-- Other input -->
        <form:select path="listNotificationUser" multiple="multiple" id="name" name="itemValue">
          <form:options />
          <form:options items="${user}" itemValue="id" itemLabel="name" />
        </form:select>
      <!-- Other input -->
      </form:form>

当我向控制器提交 POST 表单时,字段 notification.listNotificationUser 始终为空(其他字段很好)。

我正在搜索并尝试一些解决方案,但它不起作用。

【问题讨论】:

    标签: spring-mvc post one-to-many


    【解决方案1】:

    我猜你的问题是你的表单中有错字:select。您正在定义 2 个选项块,我猜您只想定义一个空选项。所以应该是这样的

    <form:select path="listNotificationUser" multiple="multiple" id="name" name="itemValue">
         <!-- Some value you can identify as empty option--> 
         <form:option value="0" label="--Options--"/> 
         <form:options items="${user}" itemValue="id" itemLabel="name" />
    </form:select>
    

    【讨论】:

    • 谢谢,但是好像不行,notification.listNotificationUser 是一个空的ArrayList :(
    • 我刚刚注意到一个问题,你的用户列表存储对象类型User,但属性listNotificationUser存储NotificationUser,所以它不起作用,你需要使用相同类型的对象
    猜你喜欢
    • 1970-01-01
    • 2023-04-10
    • 1970-01-01
    • 2016-06-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-10-03
    • 2023-01-16
    相关资源
    最近更新 更多