Saurabh Deshpande
Saurabh Deshpande

Reputation: 1221

Accessing Java string array elements into JSP

I am developing a web application. I have a java class which has array of type String. In the same package, I have .jsp page which handles UI. I want to show contents of java String array into jsp's select tag.

<select>
   <option>_____</option>
</select>

How do I populate this select box with Java String array?

Upvotes: 1

Views: 5158

Answers (5)

anonymous
anonymous

Reputation: 244

read the elements of the array in a loop and then print it inside the loop

<select> 
<%
for(int i=0; i<arr.size(); i++){
<option value="<%= arr[i]%>"><%= arr[i]%></option>
} 
%>
</select>

Upvotes: -1

Pradip
Pradip

Reputation: 3177

Have you tried with POJO class. and access it from jsp like below.

<select>
<% String[] pojoObj= (String)request.getAttribute("data");
for (String str: pojoObj ){
%>
<option><%=str%></option>
<%}%>
</select>

Upvotes: 0

Alex
Alex

Reputation: 11579

Use JSTL in JSP and the code will be much cleaner:

<html:select property="yourPropName">
<html:options name="yourDataList" />
</html:select>

Upvotes: 0

Suresh Atta
Suresh Atta

Reputation: 122026

Iterate over the loop with for-each loop.

With Expression Language,It looks like,

   <select name="item">   
       <c:forEach items="${itemsArray}" var="eachItem">   
            <option value="${eachItem}">${eachItem}></option>   
       </c:forEach>   
   </select>  

Upvotes: 2

Prabhaker A
Prabhaker A

Reputation: 8483

you can use <c:foREach> tag .

<select>
   <c:forEach var="option" items="${requestScope.array}">
       <option>${option}</option>
   </c:forEach>
</select>

Here is sample code

Upvotes: 0

Related Questions