1

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?

Saurabh Deshpande
  • 1,153
  • 4
  • 18
  • 35

5 Answers5

2

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>  
Suresh Atta
  • 120,458
  • 37
  • 198
  • 307
0

you can use <c:foREach> tag .

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

Here is sample code

Prabhaker A
  • 8,317
  • 1
  • 18
  • 24
0

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

<html:select property="yourPropName">
<html:options name="yourDataList" />
</html:select>
Alex
  • 11,451
  • 6
  • 37
  • 52
  • this DataList is nothing but string array elements which I want to show in select – Saurabh Deshpande Sep 05 '13 at 05:01
  • @Saurabh Deshpande yourDataList is your array string or List from the request or session. It's name of request or session attribute where you put your array. – Alex Sep 05 '13 at 05:03
0

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>
Pradip
  • 3,189
  • 3
  • 22
  • 27
  • 4
    [Sorry, a big NO to scriplets](http://stackoverflow.com/questions/3177733/how-to-avoid-java-code-in-jsp-files), Recommending scriplets is highly discouraged. – Suresh Atta Sep 05 '13 at 05:01
  • This link may help you to understand why to avoid scriptlets in jsp . http://thewebplant.com/why-no-scripts-should-be-written-in-jsps-java/ – Prabhaker A Sep 05 '13 at 05:06
-1

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>
anonymous
  • 244
  • 2
  • 4
  • 23