How to set a Cookie in Liferay portlet?

前端 未结 1 637
后悔当初
后悔当初 2021-01-02 14:59

I am having problems of trying to set a session cookie(s) in Liferay 6.0 portlets. I want to be able to set a cookie to the client browser to store applicat

相关标签:
1条回答
  • 2021-01-02 15:22

    Without heavily modifying the Liferay portal itself, I found that the only way to set the portlet cookies is to have the portlet generate a javascript, which will then let the client set the cookie.

    So I added the following to the doView method.

    if (renderRequest.getPortletSession(true).getAttribute("set_cookie")!=null){
        return;
    }
    
    String cookie_value = renderRequest.getPortletSession(true).getId();
    String cookie_hours = "6";
    
    StringBuffer buf = new StringBuffer();
    buf.append("\n <script>");
    buf.append("\n var today = new Date();");
    buf.append("\n var expires_date = new Date ( today.getTime() + (" + cookie_hours + "*1000*60*60) );");
    buf.append("\n document.cookie = \"linkedIn=" + util.getAppKey() + ";expires=\"+expires_date.toGMTString();");    
    buf.append("\n </script>");
    
    renderResponse.setContentType("text/html");
    PrintWriter out = renderResponse.getWriter();
    out.println(buf.toString());
    renderRequest.getPortletSession(true).setAttribute(SET_COOKIE, cookie_value);
    

    Not an optimal, but a working solution nethertheless ;)

    0 讨论(0)
提交回复
热议问题