Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c:forEach not working

Tags:

java

jsp

web

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 ;)

like image 793
gausss Avatar asked Jan 16 '23 15:01

gausss


1 Answers

${registrationServlet.inputLangs} means:

  • find an attribute named "registrationServlet" in the page scope
  • if not found, find an attribute named "registrationServlet" in the request scope
  • if not found, find an attribute named "registrationServlet" in the session scope
  • if not found, find an attribute named "registrationServlet" in the application scope
  • if found, call getInputLangs() on the found object

So, 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}">
like image 148
JB Nizet Avatar answered Jan 21 '23 08:01

JB Nizet