java 如何在 Liferay Portlet 中设置 Cookie?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3749199/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 03:15:13  来源:igfitidea点击:

How to set a Cookie in Liferay portlet?

javaportletliferay

提问by

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.

我在尝试在Liferay 6.0 portlet 中设置会话 cookie 时遇到问题。我希望能够为客户端浏览器设置一个 cookie,以存储用于 Linkedin 身份验证的应用程序密钥,然后其他 portlet 可以在其中检索它。

I am able to read cookies by using a following:

我可以使用以下方法读取 cookie:

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

采纳答案by

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.

在没有大量修改 Liferay 门户本身的情况下,我发现设置 portlet cookie 的唯一方法是让 portlet 生成一个 javascript,然后让客户端设置 cookie。

So I added the following to the doView method.

所以我在 doView 方法中添加了以下内容。

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

尽管如此,这不是最佳方案,而是可行的解决方案;)