我对 Spring 框架还是很陌生,但遇到以下问题: 我正在尝试使用 Spring MVC 3.0 在单个发布请求中插入多条记录 我成功绑定了 List 对象,它正在 JSP 上填充,当我提交形成请求到达控制器方法(post)但返回的对象不包含正确的值,它的打印为空。
我的代码如下:
form.jsp
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%@taglib uri="http://www.springframework.org/tags/form" prefix="f"%>
<%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<f:form commandName="teamBean" method="post">
<f:input path="players[0].fname" />
<f:input path="players[0].lname" />
<f:input path="players[0].phone" />
<f:input path="players[0].email" />
<input type="submit" value="submit" />
</f:form>
</body>
</html>
DynaminFormController.java
@Controller
@RequestMapping("/form")
public class DynaminFormController {
List<Player> players = new ArrayList<>();
@RequestMapping(method = RequestMethod.GET)
public String getForm(Map<String, TeamBean> map) {
TeamBean teamBean = new TeamBean();
players.add(new Player("dd", "dd", "dd", "dd"));
players.add(new Player("cc", "cc", "cc", "cc"));
teamBean.setPlayers(players);
map.put("teamBean", teamBean);
return "form";
}
@RequestMapping(method = RequestMethod.POST)
public String postForm(TeamBean teamBean) {
System.out.println("DynaminFormController.postForm()");
System.out.println(teamBean);//printing null
return "view";
}
}
TeamBean.java
public class TeamBean {
private List<Player> players;
public List<Player> getPlayers() {
return players;
}
public void setPlayers(List<Player> players) {
this.players = players;
}
@Override
public String toString() {
return "TeamBean [players=" + players + "]";
}
}
Player.java
public class Player {
private String fname;
private String lname;
private String phone;
private String email;
public Player(String fname, String lname, String phone, String email) {
this.fname = fname;
this.lname = lname;
this.phone = phone;
this.email = email;
}
///getters setters...
@Override
public String toString() {
return "Player [fname=" + fname + ", lname=" + lname + ", phone="
+ phone + ", email=" + email + "]";
}
}