我正在尝试将一个ArrayList迭代器从Spring类传递给JSP,但是当我使用c:foreach循环时,这些值没有显示出来。有人可以帮忙吗?这是我的Spring课程的重要部分。
import org.springframework.ui.Model;
import org.springframework.web.servlet.mvc.Controller;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import java.io.IOException;
import java.util.ArrayList;
public class HelloWorldController implements Controller {
protected final Log logger = LogFactory.getLog(getClass());
public ModelAndView handleRequest(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
logger.info("Return View");
ArrayList<RandomNumber> random = new ArrayList<RandomNumber>();
for (int i = 1; i <= 10; i++) {
RandomNumber number = new RandomNumber();
number.setNumber((int) Math.random() * 100);
random.add(number);
}
ModelAndView modelAndView = new ModelAndView("helloworld.jsp");
Model model = (Model) modelAndView.getModel();
model.addAllAttributes(random);
return modelAndView;
}
}
这是我的JSP的相关部分。
<table>
<c:forEach var="random" items="${random}">
<tr><td>${random.number}</td></tr>
</c:forEach>
</table>
答案 0 :(得分:1)
我要换行:
model.addAllAttributes(random);
为:
model.addObject("randoms", random);
您现在在上下文中有一个“randoms”属性(在名称中添加's'以解决我认为使用var命名的另一个问题)。然后将jsp更改为(注意random
以获取var名称,避免与集合randoms
重叠:
<c:forEach var="random" items="${randoms}">