我有,當發生在我的應用程序的驗證錯誤,我顯示JSP。在Servlet中,我在請求中設置了ArrayList<String>
錯誤,並試圖在JSP中打印它們,並使用以下代碼。我知道ArrayList
中有1個錯誤,因爲我將它打印到服務器控制檯,但唯一要打印的是「 - 」。我正確使用forEach
循環嗎?JSP forEach循環
<c:forEach var="error" items="${errors}">
<h1>-${error}</h1>
<br>
</c:forEach>
下面是從doPost方法在Servlet的部分代碼:
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上下文對象(並且您可能不應該)。 –