ResourceServingPortlet是從Portlet 2.0才引入的接口,若是使用了它,就沒有必要使用servlet來處理資源或者處理Ajax請求了。app
- public abstract interface ResourceServingPortlet
- {
- public abstract void serveResource(ResourceRequest paramResourceRequest, ResourceResponse paramResourceResponse)
- throws PortletException, IOException;
- }
這個接口能夠讓Portlet容器來處理和資源相關的請求。值得一提的是,這個ResourceResponse能夠讓Portlet容器渲染jsp頁面,也能夠渲染二進制內容。jsp
還有一點很是很是重要:就是當一個resource請求到達某個Portlet時候,Portlet容器會調用這個Portlet的serveResource方法,可是這個Portlet的render方法,乃至同一個Portal 頁面上的全部的其餘的Portlet的render方法都不會被調用。ide
步驟1: 首先在Portlet中定義一個resource,這裏咱們給了一個resourceURL,由於GenericPortlet已經實現了 ResourceServingPortlet,因此這裏無需顯示的實現它並且能夠直接使用serveResource方法函數
- public class DateTimePortlet extends GenericPortlet {
- @RenderMode(name = "view")
- public void showHomePage(...)... {
//建立一個ResourceURL,他將會在頁面上被點擊連接事件所使用到- ResourceURL dateTimeResourceURL = response.createResourceURL();
//給這個ResourceURL賦值惟一的資源ID- dateTimeResourceURL.setResourceID("dateTime");
- //將這個resourceURL放在RenderRequest的屬性上
- request.setAttribute("dateTimeResourceURL", dateTimeResourceURL);
- getPortletContext().getRequestDispatcher(
- //請求分發到頁面來渲染
- response.encodeURL("/WEB-INF/jsp/home.jsp")).
- include(request, response);
- }
- ...
- }
步驟2:而後在這個Portlet中定義一個事件處理函數,來響應從頁面發來的Ajax請求spa
- public class DateTimePortlet extends GenericPortlet {
- @RenderMode(name = "view")
- public void showHomePage(...)... {
- }
- ...
- public void serveResource(...)...{
- OutputStream outStream
- = response.getPortletOutputStream();
- StringBuffer buffer = new StringBuffer();
- if (request.isUserInRole("User")) {
- SimpleDateFormat sdf = new SimpleDateFormat(
- "dd-MMM-yyyy hh:mm:ss a");
- buffer.append("Hello World (<i> "
- + sdf.format(new Date())+ " </i>)");
- } else {
- buffer.append("<font color=\"red\"> You are not authorized to view server date/time");
- }
- outStream.write(buffer.toString().getBytes());
- }
- }