How to set a Cookie in Liferay portlet?

♀尐吖头ヾ 提交于 2019-11-30 13:47:43

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 ;)

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!