简体   繁体   中英

How to set a Cookie in Liferay 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.

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM