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.
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.
Step 3: Controller Class - return page with the data using model.addAttribute() method
Step 4: JSP Page - On the JSP page load the data using the JSTL loop.
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.
When it loads from the POST method, JSTL checks with the before-selected record and then it keeps the same record as selected.
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>
0 Comments