tags:

views:

149

answers:

2

Hi everyone

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

A: 

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}
Rob Tanzola
+1  A: 

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>");
}
BalusC