Search code examples
javajspservletsjstl

Can't print the Java List object in JSP, with JSTL


I have a servlet

@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException {
    List<String> topics = new ArrayList<>();
    ServletConfig config = getServletConfig();
    
    topics.add(config.getInitParameter("first"));
    System.out.println(config.getInitParameter("first")); //prints proper value, not null;

    topics.add(config.getInitParameter("second"));
    System.out.println(config.getInitParameter("second")); //prints proper value, not null;

    topics.add(config.getInitParameter("third"));
    System.out.println(config.getInitParameter("third")); //prints proper value, not null;

    req.setAttribute("params", topics); //doesn't show up
    req.setAttribute("name", config.getInitParameter("name")); //works good
    req.getRequestDispatcher("index.jsp").forward(req, resp);
}

and

index.jsp

...
<ol>
    <c:forEach var="param" items="${params}">
        <li>${param}</li>
    </c:forEach>
</ol>
...

Servlet configuration is ok, initialization is ok, mapping and naming is also ok, that's why when I access respective URL, I do print the parameters in output console stream and they are there. However, for some strange reason, JSP displays:

 1. {}
 2. {}
 3. {}

N.B. I don't want to use Scriptlet Java code, I'm trying to use JSTL. I have seen a lot of projects working in this way.. what's wrong here? just got tired of figuring out.


Solution

  • I've spent on this half of my day, and at the end, it really got me tired and anxious, because it seems so obvious and simple code - what should be going wrong? As some may be searching for the solution of same kind of problem, I think, it's better to have this answered here - what was the problem.

    The crucial point here is the name of the iteration variable - the identifier param.

    At the beginning of [probably] all .jsp files, we have the statement for importing core tags and we give it some prefix

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



    The reason, why

    ...
    <ol>
        <c:forEach var="param" items="${params}">
            <li>${param}</li>
        </c:forEach>
    </ol>
    ...
    

    was not working and was showing

     1. {}
     2. {}
     3. {}
    

    is that, param is the keyword identifying one of the core tags, from jstl/core.

    The <c:param> fetches/gets the Request Parameter(s) array.
    So, each time forEach loop was iterating, param variable was assigned to request parameter(s) from query string rather than iteration value from ${params} variable/placeholder, and as I was passing nothing - empty array was appearing.

    P. S. Be cautious not to use JSTL tags as variables/identifiers in your code.

    Hope some of you will find this information useful.