Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Output a String from an array in JSP

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

like image 336
Sandeep Bansal Avatar asked Apr 07 '26 10:04

Sandeep Bansal


2 Answers

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>");
}
like image 80
BalusC Avatar answered Apr 08 '26 23:04

BalusC


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}
like image 40
Rob Tanzola Avatar answered Apr 09 '26 00:04

Rob Tanzola



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!