我试图让它从用户输入中打印出我的链接列表。此代码将对象添加到链接列表,因为我可以看到它被打印到控制台但它们没有打印到页面。感谢。
控制器:
@Controller
@RequestMapping("/addr")
public class AddressController {
public Collection<Address> addresses = (Collection<Address>) Collections.synchronizedCollection(new LinkedList<Address>());
/* @RequestMapping("/new")
public String getAddressForm() {
System.out.println("Test");
return "addressProject/addressBook";
}
*/
@RequestMapping("/new")
public ModelAndView submitForm(String name, String email, String group, String phoneNumber, String address){
Address addr = new Address(name, email, group, phoneNumber, address);
addresses.add(addr);
ModelAndView modelandview = new ModelAndView("addressProject/addressBook");
modelandview.addObject("addresses", addr);
System.out.println("Address: name=" + addr.getName() + ", email=" + addr.getEmail() + ", group=" + addr.getGroup() + ", phoneNumber=" + addr.getPhoneNumber() + ", address=" + addr.getAddress());
return modelandview;
}
}
JSP:
<body>
<div class="container">
<form>
Name: <input type="text" name="name"><br>
<br/>
Email: <input type="text" name="email"><br>
<br/>
Group: <input type="text" name="group"><br>
<br/>
Phone Number: <input type="text" name="phoneNumber"><br>
<br/>
Address: <input type="text" name="address"><br>
<br/>
<input type="submit" />
</form>
</div>
<h2>Addresses v5</h2>
<c:forEach items="${addresses}" var="address">
<tr>
<td>${address}</td>
</tr>
答案 0 :(得分:1)
您将地址添加到模型而不是列表:
modelandview.addObject("addresses", addr);
应该是:
modelandview.addObject("addresses", addresses);
JSP。
<table>
<c:forEach items="${addresses}" var="address">
<tr>
<td>${address}</td>
</tr>
</c:forEach>
<table>
确保已在JSP文件的顶部声明了taglib指令:
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>