我在尝试在Liferay 6.0 portlet中设置会话cookie时遇到问题.我希望能够将cookie设置到客户端浏览器以存储用于linkedin身份验证的应用程序密钥,然后可以由其他portlet检索它.
我可以使用以下内容读取cookie:
public void addLinkedInCV(ActionRequest request,ActionResponse response) throws PortalException,SystemException { HttpServletRequest convertReq = PortalUtil.getHttpServletRequest(request); Cookie[] cookies = convertReq.getCookies(); ... }
这是我尝试阅读一个失败的尝试.
@Override public void doView(RenderRequest renderRequest,RenderResponse renderResponse) throws IOException,PortletException { HttpServletResponse convertRes = PortalUtil.getHttpServletResponse(renderResponse); HttpServletResponse originalRes = (HttpServletResponse) ((HttpServletResponseWrapper) convertRes).getResponse(); Cookie linkedInCookie = new Cookie("linkedIn",util.getAppKey()); originalRes.addCookie(linkedInCookie); }
解决方法
在没有大量修改Liferay门户本身的情况下,我发现设置portlet cookie的唯一方法是让portlet生成一个javascript,然后让客户端设置cookie.
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);
虽然不是最佳的,但仍然是一种有效的解决方案;)