java - Liferay 7 共享 session 属性

标签 java tomcat liferay

我正在尝试使用 Liferay 共享 session 属性。

我想在不同 URL 上的不同 WAR 文件中的两个不同 portlet 上使用相同的属性,使用以下代码基于:

Liferay 7 not able to set the global session attribute

我要保存的值:一个字符串

在 portlet 1 中设置:

String sharedKey = "LIFERAY_SHARED_" + key;
HttpSession session = PortalSessionThreadLocal.getHttpSession();
session.setAttribute(sharedKey, bean);

Portlet 1 能够很好地保留、重置和使用属性。

在 portlet 2 中读取:

key = "LIFERAY_SHARED_" + key;
HttpSession session = PortalSessionThreadLocal.getHttpSession();
Object bean = session.getAttribute(key);

此值始终为 null。

这两个 portlet 都是 Spring MVC portlet。

两个 portlet 都有:

<instanceable>false</instanceable>
<private-session-attributes>false</private-session-attributes>
<requires-namespaced-parameters>false</requires-namespaced-parameters>

在他们的 liferay portlet XML-s 中。

两个 portlet 都扩展了 org.springframework.web.portlet.DispatcherPortlet。

Liferay 版本:

Liferay DXP 数字企业 7.0.10 GA1

如有任何帮助,我们将不胜感激。 让我知道是否有人需要任何澄清。

非常感谢, 彼得

最佳答案

Kyle Stiemann 最近写了一篇 nice article on using sessions在 portlet 中。 TL;DR:您正在使用带有前缀"LIFERAY_SHARED_" 属性的 HttpSession,但您应该使用 portlet session :这就是 Liferay 管理的,HttpSession 可能是“模拟的”,例如可能不是tomcat管理的对象。

引用他文章中的一个选项:

Use Liferay session.shared.attributes prefixes (such as LIFERAY_SHARED_) to share one or more session attributes between portlets in different applications/WARs.

Liferay exposes certain session attributes to all portlets based on certain prefix values. Although these prefixes are configurable via portal-ext.properties, I recommend using one of the default prefixes: LIFERAY_SHARED_.

For example:

// Portlet A 
portletRequest.getPortletSession(true)
    .setAttribute("LIFERAY_SHARED_" + CONSTANTS.ATTR_NAME, "value", 
                  PortletSession.APPLICATION_SCOPE);

// Portlet B (in a different WAR) 
String attrValue = portletRequest.getPortletSession(true)
    .getAttribute("LIFERAY_SHARED_" + CONSTANTS.ATTR_NAME, 
                  PortletSession.APPLICATION_SCOPE);

Pros:

  • Only exposes the necessary attribute(s) to other portlets (instead of exposing the entire session).

Cons:

  • Exposes session attribute(s) to all portlets.
  • Tight coupling without indicating which other portlets might be utilizing this data.
  • Non-standard method of sharing session data.

请注意,强烈建议仅使用原始类型作为 session 属性。消除自定义序列化和类加载问题的需要。另请注意,此处需要具有附加范围参数的 getPortletSession 变体。

但是,尽管这在技术上为您的问题提供了答案,但您还想阅读 "Session Storage is Evil" .

TL;DR:不要使用上述技术。而是消除 session 的使用。

关于java - Liferay 7 共享 session 属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54558922/

相关文章:

java - 如何使我的 Spring portlet URL 友好?

java - 组织与集团关系

java - 在 Android 中使用 Google 帐户登录

java - 如何使用 Fluent 等待 Listbox WebElement

java - Tomcat + Servlet + Solr 国际字符不正确

java - 一种在Java应用程序启动时加载大量资源的方法

java - 如何在liferay中通过代码动态添加iframe

java - JFileChooser 似乎正在运行,但没有显示

java - 通过扩展 Thread 类来创建 Thread

java - 使用 Tomcat 5.5,如何以编程方式定位特定的 servlet 实例或添加新的映射?