websphere portal technical conference europe 2007 session number: d03 developing ajax-enabled...

53
WebSphere Portal Technical Conference Europe 2007 WebSphere Portal Technical Conference Europe 2007 Session Number: D03 Developing AJAX-enabled Portlets in WebSphere Portal 6: Concepts, Patterns and Best Practices Stefan Behl, WebSphere Portal Web 2.0 Development Engineer

Upload: jasper-barton

Post on 04-Jan-2016

218 views

Category:

Documents


3 download

TRANSCRIPT

Page 1: WebSphere Portal Technical Conference Europe 2007 Session Number: D03 Developing AJAX-enabled Portlets in WebSphere Portal 6: Concepts, Patterns and Best

WebSphere Portal Technical Conference Europe 2007WebSphere Portal Technical Conference Europe 2007Session Number: D03

Developing AJAX-enabled Portlets in WebSphere Portal 6:Concepts, Patterns and Best Practices

Stefan Behl, WebSphere Portal Web 2.0 Development Engineer

Page 2: WebSphere Portal Technical Conference Europe 2007 Session Number: D03 Developing AJAX-enabled Portlets in WebSphere Portal 6: Concepts, Patterns and Best

WebSphere Portal Technical Conference Europe 20072

Disclaimer

The following includes material that isdirectional in nature and does not imply anyproduct plan commitment on the part of IBM.

Screenshots in this presentation are fromprototypes and likely to change significantly

by the time products are released.

Page 3: WebSphere Portal Technical Conference Europe 2007 Session Number: D03 Developing AJAX-enabled Portlets in WebSphere Portal 6: Concepts, Patterns and Best

WebSphere Portal Technical Conference Europe 20073

Agenda

Introducing AJAX and related technologiesAJAXRESTBrowser featuresFrameworks

Using AJAX in a portal environmentChallengesClient-side aggregation

Developing AJAX portletsDeveloping AJAX portlets for WebSphere Portal 6.0Evolution of portlet standards: AJAX support in JSR 286 and WSRP 2.0AJAX support in WebSphere Portal 6.1

Summary

Page 4: WebSphere Portal Technical Conference Europe 2007 Session Number: D03 Developing AJAX-enabled Portlets in WebSphere Portal 6: Concepts, Patterns and Best

WebSphere Portal Technical Conference Europe 2007WebSphere Portal Technical Conference Europe 2007

Part I

Introducing AJAXand related technologies

Page 5: WebSphere Portal Technical Conference Europe 2007 Session Number: D03 Developing AJAX-enabled Portlets in WebSphere Portal 6: Concepts, Patterns and Best

WebSphere Portal Technical Conference Europe 20075

Browser

What is AJAX ?

AJAX is the acronym for Asynchronous JavaScript and XML

The purpose is to create more dynamic and responsive web pages

It is a pattern where a page view displayed in a web browser retrieves data or markup fragments from a service and refreshes just a part of the page

Markup(HTML)

Data(XML)

Request Services

Server

Page 6: WebSphere Portal Technical Conference Europe 2007 Session Number: D03 Developing AJAX-enabled Portlets in WebSphere Portal 6: Concepts, Patterns and Best

WebSphere Portal Technical Conference Europe 20076

What is AJAX ? (cont.)

AJAX is NOT hypeIt is very real and very useful for highly interactive applications

AJAX enables major improvements in responsiveness and performance

Examples: Yahoo! Mail, Google Maps, live.com, etc.AJAX is not only appealing to cool web sites but also to enterprise customers

AJAX is based on existing technologies and standardsHTML, Javascript & DOM, REST, XML / XSLT, ATOM / APP, Web ServicesNot always XML – other data formats such as JSON, HTML can be used as wellNot always asynchronous

AJAX is not trivialWithout tools, it requires requires deep and broad skills in web developmentBut: the benefits to be gained can be huge compared to classic web applications

Page 7: WebSphere Portal Technical Conference Europe 2007 Session Number: D03 Developing AJAX-enabled Portlets in WebSphere Portal 6: Concepts, Patterns and Best

WebSphere Portal Technical Conference Europe 20077

AJAX – Advantages and Challenges

Advantages

Improved UI response times and better usability due to asynchronous data transfer and direct markup updates on the client

Better scalability and improved failure safety due to workload distribution and decoupling of services

Reduced server load due to client-side processing and rendering

Extremely helpful in complex web pages aggregating many different fragments allows to update single page fragments

Challenges

Currently there is no AJAX standard; browsers behave differently and have different APIs

Higher complexity: Developers need to deal with a variety of technologies, like XML parsing, DOM manipulation, JavaScript and browser specific issues

Bypasses standard browser paradigms (e.g. back button, reload); requires extra effort to get these paradigms working again

Complex web pages with different topics typically have inter-dependencies that have to be managed

Page 8: WebSphere Portal Technical Conference Europe 2007 Session Number: D03 Developing AJAX-enabled Portlets in WebSphere Portal 6: Concepts, Patterns and Best

WebSphere Portal Technical Conference Europe 20078

What is REST?

REST is the acronym for Representational State Transfer

It is the architectural model on which the World Wide Web is based

Principles of RESTResource-centric approachAll relevant resources are addressable via URIsStateless prototcol based on HTTP GET, POST, PUT, and DELETEContent type negotiation allows retrieving alternative representations from same URI

