thonnor
thonnor

Reputation: 1246

JSTL populate several dropdowns using the same SQL query

I am creating a webapp using JSTL - desperately trying not to use Java code and scriptlets.

My site is a football site where I enter a fixture and the players names who took part (11-13 names)

I have a players table containing all of the players names.

I need to populate a dropdown menu with all of their names and repeat this code 13 times (13 drop down menus with the same list)

I obviously don't want to write 13 bits of code for this.

Very basic Pseudo code elsewhere might look like...

String playerDropDown = getPlayersFromDB();

print playerDropDown;
print playerDropDown;
print playerDropDown;
print playerDropDown;
print playerDropDown;
print playerDropDown;
print playerDropDown;
...
...

Any advice/guidance is appreciated.

Upvotes: 0

Views: 447

Answers (1)

Riaan Schutte
Riaan Schutte

Reputation: 535

I do this all the time. Create a new JSP page and just write your select and a for loop with all your player names added as options. Then in your main JSP page include this page.

Might look something like this:

players_select.jsp

<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %
<% 
    List players = Players.getAll();
%>
<select>
<c:forEach var="player" items="<%=players %>">
    <option>${player}</option>
</c:forEach>
</select>

main.jsp:

...
<jsp:include page="../includes/players_select.jsp"/>
...
<jsp:include page="../includes/players_select.jsp"/>
...
<jsp:include page="../includes/players_select.jsp"/>
...

This way if you make the change in players_select.jsp it affects all usages.

Upvotes: 1

Related Questions