Getting the HttpServletRequest from PortletRequest Object

| Posted by watashii | Filed under Java, Programming, Web

In my JSF / icefaces based portlet running on Weblogic Portal, I got the following error:
com.icesoft.faces.webapp.http.portlet.PortletExternalContext cannot be cast to javax.servlet.http.HttpServletRequest

It turned out I cannot simply obtain the HTTPServletRequest object like this:

FacesContext ctx = FacesContext.getCurrentInstance();
HttpServletRequest portletRequest = (HttpServletRequest) ctx.getCurrentInstance().getExternalContext().getRequest();

In a portlet environment, to get the request/response objects, we must obtain the javax.portlet.PortletRequest/PortletResponse objects instead (which inherits methods from java.servlet.HTTPServletRequest/HTTPServletResponse):

FacesContext ctx = FacesContext.getCurrentInstance();
PortletRequest portletReq = (PortletRequest) ctx.getExternalContext().getRequest();

However sometimes we may require the HttpServletRequest / HttpServletResponse object.  To obtain this, we must extract an attribute from the PortletRequest / PortletResponse object:

FacesContext ctx = FacesContext.getCurrentInstance();
PortletRequest portletReq = (PortletRequest) ctx.getExternalContext().getRequest();
HttpServletRequest httpServletReq = (HttpServletRequest) portletReq.getAttribute("javax.servlet.request");

Tags: , , , , , ,