views:

151

answers:

1

Hi all, when I use <c:out value="${track}"> in a jsp, where should the attribute track be located in (servletContext, httpSession and request)?

I tried to have a controller to set the attribute track to the httpSession, but then ${track} doesn't give me anything in the .jsp. On the other hand, if I set it to the servletContext, ${track} give me the value. It doesn't seem right. Can you give a direction on passing attributes between .jsp (using jstl) and controllers (.java)? Thanks in advance.

+1  A: 

It will under the hoods use JspContext#findAttribute() to find the attribute. The linked javadoc mentions the following:

Searches for the named attribute in page, request, session (if valid), and application scope(s) in order and returns the value associated or null.

So, it will return the first non-null value which is found after searching in the order of page, request, session and application (servletcontext) scopes.

If you have attributes with the same name in multiple scopes and/or you'd like to get the attribute from a specific scope, then you can access it by the attribute maps available by the ${pageScope}, ${requestScope}, ${sessionScope} and/or ${applicationScope}. E.g.

${requestScope.track}

Back to your actual problem: if you have problems with accessing session scoped attributes, then it can only mean that the JSP is not using the same session as the servlet is using. You can debug it by printing the Session ID in servlet as follows

System.out.println(session.getId());

and in JSP by

${pageContext.session.id}

Both should print the same. If not, then it is definitely not sharing the same session. The session is domain, context and cookie dependent.

You can display all available session attributes by just printing ${sessionScope}. It will display a string in format as described in AbstractMap#toString(), containing all session attributes.

${sessionScope}
BalusC
Thank you so much Balus!! Your answer is always great!! As what you guess, the problem is with diff sessions. Thanks!!
Kenneth
You're welcome. But was you able to fix the problem? It at least indicates that you was doing a redirect instead of a forward to the JSP (i.e. `resposne.sendRedirect(jspURL)` instead of `request.getRequestDispatcher(jspURL).forward(request, response)` and that you was using an absolute URL instead of a relative URL to the JSP (e.g. `jspURL = "http://example.com/search.jsp"` instead of `jspURL = "search.jsp"`).
BalusC
You are very experienced. You found my problem again.... :D .. thank you!!
Kenneth
Oh, let me guess more, the domain name which you used in the absolute URL was different as opposed to the domain name as it was in request URL (which you see in browser address bar)? Or you probably used an IP address in one and a hostname in the other? :)
BalusC
hehe.. they were different and the cause was silly... *** a typo ***... :P ... Thanks for all your helps..
Kenneth