Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
531 views
in Technique[技术] by (71.8m points)

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?

Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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:


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...