java - Assigning a HashMap to a variable within JSP -
java - Assigning a HashMap to a variable within JSP -
i have controller servlet creating object , placing hashmap , i'm forwarding jsp attribute, in jsp wish set hashmap variable, how able this?
see code below:
controllerservlet
map<integer, post> posts = new hashmap<integer, post>(); // needs refactoring db query post p = new post(); p.setid(1); p.settitle("hello world!"); p.setbody("this 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")
please not utilize servletcontext communicate between servlet , jsp page ! you'd improve utilize request attributes usage, servletcontext
attributes mutual servlets , sessions.
in controller utilize :
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 on map <c:foreach>
jstl tag, unless map in linkedhashmap
or treemap
order of iteration unspecified. illustration :
<table><tr><th>title</th><th>author</th><tr> <c:foreach var="entry" items="${posts}"> <!-- key ${entry.key} value ${entry.value} --> <tr><td>${entry.value.title}</td><td>${entry.value.author}</td></tr> </c:foreach> </table>
java jsp servlets
Comments
Post a Comment