0
我有我的控制器Servlet創建一個對象並將其放入HashMap中,並將其作爲屬性轉發給我的JSP,在我的JSP中我希望將此HashMap設置爲變量,我怎麼能做到這一點?爲JSP中的變量分配HashMap
見下面的代碼:
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")
爲什麼你把它放到HashMap而不是ArrayList(然後索引會是你的鍵在數組中)?而且你確定要使用servletContext(它會被許多請求共享),而不是請求? – Gas 2014-10-04 15:09:07