Spring MVC将ArrayList传递回控制器

Spring MVC将ArrayList传递回控制器,第1张

Spring MVC将ArrayList传递回控制器

我找到了答案

包装器:

public class UserListWrapper {private ArrayList<User> users;public ArrayList<User> getUsers() {    return users;}public void setUsers(ArrayList<User> users) {    this.users = users;}

控制器:

@Controllerpublic class AdminController {@Autowiredprivate UserDao userDao;@RequestMapping(value = "/admin", method = RequestMethod.GET)public ModelAndView adminPage() {    ModelAndView model = new ModelAndView();    UserListWrapper wrapper = new UserListWrapper();    wrapper.setUsers(new ArrayList<User>(userDao.findAll()));    model.addObject("userListWrapper",wrapper);    model.setViewName("admin");    return model;}@RequestMapping(value = "admin/remove", method = RequestMethod.POST)public ModelAndView removeUser(@ModelAttribute(value = "userListWrapper") UserListWrapper userListWrapper) {    ModelAndView model = new ModelAndView();    userDao.removeFlaggedUsers(userListWrapper.getUsers());    model.setViewName("redirect:/admin");    return model;}

}

视图:

<form:form action="/admin/remove" method="POST"  modelAttribute="userListWrapper">        <table > <thead>     <tr>         <th>First name</th>         <th>Last name</th>         <th>Email/login</th>         <th>Profession</th>         <th>Select<th>     </tr> </thead> <tbody>     <c:forEach varStatus="us" var="user" items="${userListWrapper.users}" >         <tr>  <td><form:input type="hidden" path="users[${us.index}].firstName"/>${user.firstName}</td>  <td><form:input type="hidden" path="users[${us.index}].lastName"/> ${user.lastName}</td>  <td><form:input type="hidden" path="users[${us.index}].login"/>${user.login}</td>  <td><form:input type="hidden" path="users[${us.index}].profession"/>${user.profession}</td>  <td><form:checkbox path="users[${us.index}].delete" value="${user.delete}"/></td>         <form:input type="hidden" path="users[${us.index}].id"/>         </tr>     </c:forEach> </tbody>        </table>         <input type="submit" value="Delete user(s)"  />        <input type="hidden" name="${_csrf.parameterName}" value="${_csrf.token}" />        </form:form>

谢谢!

编辑:别忘了还要添加您未显示的字段

例如:

如果不添加ID,则删除将不起作用,因为返回的User对象中的ID为NULL。



欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/5123093.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-11-17
下一篇 2022-11-17

发表评论

登录后才能评论

评论列表(0条)

保存