Home > Back-end >  c:forEach does not print anything
c:forEach does not print anything

Time:07-26

I'm exploring spring mvc and I'm trying to print a list in a jsp file. Here the relevant parts of the code:

Controller

@Transactional
    @RequestMapping("/homepage")
    public String getHomePage(HttpServletRequest request, Model model) {
        List<ProfessoreDAO> professori = (List<ProfessoreDAO>) sessionFactory
            .getCurrentSession()
            .createQuery("from ProfessoreDAO", ProfessoreDAO.class)
            .getResultList();
        System.out.println("Recuperati professori: "   professori);
        model.addAttribute("professori", professori);
        return "homepage";
    }

jsp file:

 <c:forEach var="professore" items="${professori}"> 
                <tr>
                    <td>
                        ${professore.nome}
                    </td>
                    <td>
                        <c:out value="${professore.cognome}" />
                    </td>
                    <td>
                        <c:out value="${professore.materia}" />
                    </td>
                </tr>
            </c:forEach>

At the moment I cannot debug on the server, but from what I see opening Firefox:

<c:foreach items="[Mario-Rossi]" var="professore">
                </c:foreach>

It seems that the property is well defined ("Mario-Rossi" is just the toString implementation result of the only object present in the list) I've tried with both

<td> ${professore.nome} </td>

and

<td> <c:out value="${professore.cognome}" /> </td>

as you can see, but I've no results

CodePudding user response:

your code looks correct, please check tag library is correctly imported

CodePudding user response:

as stated in the answer above I had forgotten to import the jstl support. To achieve this (I'm using tomcat 9, solution can slightly change depending on the tomcat version) I did:

pom.xml

<dependency>
    <groupId>org.glassfish.web</groupId>
    <artifactId>jakarta.servlet.jsp.jstl</artifactId>
    <version>1.2.6</version>
</dependency>

jsp file

<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
  • Related