2014-12-06 120 views
0

如何將對象數組(Mcq [] mcq)從servlet傳遞到JSP?如何在jsp中使用taglib從對象數組中提取數據?JSP:如何將對象數組從JSP傳遞到JSP

CLASS:

public class Mcq { 
private String question; 
private String choice_1; 
private String choice_2; 

/* GETTERS AND SETTERS */ 
} 

CONTROLLER:

String question, choice_1, choice_2; 
Mcq[] mcq = new Mcq[100]; 

for(int i=0; i<mcqCount; i++){ 
    question = request.getParameter("mcq-question-"+i); 
    choice_1 = request.getParameter("mcq-choice-"+i); 
    choice_2 = request.getParameter("mcq-choice-"+i); 
    mcq[i].setQuestion(question); 
    mcq[i].setChoice_1(choice_1); 
    mcq[i].setChoice_2(choice_2); 
} 

request.getSession().setAttribute("mcq", mcq);  
RequestDispatcher dispatcher; 
dispatcher = request.getRequestDispatcher("testpage.jsp"); 
dispatcher.forward(request, response); 

HTML(testpage.jsp):

<body> 
    <h1>   
     Question: ${mcq.getQeustion()} 
     Choice-1: ${mcq.getChoice_1()} 
     Choice-2: ${mcq.getChoice_2()} 
    </h1> 
</body> 

回答

0
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>  
    <body> 
     <h1> 
      <c:forEach var="mcq" items="${mcq}"> 
       Question: ${mcq.question} 
       Choice-1: ${mcq.choice_1} 
       Choice-2: ${mcq.choice_2} 
      </c:forEach> 
     </h1> 
    </body> 

的EL 「$ {MCQ}」 表達應能夠抓住Mcq已經因爲你讓他們成爲一個會議屬性。