Many times I have seen that people get confused between Portlet Session and its scope. Liferay allows 2 scopes for the "PortletSession" in which data can be stored.
Here are they:
1) PortletSession.APPLICATION_SCOPE
- Data is shared across all the portlet which are under SAME war file
2) PortletSession.PORTLET_SCOPE
- Data is shared among multiple request for PARTICULAR portlet only (Not even with the portlets which are in the same war file)
Lets look at how to use both the scope
Here are the overall steps to use/verify PortletSession
1) Create a portlet and add/store data inside PortletSession
2) Read / Consume the data added by the another Portlet
Lets look at the detailed steps:
1) Create a portlet and add data inside "PortletSession"
// Sample First Portlet's controller
public void doView(RenderRequest renderRequest,
RenderResponse renderResponse) throws IOException, PortletException {
// Setting the values inside the application scope inside firs portlet whose value we will fetch inside second portlet (Same war file)
ps.setAttribute("fpPSValue","added value from the second portlet",PortletSession.APPLICATION_SCOPE);
}
2) Read / Consume the data added by the another Portlet
// Sample Second Portlet's Controller
public void doView(RenderRequest renderRequest,
RenderResponse renderResponse) throws IOException, PortletException {
PortletSession ps = renderRequest.getPortletSession();
String s,s1 = "";
if(ps.getAttribute("fpPSValue",PortletSession.PORTLET_SCOPE) != null) {
// Retrieving data from the Portlet Scope
s1 = (String)ps.getAttribute("fpPSValue",PortletSession.PORTLET_SCOPE);
}
if(ps.getAttribute("fpASValue",PortletSession.APPLICATION_SCOPE) != null) {
// Retrieving data from the Application Scope
s = (String)ps.getAttribute("fpASValue",PortletSession.APPLICATION_SCOPE);
}
if("".equalsIgnoreCase(s1)) {
// If data is not available then set data in the portle scope
ps.setAttribute("fpPSValue","added value from the second portlet",PortletSession.PORTLET_SCOPE);
}
}
Note:
1) In above code if we dont get the data on line
"s = (String)ps.getAttribute("fpASValue",PortletSession.APPLICATION_SCOPE);"
then make sure that both the portlets i.e. (First & Second) portlet are under same war file
2) Data added via line
"ps.setAttribute("fpPSValue","added value from the second portlet",PortletSession.PORTLET_SCOPE);"
will always be consumed by the same portlet and no other portlet can ever access that data
We are done!
Cheers!
Henal Saraiya
(Senior Consultant)
CIGNEX Datamatics
No comments:
Post a Comment