An Introduction to Portal and Portlets

Embed Size (px)

Citation preview

  • 8/10/2019 An Introduction to Portal and Portlets

    1/18

  • 8/10/2019 An Introduction to Portal and Portlets

    2/18

    I believe, most of all have used i-Google(http://www.google.com/ig). Now thats perfectexample of a Portal.

    Following figure shows whats explained above:

    Here entire application i-Google can be seen as a Portal and each individual application(Gmail, Todays Horoscope, Google Translate etc) running on the page (which you seein above figure) can be seen as individual Portlets.

    Here if we see, i-Google provides all the features described in the Portal definitionearlier. For example,

    1. Content AggregationIt aggregates content from individual portlet applicationand shows it as a single web page which you see in previous figure.

    2. Single Sign-OnOnce you log-in to i-Google. Thats it. You dont need to log-inagain to any portlet application which uses the same authentication platform. Forexample, Gmail as shown in previous figure.

    3.

    PersonalizationEach user can change the look and feel, color scheme etcaccording to his own choice by changing the theme.

    Good enough ! From so many techie definitions and example, now we can concludethat a Portal application is made-up of three main building blocks:

    http://www.google.com/ighttp://www.google.com/ighttp://1.bp.blogspot.com/-a8ozDI92Xtc/UwJZD_q1MnI/AAAAAAAAPzg/KtPGQvb4mDQ/s1600/PortalExample.jpghttp://www.google.com/ig
  • 8/10/2019 An Introduction to Portal and Portlets

    3/18

    Portal Portlets Portlet Container

    We already saw what is Portal and Portlets. But what is Portlet Container? Well hereit is:

    As we understood that a portlet is nothing but another type of java technology based

    web component, we definitely need a container where it can be hosted and run similarto web containers where we host the normal web applications (war files).

    A portlet container runs portlets and provides them with the required runtimeenvironment. A portlet container contains portlets and manages their lifecycle. It alsoprovides persistent storage for portlet preferences. A portlet container receivesrequests from the portal to execute requests on the portlets hosted by it.

    A portlet container is not responsible for aggregating the content produced by theportlets. It is the portal who takes care of it.

    A portal and a portlet container can be built together as a single component of anapplication suite or as two separate components of a portal application.

    Putting it all together, following figure gives a high level view of what a portalapplication consists of and how a request is processed.

    Here if you see, HTTPRequest from the client is further divided into two sub categories:Render Request and Action Request. (I will explain these with more details in my futureblogs on Portlets. Keep reading my blogs :-) )

    http://2.bp.blogspot.com/-yJTKzrFEQpM/UwJZUqfgQMI/AAAAAAAAPzo/__tvBaWO7Yw/s1600/PortalApplicationHighLevelView.jpg
  • 8/10/2019 An Introduction to Portal and Portlets

    4/18

    Portlets - Relationship With J2EE and Servlet Specification

    In my previous post -An Introduction to Portal and Portletswe had an overall ideaabout Portal and Portlets and got answer to many common questions like - What isPortal ? What is Portlet ? What is Portal Container ? What are the features provided byPortal applications ? etc.

    In this post, I will try to explain What is Portlet Specification? What isrelationship between Portlet API and J2EE specification? What is similaritiesand differences between Portlet API and Servlet Specification?

    Let's start with What is Portlet Specification?

    Portlet Specification, or Java Portlet Specification is a specification provided by JCP(Java Community Process)which defines Portlet API and standardizes rules for variouscomponents of Portlet API (like portlet preferences, user data, portlet request andresponse, deployment, packaging, security etc) to achieve interoperability amongvarious portlets and portals.

    The first version of Portlet Specification(JSR-168)was released in October, 2003.In February 2006, the second enhanced version of Portlet Sepecification(JSR-286).

    (To learn about differences between JSR-168 and JSR-286, keep following my futureposts :-) )

    Well, we all know that for Web Applications, a specification is already there named:J2EE (Java 2 Enterprise Edition) specification. Then why we need a separatespecification for Portlets.

    The answer lies in similarities and differences between Portal application (or Portlets)and Web Applications (or Servlets).

    Just have a look at following pictorial comparison between a J2EE Web Application and aPortal Application.

    Web Application vs Portal ApplicationDon't both of them look and work in almost same manner? For example, a webapplication can contain multiple servlets and a portal application can contain multipleportlet applications. Servlets process incoming requets and generates output (HTML),

    same way, portlets also process incoming requests and generates markup fragments (apart of entire output).

    Yet, there are some subtle differences. For example, incoming requests in case ofportlets are further divided into two categories: ActionRequests and RenderRequests(Keep following my future posts for more details about Request Types in Portlets),portal does content aggregations from different portlets before sending output back tothe client. Each portlet can have their own preferences (called portlet prefrences),portal provides personalization and other features which a general web applicationdoesn't do.

    From above, what we can say is that portal applications are sophisticated version ofweb applications with all the features a web application provides along with somespecialized features like content aggregation, personalization, single sign-onetc. Similarly, portlets are also analogous to servlets in terms of functionality, conceptsand behavior.

    http://ajax-and-portlets.blogspot.com/2011/09/introduction-to-portal-and-portlets.htmlhttp://ajax-and-portlets.blogspot.com/2011/09/introduction-to-portal-and-portlets.htmlhttp://ajax-and-portlets.blogspot.com/2011/09/introduction-to-portal-and-portlets.htmlhttp://jcp.org/en/home/indexhttp://jcp.org/en/home/indexhttp://jcp.org/en/home/indexhttp://jcp.org/aboutJava/communityprocess/final/jsr168/http://jcp.org/aboutJava/communityprocess/final/jsr168/http://jcp.org/aboutJava/communityprocess/final/jsr168/http://jcp.org/aboutJava/communityprocess/final/jsr286/http://jcp.org/aboutJava/communityprocess/final/jsr286/http://jcp.org/aboutJava/communityprocess/final/jsr286/http://jcp.org/aboutJava/communityprocess/final/jsr286/http://jcp.org/aboutJava/communityprocess/final/jsr168/http://jcp.org/en/home/indexhttp://jcp.org/en/home/indexhttp://ajax-and-portlets.blogspot.com/2011/09/introduction-to-portal-and-portlets.html
  • 8/10/2019 An Introduction to Portal and Portlets

    5/18

    Due to all these reasons, Portlet Specificaiton (or Portlet API V1.0) is based on J2EEV1.3 specification. Portlets and Portlet Containers meet all the requreiments specifiedin J2EE specification. Poerlet API V1.0 derives many functional and behavioralspecifications from Servlet Specificaton 2.3.

    Similarly, Portlet API 2.0 is based on J2EE V1.4 and Servlet Specification 2.4.

    Following table provides comparision between Portlet and Servlets from various angle:

    Servlets Portlets

    Servlets are Java technologybased web components which aremanaged by Servlet Container orServlet Engine

    Servlets are Java technologybased web components which aremanaged by specializedcontainers called Portlet Container

    Servlets generates dynamiccontent as output

    Portlets also generates dynamiccontents as output but the outputis only fragment of the markupwhich will be aggregated by portalinto final page

    Servlets works viarequest/response mechanism

    Portlets also work viarequest/response mechanism,however,portlet request/responsemechanism is more refined(further categorized into actionrequest and render request)

    Servlets are directly bound toURLs

    Portlets are not directly bound toURLs

    Servlets dont have concept ofmodes and window states

    Portlets have pre-defined modes(View,Edit,Help etc) and windowstates(minimized,normal,maximized)

    In servlet, there is no concept ofmultiple instances because theydo not directly have any visibilityon client side.

    Portlet can exists multiple timeson a single page each instancebeing independent of each other

    Servlets dont have any concept ofpreferences to store any

    customization data like portlets

    Portlets have concept of PortletPreferences where you can store

    and retrieve any customizationand configuration data specific tothat particular instance of theportlet on the page

    Servlets dont have access to userprofile information (infact in webapp, there is no direct concept ofuser profile)

    Portlets have access to userprofile information

    Servlets do not have URLrewriting functions similar to

    Portlets

    Portlets have URL rewritingfunctions for creating hyperlinks

    within their content, which allowportal server indenpendentcreation of links and actions inpage fragments

    Servlet session has only one Portlet session is further divided

  • 8/10/2019 An Introduction to Portal and Portlets

    6/18

    common scope for store sessionlevel data

    into two scopes: Application-Widescope and Portlets Private scope.

    Servlets have access to clientrequest URLs, can set characterencoding and HTTP headers onresponse.

    Portlets dont have access to clientrequest URLs directly and cannotset character encoding or HTTPheaders on the response.

    A portlet application can contain JSPs and Servelts bundled with Portets and sharesclassloader, application context and session.

    Portlets can leverage servlets, JSPs and JSP tab libraries to generate output markupfragments. A portlet can call a JSP or Servlet using portlet request dispatcher just like aservlet can invoke another servlet or JSP.

    When a portlet invokes a servlet or JSP,

    All the portlet request attributes gets transferred to servlet request. Attributes set in portlet session are accessible from servlet session and vice-

    versa.

    Both portlet and servlet shares same output stream.

    A portlet container is nothing but extension of servlet container. It can be built on top ofexisting servlet container or a portlet container itself can implement all the features of aservlet container.

    That's it on Portlet Specification and it's relationship with J2EE and Servlets.Keep following my future posts on more details about Portlet API.

    Ajax Best Practice in Portlets

    Since the time AJAX has come into picture and with various new AJAX frameworks (like DOJO,

    JQuery, Yahoo UI Library, Google Web Tollkit etc), most of the websites now-a-days are

    enriched with AJAX to provide Outstanding and Stunning GUI features to the users. With

    Portals and Portlet technologies, the web development has become even better than ever

    before.

    This being said, definitely there are plenty of scenarios where we would like to use AJAX with

    Portlets too. Now this is a bit tricky. There is a subtle difference in implementation (processing

    user request, serving web response, maintaining state, maintaining lifecycle of server side

    components like servlets, jsp etc) between regular web applications and portlet based

    applications. This difference makes AJAX implementation a bit tricky when it comes to Portlets.

    Here, I will explain how to implement AJAX in both JSR 168 and JSR 286 Portlets.

    Let's start understanding it with the difference I described above. Web applications don't have

    states/modes similar to Portlets (View Mode, Edit Mode etc).

  • 8/10/2019 An Introduction to Portal and Portlets

    7/18

    Following is a lifecycle diagram of a java based web application.

    Life cycle Of A Servlet Based Web Application

    Here as we see, all the request (be it a normal web request or an AJAX request) are processed

    by only 1 method: service method of the servlet. Also there is no need of generated markup

    (output HTML, XML etc by service method) aggregation as there is only 1 application running at

    a time.

    Now, moving to Portlets from Web Application, the scenario is a bit different. In case of

    portlets, there are multiple web-applications (called portlets) which runs in small i-frame like

    windows on a single web page. All of these portlets run under a Portal application (controller by

    portal container) which controls multiple aspects of the entire application like user-interaction

    with individual portlets, their window states (Minimized, Maximized etc), entire web-page output

    (which is eventually aggregation of markup generated by individual portlets) etc. Following

    block diagram illustrates how overall portal application works:

    http://1.bp.blogspot.com/-kjatQk7o-OQ/UwJbeL0z-YI/AAAAAAAAPz0/K2esaBSycSY/s1600/LifecycleOfAServletBasedWebApp.jpg
  • 8/10/2019 An Introduction to Portal and Portlets

    8/18

    Portal Web Application

    When user interacts with a particular portlet, portal container makes sure request is passed to

    appropriate portlet, and generated output (markup) is aggregated appropriately with entire web

    page output without affecting other portlets.

    Following diagram shows how request are processed in a portlet based application.

    http://3.bp.blogspot.com/-mX9NGMPUtKs/UwJb915pEgI/AAAAAAAAPz8/sVwPHOfaECw/s1600/PortalWebApplication.jpghttp://1.bp.blogspot.com/-mUafZVQ9T8c/UwJcsS70pbI/AAAAAAAAP0E/zID3e9U-vAw/s1600/Portlet+Cycle+Diagram.jpghttp://3.bp.blogspot.com/-mX9NGMPUtKs/UwJb915pEgI/AAAAAAAAPz8/sVwPHOfaECw/s1600/PortalWebApplication.jpghttp://1.bp.blogspot.com/-mUafZVQ9T8c/UwJcsS70pbI/AAAAAAAAP0E/zID3e9U-vAw/s1600/Portlet+Cycle+Diagram.jpghttp://3.bp.blogspot.com/-mX9NGMPUtKs/UwJb915pEgI/AAAAAAAAPz8/sVwPHOfaECw/s1600/PortalWebApplication.jpg
  • 8/10/2019 An Introduction to Portal and Portlets

    9/18

    Here we can see that web requests are divided into two categories:

    RenderRequest: These are the requests when portlets are in view mode and being rendered

    (e.g. when the first time users requests a web page via HTTP GET or POST URL request)

    ActionRequest: These are HTTP GET or POST requests initiated due to user interaction with

    portlet (e.g. clicking any URL on the page, submitting form etc).

    Here if we see, every request - be it a render request or action request, goes through render

    phase (doView() method). This means, Portlet URLs enable window state changes and mode

    changes that require a subsequent render request to the portal or portlet container. The result?

    The response contains not only the content for the target portlet, but also that for the entireportal, including all the other rendered portlets. This is true in case of AJAX request

    too. Following figure shows an example of a Sample JSR168 Portlet that made an asynchronous

    call with actionURL, causing the entire portal page to be embedded in the portlet window as a

    part of AJAX response. This is obviously what we don't want.

    AJAX Implementation in JSR-168 using processAction() method

    In above figure, we are supposed to get only "AJAX Response using Portlet 1.0 Spec -

    processAction() method ..." as AJAX response, however along with that, we got entire HTML

    of the portlet which got appended to the response by doView() method after request was

    processed by processAction() method.

    To resolve this problem, we have two solutions depending on which portlet spec. you are using.

    For JSR-168 based portlets, there is no provision in the portlet specification which says how to

    deal with AJAX requests.

    http://2.bp.blogspot.com/-Ceg4EFu760E/UwJc2ceQqAI/AAAAAAAAP0M/rtgopLruS_k/s1600/AJAX+Implementation+in+JSR-168+using+processAction()+method.jpg
  • 8/10/2019 An Introduction to Portal and Portlets

    10/18

    So for JSR-168 portlets, we have to follow a trick. Well, what's that ?

    Answer to this question lies in Portlet Specification 1.0 (JSR-168).

    Following is the snippet from Portlet Specification 1.0 :

    "A Portlet Application is also a Web Application. The Portlet Application may contain servlets and

    JSPs in addition to portlets. Portlets, servlets and JSPs may share information through their

    session.

    The PortletSessionmust store all attributes in the HttpSessionof the portlet application. A

    direct consequence of this is that data stored in the HttpSessionby servlets or JSPs is accessible

    to portlets through the PortletSessionin the portlet application scope. Conversely, data stored

    by portlets in the PortletSessionin the portlet application scope is accessible to servlets and

    JSPs through the HttpSession."

    This means, we can divide our logic into two pieces:

    For regular portlet requests, we can extend GenericPortlet class and implement doView() and

    processAction() methods in the normal way we always do.

    For Ajax requests, we can write a separate Servlet which will handle ajax requests like normal

    web applications do.

    Following figure shows what exactly I am talking about.

    http://1.bp.blogspot.com/-2vHWpDnXceY/UwJdMFbPydI/AAAAAAAAP0U/TNNi4KSL1cs/s1600/Ajax+Implementation+Best+Practice+for+JSR-186+Portlet.jpg
  • 8/10/2019 An Introduction to Portal and Portlets

    11/18

    Ajax Implementation Best Practice for JSR-168 Portlet

    So what all we need to do is:

    1. Write a class extending GenericPortlet (or any other portlet like MVCPortlet in Liferay etc) for

    regular general portlet request processing.

    2. Write a servlet to handle ajax requests like following:

    public class AjaxServlet extends HttpServlet {

    protected void doPost(HttpServletRequest request,

    HttpServletResponse response) throws ServletException, IOException {

    //Write your business logic for Ajax processing here

    }

    protected void doGet(HttpServletRequest request,

    HttpServletResponse response) throws ServletException, IOException {

    doPost(request, response);

    }

    }

    3. Write javascript functions to implement ajax call (preferably using some good javascript/ajax

    library like jquery, dojo etc).

    Following in an example of such a javascript function using jquery.

    function _callAjax()

    {

    var url='';

    //Make ajax call

    $.ajax({

  • 8/10/2019 An Introduction to Portal and Portlets

    12/18

    type : "POST",

    url : url,

    cache:false,

    dataType: "text",

    success : function(data)

    {

    //Write you success logic here

    },

    error : function(XMLHttpRequest, textStatus, errorThrown)

    {

    //Write you error-handling logic here

    }

    });

    };

    That's it. You are done :)

    Now, lets's move to JSR-286 Portlets (Portlet Specification 2.0). Here, the situation is better ina way that we don't have to worry about writing a separate servlet for Ajax requests. Portlet

    itself provides special method called serveResource(ResourceRequest request,

    ResourceResponse response) to do this.

    Requests made using ResourceRequest (generated by resourceURL tags provided by portlet

    taglib), are served by serveResource() methods.

    Following figure shows how it works:

  • 8/10/2019 An Introduction to Portal and Portlets

    13/18

    Ajax Implementation in JSR-286 Portlet

    Following is a sample PortletClass (extending GenericPortlet) showing how to do it.

    package com.jsr286.portlets;

    import java.io.IOException;

    import javax.portlet.ActionRequest;

    import javax.portlet.ActionResponse;

    import javax.portlet.GenericPortlet;

    import javax.portlet.PortletException;

    import javax.portlet.PortletRequestDispatcher;

    import javax.portlet.RenderRequest;

    import javax.portlet.RenderResponse;

    import javax.portlet.ResourceRequest;

    import javax.portlet.ResourceResponse;

    import com.liferay.portal.util.PortalUtil;

    public class TestPortlet extends GenericPortlet {

    protected String viewJSP;

    http://3.bp.blogspot.com/-I_PUhLN5bV0/UwJdcOgF7eI/AAAAAAAAP0c/9i1W2sQuhSM/s1600/Ajax+Implementation+in+JSR-286+Portlet.jpg
  • 8/10/2019 An Introduction to Portal and Portlets

    14/18

    public void init() throws PortletException

    {

    viewJSP = getInitParameter("view-jsp");

    }

    protected void doView(RenderRequest request, RenderResponse response)

    throws PortletException, IOException {

    System.out.println("########### Inside com.jsr286.portlets.TestPortlet ... doView()

    method.....");

    include(viewJSP, request, response);

    }

    public void processAction(ActionRequest request, ActionResponse response)

    throws PortletException, IOException {

    System.out.println("########### Inside com.jsr286.portlets.TestPortlet ...

    processAction() method.....");

    HttpServletResponse httpResp = PortalUtil.getHttpServletResponse(response);httpResp.setContentType("text");

    httpResp.getWriter().print("AJAX Response using Portlet 2.0 Spec - processAction()

    method .... ");

    httpResp.flushBuffer();

    return;

    }

    protected void include(String path, RenderRequest renderRequest,RenderResponse

    renderResponse) throws IOException, PortletException

    {

    PortletRequestDispatcher portletRequestDispatcher =

    getPortletContext().getRequestDispatcher(path);

    if (portletRequestDispatcher == null)

    {

    System.out.println(path + " is not a valid include");

    } else

    {

  • 8/10/2019 An Introduction to Portal and Portlets

    15/18

    portletRequestDispatcher.include(renderRequest, renderResponse);

    }

    }

    public void serveResource(ResourceRequest request, ResourceResponse

    response) throws PortletException,IOException

    {

    System.out.println("########### Inside com.jsr286.portlets.TestPortlet ...

    serveResource() method.....");

    response.setContentType("text");

    response.resetBuffer();

    response.getWriter().print("Correct Ajax Resopnse from Portlet 2.0 Spec -

    serveResource() method .... ");

    response.flushBuffer();

    }

    }

    And following is a JSP fragment showing how to place AJAX call using resourceURL.

    function _callAjax()

    {

    var url = ';

    //Make ajax call

    $.ajax({

    type : "POST",

  • 8/10/2019 An Introduction to Portal and Portlets

    16/18

    url : url,

    cache:false,

    dataType: "text",

    success : function(data)

    {

    //Write you success logic here

    },

    error : function(XMLHttpRequest, textStatus, errorThrown)

    {

    //Write you error-handling logic here

    }

    });

    };

    That's it on how to implement AJAX in both JSR-168 and JSR-286 portlets.

    Please provide your valuable comments/suggestions.

    Opening Portlet with Maximized Window in Render Mode

    There is no provision in portlet API for opening a portlet with maximized window in render mode(doView() method). When a portlet gets loaded into browser for the first time, it always opens

    up in normal window.

    I happened to come across a scenario where I had to open-up portlet in a maximized window

    which I achieved in following way:

    javax.portlet.PortletURL object allows to set Window State. We can utilize this facility in

    following way to open a portlet with maximized window in render (doView() method) mode.

    1. In doView method, Generate a render URL from renderResponse.

    2. Add all the request parameters from renderRequest to these new URL.

    3. Set window state to Maximized on this new URL.

    4. Set this new URL value as renderRequest attribute and pass the control to view.jsp (your jsp

    file which generates output in render mode).

    5. In view.jsp, retreive the URL we created in step-1 and redirect the page to this new URLusing javascript by setting location.href value.

    That's it. Next time, when the portlet will be rendered, it will open up in Maximized mode.

  • 8/10/2019 An Introduction to Portal and Portlets

    17/18

  • 8/10/2019 An Introduction to Portal and Portlets

    18/18

    PortletRequestDispatcher portletRequestDispatcher =

    getPortletContext().getRequestDispatcher(path);

    if (portletRequestDispatcher == null)

    {

    Logger.error(path + " is not a valid include");

    }

    else

    {

    portletRequestDispatcher.include(renderRequest, renderResponse);

    }

    }

    In view.jsp,

    var maximizedFlag = '';

    //Redirect to New Render URL only if current window is not in maximized state

    if(maximizedFlag=='false')

    {

    location.href='';

    }