mardi 10 octobre 2017

List passed from controller to jsp is null

I am trying to pass a list of strings from a servlet to a jsp and I am trying to print it out in the jsp using jstl. The list is correctly populated, however it is null when it gets passed to the jsp and nothing gets printed in the view. Here is the code used in my servlet:

 protected void doGet(HttpServletRequest request, HttpServletResponse 
 response) throws ServletException, IOException {
    // TODO Auto-generated method stub
    List<String> list = getList();
    HttpSession session = request.getSession();
    session.setAttribute("list", list);

    response.setContentType("text/html");
    request.setAttribute("list", list);
    request.getRequestDispatcher("/index.jsp").forward(request, response);
}

and here is what I used in my jsp:

   <%@taglib prefix="c" uri="http://ift.tt/QfKAz6"%>
   <html>
   <body>
   <h2>Spring MVC and List Example</h2>
   <ul>

   <c:forEach items="${list}" var="item">
   <p>Question: ${item}</p>
   </c:forEach>

   </ul>
   </body>
   </html>

I have also tried using this code in my controller and it does not work either:

@RequestMapping(value = "/index", method = RequestMethod.GET)
public static ModelAndView getdata() {

    List<String> list = getList();
    //return back to index.jsp
    ModelAndView model = new ModelAndView("index");
    model.addObject("lists", list);

    return model;
  }

I debugged my code and my list is perfectly populated in my servlet so the problem comes from transferring the list from the controller to the jsp. I added this in my jsp:

    <c:if test="${ empty list}">
    yes
    </c:if>

and the string yes got printed in my view meaning that the list ends up being empty in the jsp.




Aucun commentaire:

Enregistrer un commentaire