Sharing data between PortletSession and HttpSession
A common issue when we’re using Portlet is about sharing data between PortletSession and HttpSession. Frequently we find code like this:
Portlet snippet
PortletSession session = request.getPortletSession();
session.setAttribute("attribute_name","attribute_value");
JSP snippet – Using JSTL
<p>${sessionScope.attribute_name}</p>
Result: The JSP prints out an empty value.
Why does it happen ?
It happens because the PortletSession and HttpSession have different scopes. By default, PortletSession uses portlet scope, as well as HttpSession uses application scope. Hence, an object into portlet scope cannot be accessible into application scope.
Using the PortletSession into JSP
One way to print a PortletSession value into a JSP is use the PortletSession within the JSP. We can do that using the following:
<%
PortletSession session = renderRequest.getPortletSession();
out.println(session.getAttribute("attribute_name");
%>
This doesn’t sound good. We intend to use JSTL instead scriptlet and the approach above doesn’t fit in our requirement. Because of this we’re going to use one of the below approaches.
Converting PortletSession into HttpSession within a Portlet
Within the portlet, we can use a code like this:
HttpServletRequest httpRequest = WpsStrutsUtil.getHttpServletRequest(request);
HttpSession session = httpRequest.getSession(true);
session.setAttribute("attribute_name","attribute_value");
The code above simply retrieve a HttpServletRequest and then we created a HttpSession.
It definatelly works, but we can do even better. Check the next example out.
Changing the PortletSession scope
As describe above, by default the PortletSession scope is a Portlet scope. As you should know, JSTL reads Application Scope. Fortunately, there is a simple way to change the default PortletSession scope. Simply add one more parameter in the setAttribute method.
PortletSession session = request.getPortletSession();
session.setAttribute("attribute_name","attribute_value",PortletSession.APPLICATION_SCOPE);
Awesome, huh? In this way, we can use JSTL to get the values from Session.
Conclusion
I’m not a Portet specialist, however I’ve already found many problem regarding the PortletSession and HttpSession. If you’re facing a problem like this, check your code out and try the approaches above.
If you have any question or comment, fell free to leave your message below.
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
다양한 언어의 JSONJSON은 Javascript 표기법을 사용하여 데이터 구조를 레이아웃하는 데이터 형식입니다. 그러나 Javascript가 코드에서 이러한 구조를 나타낼 수 있는 유일한 언어는 아닙니다. 저는 일반적으로 '객체'{}...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.