REST style servicesEasy to access from code running in web browsers, any other client or servers very popular in the context of AJAXCan take full advantage of the WWW caching infrastructureCan serve multiple representations of the same resource

More info: http://www.ics.uci.edu/~fielding/pubs/dissertation/top.htm

Page 9: WebSphere Portal Technical Conference Europe 2007 Session Number: D03 Developing AJAX-enabled Portlets in WebSphere Portal 6: Concepts, Patterns and Best

WebSphere Portal Technical Conference Europe 200710

Frameworks

WebSphere Portlet Factory 6.0Incremental Search Builder

• Type-ahead field: provides a drop-down list of suggestions to users as they typeAsynchronous Client Loader Builder

• Allows a portlet to update without refreshing the entire Portal pageAny action can easily be exposed as a REST-style serviceEspecially useful when combined with back-end integration builders

DoJoJavascript framework (Abstraction Layer to allow browser independence)Many widgets availableRich Javascript framework that can be used within portlets

AJAX and JSF combined: JSF Widget Set (JWL)Extends the JSF server-side programming model to the clientAdds visual components to the AJAX approachProvides client-side XML data model with updates on client sideFull visual tooling via Rational Application Developer (RAD)Recommended if you want to use the AJAX pattern in your portlets

Page 10: WebSphere Portal Technical Conference Europe 2007 Session Number: D03 Developing AJAX-enabled Portlets in WebSphere Portal 6: Concepts, Patterns and Best

WebSphere Portal Technical Conference Europe 200711

WebSphere Portlet Factory: AJAX Builders In Action

Type-ahead

Partial-pagerefresh

Client-side Data access viaREST service

Page 11: WebSphere Portal Technical Conference Europe 2007 Session Number: D03 Developing AJAX-enabled Portlets in WebSphere Portal 6: Concepts, Patterns and Best

WebSphere Portal Technical Conference Europe 2007WebSphere Portal Technical Conference Europe 2007

Part II

Using AJAX in a Portal Environment

Why AJAX has special challenges in a portal environmentClient-side aggregation

Page 12: WebSphere Portal Technical Conference Europe 2007 Session Number: D03 Developing AJAX-enabled Portlets in WebSphere Portal 6: Concepts, Patterns and Best

WebSphere Portal Technical Conference Europe 200713

Main Challenge: Supporting Web Capabilities

AJAX bypasses standard browser paradigms and Web capabilitiesE.g. back button, bookmarkability, reload, caching, crawlabilityRequires extra effort to get these capabilities working again

In a portal environment this is even more challengingComponents (typically portlets) are combined with other components into a larger portal applicationURLs can no longer be generated in an isolated manner as a portal URL needs to encode the navigational state of the entire portal pageNavigational state is the aggregation of

• Portal state: Page selection, theme template, etc.• Portlet states: Render parameters, portlet mode, window state

Restrictions due to navigational state behaviorAJAX is tailored towards replacing fragments on a page

• This leads to problems with navigational state as it is part of every URLAs a consequence, portlets cannot simply create URLs that change navigational state / render parametersNavigational state changes require support from a portal-aware Javascript library

• Conceptually, every URL on the page needs to be updated

Page 13: WebSphere Portal Technical Conference Europe 2007 Session Number: D03 Developing AJAX-enabled Portlets in WebSphere Portal 6: Concepts, Patterns and Best

WebSphere Portal Technical Conference Europe 200714

Bookmarkability, Back Button, Multiple Windows

Capability Web 1.0 Web 2.0

Bookmarkability

A user can create a browser bookmark from any link on a page. Each link contains the latest navigational state of all portal artifacts visited so far.

Available through different means

Can be supported with a special „Bookmark this page“ link. A user would have to select this link to create URL that is bookmarkable.

Back Button Forward Button Reload

A user can navigate using the browsers back, forward and reload button with the expected behavior (e.g. like static html pages).

Limited support available

Javascript Frameworks such as DoJo support back and forward button in a limited fashion. It is not working in Safari and for the reload scenario. The history of back and forward button is also not working as expected from the Web 1.0 behavior.

Multiple Browser Window Support

A user can open multiple browser windows or tabs and navigate through portal independently using any link on the page. Every window/tab has its own state.

Partially available

A user can open a new browser window or tab to a new view. However, true independent navigation is not possible. The latest view will always be shown in the window the user navigates last.

Page 14: WebSphere Portal Technical Conference Europe 2007 Session Number: D03 Developing AJAX-enabled Portlets in WebSphere Portal 6: Concepts, Patterns and Best

WebSphere Portal Technical Conference Europe 200715

Crawlability and Caching

Capability Web 1.0 Web 2.0

Crawlability The markup that is returned from a portlet is analyzed by the search engine. Best practice is to return special markup when a portlet is accessed by a search engine. For simple portlets this might not be required.

Not available

An AJAX portlet needs to be enabled explicitly by returning markup directly on the server side. The search engine does not understand Javascript.

Browser & Reverse Proxy Caching

The full portal page is cached in a reverse proxy or browser cache. Therefore the page expires with the time of the shortest expiration of all artifacts on the page. Artifacts with a long expiration time would still be loaded in this case.

Available

Each artifact on the page is loaded on demand from within the browser. Therefore, the reverse proxy and browser cache hold each artifact on its own with the maximum effect for cachability. When an artifact never expires it is not loaded again with follow-on request.

