我正在使用 Spring 来填充表单中的项目,使用控制器和视图之间传递的对象:
领域对象
public class Client {
private String name;
private int id;
private Bar bar;
// getters and setters omitted
}
public class Bar {
private Integer id;
private String name;
// getters and setters omitted
}
控制器
@RequestMapping(method = RequestMethod.GET, value = "/")
public String index(Model m) {
m.addAttribute("Client", new Client());
Bar o1 = new Bar();
o1.setName("n 1");
o1.setId(1);
Bar o2 = new Bar();
o2.setName("n 2");
o2.setId(2);
Bar o3 = new Bar();
o3.setName("n 3");
o3.setId(3);
Bar o4 = new Bar();
o4.setName("n 4");
o4.setId(4);
Bar o5 = new Bar();
o5.setName("n 5");
o5.setId(5);
List<Bar> orders = new ArrayList<Bar>();
orders.add(o1);
orders.add(o2);
orders.add(o3);
orders.add(o4);
orders.add(o5);
m.addAttribute("ordersList", orders);
return "index";
}
@RequestMapping(method = RequestMethod.POST, value = "/")
public String indexPost(@ModelAttribute("Client") Client g, BindingResult r) {
log.info(g.getId() + " " + g.getName());
log.info(g.getBar().getName());
return "index";
}
查看 (index.jsp)
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%@ taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<html xmlns="http://www.w3.org/1999/xhtml">
<body>
<form:form method="POST" modelAttribute="Client">
<form:label path="name">Name</form:label>
<form:input path="name" />
<form:label path="id">Id</form:label>
<form:input path="id" />
<form:label path="orders">Order</form:label>
<form:select path="bar" items="${ordersList}" />
<form:button>Insert</form:button>
</form:form>
</body>
</html>
问题
当我填写表格并提交时,控制器抛出 NullPointerExceptionlog.info(g.getBar().getName());
我认为这是因为 getBar() 返回null
。这个数据绑定我哪里错了?