Get data from database and display into dropdown in Spring boot and JSP

How to read data from the database in a list using spring boot and display the data list in the dropdown on a JSP page.

In this example, let’s create a simple spring boot application that will read the list of data from the MySQL database and display the data in the dropdown in another form.

Task Scenario:

We have a list of hotels in the database and need to display the hotel list in the dropdown while booking a hotel so customers can select the required hotel.

Spring Controller:

Get the list of data hotelList from the database and add the hotel list into the model as an attribute with the response.

 public String booking(@ModelAttribute("form")BookingForm form, Model model) {
     List<HotelDTO> hlist = hotelService.list();
     model.addAttribute("hList", hlist);
  return "booking";

JSP View

Create a dropdown into the JSP page and get the hotel list attribute and fetch the required data using for each loop as shown in the below example.

<div class="col-md-6 mb-4 pb-2">                 
               <select class="select form-control-lg" name="hotelName">
               <option value="1" disabled>Select Hotel</option>
                 <c:forEach items="${hList}" var="list" varStatus="u">
                 <option value="${list.hotelName}">${list.hotelName}</option>
               <label class="form-label select-label">Select Hotel</label>