how to assign arraylist to select option in jsp

后端 未结 2 1594
甜味超标
甜味超标 2021-02-06 16:11

I have the list:

ArrayList list = new ArrayList();

I write this list select option:


    
                        
    
提交评论

  • 2021-02-06 16:43

    It's not recommended to use java code inside jsp. You should try to avoid it.

    The approach that needs to be followed in your case, is to first set the Arraylist as an attribute in the servlet that is calling the jsp page.

    Servlet Code

    ArrayList databaseArrayList = new ArrayList();
    ...
    request.setAttribute("databaseList", databaseArrayList);     
    

    Then, in the JSP code, use jstl to iterate through the values of the list to populate the select options.

    JSP Code

    <select name="database1">
      <c:forEach items="${databaseList}" var="databaseValue">
        <option value="${databaseValue}">
            ${databaseValue}
        </option>
      </c:forEach>
    </select>
    

    I've written an article for looping over HashMap and ArrayList in JSP

    0 讨论(0)
  • 提交回复
    热议问题