Output a String from an array in JSP

依然范特西╮ 提交于 2019-12-04 04:34:19

问题


I want to make a quiz, I want to have to output an array of questions after a form is submitted.

I know to use a bean I think but how would I do this?

Thanks


回答1:


Use the JSTL <c:forEach> for this. JSTL support is dependent on the servletcontainer in question. For example Tomcat doesn't ship with JSTL out of the box. You can install JSTL by just dropping jstl-1.2.jar in /WEB-INF/lib of your webapplication. You can use the JSTL core tags in your JSP by declaring it as per its documentation in top of your JSP file:

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>

You can locate an array (Object[]) or List in the items attribute of the <c:forEach> tag. You can define each item using the var attribute so that you can access it inside the loop:

<c:forEach items="${questions}" var="question">
    <p>Question: ${question}</p>
</c:forEach>

This does basically the same as the following in plain Java:

for (String question : questions) { // Assuming questions is a String[].
    System.out.println("<p>Question: " + question + "</p>");
}



回答2:


With JSP 2.0, it might look something like this:

<% 
request.setAttribute( "questions", new String[]{"one","two","three"} );  
%>   
<c:forEach var="question" items="${questions}" varStatus="loop">  
    [${loop.index}]: ${question}<br/>  
</c:forEach>  

where questions would be set in the code that handles the submit instead of in the JSP.

If you are using JSP 1.2:

<c:forEach var="question" items="${questions}" varStatus="loop">  
    <c:out value="[${loop.index}]" />: <c:out value="${question}"/><br/>  
</c:forEach>  

Using EL and JSTL you will be able to access any Question object properties if you are storing objects in the array instead of just Strings:

${question.myProperty}


来源:https://stackoverflow.com/questions/2733531/output-a-string-from-an-array-in-jsp

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!