最近在用Spring mvc時遇到一個問題,在網上搜了很多資料。幾乎沒看到解決辦法!
例如:當我們在做批量添加或者更新時,在Controller層接收表單數據的問題!
我們做一個對用戶批量添加的實驗!
用戶Model:
public class User { //用戶名 private String username; //密碼 private String password; public String getUsername() { return username; } public void setUsername(String username) { this.username = username == null ? null : username.trim(); } public String getPassword() { return password; } public void setPassword(String password) { this.password = password == null ? null : password.trim(); } public User(String username, String password) { super(); this.username = username; this.password = password; } public User() { super(); } }
控制層:
@Controller @RequestMapping("/") public class UserController { /** * Logger for this class */ private static final Logger logger = Logger.getLogger(UserController.class); @RequestMapping("/user") public void test(List<User> users){ logger.debug(JSONArray.toJSON(users)); } }
我們在創建一個jsp:
<%@ page language="java" import="java.util.*" pageEncoding="UTF -8"%> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <title>表單批量提交</title> </head> <body> <form action="user" method="post"> 用戶名:<input type="text" name="username[0] "><br/> 密碼:<input type="text" name="password[0] "><br/> 用戶名:<input type="text" name="username[1] "><br/> 密碼:<input type="text" name="password[1] "><br/> <input type="submit"> </form> </body> </html>
現在我們來測試下
我們可以看到後台報錯了.具體為何大家可以去看源碼
可以用2種方式解決這個問題:
1.在表單提交之前,把表單序列化成JSON格式傳到後台,在來解析封裝成List<User>.
2.我們創建一個UserModel
public class UserModel { private List<User> users; public List<User> getUsers() { return users; } public void setUsers(List<User> users) { this.users = users; } public UserModel(List<User> users) { super(); this.users = users; } public UserModel() { super(); } }
修改我們的控制層和頁面
1 @RequestMapping("/user")
2 public void test(UserModel userModel ){
3 logger.debug(JSONArray.toJSON(userModel));
4 }
<%@ page language="java" import="java.util.*" pageEncoding="UTF -8"%> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <title>表單批量提交</title> </head> <body> <form action="user" method="post"> 用戶名:<input type="text" name="users [0].username"><br/> 密碼:<input type="text" name="users [0].password"><br/> 用戶名:<input type="text" name="users [1].username"><br/> 密碼:<input type="text" name="users [1].password"><br/> <input type="submit"> </form> </body> </html>
我們來看下控制台打印的結果:
這樣我們就解決啦!
查看本欄目