Filling HTML <select> dropdown list in JSP with values fetched from database in Servlet
I have a database flights_DB
containing a table called Passengers
. Each passenger is uniquely identified by his passport number.
I would like to create a drop-down list containing all the passport numbers in the table Passengers
. How can I achieve this using JSP and Servlets?
Assuming that you've the model and DB part already finished (as per the comments on the question), just create a servlet class and implement the doGet()
method accordingly. It's relatively simple, just retrieve the list of passengers from the DB, store it in request scope and forward to the JSP which should present it. The below example assumes that you're using EJB/JPA as service/DB layer, but whatever service/DB layer you use, you should ultimately end up getting a List<Passenger>
from it anyway.
@WebServlet("/passengers")
public class Passengers extends HttpServlet {
@EJB
private PassengerService service;
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
List<Passenger> passengers = service.list();
request.setAttribute("passengers", passengers);
request.getRequestDispatcher("/WEB-INF/passengers.jsp").forward(request, response);
}
}
Create a JSP file /WEB-INF/passengers.jsp
which uses JSTL <c:forEach>
to iterate over it, printing a new HTML <option>
everytime:
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
...
<select name="passenger">
<c:forEach items="${passengers}" var="passenger">
<option value="${passenger.id}"><c:out value="${passenger.name}" /></option>
</c:forEach>
</select>
(this example assumes the Passenger
entity to have id
and name
properties)
That should basically be it. Just open the page by invoking the servlet's URL like so http://example.com/contextpath/passengers.
See also:
- doGet and doPost in Servlets
- Show JDBC ResultSet in HTML in JSP page using MVC and DAO pattern
- Populating cascading dropdown lists in JSP/Servlet