2011年9月19日 星期一

如何在portal(portlet)中取得 HttpServletRequest

portal中,為了每個獨立的portlet能獨立處理自已的邏輯,所以在request中就區分了兩種request:javax.portlet.ActionRequest 和 javax.portlet.RenderRequest。
那這時如果要取得:javax.servlet.http.HttpServletRequest 的參數的話:就要寫:
javax.servlet.ServletRequest servletRequest = (javax.servlet.ServletRequest) request.getAttribute("javax.servlet.request");
再把 servletRequest cast HttpServletRequest,就可以了, 如下:
HttpServletRequest request = (HttpServletRequest) servletRequest;

補充:
如果要把這個抽出來寫一個 讓RenderRequest和ActionRequest 共用的method
因為:
portlet的 RenderRequest 是繼承 javax.portlet.PortletRequest

public abstract interface javax.portlet.RenderRequest extends javax.portlet.PortletRequest

ActionRequest 是繼承 ClientDataRequest ,它又繼承 PortletRequest
public abstract interface javax.portlet.ActionRequest extends javax.portlet.ClientDataRequest
public abstract interface javax.portlet.ClientDataRequest extends javax.portlet.PortletRequest

   private HttpServletRequest getHttpRequest(PortletRequest request) {
        javax.servlet.ServletRequest servletRequest = (javax.servlet.ServletRequest) request.getAttribute("javax.servlet.request");
        HttpServletRequest httpRequest = (HttpServletRequest) servletRequest;
        return httpRequest;
    }

這樣就可以在 processaction和doview,這樣寫

HttpServletRequest httpRequest = getHttpRequest(request);

沒有留言:

張貼留言