Setting headers and cookies through portlet

You can use the two phase rendering concept to set both headers and cookies through a portlet, I wanted to try that so i built this TwoPhaseRenderingPortlet.java, you can download the sample code from here


package com.ibm.webspherenotes.jsr286;

import java.io.IOException;

import javax.portlet.GenericPortlet;
import javax.portlet.PortletException;
import javax.portlet.RenderRequest;
import javax.portlet.RenderResponse;
import javax.servlet.http.Cookie;

public class TwoPhaseRenderingPortlet extends GenericPortlet {
protected void doHeaders(RenderRequest request, RenderResponse response) {
System.out.println("Entering TwoPhaseRenderingPortlet.doHeaders()");

Cookie c = new Cookie("myCookieName", "myCookieValue");
c.setPath(request.getContextPath());
response.addProperty(c);

response.setProperty("myHeaderName", "myHeaderValue");

System.out.println("Exiting TwoPhaseRenderingPortlet.doHeaders()");
}

protected void doView(RenderRequest request, RenderResponse response)
throws PortletException, IOException {
System.out.println("Entering TwoPhaseRenderingPortlet.doView()");
response.setContentType("text/html");
response.getWriter().println("Hello from two phase rendering portlet");
System.out.println("Exiting TwoPhaseRenderingPortlet.doView()");
}
}


The Response.setProperty() method is used for setting header and you can use it even for setting cookie. But for setting cookie there is specialized Response.setProperty() method that takes cookie object

2 comments:

  1. Hi Sunil,

    I was wondering if you had any examples around setting cookies on an AJAX response. I've tried the adding a cookie using resourceResponse.addProperty(new Cookie...) in the portlet serveResource(ResourceRequest request, ResourceResponse response) method but it doesn't seem to get delivered to the browser

    ReplyDelete