2013-08-03 408 views
0

我有,當發生在我的應用程序的驗證錯誤,我顯示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()); 
     } 
    } 
+0

僅供參考:您可以調用request.getRequestDispatcher()。您不需要鏈接會話和servlet上下文對象(並且您可能不應該)。 –

回答

-1

嘗試,提醒每一次迭代中,理想的應該工作。

+0

我沒有看到在響應中設置屬性的方法。 – user1154644

+0

您無法設置屬性作爲迴應,我的意思是將其設置爲測試目的的任何其他範圍,如會話等,如果它有效,這意味着您沒有轉發請求,並且您的頁面有新的請求對象。 –

0

它應該可以工作,但我會這樣測試:
1.確定<c:out value="${errors}"/>確保數據存在於請求中。
2.更改名稱error到例如err1別的東西,並顯示它,以確保不存在任何名稱衝突。
3.檢查您是否添加了<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>