How to dynamically load dropdown list item - JSP/HTML, JSTL

Spring MVC

It is very easy to load a list item with the database data. if any errors are raised after submitting the page then the list item will keep the same record as selected in a dropdown list.

Step 1: Model Class - Initialize a HashMap collection in a model class. Where we will keep the list records from a database. Here key as a code and the value as description.
Dto Class


Step 2: DAO Class - Get data from a database. Put the code and description value into the LinkedHashMap collection as key and value. And return to the controller class.

DAO Class


Step 3: Controller Class - return page with the data using model.addAttribute() method

Controller

Step 4: JSP Page - On the JSP page load the data using the JSTL loop.

JSP Page

Here <c:forEach var="list" items="${model.lisIte}">,  items="${model.lisIte}" attribute extracts the value from LinkedHashMap collection and keeps each record into var="list".

And then in the option tag, it just sets the key as value and value as display.

Here <c:if test="${model.age eq list.key}">selected="selected"</c:if>, this is simple jstl if condition. After the submit page, if any errors are raised then we need to keep all item's values in items. So for the dropdown list, we need to load the dropdown list in the POST method also. 
When it loads from the POST method, JSTL checks with the before-selected record and then it keeps the same record as selected.

Finally, check in the browser. It is loaded. 

Final Output in browser
Done 😀




Code - 👇

1. Model/Dto Class : 
public class modelDto {
private LinkedHashMap<String, String> lisIte;
}

2. DAO Class : 
public LinkedHashMap<String, String> loadListItem(String comId) throws Exception {
LinkedHashMap<String, String> temLisIte = new LinkedHashMap<>();
String qry = "SELECT AGEFORNO,FORMDESC FROM ACAGEING WHERE COMPCODE= ?";

try(Connection conn = oPool.getConnection(); PreparedStatement stmt = conn.prepareStatement(qry)){
stmt.setString(1,comId);
try(ResultSet rs = stmt.executeQuery()){
while (rs.next()){
temLisIte.put(rs.getString(1), rs.getString(2));
}
}
}catch (Exception e){
e.printStackTrace();
LOGGER.error(Constants.ERROR_LOG);
}
return temLisIte;
}

3. Controller : 
formDto.setLisIte(service.loadListItem(compId));
model.addAttribute("model", formDto);

4. JSP Page : 

<div class="form-floating">
    <select id="P9" name="age" class="form-control">
        <c:forEach var="list" items="${model.lisIte}">
            <option value="${list.key}" <c:if test="${model.age eq list.key}">selected="selected"</c:if> >${list.value}</option>
        </c:forEach>
    </select>
    <label for="P9">Age</label>
</div>

Post a Comment

0 Comments