To accomplish one of our project requirements, a specific piece of information (CSS_Key) needs to be maintained in the browser cookie that controls the styles dynamically for the application. This key should be read in the first screen of the application as a URL parameter and the value needs to be maintained in the cookie. But the cookie did not get added to the browser, when we tried to add the cookie using “response.addProperty (cookieObj)” in the render phase of a custom JSR 286 portlet. If this cookie does not get added to the browser, the application will not show the dynamic styles in page based on the URL parameter received in the first page.
While setting a cookie in doView method, response already gets committed and hence we are unable to add the cookie using response.addProperty (cookieObj).
To avoid this issue we need to enable and use the two phase rendering feature of JSR 286 portlets. In general, while developing any portlet we confine our scope to define and access components within portlet. By using two phase rendering, we can set page level components like page title, meta tag, cookie and so on. Page level components do not come under the portlet scope. Two phase rendering splits the rendering phase into two phases, first phase gives us access to the page level components (doHeader method) and the second phase renders the actual view of the portlet (doView method). “doHeader” method gets called before “doView” method and hence before the response gets committed, we can set page level components like page title, meta tag, cookie and so on.
We need to follow below mentioned two steps to enable and use two phase rendering.
Add this code to portlet.xml within <portlet> tag. By default this is set to false.
Sample code to be added in portlet class is mentioned below:
protected void doHeaders(RenderRequest renderRequest,
Cookie cssKeyCookie = new Cookie(“CSS_Key”, “testValue”);