0

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.

1
  • Can you please remove sql tag. Commented Jan 6, 2014 at 1:49

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

6 Comments

Interesting, so Players.getAll() is a simple Java method that returns a List ??
Yes, a public static method that either returns a List of Strings, which will work in the example provided or if you prefer working with objects and methods returns a List of Player objects. If the latter then <option>${player}</option> becomes <option>${player.name}</option>.
Brilliant, thank you so much. I've already begun making the 'List' changes to my code. I'll post another comment once I've cracked it :)
I think you still need to import java.util.List.
Thanks to you both for contributing.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.