1

I'm trying to learn Spring / mvc framework. I've created a basic example where I'm printing a simple string to the screen, this is fine, I now want to iterate over the list of strings but nothing is appearing. It seems as though my foreach is looking at the collection as a whole instead of the elements within. I'm printing an additional character in the loop and only one is displayed yet there are 4 items.

Printing ti straight to the screen without the foreach shows the contents in the fashion of [a,b,c,d].

I'm not sure what it is that I'm doing wrong, any help is appreciated.

Controller:

    @Controller
public class HelloController {

    //the request mapping simply says, what url am i tied to?
    @RequestMapping(value = "/greeting") //defines the url and the method 
it is tied to
    public String sayHello(Model model){ //model is a key-value pair.

        List<String> stringList = new ArrayList<String>();
        stringList.add("A");
        stringList.add("B");
        stringList.add("C");
        stringList.add("D");

        model.addAttribute("greeting", "Hello, World"); //greeting is key, value hello world
        //the jsp page will reference back to 'greeting' as above.
        model.addAttribute("stringList", stringList);
        model.addAttribute("stringlist2", "stringlist2");

        return "hello";//this ties us to the jsp pages
    }
}

JSP:

<h1>
    ${greeting}
    ${stringList}
    ${stringlist2}
    <%--this maps to the model attribute greeting in the controller.--%>
</h1>

<c:forEach items="${stringList}" var="elt">
    <div>:<c:out value="${elt}"/></div>
</c:forEach>

Result on page:

Hello, World [A, B, C, D] stringlist2
: //this is the extra char I'm printing in the foreach.
BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
null
  • 3,469
  • 7
  • 41
  • 90

1 Answers1

2

view source shows: <c:foreach items="[A, B, C, D]" var="elt"> <div>:<c:out value=""></c:out></div> </c:foreach>

Your server was unable to find, parse and execute JSTL tags.

That can happen if you forgot to declare the c namespace prefix as below in top of JSP:

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

If it still doesn't work, or you get an exception saying "The absolute uri: http://java.sun.com/jstl/core cannot be resolved", then that can happen if you you're using the jurassic JSTL 1.0 (which is really unexpected these days), or that you forgot to install JSTL too. For installation instructions and other troubleshooting hints, head over to our JSTL wiki page.

Community
  • 1
  • 1
BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555