PortletSession特别适用于同一个Portlet应用下的多个Portlet之间交互。
步骤1:把要交互的多个Portlet都定义在同一个portlet.xml中
- <portlet-app...>
- <portlet>
- <portlet-name>recentBook</portlet-name>
- <portlet-class>
- chapter11.code.listing.base.RecentlyAddedBookPortlet
- </portlet-class>
- <expiration-cache>0</expiration-cache>
- <cache-scope>private</cache-scope>
- ...
- <resource-bundle>
- content.Language-ext
- </resource-bundle>
- <portlet-info>
- <title>Recently Added Book</title>
- </portlet-info>
- </portlet>
- <portlet>
- <portlet-name>bookCatalog</portlet-name>
- <portlet-class>
- chapter11.code.listing.base.BookCatalogPortlet
- </portlet-class>
- ...
- <expiration-cache>60</expiration-cache>
- <cache-scope>private</cache-scope>
- ...
- <resource-bundle>
- content.Language-ext
- </resource-bundle>
- <portlet-info>
- <title>Book Catalog</title>
- </portlet-info>
- ...
- </portlet>
- ...
- </portlet-app>
步骤2:在代码中使用PortletSession来存/取 数据:
一般Portlet交互,从其行为看,分为发送者Portlet和接收者Portlet:
发送者Portlet会添加数据到PortletSession的APPLICATION_SCOPE上来使得这数据可以跨Portlet交互:
- @ProcessAction(name = "addBookAction")
- public void addBook(ActionRequest request,
- ActionResponse response)throws... {
- ...
- if (errorMap.isEmpty()) {
- //调用bookService让其添加一本书到book catalog中
- bookService.addBook(new Book(category, name, author, Long.valueOf(isbnNumber))); //将书的ISBN号添加到PortletSession的APPLICATION_SCOPE上用于Portlet之间的交互
- request.getPortletSession().setAttribute ("recentBookIsbn", isbnNumber, PortletSession.APPLICATION_SCOPE);
- ...
- }
- }
接收者Portlet会从PortletSession的APPLICATION_SCOPE上吧数据拿下来用于处理或者显示:
- public class RecentlyAddedBookPortlet extends GenericPortlet @RenderMode(name="view")
- public void showRecentBook(RenderRequest request,
- RenderResponse response)throws ...{
- //从PortletSession的APPLICATION_SCOPE上获取用于交互的数据
- String isbnNumber = (String)request.getPortletSession().getAttribute("recentBookIsbn", PortletSession.APPLICATION_SCOPE);
- ...
- //获取数据(ISBN号)之后,如果不为空,则让bookService基于这个isbn号进行查询返回对应的书,否则返回最近一本书
- if(isbnNumber != null) {
- if(bookService.isRecentBook
- (Long.valueOf(isbnNumber))) {
- book = bookService.getBook(Long.valueOf(isbnNumber));
- } else {
- book = bookService.getRecentBook();
- }
- } else {
- book = bookService.getRecentBook();
- }
- //把获得的书的内容放到RenderRequest上
- request.setAttribute("book", book);
- //让Portlet引擎用添加的书的内容渲染到指定JSP页面上
- getPortletContext().getRequestDispatcher( response.encodeURL(Constants.PATH_TO_JSP_PAGE + "recentPortletHome.jsp")).include(...);
- }
- }
有些Portal服务器有额外的在跨Portlet应用的Portlet之间共享session数据的方法,比如Liferay Portal中,可以在portal-ext.properties中定义session.shared.attributes属性,在liferay-portlet.xml中定义<private-session-attributes>元素,但是这些方法会导致移植性问题