Page 15: WebSphere Portal Technical Conference Europe 2007 Session Number: D03 Developing AJAX-enabled Portlets in WebSphere Portal 6: Concepts, Patterns and Best

WebSphere Portal Technical Conference Europe 200716

Portal WAR

Without AJAX – The classic portal

Browser

RequestPortlet

WAR

Response

WAR

Portlet

WAR

WAR

Portlet

WAR WAR

Portlet

WAR

Each request goes to the main portal servlet

Each interaction causes a full page refreshEven if the portlet does not communicate with other portlets

Serv

let

Click

Portal Server

Page 16: WebSphere Portal Technical Conference Europe 2007 Session Number: D03 Developing AJAX-enabled Portlets in WebSphere Portal 6: Concepts, Patterns and Best

WebSphere Portal Technical Conference Europe 200717

Using AJAX in Portals

A portal page is normally composed of lots of fragmentsHeader, footerNavigationToolbarsPortletsUI widgets inside the portlets

User interaction will typically only affect a single fragmentLots of situations where applying AJAX makes sense!

Page 17: WebSphere Portal Technical Conference Europe 2007 Session Number: D03 Developing AJAX-enabled Portlets in WebSphere Portal 6: Concepts, Patterns and Best

WebSphere Portal Technical Conference Europe 200718

Browser

AJAX flavor 1 – Client-side Aggregation

Client-side aggregation

Portal WAR

Portal Server

Portlet

WAR WAR

Portlet

WAR

WAR

Portlet

WAR WAR

Portlet

WAR

JS H

andle

r

Client-side aggregationBrowser-side page aggregation, navigation, and customization delivered with WebSphere Portal 6.1Implemented using AJAX, XML, Dojo, and JavaScript

AJAX handling implemented entirely by the portalAJAX-enabled portal refreshes only those portlets affected by the user interaction

Serv

let

ClickXHR

XHR

Property Broker, Shared session etc.c

Page 18: WebSphere Portal Technical Conference Europe 2007 Session Number: D03 Developing AJAX-enabled Portlets in WebSphere Portal 6: Concepts, Patterns and Best

WebSphere Portal Technical Conference Europe 200719

Client-side Aggregation (cont.)

Considers portlets as page fragments that are reloaded individually

No special programming required inside the portletMay occasionally conflict with JavaScript handling inside the portletse.g dynamically generated HTML FORMs, onLoad handlers

Portal is doing the AJAX handlingTracks and updates state across all portletsRefreshes multiple portlets in case of inter-portlet communication (or even the entire page if necessary)Closely integrated with the server-side implementation to find out which portlets were affected by a request

Page 19: WebSphere Portal Technical Conference Europe 2007 Session Number: D03 Developing AJAX-enabled Portlets in WebSphere Portal 6: Concepts, Patterns and Best

WebSphere Portal Technical Conference Europe 2007WebSphere Portal Technical Conference Europe 2007

Part III

Developing AJAX portlets

How to develop AJAX portletsEvolution of portlet standardsAJAX support in WebSphere Portal 6.1

Page 20: WebSphere Portal Technical Conference Europe 2007 Session Number: D03 Developing AJAX-enabled Portlets in WebSphere Portal 6: Concepts, Patterns and Best

WebSphere Portal Technical Conference Europe 200721

Using AJAX inside of portlets

Two scenarios

Data RetrievalClient loads data and displays it without changing the viewExamples• Typeahead feature – a user enters text into a text field and receives

tips or auto-completion about the entered text• Refreshing stock quotes – a portlet displays the latest stock quotes

every five minutes

Markup RetrievalClient loads markup with the purpose of displaying a new view or loading data and transforming this into markup/DOMExamples• A servlet /portlet is accessed and the returned markup is being used to

replace the current view in the DOM• A REST Service returns an ATOM feed which is converted into

markup /DOM using XSLT

Page 21: WebSphere Portal Technical Conference Europe 2007 Session Number: D03 Developing AJAX-enabled Portlets in WebSphere Portal 6: Concepts, Patterns and Best

WebSphere Portal Technical Conference Europe 200722

AJAX flavor 2Portlet connecting to an external data source

Portal WAR

Browser

Portal Server

Portlet

WAR WAR

Portlet

WAR

WAR

Portlet

WAR WAR

Portlet

WAR

Serv

let

Click

External Server(e.g. Mail Server)

ContentProducer

Serv

let

XHR

e.g. XML

JS

AJAX-enabled portlet only reloads affected contentContent source is outside the portalCan be implemented using JSR 168Possible in WebSphere Portal 6.0

Page 22: WebSphere Portal Technical Conference Europe 2007 Session Number: D03 Developing AJAX-enabled Portlets in WebSphere Portal 6: Concepts, Patterns and Best

WebSphere Portal Technical Conference Europe 200723

Portlet connecting to an external data source

Portlet is doing the AJAX handlingWorks on any standards-compliant portalPortlets usually need AJAX Javascript libraries – watch out for conflicts!

AJAX call cannot use portlet APIs or affect the portlet stateCan be used to update backend data and clean server-side caches if necessaryView changes are typically lost in case of a full page refresh

Useful if the portlet is displaying content from a different source anyway

E.g. from mail serverImproves performance by avoiding to route calls through the portal serverTake care of same-origin policy!

