Populate a select dropdown with list of options with values, index and hashmap
In the servlet code, you need to set the list or hashmap and forward the request to JSP.
ArrayList countryList = new ArrayList();
//...
request.setAttribute("countryList", countryList);
//forward the request to jsp
request.getRequestDispatcher("/WEB-INF/country-selection.jsp").forward(request, response);
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. Then, in the JSP code, use JSTL to iterate through the values of the list to populate the select options.
Here we loop over the array list to generate the options of the select dropdown.
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<select name="country">
<c:forEach items="${countryList}" var="countryName" varStatus="loop">
<option value="${loop.index}">
${countryName}
</option>
</c:forEach>
</select>
In the above example, we used the varStatus
attribute of the forEach tag. It can help us access the indexes in the loop using JSTL expression language.
The above code will generate a list of options inside a select drop down
<select name="country">
<option value="0">Argentina</option>
<option value="1">Australia</option>
<option value="2">Austria</option>
<option value="3">Belgium</option>
<option value="4">Brazil</option>
<option value="5">Canada</option>
<option value="6">China</option>
</select>
In case we are working with Hashmap and we have set a hashmap in the servlet. The key-value pair of each hashmap element can be used to set the value and text of the option as follows.
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<select name="country">
<c:forEach items="${countryList}" var="country">
<option value="${country.key}">${country.value}</option>
</c:forEach>
</select>
Here again we used the forEach
loop to access the elements of the Hashmap