【问题标题】:JSP: How to pass array of object from servlet to JSPJSP:如何将对象数组从 servlet 传递到 JSP
【发布时间】:2014-12-06 19:25:12
【问题描述】:

如何将对象数组 (Mcq[] mcq) 从 servlet 传递到 JSP?如何在 jsp 中使用 taglib 从对象数组中提取数据?

类:

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

/* GETTERS AND SETTERS */
}

控制器:

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>

【问题讨论】:

    标签: java arrays jsp servlets model-view-controller


    【解决方案1】:
        <%@ 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 的,因为您已将它们设置为会话属性。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-05-07
      • 1970-01-01
      • 2011-08-17
      • 2012-05-04
      • 1970-01-01
      • 1970-01-01
      • 2020-06-14
      相关资源
      最近更新 更多