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 ;)
${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}">
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With