填充 HTML <选择>JSP 中的下拉列表,其中包含从 Servlet 中的数据库获取的值 [英] Filling HTML &lt;select&gt; dropdown list in JSP with values fetched from database in Servlet

查看:16
本文介绍了填充 HTML <选择>JSP 中的下拉列表,其中包含从 Servlet 中的数据库获取的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个数据库 flights_DB,其中包含一个名为 Passengers 的表.每个乘客都由他的护照号码唯一标识.

I have a database flights_DB containing a table called Passengers. Each passenger is uniquely identified by his passport number.

我想创建一个下拉列表,其中包含表 Passengers 中的所有护照号码.如何使用 JSP 和 Servlets 实现这一点?

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?

推荐答案

假设您已经完成了模型和数据库部分(根据问题的评论),只需创建一个 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.

这篇关于填充 HTML <选择>JSP 中的下拉列表,其中包含从 Servlet 中的数据库获取的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