0

I have my controller Servlet creating an object and placing it into a HashMap and I'm forwarding this to my JSP as an attribute, in my JSP I wish to set this HashMap to a variable, how am I able to do this?

See code below:

ControllerServlet

Map<Integer, Post> posts = new HashMap<Integer, Post>();

// Needs refactoring to a DB query
Post p = new Post();
p.setId(1);
p.setTitle("Hello World!");
p.setBody("This is my first blog post!");
p.setAuthor("Jacob Clark");
p.setPublished(new Date());

posts.put(p.getId(), p);

getServletContext().setAttribute("posts", posts);

RequestDispatcher rd = getServletContext().getRequestDispatcher("/WEB-INF/index.jsp");
rd.forward(request, response);

JSP

getServletContext().getAttribute("posts")
Jacob Clark
  • 3,087
  • 4
  • 29
  • 58
  • Why are you putting it to HashMap instead of ArrayList (then index would be your key in the array)? And you for sure want to use servletContext (it will be shared by many requests then), not request ? – Gas Oct 04 '14 at 15:09

1 Answers1

2

Please do not use ServletContext to communicate between a servlet and a JSP page ! You'd better use request attributes for that usage, ServletContext attributes are common to all servlets and all sessions.

In your controller you use :

request.setAttribute("posts", posts);

RequestDispatcher rd = getServletContext().getRequestDispatcher("/WEB-INF/index.jsp");
rd.forward(request, response);

Then in JSP :

<jsp:useBean name="posts" scope="request" class="java.util.Map"/>
${posts["1"].title}

You can iterate over the map with <c:foreach> JSTL tag, but I unless the Map in is LinkedHashMap or a TreeMap the order of iteration is unspecified. Example :

<table><tr><th>Title</th><th>Author</th><tr>
<c:forEach var="entry" items="${posts}">
   <!-- Key is ${entry.key} Value is ${entry.value} -->
   <tr><td>${entry.value.title}</td><td>${entry.value.author}</td></tr>
</c:forEach>
</table>
Serge Ballesta
  • 136,215
  • 10
  • 111
  • 230