Filling HTML <select> dropdown list in JSP with values fetched from database in Servlet

心已入冬 提交于 2019-11-26 02:59:29

问题


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?


回答1:


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


来源:https://stackoverflow.com/questions/13728485/filling-html-select-dropdown-list-in-jsp-with-values-fetched-from-database-in

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!