Post on 26-Mar-2015
© 2007 IBM Corporation
2007 【 IBM developerWorks 開發者大會】
Web 2.0, AJAX, REST and others
Matthew Tan (tanma@sg.ibm.com)Senior Solution Consultant,IBM Asia Pacific, SWG HQ
30th October 2007
2 © 2007 IBM Corporation
2007 【 IBM developerWorks 開發者大會】
IBM developerWorks| Oct 2007
Agenda
Overview of Web 2.0
About AJAX
About Rest and Others
Application of AJAX, REST in ATOM / RSS and Web 2.0
3 © 2007 IBM Corporation
2007 【 IBM developerWorks 開發者大會】
IBM developerWorks| Oct 2007
What is Web 2.0 ?
A term coined by Tim O‘Reilly (see http://www.oreillynet.com/pub/a/oreilly/tim/news/2005/09/30/what-is-web-20.html )
Increasingly used for next generation World Wide Web Applications and Services/
Web 2.0 has many aspects:
Business Models that survived and have promise for the future
Approaches such as services instead of products, the Web as a platform, ...
Concepts such as folksonomies, syndication, participation, reputation, ....
Technologies such as AJAX, REST, Tags, Microformats, ...
And many others ...
4 © 2007 IBM Corporation
2007 【 IBM developerWorks 開發者大會】
IBM developerWorks| Oct 2007
How do Web 2.0 Sites differ from „Web 1.0“ Sites ?
Strict „Web 1.0“ site– „Web Master“ runs web site, users
consume
– Few content editors
– Web site provides content and applications for users
– View-only markup
– Only human users
– Accumulates relatively small amounts of information and content
– Fixed categories / Taxonomy
– Unidirectional
Modern „Web 2.0“ site– Users collectively contribute to the web site, they
don‘t just consume
– Every user is a content editor and rater
– Web site provides content, applications, and collective contributions of all users
– Semantically tagged markup
– Humans and applications as „users“
– Accumulates huge amounts of information and content
– FlexibleTagging / Folksonomy
– Bi-directional
WebSite
WebSite
DataData
App
App
App
App
5 © 2007 IBM Corporation
2007 【 IBM developerWorks 開發者大會】
IBM developerWorks| Oct 2007
Observations
Web 2.0 consists of social and technical aspects
The social aspects of Web 2.0 are much more fundamental than the technologies
Web 2.0 Sites can derive huge value from their user community if they achieve critical mass Some Web 2.0 companies have achieved extremely high market captialization (Google ($109,66 bn) bought YouTube for $1,65 bn)
The Web 2.0 Site itself often only provides the infrastructure and guidelines for user participation
The community then adds value to the site, e.g. by writing articles, posting videos, sharing bookmarks, etc
Typically, these Web 2.0 sites have APIs for use by developers of mashup applications acting as multipliers
Web 2.0 user interfaces typically apply the AJAX technology in order to achieve more responsive UIs
6 © 2007 IBM Corporation
2007 【 IBM developerWorks 開發者大會】
IBM developerWorks| Oct 2007
Web 2.0 Concepts that are interesting for enterprise use
Self-establishing Communities collaborating around topics of common business interest
Support User Contribution, treat users as co-authors and leverages their skills better
Accumulation of user knowledge to make apps smarter the more people use them
Enable users to add value by adding meta data, e.g. rate, tag, bookmark, comment
Allow users to Take Control and let them make applications most useful to them
Separate User Interface from Services to make services re-usable
Fine grained access to data supporting mashups
Mashups combining existing services into new, useful applications joining information
Situational Development of applications through line of business can help make businesses more agile
AJAX to enable rich, interactive, highly responsive Web UI
Use of Semantic Tags and Microformats to enable dynamic augmentation with contextual menus or information
7 © 2007 IBM Corporation
2007 【 IBM developerWorks 開發者大會】
IBM developerWorks| Oct 2007
Agenda
Overview of Web 2.0
About AJAX
About Rest and Others
Application of AJAX, REST in ATOM / RSS and Web 2.0
8 © 2007 IBM Corporation
2007 【 IBM developerWorks 開發者大會】
IBM developerWorks| Oct 2007
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 also about building web clients in a Service Oriented Architecturethat can connect to any kind of server: J2EE, PHP, ASP.Net, Ruby on Rails, etc.
AJAX involves existing technology & standards: JavaScript and XML
Pattern: Page view displayed in a web browser retrieves data or markup fragmentsfrom a service and refreshes just a part of the page
AJAX is non-trivial, it requires deep and broad skills in web development ...... but the benefits to be gained can be huge compared to classic web applications
AJAX enables major improvements in responsiveness and performance of web applications, e.g. used at Yahoo! Mail, Google Maps, live.com, and others
AJAX is NOT hype – it is very real and very useful for highly interactive applications
9 © 2007 IBM Corporation
2007 【 IBM developerWorks 開發者大會】
IBM developerWorks| Oct 2007
AJAX compared to classic Web UIs
Browser Server Browser Server
service
In the typical web application, each request causes a complete refresh of the browser page
An Ajax application begins the same way.
After the initial page loads, Javascript code retrieves additional data in the background and updates only specific sections of the page
Ajax forces you to think about discrete services. It may drive requirements for new services from your IT department
10 © 2007 IBM Corporation
2007 【 IBM developerWorks 開發者大會】
IBM developerWorks| Oct 2007
AJAX In a Nutshell
Ajax isn’t just a technology. It’s really several technologies, each flourishing in its own right, coming together in powerful new ways. Ajax incorporate
standards-based presentation using XHTML and CSS
dynamic display and interaction using the Document Object Model
data interchange and manipulation using XML and XSLT
asynchronous data retrieval using XMLHttpRequest
and JavaScript binding everything together.
11 © 2007 IBM Corporation
2007 【 IBM developerWorks 開發者大會】
IBM developerWorks| Oct 2007
12 © 2007 IBM Corporation
2007 【 IBM developerWorks 開發者大會】
IBM developerWorks| Oct 2007
13 © 2007 IBM Corporation
2007 【 IBM developerWorks 開發者大會】
IBM developerWorks| Oct 2007
Traditional Model for Web Applications Vs AJAX model
14 © 2007 IBM Corporation
2007 【 IBM developerWorks 開發者大會】
IBM developerWorks| Oct 2007
Agenda
Overview of Web 2.0
About AJAX
About Rest and Others
Application of AJAX, REST in ATOM / RSS and Web 2.0
15 © 2007 IBM Corporation
2007 【 IBM developerWorks 開發者大會】
IBM developerWorks| Oct 2007
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 REST
– Resource centric approach
– All relevant resources are addressable via URIs
– Uniform access via HTTP – GET, POST, PUT, DELETE
– Content type negotiation allows retrieving alternative representations from same URI
REST style services
– are easy to access from code running in web browsers, any other client or servers very popular in the context of AJAX
– can take full advantage of the WWW caching infrastructure
– can serve multiple representations of the same resource
More info: http://www.ics.uci.edu/~fielding/pubs/dissertation/top.htm
16 © 2007 IBM Corporation
2007 【 IBM developerWorks 開發者大會】
IBM developerWorks| Oct 2007
Agenda
Overview of Web 2.0
About AJAX
About Rest and Others
Application of AJAX, REST, ATOM / RSS and Web 2.0
17 © 2007 IBM Corporation
2007 【 IBM developerWorks 開發者大會】
IBM developerWorks| Oct 2007
Application In IBM Portal – An Example
w3 portal for all IBM employees
> 340,000 users
Portlets provide essential information
Highly personalized - displays the right info to the right users at the right time
End-user customizable - users can create custom pages
Has become a key tool for every IBMer
Major productivity gain
–Targeted info delivery to users
–Users can easily find the apps they need
18 © 2007 IBM Corporation
2007 【 IBM developerWorks 開發者大會】
IBM developerWorks| Oct 2007
Openness
Portals provide governed business mashups combining public information, enterprise apps and data
Critical enabler:
Standards based access to integration and innovation
Thin Clients
Mobile Clients
Rich Clients
role-based
composite applications
in context
process-
driven
Security-Rich Composite application or view, that assembles and delivers
services in the form of portlets in the context of a business process
19 © 2007 IBM Corporation
2007 【 IBM developerWorks 開發者大會】
IBM developerWorks| Oct 2007
Application of Web 2.0 / AJAX / REST in WP and related Products
WP6 allows User Contribution to portal sites through both WCM and PDM
WP6 enables Situational Development through Composite Application Templates and through Lotus Designer / Portlet Factory / Forms Designer
WP6 allows users Taking Control of their pages and choose content (if allowed by admin)
Custom AJAX Portlets can be written today to run on WebSphere Portal, e.g. using the Dojo framework and widgets or the AJAX support in RAD
WP6 exploits AJAX for context menus, search menu, and some admin portlets
WebSphere Portlet Factory can generate AJAX Portlets with incremental update and autocomplete
IBM is strongly engaged in Dojo (see http://dojotoolkit.org/ ) as major contributor
20 © 2007 IBM Corporation
2007 【 IBM developerWorks 開發者大會】
IBM developerWorks| Oct 2007
Application of Web 2.0 used in WebSphere Portal 6
REST Services to open up portal for mashup applications – services for server persistence, portlet settings and user profile access to simplify Web 2.0 application development
AJAX Portlet Programming Model Extensions based on Dojo+IBM Extensions
Client Side Aggregation and Customization using REST Services for better UX and improved performance
AJAX Client Side Feed Consumption to enable highly efficient integration of information through feeds (Atom and RSS)
Semantic Tags to allow smart markup to enable value add by portal, e.g. dynamic menus
Client Side C2A/Property Broker and Drag & Drop based on Semantic Tags integrated with server side property broker and C2A support to enable cross-portlet interaction locally in the browser as well as with server side code
Sample AJAX Portlets with source showcasing the new capabilities to demonstrate and give samples to customers for how to exploit all the above
Integration, Aggregation and Customization of Google Gadgets
21 © 2007 IBM Corporation
2007 【 IBM developerWorks 開發者大會】
IBM developerWorks| Oct 2007
REST style Web Services exposing Portal to Mashups
Goals:– Separate portal user experience from portal data
– Expose relevant data separately for use by other apps ( Mashups)
Public REST style Web services for– Access to Navigation Node Hierarchy
– Access to Page Definitions
– Access to User Profiles
– Access to generic Content Persistence
– Access to markup fragments of individual portlets
Mashups can use these services to implement custom applications leveraging portal infrastructure services
WebSphere Portal’s Web 2.0 Client Side Aggregation uses these services as well
22 © 2007 IBM Corporation
2007 【 IBM developerWorks 開發者大會】
IBM developerWorks| Oct 2007
WebSpherePortal
IBM Collaboration Services, Feeds and Application Examples
Portal Services
User Service
Persistence Service
Contacts Service
DominoMail Services
Calendar Services
Sametime
Portlet Service
Awareness Service
Conference Service
IM Service
QuickrDocuments Services
Team Space Services
Custom Situational Application:Problem tracking application
allowing to see author presence and location in map and contact via IM
Custom Situational Application:Simple AJAX Mail / Cal summary
views with awareness
Product:WebSphere Portal
Client Side Aggregation
Search Service
Geneva Portlets, Notes Plugin,
Sametime Plugin, Desktop Integration
Product:Common PIM Portlets
for Mail and Calendar Access
ConnectionsPersona, Community Services
Activity, Blog Services
Internet ServicesMaps
23 © 2007 IBM Corporation
2007 【 IBM developerWorks 開發者大會】
IBM developerWorks| Oct 2007
Web 2.0 Fragment Model
Simple and extensible Web 2.0 fragment programming model
Agnostic of how fragments are generated, may be
– generated by portlets on WebSphere Portal
– generated by PHP code on Web.0 or PHP servers
– generated by .NET servers
Can start simple, with option to grow more sophisticated
– (1) Basic fragments – HTML only
– (2) Slightly more advanced – add use of Semantic Tags
– (3) More advanced – add use of Dojo and custom JavaScript
Fragments can use public JavaScript interfaces to conveniently invoke WebSphere Portal’s REST-style Web services
24 © 2007 IBM Corporation
2007 【 IBM developerWorks 開發者大會】
IBM developerWorks| Oct 2007
Web 2.0 Fragment Programming Model
Web 2.0 Fragment
Semantic Tags
Dojo Widget Markup
JavaScript Functions
REST Calls to Portal Services User Profile Access Settings Access Persistence Service Access
REST Calls to other Services, e.g. other WPLC services Weather Info, News, Sports, … CRM, HR, … Services etc
Basic
Intermediate
Advanced……
…
…
26 © 2007 IBM Corporation
2007 【 IBM developerWorks 開發者大會】
IBM developerWorks| Oct 2007
Web 2.0 Client Side Aggregation (CSA) uses AJAX, XML, Dojo, JS
Browser-side Aggregation, Navigation and Customization
Superior user experience
– Highly reactive and direct user interface
– Many actions possible without server roundtrips
– Avoids page flickering
Accesses and manipulates portal information through REST services
Renders XML obtained from the server on the browser side
Implemented using AJAX, XML, Dojo, and JavaScript
Improved performance and scalability through
– Reduced server side processing - offloads rendering to browser
– Reduced bandwidth requirements between server and browser
– Reduced client-side processing – mostly fragment reloads, few page reloads
– Improved cachability, all artifacts can be cached independently
27 © 2007 IBM Corporation
2007 【 IBM developerWorks 開發者大會】
IBM developerWorks| Oct 2007
AJAX based Client Side Aggregation in the Web Browser
Services created with Google Gadgets
Atom / RSS Feeds
REST-accessible Markup Fragmentsfrom WP Portlets or any other URL
WSRP Services
29 © 2007 IBM Corporation
2007 【 IBM developerWorks 開發者大會】
IBM developerWorks| Oct 2007
Other Web 2.0 Capabilities - Semantic Tags, Context Menus and Drag&Drop
Extensible set of tag types such as person, address, phone number, document, ... is used to mark content elements with types (semantic tagging)
Behaviours like e.g. context menus, annotations, highlighting, drag & drop, etc can be applied to everything that is semantically tagged
D&D D&D
Conference Participants IBMST Thomas SchaeckST 5 Technology Park Dr 555-5555ST
Westford, MAST
GroupST LocationsST‘ Click to dial
30 © 2007 IBM Corporation
2007 【 IBM developerWorks 開發者大會】
IBM developerWorks| Oct 2007
Other Web 2.0 Capabilities - Semantic Tags (Portal-Independent Technology)
31 © 2007 IBM Corporation
2007 【 IBM developerWorks 開發者大會】
IBM developerWorks| Oct 2007
AJAX based RSS/Atom Feed Consumption
Allow simple consumption and display of Feeds in portal pages– Atom feeds
– RSS feeds
Implemented using AJAX, Dojo and JavaScript
Gets settings defining the feed to display from portal
Retrieves feeds from origin servers via AJAX proxy
Renders feeds in the browser rather than causing server load
32 © 2007 IBM Corporation
2007 【 IBM developerWorks 開發者大會】
IBM developerWorks| Oct 2007
AJAX RSS/Atom Feed Consumption directly from Origin
33 © 2007 IBM Corporation
2007 【 IBM developerWorks 開發者大會】
IBM developerWorks| Oct 2007
Google Gadget Integration
Enable customers to easily integrate Google Gadgets into portal pages
From an end user perspective, Google Gadgets integrated in WebSphere Portal behave just like local portlets: viewable and customizable like any local portlet
If allowed by admin, users can drag Generic Gadget Portlets on their pages and select Gadgets to display from the Gadget Catalog
–Gadget Portlet initially lets user select the Gadget to display from the Gadget Catalog
–Gadget Portlet then displays the selected Gadget–User can view and customize the selected gadget
like any local portlet
Administrators can pre-define Gadget Portlets for the portlet palette
–Generic Gadget Portlet is pre-configured by the admin to connect it to a certain gadget, e.g. an admin could create a “Map Portlet” by creating a Gadget Portlet and connecting it to the Google Maps Gadget
–Users can then select such pre-configured Gadget Portlets from the palette and drag them onto their pages like any local portlet
34 © 2007 IBM Corporation
2007 【 IBM developerWorks 開發者大會】
IBM developerWorks| Oct 2007
Google Gadget Integration – A Gadget integrated in Portal as a portlet
35 © 2007 IBM Corporation
2007 【 IBM developerWorks 開發者大會】
IBM developerWorks| Oct 2007
Google Gadget Integration – Selecting a Gadget to integrate into Portal as a portlet
36 © 2007 IBM Corporation
2007 【 IBM developerWorks 開發者大會】
IBM developerWorks| Oct 2007
IBM Portlet for Google Gadgets Architecture
IBM Portletfor
Google GadgetsGoogle Gadget
Google RSS Feed listing
available gadgets
View Mode
Customize Mode
Configuration Mode
Customize Mode
View Mode
37 © 2007 IBM Corporation
2007 【 IBM developerWorks 開發者大會】
IBM developerWorks| Oct 2007
AJAX Portlets using Dojo
38 © 2007 IBM Corporation
2007 【 IBM developerWorks 開發者大會】
IBM developerWorks| Oct 2007
Web 2.0 Portal Architecture
WebSphere Portal Foundation
AJAX FeedConsumer
Connections (Activities, Blue Pages,
Social Bookmarks, Blogs)
AJAX FragmentConsumer
AJAX Programming Model Extensions(Dojo Framework & Widgets + AJAX.0 + REST accessor JS functions + Semantic Tags + Client Side Click-2-Action)
REST style Portal Services(Persistence, User Profiles, Portlet Settings, Navigation, Pages, etc)
Quickr(Wikis, Blogs,
Lists, Doc Libs, Discussions)
ConnectionsPortlets
MyPlacesPortlet
FeedService
HTML+Dojo+JSFragments
(from J2EE,.NET,PHP,HTTP or other Server)
WebSphere Application Server
ClassicJSR 168 Portlets
AJAX enabledJSR 168 Portlets
WSRPConsumer
WSRPService
39 © 2007 IBM Corporation
2007 【 IBM developerWorks 開發者大會】
IBM developerWorks| Oct 2007
Conclusion
Web 2.0 is important for the enterprise
AJAX and REST are important technologies related to Web 2.0
IBM uses Web 2.0 concepts and technologies successfully in its intranet
WebSphere Portal already today in WP 6 provides Web 2.0 capabilities and leverages Web 2.0 technologies such as AJAX
Future releases of WebSphere Portal will add more Web 2.0 features and expand use of AJAX and REST
WebSphere Portal will integrate with Lotus Connections and Lotus Quickr
40 © 2007 IBM Corporation
2007 【 IBM developerWorks 開發者大會】
IBM developerWorks| Oct 2007
AJAX Development – Real Example
41 © 2007 IBM Corporation
2007 【 IBM developerWorks 開發者大會】
IBM developerWorks| Oct 2007
This article introduces the idea of integrating Ajax into your portal applications. Since there are many Ajax articles already available (see Resources), we assume that you understand the basics of Ajax. This includes what Ajax means, how it got its name, the fact that it's not new, and how Google brought this technology into the mind set of every executive and technologist on the planet.
My intention is to equip you with useful information related to using Ajax in your portal applications, so when the CTO's office asked if your portal applications are Ajax enabled, you can stand up and say, “Definitely.”
Therefore, this article describes areas to consider if you decide to inject Ajax into your portal. While the focus is on portal applications, the tips are generally applicable to most complex applications. This article also prepares you for a future tutorial, in which we will detail the creation of an Ajax portlet application.
Note - much of what you see and read about Ajax is not really Ajax; it's Dynamic HTML, or DHTML. Ajax, in its proper sense, consists of a single JavaScript object called XMLHttpRequest. This class provides a background communication channel to a server and for the resulting response. Everything else, including drag-and-drop, DOM updates, styling, and all the other things that make everyone go "ohh and ahh", is DHTML.
Introduction
42 © 2007 IBM Corporation
2007 【 IBM developerWorks 開發者大會】
IBM developerWorks| Oct 2007
When is Ajax and Portal a good fit ?
One of the most expensive actions in a portal environment is to refresh the page.
When the user clicks a link or takes some other action on the page, the portal processes the actionPerformed()method for the target portlet and the doView() methods for each portlet on the page. Then, it aggregates the results and sends the entire HTML document down to the browser.
While caching can reduce a lot of the overhead, there is still a lot going on. You could use Ajax to handle many of the user interaction events in the background, and then to update portions of the page, without requiring a full portal refresh cycle. This technique greatly improve the end-user experience by increasing the responsiveness of individual actions, and the overall application performance. In many circumstances, using Ajax contributes to a cleaner overall architecture of your application. Having a secondary Ajax controller (such as a servlet or Web service) forces a stronger separation of your model code.
When applying a full Ajax controller design to your application, you should let the Ajax controller handle all basic user input actions and segmented display updates. Only use the portal actionPerformed() method for page-level transitions or to process major state changes.
43 © 2007 IBM Corporation
2007 【 IBM developerWorks 開發者大會】
IBM developerWorks| Oct 2007
So, why would you not want to use this new fangled paradigm in rich internet applications? All the weekly technical magazines insist that this is the way to go, and besides, your boss told you to use it because it's "one of our business goals." OK, we won't tell you not to use it, but we do want you to know about some potential pitfalls:
Using multiple controllers (for example a portlet, a servlet, and a Web service) adds to the complexity of the application.
Using Ajax forces a lot of logic to be processed on the client. JavaScript can be difficult to debug, especially in a cross-browser environment. Accessibility issues and mobile devices can force you to have redundant code. Because many screen readers and other assistive devices do not support JavaScript/Ajax, you need to provide alternate functionality. Your application might not require extra data updates to the browser between pages. So with all that said, you might decide that Ajax isn't for you and you will find another article to read. Wait, that's no fun. Read on, my friend, this stuff is way too cool not to add to your applications.
The bottom line is to take it slow. Find an application that could use a little kick, and add a dash of Ajax to a user form or wizard. Once you get your feet wet and understand how a little effort can produce some effective user enhancements, you will be ready to really add some magic to your portal applications.
When is Ajax and Portal NOT a good fit ???
44 © 2007 IBM Corporation
2007 【 IBM developerWorks 開發者大會】
IBM developerWorks| Oct 2007
When you add Ajax to a portal application, you are effectively adding multiple controllers to the classic MVC pattern. This decision has the potential benefit of forcing a cleaner separation of the model logic. The downsides are the added complexity and the unavoidable requirement to break the controller apart into these three aspects:
• The portlet • The servlet or Web service • The JavaScript-based client
The basic premise of using Ajax in a portal application is the need for a separate controller. Under normal circumstances, you use a servlet to perform the communications with the Ajax client. You can either bundle the servlet with the portlet WAR file or include it as part of a stand-alone Web application.
Figure 1 shows potential Ajax server targets
If you bundle the servlet with the portlet WAR file, then you can share session data between the servlet and the portlet. The servlet, portlet, and the model code are tightly coupled.
If you do not need this level of coupling and the data and logic to be processed by Ajax are not dependent on the portlet, then you can create a stand-alone servlet or Web service to promote reuse.
Design Considerations
45 © 2007 IBM Corporation
2007 【 IBM developerWorks 開發者大會】
IBM developerWorks| Oct 2007
Figure 1 shows potential Ajax server targets.
46 © 2007 IBM Corporation
2007 【 IBM developerWorks 開發者大會】
IBM developerWorks| Oct 2007
One of the downsides to implement Ajax is the difficulty in writing good cross-browser JavaScript.
There are many JavaScript and DHTML toolkits that provide Ajax abstractions. In fact, there are too many to test, to determine which one best fits your needs. As with all open source projects, there will likely be a shake-out over the next couple of years. A few of the most promising and well-designed toolkits that we have used are: Dojo, Rico, and DWR (see Resources). DoJo is preferred because it has an advanced Aspect-like architecture. DWR, or Direct Web Rendering, provides an easy mechanism to reference host-based JavaBeans from the client Javascript. Because there are many other good ones available, you need to determine what works for you.
Ajax toolkits
47 © 2007 IBM Corporation
2007 【 IBM developerWorks 開發者大會】
IBM developerWorks| Oct 2007
To implement Ajax in your portal application, you need to follow a few simple steps. The following discussion assumes that you are bundling your Ajax servlet with your portlet WAR file.
1. Create and define the Ajax servlet. 2. Define a JavaScript reference variable that points to the servlet.3. Load any external JavaScript files. 4. Implement the Ajax framework.
Adding Ajax to a portlet application
48 © 2007 IBM Corporation
2007 【 IBM developerWorks 開發者大會】
IBM developerWorks| Oct 2007
1. Create and define the Ajax servlet
Listing 1. Servlet mapping in the web.xml
<servlet> <servlet-name>MyAjaxServlet</servlet-name> <display-name>MyAjaxServlet</display-name> <description></description> <servlet-class> com.ibm.ajax.MyAjaxServlet </servlet-class> </servlet> <servlet-mapping> <servlet-name>MyAjaxServlet</servlet-name> <url-pattern>/Ajax</url-pattern> </servlet-mapping>
The process of bundling a servlet with your portlet WAR file is very straight forward; however, even seasoned portlet developers are not always sure of all the details. So, here are the complete and sordid details.
• Define the servlet in the web.xml file, as in Listing 1 • Include the servlet JAR file or classes.
49 © 2007 IBM Corporation
2007 【 IBM developerWorks 開發者大會】
IBM developerWorks| Oct 2007
You need to define the global reference (see Listing 2) in the JSP file so that you have access to the portlet request library. After the global variable is defined, any JavaScript included can safely use it to point to the servlet.
Listing 2. Global reference to the servlet.<script type="text/javaScript"> var PATH = "<%= request.getContextPath() %>"; var Ajax_SERVLET = PATH + "/Ajax"; </script>
2. Define a JavaScript reference to the servlet
50 © 2007 IBM Corporation
2007 【 IBM developerWorks 開發者大會】
IBM developerWorks| Oct 2007
As with any external resource to be added to a portlet page, you must encode the URL and set the base context, as in Listing 3.
Listing 3. Script to encode the URL and set the base context.<script type="text/javascript" src="<%=renderResponse.encodeURL( renderRequest.getContextPath() + "/js/myajax.js?v1.1.2")%>" > </script>
Tip: By using a string argument on the JavaScript parameter, you force the browser to perform a cache refresh on each load. If you have JavaScript that might change frequently, this refresh forces browsers not to used old cached code. This example uses a version ID (?v1.1.2), but any string will work.
3. Load any external JavaScript files
51 © 2007 IBM Corporation
2007 【 IBM developerWorks 開發者大會】
IBM developerWorks| Oct 2007
Making Ajax perform its magic consists of a few boilerplate actions. Here’s the overview.
• Create a global XMLHttpRequest object variable. Because all communications are asynchronous, you must define a unique variable for each Ajax event.
• Define an event to trigger the process. Typically, you use a JavaScript event in an input tag. For example:<input onChange='eventHandlerFunction()' ... >
• Define a function to handle the event; specifically, implement these tasks: • Instantiate the XMLHttpRequest (xhr) object variable. Details of this are browser
specific, which we will cover in the future tutorial. • Set the xhr callback function. xhr.onreadystatechange() • Set the servlet, type, and parameters. xhr.open(), xhr.setRequestHandler(), and
xhr.send()• Define a call-back function to process the communication states and the response
data. • This function handles the various communication state changes, such as when
the call starts, when a connection is established, and when the response has been received.
• Processing of the response typically consists of parsing the returned XML (or other contents), and using this data to update the DOM tree.
4. Implementing the AJAX Framework
52 © 2007 IBM Corporation
2007 【 IBM developerWorks 開發者大會】
IBM developerWorks| Oct 2007
53 © 2007 IBM Corporation
2007 【 IBM developerWorks 開發者大會】
IBM developerWorks| Oct 2007
There are several issues that you should be aware of when implementing Ajax in a portal application.
Global JavaScript variables
In general, avoid using global variables in JavaScript within a portal application because of the fact that the portal aggregates several portlets into a single page. Namespacing of global JavaScript variables (as in Listing 4) is a good practice because you guarantee unique variable names, even if the same portlet is deployed twice on the same page.
Listing 4. Namespacing JavaScript variables.// Global XMLHttpRequest variable var <portlet:namespace />xhrFieldsRequest;
Tip: If you use an Ajax toolkit, the abstraction layer will resolve any naming conflicts.
Portal Specific Concerns for AJAX
54 © 2007 IBM Corporation
2007 【 IBM developerWorks 開發者大會】
IBM developerWorks| Oct 2007
ID attributes are often used in Ajax to quickly update a portion of the page. Because ID attributes within any HTML tag are global to the DOM, you need to make sure they are unique. If you have duplicate ID attributes, then results are unpredictable but generally not what you want, and the problem can be maddening to track down.
To be safe, namespace all ID attributes, even though doing this can make your code difficult to read, as you can see in Listing 5.
Listing 5. Safely namespacing an ID attribute.
<h1 id="<portlet:namespace />header">Hello</h1> <script type="text/javascript"> var x = document.getElementByID ("<portlet:namespace/>header"); x.innerHtml = "GOODBYE!"; </script>
Tips: Using ID attributes
55 © 2007 IBM Corporation
2007 【 IBM developerWorks 開發者大會】
IBM developerWorks| Oct 2007
One pitfall that you can easily fall into is the inherent lack of state management when using Ajax calls in a portal. There is nothing to stop the user from taking an action in a portlet that can cause a page refresh. You need to make sure that any Ajax activity can be restarted without any dependency on the previous state. While it is possible to use cookies or Ajax calls to a servlet to check and store state information, avoid a dependency on the page's state. Make all Ajax calls atomic.
Other state issues that can easily trip you up are the back button and bookmarked URLs. In general, avoid major state changes based on Ajax. Leave that to real portal actionPerformed() calls.
Sharing session data
When you bundle a servlet with your portal application, you can share session data between the servlet and portlet. Typically, you want to use Application scope when sharing session data. To the servlet, this is the normal Session scope. To access Portlet scope variables from the servlet requires a special namespaced name value that is based on the portlet's ID that was set when it was originally deployed into a portal. It is very difficult to extract this value during development. Although mostly academic, the syntax of the Portlet scope variables is:
javax.portlet.p.<ID>?<NAME>Where:<ID> is the unique identification for the portlet<NAME> name used to set the object in the Portlet session
Tips: State maintenance
56 © 2007 IBM Corporation
2007 【 IBM developerWorks 開發者大會】
IBM developerWorks| Oct 2007
Action URLs can be very tricky to deal with when using Ajax. In general, you should not attempt to store Action URLs in the shared session, because they are only valid for the current doView(). Attempting to use an ActionURL that was stored in the session from a previous doView() cycle will cause unpredictable results.
An example of when you would want to store Action URLs into the session is an Ajax-driven paging data table that contains Action URL links as part of the data set. When the user clicks Next, the browser generates an Ajax call to the servlet. Then, the servlet extracts the next page of data from the session, and it must have predefined Action URLs. Just be sure that anytime a doView() call is processed that any session data holding any Action URLs is regenerated.
Tips: Action URLs
57 © 2007 IBM Corporation
2007 【 IBM developerWorks 開發者大會】
IBM developerWorks| Oct 2007
Portal pages are often very busy, with a lot of aggregated information stuffed onto a single page. Because Ajax calls are performed in the background and they do not trigger the activity icon on the browser, you need to provide a consistent, visual mechanism to inform the user that something is going on. Otherwise, they can get confused and not know that the application is busy processing some action. (We surely don't want confused users.)
You could implement this notification using a floating DIV section display during activity, or using a simple message on the browser's status bar (although this is considered bad form by some). You could also integrate a custom theme extension that would display a common Please Wait message for any Ajax-enabled portlet on the page.
Tips: Activity Notification
58 © 2007 IBM Corporation
2007 【 IBM developerWorks 開發者大會】
IBM developerWorks| Oct 2007
In this article, we described how and why you would use Ajax in your portal applications.
Conclusion
59 © 2007 IBM Corporation
2007 【 IBM developerWorks 開發者大會】
IBM developerWorks| Oct 2007
Learn
Introduction to Ajax on DeveloperWorks Dojo Rico DWR script.aculo.us Behaviour Zimbra Ajax Patterns http://www.clearnova.com/ajax/index.html http://www.yourhtmlsource.com/javascript/ajax.html http://en.wikibooks.org/wiki/Programming:Ajax Mozilla Developer Center Ajax in Action Dynamic HTML, The Definitive Guide, O'Reilly JavaScript, The Definitive Guide, O'Reilly Build enterprise SOA Ajax clients with the Dojo toolkit and JSON-RPC
Get products and technologies
Ajax Toolkit Framework (IBM alphaWorks) Ajax Toolkit Framework (eclipse.org)
Resources