Passing Objects to JSP Include Pages
When working with plain old JSP, it is often useful to extract reusable bits into separate JSP files that you include in your pages via the jsp:include tag. However, sometimes you need to be able to pass objects to those included pages. The jsp:include tag allows a jsp:param sub-tag that can be used to pass String values, but what if you need to pass another object type?
There are two easy ways to do this, but first you need to decide whether you need the object to be persistent across multiple requests. If so, then your best bet is to use session.setAttribute(). For example, let's assume I have a HashMap called myMap that I want to persist for the duration of the user session.
HashMap myMap = new HashMap();
myMap.put("myValue","test");
session.setAttribute("myMap",myMap);
Then from your included JSP page (or any other JSP pages after the session has been initialized), you would call session.getAttribute() to retrieve your object:
HashMap myMap = (HashMap)session.getAttribute("myMap");
The downside with this approach is that it wastes memory if you really only need the HashMap to persist for the duration of the request, i.e. you just want to pass it to the included JSP page and then be done with it. I better approach for this situation is to use the request object:
request.setAttribute("myMap",myMap);
Then in your included JSP page:
HashMap myMap = (HashMap)request.getAttribute("myMap");
Posted by rickg ( Apr 25 2006, 11:32:44 PM PDT ) Permalink Comments [4]

