Skip to main content

Development

Setting cookie in Render Phase of a JSR 286 Portlet

Problem:

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.

Root cause:

While setting a cookie in doView method, response already gets committed and hence we are unable to add the cookie using response.addProperty (cookieObj).

Solution:

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.

Step 1:

Add this code to portlet.xml within <portlet> tag. By default this is set to false.

<container-runtime-option>

<name>javax.portlet.renderHeaders</name>

<value>true</value>

</container-runtime-option>

Step 2:

Sample code to be added in portlet class is mentioned below:

protected void doHeaders(RenderRequest renderRequest,

RenderResponse renderResponse){

//Setting cookie

Cookie cssKeyCookie = new Cookie(“CSS_Key”, “testValue”);

cssKeyCookie.setPath(“/”);

cssKeyCookie.setMaxAge(3600000);

renderResponse.addProperty(cssKeyCookie);

}

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Kirupakaran Baskaran

More from this Author

Categories
Follow Us
TwitterLinkedinFacebookYoutubeInstagram