且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

填充 HTML <选择>JSP 中的下拉列表,其中包含从 Servlet 中的数据库获取的值

更新时间:2023-02-01 10:36:59

假设您已经完成了模型和数据库部分(根据问题的评论),只需创建一个 servlet 类并相应地实现 doGet() 方法.它相对简单,只需从数据库中检索乘客列表,将其存储在请求范围内并转发到应该呈现它的 JSP.下面的示例假设您使用 EJB/JPA 作为服务/DB 层,但是无论您使用什么服务/DB 层,您最终都应该从中获得一个 List.

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);
    }

}

创建一个 JSP 文件 /WEB-INF/passengers.jsp 使用 JSTL <c:forEach> 对其进行迭代,打印一个新的 HTML <option> 每次:

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>

(此示例假设 Passenger 实体具有 idname 属性)

(this example assumes the Passenger entity to have id and name properties)

基本上应该是这样.只需像这样调用 servlet 的 URL 来打开页面 http://example.com/contextpath/passengers.

That should basically be it. Just open the page by invoking the servlet's URL like so http://example.com/contextpath/passengers.