Common pattern for closer portlet integration is to use a servlet that is packaged within the portlet WAR file

See next slides

Page 23: WebSphere Portal Technical Conference Europe 2007 Session Number: D03 Developing AJAX-enabled Portlets in WebSphere Portal 6: Concepts, Patterns and Best

WebSphere Portal Technical Conference Europe 200724

Domain A

AJAX Proxy

AJAXProxy

Server

Browser

HTML Page

HTTP GETDomain A

AJAXPortlet

HTTP GETDomain B

Trusted sites

Domain B

Server

Today's browsers restrict the functionality of asynchronous requests to the same domain because of security reasons

Example: Your portlet is served from www.mycompany.com but your AJAX application tries to load a feed from cnn.com. This would be blocked from the browser

AJAX proxy: Central security component to manage access to other domains

Page 24: WebSphere Portal Technical Conference Europe 2007 Session Number: D03 Developing AJAX-enabled Portlets in WebSphere Portal 6: Concepts, Patterns and Best

WebSphere Portal Technical Conference Europe 200725

AJAX flavor 3Using a servlet packaged with the portlet

Portal WAR

Portal Server

WAR

Portlet

WAR

Serv

let Servlet

Browser

ClickJS

Portlet

WAR

WAR

Portlet

WAR

WAR

Portlet

WAR

HTTPSession

Portlet WAR contains one portlet and one servlet (might act as a proxy)

Portlet is embedded into markup like any other portletPortlet is able to transfer some data through the HTTPSessionto the servlet using the APPLICATION Scope

• request.getPortletSession().setAttribute("myName", someValue, PortletSession.APPLICATION_SCOPE);

The portlet markup contains Javascript and a URL pointing back to the servlet

Servlet is directly accessed through Javascript in portlet markup

Possible in WebSphere Portal 6.0

e.g. XML /HTML

External Server(e.g. Mail Server)

Page 25: WebSphere Portal Technical Conference Europe 2007 Session Number: D03 Developing AJAX-enabled Portlets in WebSphere Portal 6: Concepts, Patterns and Best

WebSphere Portal Technical Conference Europe 200726

Implementation hints

Portlet ImplementationEncode portlet context path into markup (needed to generate URL to servlet on the client)On the client, submit XMLHttpRequests using URLs pointing to the servletAppend the URL as a request parameter

Servlet ImplementationReturns content either directly or from any given URL passed along as a request parameterServlet could also just access any backend like SAP or JCR to return content, or use any JSP to create new markup

