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-name>bookCatalog</portlet-name>
chapter11.code.listing.base.BookCatalogPortlet
<expiration-cache>60</expiration-cache>
<title>Book Catalog</title>
</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();
//把獲得的書的内容放到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>元素,但是這些方法會導緻移植性問題
本文轉自 charles_wang888 51CTO部落格,原文連結:http://blog.51cto.com/supercharles888/847440,如需轉載請自行聯系原作者