如何在Liferay portlet中设置Cookie? [英] How to set a Cookie in Liferay portlet?
问题描述
我在尝试在 Liferay 6.0 portlet 中设置会话cookie时遇到问题。我希望能够将cookie设置为客户端浏览器以存储用于linkedin身份验证的应用程序密钥,然后可以通过其他portlet检索它。
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 application key for the linkedin authentication, where it can be then retrieved by other portlets.
我能够使用以下内容读取cookie:
I am able to read cookies by using a following:
public void addLinkedInCV(ActionRequest request, ActionResponse response)
throws PortalException, SystemException {
HttpServletRequest convertReq = PortalUtil.getHttpServletRequest(request);
Cookie[] cookies = convertReq.getCookies();
...
}
这是我尝试阅读的失败。
Here's my failed attempt to read one.
@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。
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.
所以我在doView方法中添加了以下内容。
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 ;)
这篇关于如何在Liferay portlet中设置Cookie?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!