public class AjaxServlet extends GenericServlet {

public void service(ServletRequest request, ServletResponse response) throws ServletException, IOException { String url = request.getParameter("url"); if (url != null) { URL _url = new URL(url); writeContent(_url, response.getWriter()); }}

private void writeContent(URL url, Writer writer) throws IOException { URLConnection conn = url.openConnection(); ...

function loadRemoteDataThroughProxy(namespace) { contextpath = document.getElementById(namespace+"_contextpath").getAttribute("name"); loadMyXML(contextpath+ "/ajaxServlet?url=http://rss.cnn.com/rss/cnn_topstories.rss", replaceDom, namespace);}

Page 26: WebSphere Portal Technical Conference Europe 2007 Session Number: D03 Developing AJAX-enabled Portlets in WebSphere Portal 6: Concepts, Patterns and Best

WebSphere Portal Technical Conference Europe 200728

Evolution of portlet standards

Current Java Portlet Specification (JSR 168) aimed at a 60% target

Support most common use casesAgree on basic functionality quicklyDefer advanced functionality to later standard versions

More functionality in Java Portlet Specification 2.0 (JSR 286)http://jcp.org/en/jsr/detail?id=286Equivalent standards update for remote portlets: WSRP 2.0http://docs.oasis-open.org/wsrp/v2/wsrp-2.0-spec.html

Key capabilities introduced with JSR 286Events: Enable portlets to communicate with each other through sending and receiving eventsShared render parameters: Enable portlets to specify which render parameters they can share with other portletsResource serving: Enables portlets to serve resources within the portlet context using resource requests

WebSphere Portal 6.1 will support JSR 286 and WSRP 2.0!

Page 27: WebSphere Portal Technical Conference Europe 2007 Session Number: D03 Developing AJAX-enabled Portlets in WebSphere Portal 6: Concepts, Patterns and Best

WebSphere Portal Technical Conference Europe 200729

Resource request

New callback interface triggered by so-called “resource URLs”serveResource(ResourceRequest, ResourceResponse)

Allow portlets to render stand-alone contentNo portal page aggregation, no theme contentPortlet has full control of the entire output, and access to all APIs and state data(e.g. portlet session)Generate binary content (PDF, SVG etc.)Pop-up windows

Allows for limited AJAX support inside portletsPortlets now have a way to return XML, JSON, HTML fragments or other contentBetter programming model than packaging a servlet in the same WAR file

Page 28: WebSphere Portal Technical Conference Europe 2007 Session Number: D03 Developing AJAX-enabled Portlets in WebSphere Portal 6: Concepts, Patterns and Best

WebSphere Portal Technical Conference Europe 200730

AJAX flavor 4Partial updates using resource request (JSR 286)

Portal WAR

XHR

Portal Server

Portlet

WAR WAR

Portlet

WAR

WAR

Portlet

WAR WAR

Portlet

WAR

Serv

let

Browser

Click

JS

XML /HTML

AJAX-enabled portlet reloads affected content using a resource request

AJAX call handled inside the portletCan be implemented using JSR 286Possible in WebSphere Portal 6.1

Page 29: WebSphere Portal Technical Conference Europe 2007 Session Number: D03 Developing AJAX-enabled Portlets in WebSphere Portal 6: Concepts, Patterns and Best

WebSphere Portal Technical Conference Europe 200731

AJAX using the resource request

Again, only portlet is responsible for AJAX handlingPortal does not know what is going on and who is affected

AJAX call can be handled inside the portletPortal APIs are accessibleCurrent state (navigational state, preferences, portlet session) can be accessedCan update preferences and portlet session in a POST request

Only limited functionality availableCannot update navigational state and send events etc.

Page 30: WebSphere Portal Technical Conference Europe 2007 Session Number: D03 Developing AJAX-enabled Portlets in WebSphere Portal 6: Concepts, Patterns and Best

WebSphere Portal Technical Conference Europe 200732

AJAX flavor 5Portlets requests (JSR 286) via XMLPortletRequest

Portal WAR

Request

Portal Server

Portlet

WAR WAR

Portlet

WAR

WAR

Portlet

WAR WAR

Portlet

WARServ

let

Browser

Client-side portal framework

Click

XM

LPortle

tReq

JS

Request 2

AJAX-enabled portlet reloads affected content using a portlet request

AJAX call handled by the portlet and the portalCan be implemented using JSR 286 and JS Portlet API provided by WebSphere Portal 6.1Solution which even handles navigational state and intercommunication properlyPossible in WebSphere Portal 6.1

Property Broker, Shared session etc.c

XML /HTML

Page 31: WebSphere Portal Technical Conference Europe 2007 Session Number: D03 Developing AJAX-enabled Portlets in WebSphere Portal 6: Concepts, Patterns and Best

WebSphere Portal Technical Conference Europe 200733

Full AJAX support in portlets

Requires coordination between portal and portletPortal provides an AJAX library for calls by the portlets

Client-side navigational state can be updatedChanges are retained even if the user clicks outside the current portlet

Full functionality is available on the serverCan write to preferences, send events, etc.Need action and render phase on the server during the AJAX call

Why is the XMLPortletRequest not part of JSR 286?Too hard to agree on a proposal, wait for experience from the field with vendor-specific extensionsSeveral major vendors (including IBM) will propose a common Javascript extension API

Page 32: WebSphere Portal Technical Conference Europe 2007 Session Number: D03 Developing AJAX-enabled Portlets in WebSphere Portal 6: Concepts, Patterns and Best

WebSphere Portal Technical Conference Europe 200734

AJAX flavor 6: Portlets using the JS Portlet API

Portal WAR

Portal Server

Portlet

WAR WAR

Portlet

WAR

WAR

Portlet

WAR WAR

Portlet

WAR

Serv

let

Browser

Client-side portalframework

Click

JS

Portlet API REST

Other

User Profile

Preferences

XMLPortletRequest

Preferences

Nav. State

User Profile

DB

Request

RequestPref. feedRequestUser Prof. feed

The full-blown solution...

XML /HTML

Page 33: WebSphere Portal Technical Conference Europe 2007 Session Number: D03 Developing AJAX-enabled Portlets in WebSphere Portal 6: Concepts, Patterns and Best

WebSphere Portal Technical Conference Europe 200735

JS Portlet API

WebSphere Portal 6.1

Client-side portlet programming modelConvenience JavaScript APIs simplifying portlet developmentClient-side equivalent to the Java Portlet APICoordinates AJAX calls with the portal• Consistent behavior after a full page refresh• Navigational state changes

Implemented using DOJOMight still change slightly

FunctionalityXMLPortletRequestRead & write navigational state(mode, window state, render parameters)Read & write portlet preferencesRead user profile informationRead & write client-side attributesReport errors to the portal framework

Page 34: WebSphere Portal Technical Conference Europe 2007 Session Number: D03 Developing AJAX-enabled Portlets in WebSphere Portal 6: Concepts, Patterns and Best

WebSphere Portal Technical Conference Europe 200736

JS Portlet API – PortletWindow

Entry point: ibm.portal.portlet.PortletWindowProvides JS functions to access to the outlined functionalityDefines useful constants for portlet modes, window states, response status, error typesInitializes with the portlet window identifier

dojoportal.declare("ibm.portal.portlet.PortletWindow", null, {

// Constructor initializer: function (/*String*/ windowid) {...},

// Function to create a new XMLPortletRequest newXMLPortletRequest: function() {...},

// Functions to read /write navigational state (portlet mode, window state, render parameters) getPortletState: function(/*Function*/ callbackfn) {...}, setPortletState: function(/*PortletState*/ state, /*Function*/ callbackfn) {...},

// Functions to read /write navigational state (portlet mode, window state, render parameters) newRenderURL: function(/*PortletState*/ state) {...},

// Functions to read /write persistent state (portlet preferences) getPortletPreferences: function(/*Function*/ callbackfn) {...}, setPortletPreferences: function(/*PortletPreferences*/preferences, /*Function*/ callbackfn) {...},

// Functions to read /write user profile information getUserProfile: function(/*Function*/ callbackfn) {...}, setUserProfile: function(/*userProfile*/userProfile, /*Function*/ callbackfn) {...},

// Functions to manage attributes getAttribute: function(/*String*/ name) {...}, setAttribute: function(/*String*/ name, /*Object*/ value) {...}, removeAttribute: function(/*String*/ name) {...}, clearAttributes: function() {...},

// Reports the given error to the portal framework reportError: function(/*ibm.portal.portlet.Error*/ error) {...},});

Page 35: WebSphere Portal Technical Conference Europe 2007 Session Number: D03 Developing AJAX-enabled Portlets in WebSphere Portal 6: Concepts, Patterns and Best

WebSphere Portal Technical Conference Europe 200737

JS Portlet API – XMLPortletRequest

ibm.portal.portlet.XMLPortletRequestProvides XMLHTTPRequest functionality for portlets

dojoportal.declare("ibm.portal.portlet.XMLPortletRequest", null, {

// Properties to read the ready state as well as register callback functions readyState: 0, /* int */ onreadystatechange: null, /*Function*/ onportletstateready: null, /* Function(ibm.portal.portlet.PortletState) */

// Properties to access the response body (either text or XML) responseText: null, /* String */ responseXML: null, /* Document */

// Properties to read the response status status: null, /* int */ statusText: null, /* String */

// Functions to open, send, and abort a synchronous or asynchronous request open: function( /*String*/ method, /*String*/ uri ) {...}, open: function( /*String*/ method, /*String*/ uri, /*boolean*/ async ) {...}, send: function( /*String or Document*/ data ) {...}, abort: function( ) {...},

// Functions to set request headers and read response headers setRequestHeader: function( /*String*/ header, /*String*/ value ) {...}, getAllResponseHeaders: function( ) {...}, getResponseHeader: function( /*String*/ header ) {...}

});

Page 36: WebSphere Portal Technical Conference Europe 2007 Session Number: D03 Developing AJAX-enabled Portlets in WebSphere Portal 6: Concepts, Patterns and Best

WebSphere Portal Technical Conference Europe 200738

JS Portlet API – PortletState

ibm.portal.portlet.PortletStateAllows to work with render parameters, portlet mode, window state (navigational state) of the portlet windowChanges are persisted when calling setPortletState() on the PortletWindow object

dojoportal.declare("ibm.portal.portlet.PortletState", null, {

// Functions to read /write portlet mode getPortletMode:function() {...}, setPortletMode:function(/*ibm.portal.portlet.PortletMode*/ portletMode) {...},

// Functions to read /write portlet mode getWindowState:function() {...}, setWindowState:function(/*ibm.portal.portlet.WindowState*/windowState) {...},

// Functions to read render parameters getParameterNames: function() {...}, getParameterValue: function(/*String*/ name) {...}, getParameterValues: function(/*String*/ name) {...}, getParameterMap: function() {...},

// Functions to set /modify /remove render parameters setParameterValue: function(/*String*/ name, /*String*/ value) {...}, setParameterValues: function(/*String*/ name, /*String[]*/ values) {...}, setParameterMap: function(/*object[] {name: string, values: string[]}*/map, /*boolean*/replace) {...}, removeParameter: function(/*String*/name) {...}

});

Page 37: WebSphere Portal Technical Conference Europe 2007 Session Number: D03 Developing AJAX-enabled Portlets in WebSphere Portal 6: Concepts, Patterns and Best

WebSphere Portal Technical Conference Europe 200739

JS Portlet API – PortletPreferences

ibm.portal.portlet.PortletPreferencesAllows to work with configuration data (persistent state) of the portletDistinguishes modifiable and read-only preferences (depends on portlet mode)Changes are persisted when calling setPortletPreferences() on the PortletWindow objectdojoportal.declare("ibm.portal.portlet.PortletPreferences", null, {

// Returns a preferences map (object[] {name: string, values: string[], readonly: boolean}) getMap: function() {...},

// Returns the names of the available preferences (String[]) getNames: function() {...},

// Functions to read preference values (String / String[]) getValue: function( /*String*/ key, /*String*/ default ) {...}, getValues: function( /*String*/ key, /*String[]*/ default ) {...},

// Checks whether the preference with the given name is a read-only preference isReadOnly: function( /*String*/ key ) {...},

// Functions to set /reset preference values reset: function ( /*String*/ key ) {...}, setValue: function ( /*String*/ key, /*String*/ value ) {...}, setValues: function( /*String*/ key, /*String[]*/ values ) {...},

// Function to clone the PortletPreferences object clone:function() {...}

});

Page 38: WebSphere Portal Technical Conference Europe 2007 Session Number: D03 Developing AJAX-enabled Portlets in WebSphere Portal 6: Concepts, Patterns and Best

WebSphere Portal Technical Conference Europe 200740

JSPJSP

Implementing a portlet using the JS Portlet API

Proposed design patternCreate the PortletWindow object in your JSPsRender the initial view in your JSPsImplement a JS class representing the portlet (use a separate JS file)Pass in namespace and PortletWindow object via constructor• Namespace is needed for dynamic DOM updates (to address DOM nodes)• PortletWindow is needed to implement business logic

Portlet WAR

JSP

JS File

Inline script

Portletclass

<b>...</b>

<div>

<a onclick=...>

</a>

<form ...>

</div>

instantiate

Page 39: WebSphere Portal Technical Conference Europe 2007 Session Number: D03 Developing AJAX-enabled Portlets in WebSphere Portal 6: Concepts, Patterns and Best

WebSphere Portal Technical Conference Europe 200741

Sample JSP<%@ page session="false" %> <%@ page import="..." %> <%@ taglib uri="http://java.sun.com/portlet" prefix="portletAPI" %> <%@ taglib uri="http://www.ibm.com/xmlns/prod/websphere/portal/v6.1/portlet-client-model" prefix="portlet-client-model" %>

<portletAPI:defineObjects/><!–- Load the JS Portlet API --><portlet-client-model:init> <portlet-client-model:require module="ibm.portal.portlet.*"/></portlet-client-model:init>

<!–- Initial markup --><b>Add new list item</b><!–- Call list portlet’s addListItem function --><form onsubmit="listPortlet<%=portletWindowID%>.addListItem(this.newItem.value); return false;"> <input name="newItem" type="text"></input> <input type="Submit" value="Add list item"></input></form><form ></form><div id="list<%=portletWindowID%>"> <!–- Display dynamic list here --></div>

<script> var portletWindow<%=portletWindowID%> = new ibm.portal.portlet.PortletWindow("<%=portletWindowID%>"); var listPortlet<%=portletWindowID%> = new ListPortlet("<%=portletWindowID%>", portletWindow<%=portletWindowID%>); // add portlet object to window (needed for callback functions!) portletWindow<%=portletWindowID%>.setAttribute("portlet", listPortlet<%=portletWindowID%>); // load preferences to display initial list portletWindow<%=portletWindowID%>.getPortletPreferences( listPortlet<%=portletWindowID%>.handleLoadPortletPreferences)</script>

Important: Namespace page DOM elements!

Important: Namespace JS identifiers!

Page 40: WebSphere Portal Technical Conference Europe 2007 Session Number: D03 Developing AJAX-enabled Portlets in WebSphere Portal 6: Concepts, Patterns and Best

WebSphere Portal Technical Conference Europe 200742

if ( typeof( ListPortlet ) == "undefined" ) {var ListPortlet = function (_namespace, _portletWindow) { this.namespace = _namespace; this.portletWindow = _portletWindow;}ListPortlet.prototype = { handleLoadPortletPreferences: function(portletWindow, status, prefs) { if (status==ibm.portal.portlet.PortletWindow.STATUS_OK) { portletWindow.setAttribute("preferences", prefs); portletWindow.getAttribute("portlet").renderList(); } else { portletWindow.reportError(new ibm.portal.portlet.Error( ibm.portal.portlet.Error.ERROR, "Error loading preferences.", "Status code: "+status)); } }, handleSavePortletPreferences: function(portletWindow, status, prefs) { if (status==ibm.portal.portlet.PortletWindow.STATUS_OK) { portletWindow.setAttribute("preferences", prefs); } else { // error handling; report error and then invoke renderList function to render previous list ... } }, renderList: function() { var prefs = this.portletWindow.getAttribute("preferences"); var listElems = prefs.getValues("list", null); // append list elements to DOM var listRoot = document.getElementById("list" + this.namespace); ... }, addListItem: function(newItem) { // update DOM ... // save preferences var prefs = this.portletWindow.getAttribute("preferences"); var listElems = prefs.getValues("list", null); listElems.push(newItem); prefs.setValues("list", listElems); // setPortletPreferences will return immediately (asynchronous request) this.portletWindow.setPortletPreferences(prefs, handleSavePortletPreferences); }}

Sample JS portlet

Important: Do not use „this“ withincallback functions! Callback functions are executed in a different context.

Page 41: WebSphere Portal Technical Conference Europe 2007 Session Number: D03 Developing AJAX-enabled Portlets in WebSphere Portal 6: Concepts, Patterns and Best

WebSphere Portal Technical Conference Europe 200743

Javascript in portlets

JavaScript in portlets is basically not different from any other webapp

The only important point is that the same browser page is shared by multiple portlets and the portal itselfThe same portlet can apprear on a page multiple times!

Namespace page DOM elements and global JavaScript identifiers!Use RenderResponse.getNamespace() or the <portletAPI:namespace/> tag Returns a unique string for every portlet on a page

Offload JS code into separate files instead of including it in each page!

Reduce page size and exploit the browser cacheExploit JS object structure to make namespacing easier

Avoid double initialization of common JS libraries!Check if library already initialized

Don’t replace global event handlers like page.onload!Somebody else may plug into them tooUse attachEvent / addEvent (and, again, avoid double attaching!)

Page 42: WebSphere Portal Technical Conference Europe 2007 Session Number: D03 Developing AJAX-enabled Portlets in WebSphere Portal 6: Concepts, Patterns and Best

WebSphere Portal Technical Conference Europe 200744

Summary

AJAX within a Portal environment is possible

It is more complex compared to a single servlet scenario (e.g. Google mail) because of its nature of aggregating multiple fragments on one page

Using a framework helps to circumvent most of the Web capabilities problems

Special support in a portlet is sometimes necessary (e.g. Crawlability)

For WebSphere Portal 6.0 it might be worth to not leverage Navigational State AJAX flavor 3 recommended (Servlet packaged with portlet)

With WebSphere Portal 6.1 it will be possible to implement AJAX portlets behaving consistently with server-side portlets using JSR 286 concepts as well as the offered JS Portlet API AJAX flavor 6 recommended (Portlet using the JS Portlet API)

JS Portlet API allows to conveniently use basic portlet concepts on the client (render parameters, preferences, user profile etc.)

Page 43: WebSphere Portal Technical Conference Europe 2007 Session Number: D03 Developing AJAX-enabled Portlets in WebSphere Portal 6: Concepts, Patterns and Best

WebSphere Portal Technical Conference Europe 200745

Additional Information and Resources

AJAX Toolkit Framework (ATF)http://www.eclipse.org/atf/

Firebug – Firefox extension, DOM Inspector & Modifier, JS Debugger & Console

http://addons.mozilla.org/firefox/1843/

Fiddler – Network traffic listener & proxy. Works with IE and FFhttp://www.fiddlertool.com

JSView – Firefox extension, easy access to external resources such as css and JS

http://addons.mozilla.org/firefox/2076/

LiveHTTPHeaders – Firefox extension, allows to look at requestshttp://livehttpheaders.mozdev.org/

Websphere Portal Business Solutions Catalog: http://catalog.lotus.com/wps/portal/portal

Webspere Portal Product Information:http://www-306.ibm.com/software/genservers/porta

WebSphere Portal Information Center Documentation:http://www.ibm.com/developerworks/websphere/zones/portal/proddoc.html

Page 44: WebSphere Portal Technical Conference Europe 2007 Session Number: D03 Developing AJAX-enabled Portlets in WebSphere Portal 6: Concepts, Patterns and Best

WebSphere Portal Technical Conference Europe 2007WebSphere Portal Technical Conference Europe 2007

Backup Slides

Page 45: WebSphere Portal Technical Conference Europe 2007 Session Number: D03 Developing AJAX-enabled Portlets in WebSphere Portal 6: Concepts, Patterns and Best

WebSphere Portal Technical Conference Europe 200747

Domain A

AJAX Proxy

AJAXProxy

Server

Browser

HTML Page

HTTP GETDomain A

AJAXPortlet

HTTP GETDomain B

Trusted sites

Domain B

Server

Today's browsers restrict the functionality of asynchronous requests to the same domain because of security reasons

Example: Your portlet is served from www.mycompany.com but your AJAX application tries to load a feed from cnn.com. This would be blocked from the browser

AJAX proxy: Central security component to manage access to other domains

Page 46: WebSphere Portal Technical Conference Europe 2007 Session Number: D03 Developing AJAX-enabled Portlets in WebSphere Portal 6: Concepts, Patterns and Best

WebSphere Portal Technical Conference Europe 2007WebSphere Portal Technical Conference Europe 2007

Tools

Page 47: WebSphere Portal Technical Conference Europe 2007 Session Number: D03 Developing AJAX-enabled Portlets in WebSphere Portal 6: Concepts, Patterns and Best

WebSphere Portal Technical Conference Europe 200749

Tools

AJAX Toolkit Framework (ATF)http://www.eclipse.org/atf/

Firebug – Firefox extension, DOM Inspector & Modifier, JS Debugger & Console

http://addons.mozilla.org/firefox/1843/

Fiddler – A network traffic listener & proxy. Works with IE and FFhttp://www.fiddlertool.com

JSView – Firefox extension, easy access to external resources such as CSS and JS

http://addons.mozilla.org/firefox/2076/

LiveHTTPHeaders – Firefox extension, allows to look at requestshttp://livehttpheaders.mozdev.org/

Page 48: WebSphere Portal Technical Conference Europe 2007 Session Number: D03 Developing AJAX-enabled Portlets in WebSphere Portal 6: Concepts, Patterns and Best

WebSphere Portal Technical Conference Europe 2007WebSphere Portal Technical Conference Europe 2007

Tools Debugging DemoUsing Eclipse with ATF

Page 49: WebSphere Portal Technical Conference Europe 2007 Session Number: D03 Developing AJAX-enabled Portlets in WebSphere Portal 6: Concepts, Patterns and Best

WebSphere Portal Technical Conference Europe 200751

Debugging PerspectiveViews

ThreadsVariablesSourceOutline

Page 50: WebSphere Portal Technical Conference Europe 2007 Session Number: D03 Developing AJAX-enabled Portlets in WebSphere Portal 6: Concepts, Patterns and Best

WebSphere Portal Technical Conference Europe 200752

Debugging PerspectiveViews

BrowserDOMMonitor

Page 51: WebSphere Portal Technical Conference Europe 2007 Session Number: D03 Developing AJAX-enabled Portlets in WebSphere Portal 6: Concepts, Patterns and Best

WebSphere Portal Technical Conference Europe 2007WebSphere Portal Technical Conference Europe 2007

Tools Debugging DemoUsing Firefox extension Firebug

Page 52: WebSphere Portal Technical Conference Europe 2007 Session Number: D03 Developing AJAX-enabled Portlets in WebSphere Portal 6: Concepts, Patterns and Best

WebSphere Portal Technical Conference Europe 200754

Debugging in Firefox using FirebugViews: Browser, Source, Variables

Page 53: WebSphere Portal Technical Conference Europe 2007 Session Number: D03 Developing AJAX-enabled Portlets in WebSphere Portal 6: Concepts, Patterns and Best

WebSphere Portal Technical Conference Europe 200755

Debugging in Firefox using FirebugViews XMLHttpRequest Monitor