How to display ArrayList values ​​that are defined in JSP itself using JSTL

I have an ArrayList that is defined in a scriptlet in the JSP. In the body section, I want to display elements using a JSTL forEach loop.

After going through tutorials like this one , I wrote the following code:

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

<%
ArrayList<String> fruits = new ArrayList<String>();
fruits.add("Orange");
fruits.add("Apple");
%>

<html>
<head>
    <title>JSTL</title>
</head>
<body>
    <c:forEach var="fruit" items="${fruits}">
        <c:out value="${fruit}" />
    </c:forEach>
</body>
</html>

      

But I am getting a blank page. Where am I going wrong in the above code?

All the tutorials I could find seem to define an ArrayList of beans in the servlet and pass them to the JSP via request

. In a series of forEach they use c:out

and ${bean.prop}

for printing. I have not tried them as such. I wanted to do something much simpler, but cannot get this code to work.

+3


source to share


3 answers


You need to put the array in your query. Do this right after the last call to fruit.add ().



<%= request.setAttribute( "fruits", fruits ); %>

      

+2


source


add pageContext.setAttribute ("fruit", fruit);



<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ page import="java.util.ArrayList" %>

<%
ArrayList<String> fruits = new ArrayList<String>();
fruits.add("Orange");
fruits.add("Apple");
pageContext.setAttribute("fruits", fruits);
%>
<html>
<head>
<title>JSTL</title>
</head>
<body>
    <c:forEach var="fruit" items="${fruits}">
     <c:out value="${fruit}" />
    </c:forEach>
</body>
</html>

      

+3


source


the easiest way to define a variable is by using and using it.

<c:set var="fruits">
   <%= fruits %>
<c:set>

<c:forEach var="fruit" items="${fruits}">
    <c:out value="${fruit}" />
</c:forEach

      

<% = fruits%> is the script you created, created in the scriptlet.

0


source







All Articles