Java populating <option> dropdown list

夙愿已清 提交于 2019-12-11 02:00:37

问题


I have the following code:

<div>
<%
    TaxonomicTypeFeed ttf = new TaxonomicTypeFeed();
    ArrayList<String> tmp = ttf.getTypes();
    System.out.println("Going to print");
        for (int i=0; i < tmp.size(); i++)
    {
        System.out.println(tmp.get(i));
    }
%>

    <form>
        <select>
        <%
            Iterator<String> i = tmp.iterator();
            while (i.hasNext())
            {
            String str = i.next(); %>
            <option value="<%str.toString();%>"><%str.toString();%>
            </option>
        <%}%>
    </select>
    </form>
</div>

It creates a dropdown list fine, however there is no text. This is the first time I have ever used any of these options before, so I have no idea if I am even going about it in the right manner,

Thanks greatly for your constructive criticism in advance, U.


回答1:


You need to print the values by <%= %>. The <% %> won't print anything.

<option value="<%=str%>"><%=str%></option>

Unrelated to the problem: this is not the best practice. Consider using taglibs/EL. You end up with better readable/maintainable code.

<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<jsp:useBean id="taxonomicTypeFeed" class="com.example.TaxonomicTypeFeed" />
...
<select>
    <c:forEach items="${taxonomicTypeFeed.types}" var="type">
        <option value="${type}">${type}</option>
    </c:forEach>
</select>

Instead of <jsp:useBean> you can also use a preprocessing servlet.



来源:https://stackoverflow.com/questions/5911201/java-populating-option-dropdown-list

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!