Reputation: 353
I have a problem with a taglib method c:forEach. I want to get a List of languages from a servlet class and show it on a jsp page with c:forEach. But it is just showing nothing^^ an empty select tag.
The for each loop in the jsp file (i have taglib import and already tried without c:out):
...
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
...
<c:forEach var="lang" items="${registrationServlet.inputLangs}">
<option><c:out value="${lang}"></c:out></option>
</c:forEach>
My Servlet Class (it is a servlet because I have to do some form submitting stuff with it too):
...
// List of languages to choose from
List<String> inputLangs;
...
// Query the languages from the database
public List<String> getInputLangs() {
try {
String query = "SELECT DISTINCT Lang FROM country";
ResultSet result = DbConnection.read(query);
while (result.next()) {
inputLangs.add(result.getString("lang"));
}
} catch (SQLException e) {
System.err.println("Couldn't get languages from DB.");
}
return inputLangs;
}
What am I doing wrong?^^
BTW. it works with pure java:
<%
RegistrationServlet reg = new RegistrationServlet();
for (String lang : reg.getInputLangs()) {
%>
<option><%=lang%></option>
<%
}
%>
But as far as I know that's a no go in jsp files ;)
Upvotes: 5
Views: 18858
Reputation: 340
Have you got correct JSTL jar files on your class path? In your case JSTL 1.1 JAR file in the /WEB-INF/lib
https://stackoverflow.com/tags/jstl/info
Upvotes: 0
Reputation: 691635
${registrationServlet.inputLangs}
means:
getInputLangs()
on the found objectSo, if you haven't stored any instance of RegistrationServlet
in any scope, this expression will always evaluate to null
. If you keep this design, the doGet()
(or doPost()
) method of your servlet should have the following line:
request.setAttribute("registrationServlet", this);
But it would be much cleaner to have
request.setAttribute("inputLangs", getInputLangs());
and, in the JSP:
<c:forEach var="lang" items="${inputLangs}">
Upvotes: 9