【发布时间】:2013-08-03 20:40:41
【问题描述】:
当我的应用程序中出现验证错误时,我正在显示一个 JSP。在 Servlet 中,我在请求中设置了错误的ArrayList<String>,并尝试使用以下代码在 JSP 中打印它们。我知道ArrayList 中有 1 个错误,因为我将它打印到服务器控制台,但唯一打印的是“-”。我是否正确使用了forEach 循环?
<c:forEach var="error" items="${errors}">
<h1>-${error}</h1>
<br>
</c:forEach>
以下是 Servlet 中 doPost 的部分代码:
ArrayList<String> errors = dataValidator.getErrors();
if (errors.isEmpty()) {
String cost = dataValidator.getCost();
request.setAttribute("cost", cost);
RequestDispatcher resultsDispatcher = request.getSession().getServletContext().getRequestDispatcher("/results.jsp");
try {
resultsDispatcher.forward(request, response);
} catch (ServletException se) {
System.out.println("Servlet Exception: " + se.toString());
} catch (IOException ioe) {
System.out.println("IO Exception: " + ioe.toString());
}
} else {
request.setAttribute("errors", errors);
RequestDispatcher errorDispatcher = request.getSession().getServletContext().getRequestDispatcher("/errors.jsp");
try {
errorDispatcher.forward(request, response);
} catch (ServletException se) {
System.out.println("Servlet Exception: " + se.toString());
} catch (IOException ioe) {
System.out.println("IO Exception: " + ioe.toString());
}
}
【问题讨论】:
-
仅供参考:您可以致电
request.getRequestDispatcher()。您不需要链接会话和 servlet 上下文对象(而且您可能也不应该这样做)。