1 - Sys-con

flashyfarctateInternet and Web Development

Jul 30, 2012 (5 years and 3 months ago)

253 views

Author:
Kris Vishwanathan

Struts p
ortlets with Ajax in action


Title:

Struts portlets with Ajax in action




Introduction


Struts framework from Apache is
very popular,

robust web application framework. Many
corporate companies have deployed tons of web applications using Struts. In addition,
they have abundant techn
ical resources to hit the ground and develop

newer
a
pplications quickly. Implementations of portals bring

in a new challenge by introducing
new frameworks and API’s.

To leverage on those existing assets and skills, WebSphere
Portal supports Struts Portlet
f
ramework using which, Struts web applications can be
easily migrated to portal.


AJAX, or Asynchronous JavaScript and XML is a new happening technology to make
web applications function like client server applications.

I mean web pages triggering
requests

basing on events (asynchronously) and refreshing only certain parts of the
page as against refreshing the whole page.



Struts Framework


There is

tons of information on Struts, AJAX and Struts Portlet Framework on the
web. In this
article,

I am going to
provide brief introduction on these topics, for more
details look in the resources section below.


Struts framework is an implementation of MVC architecture, with Model being the
business logic represented using Java beans, EJB’s

etc.
, View is the presenta
tion
layer
represented

using JSP
’s
, ActionForms,

and tag libraries
, Controller is the
ActionServlet and Action classes.





Action Servlet

Action c
lasses

S
truts configuration

file


Model


View

Controller



Presentation Layer:

JSP’s
,
Action Forms

Tag
l
ibraries



Form Bean’s,

EJB

etc.

Author:
Kris Vishwanathan

Struts p
ortlets with Ajax in action

Fig 1: MVC Architecture and Struts Components



Struts Control Flow:


Here is the typical request
-
response

cycle for the web

application using S
truts:




Client requests a path matching Action URI pattern.



The
web
container passes the request to the ActionServlet.



ActionServlet looks up for the Struts

configuration file
, if this application has
multiple

modules
it looks for the appropriate mapping for the given path in
any of the struts configuration file.



If the mapping specifies a form bean
, Act
ionServlet looks if one

created

or it
creates one.



Once the form bean created, ActionServlet populates values from HTT
P
request.

If the mapping has validate property as true, ActionServlet invokes
validate method on the form bean. If the validation fails, control flow ends
there.



If the struts configuration file specifies the action mapping, then the
appropriate action cl
ass
‘execute’ method
invoked with instantiated form bean

as a parameter
.



The Action may call other business
objects;

re
-
populate the form bean with
latest values and other business functions as needed.



Basing on where you want to send the control next, Act
ion reads
ActionForward, Action URI from the struts configuration file and returns to
ActionServlet.



If the ActionForward is a URI to JSP to display the page, control flow ends by
sending the output to the browser or if it is forward to another Action URI
the
above flow starts again.




Ajax

in Action


Ajax


asynchronous JavaScript and XML is
though not
a new technology,

but most
happening thing in the web world that

gives desktop, and client server application
feel to your web applications.


Ajax
Control
Flow:




Web page sends its requests using
XMLHttpRequest object and
JavaScript
function, which handles talking to the server.



For the web

application

server nothing changed it still responds to each
request, the way it did it before.



The servers response ha
s on
ly

the data it needs in the XML form, without any
markup or presentation



The JavaScript dynamically updates the web page without redrawing

the
whole page.

Author:
Kris Vishwanathan

Struts p
ortlets with Ajax in action



Most of the page does not change, only part of the page that needs to
change is updated
,

that too

asynchronously.



F
ig 2: Ajax control flow




Struts Portlet Framework


Developers that have experience with Struts framework should
easily adapt to Struts
Portlet f
ramework. The packaging for Struts Portlet Application is simi
lar to Struts
application in the servlet environment. However, WebSphere Portal introduces additional
challenges such as portlet modes,
states
, inter
-
portlet communications, portlet two
phase processing and multiple device support etc., which are addressed

through Struts
Portlet Framework.

For detailed
explanation on this topic,

refer to
the Redbook
IBM
Rational Application Developer V6 Portlet Application Dev
elopment and Portal Tools


A portlet has a different processing and rendering then
a

servlet.

A servlet will do all of
its processing in the service method, where as portlet will divide action processing and
rendering into two separate methods, hence the
portlet processing is defined in two
phase approach
. Below figure explains the two phase processing approach of a Struts
portlet.


JavaScript
event

XML response

JavaScript

XMLHttpRe
quest

BackendServer

c
reates

sendRequest()

callback()

p
arse
response
message

refresh
web page

Author:
Kris Vishwanathan

Struts p
ortlets with Ajax in action


Fig 3: Struts portlet control flow


T
o
invoke actions in the

rendering

phase

there is a new inte
rface called
IStrutsPrepareRenderer,
. For more details refer to
Executing Struts actions during the
render phase of IBM WebSphere Portal.


IBM support
s Struts portlet framework for both IBM API and JSR 168 API portlet
containers. Users can easily migrate existing Struts applications into Struts portlet
application using either of the portlet API’s. For more infor
mation on the migration, and

developing n
ewer applications using Struts
Portlet f
ramework refer to
Portal Info Center
.




Struts portlets with Ajax



Though Ajax is not the right solution for every web appl
ication, there is increasing
curiosity and enthusiasm among organizations to explore its benefits and see how it
works for their applications.
Ajax is not new, but its all on the client side and making it to
work with different server side frameworks is a
challenge.
This article is a result of
my
client experience to develop
Struts portlet application with

Ajax. In the above sections I
described briefly about Struts and Ajax,
in the below sections I will be describing some of
the

challenges
we faced

during
the implementation
.
To develop Ajax applications t
here
are several toolkits

such as Google

Web T
oolkit (GWT)
, DOJO
, Ajax faces and JSON

etc. but we chose plain vanilla implementation for simplicity.


The tricks to asynchronously render the content using Aj
ax is more to do with JavaScript
and XMLHttpRequestObject as against any server side technology, However getting the
r
eturns form bean and the jsp

r
eturns form bean with the jsp

processAction()

WPStrutsPortlet

ActionServlet

WPRequestProccessor

WP
ViewCommand

i
nit()

i
nit()

invokes

s
tores in sess
ion

render

r
eads form bean from session

Author:
Kris Vishwanathan

Struts p
ortlets with Ajax in action

blend of Ajax working with server side frameworks involves careful design and
architectural thinking.



Fig 4
:
Struts Portlet with Ajax data flow


Making asynchronous calls to server using Ajax best fits into portal scenario with
different portlets representing different backend application views.
However
, this
feature
is not supported with portlet URL’s

as each re
sponse from portlet container represents a
portal page with different portlets with different window states and modes.
With this

limitation, alternative we have is XMLHttpRequest object calling a servlet from a servlet
container as depicted in the above di
agram.


To demonstrate the above scenario I have used the simple downloadable example as
shown below:



XML Response


to refresh the JSP

Browser

Server

JavaScript

XMLHttpRequest

WPStrutsPortlet

ActionServlet

Action classes

Servlet

renders

invokes

JSP


1


2


3

PortletJSP

Author:
Kris Vishwanathan

Struts p
ortlets with Ajax in action

When the user clicks on the menu items, right side blue box items gets refreshed without
unloading the whole page.




Below are some of the
challenges

we had and I explained how we addressed them.



JavaScript
Objects


Ajax applications
use

XMLHttp
Request
Object and client side JavaScript, and as

these

applications become more complex it becomes difficult
to
maintain
the code
using plain
JavaScript func
tions.
Object oriented programming is ideal and proven for such complex
applications.
JavaScript offers many different ways of defining objects, but it is not full
-
fledged object oriented programming language. There are several efforts from different
indi
viduals on
providing workarounds for object oriented programming features
such as
inheritance, reflection and interfaces etc. using

JavaScript.


JSON (JavaScript Object Notation) provides guidance on JavaScript object notation. In
our example, we have use
d JSON guidelines and defined all the JavaScript functions as
objects. In addition, we have defined all the functions as external js files so that all the
client side logic is kept modular and separate from the JSP file, thus following the portlet
best pra
ctices.


Here is the

JavaScript code snippet
from the downloadable sample application
defining
an
object and calling the function

as object instance methods.


if (typeof(contentHelper) === 'undefined'){


var
contentHelper =

[];

}

contentHelper['<%=topazNam
espace%>'] = new ContentHelper({


namespace



: "<%=topazNamespace%>",


urlContextPath


: "<%=request.getContextPath()%>"

});



I defined all other

JavaScript functions

in different js files. Below is the definition of
‘ContentHelper’ function.

Author:
Kris Vishwanathan

Struts p
ortlets with Ajax in action


function

ContentHelper(params)
{


//Parameter Variables


if
(!params)
{



alert(
'Missing parameters while instantiating!'
);



return {}
;


}




if
(
typeof
(
w
ebFormUtils)==
'undefined'
)
{



alert(
"The utils package is not included!"
);



return
;


}




var
namespace = para
ms.namespace;


var
urlContextPath = params.urlContextPath;




var
formUtils =
new
w
ebFormUtils(
{



namespace : namespace


}
);




var
ajaxurls =
new

AjaxURLs(
{



namespace : namespace,



urlContextPath : urlContextPath


}
);




var
a
jax
Engine

=
new
AJAXEngin
e(
{



engineStatusHandler : displayAJAXRequests,



validatorFunction : formUtils.validateAJAXResponse,



redirectHandlerFunction : formUtils.handleAJAXRedirect,



retryPromptMessage :
"Warning, there was a problem during an attempt to
communicate with the
server
\
n"
+









"Would you like to retry? (It's
recommended to wait a bit first)
\
n"

+









"If the problem

persists, please contact
Help Desk
"
,



autoRetries : 2,



retryDelay : 10000


}
);


…..

…..

}


Above object/function in turn instantiates othe
r objects such as AjaxUrls and AjaxEngine
etc.



Handling

namespace
with Ajax response


As specified in Fig 3: Struts portlets make asynchronous Ajax requests to servlets.
Servlets process the request and send the response back to the
client, which in turn

is

suppose to refresh certain part
s

of the portlet JSP page.

Portlets being namespace
aware, it is very important that any
web page refresh be

namespace aware.
Author:
Kris Vishwanathan

Struts p
ortlets with Ajax in action

Unfortunately,

servlet is not aware of portlet namespace. To resolve this issue we have
passed
namespace as parameter for every Ajax request, so that servlet
response
can
prefix all the object ids with appropriate namespace.


Accessing form bean in the servlet


Struts actions have nice way of collecting all the HTML form elements using an Action
For
m bean. Behind the scenes, Struts Framework binds all the HTML form elements to
Form bean as per the action mapping specified in Struts configuration file.


Through Ajax request when you are posting a form to a servlet you can use a similar
mechanism using

BeanUtils package, so that you don’t need to do
request.getParameter() for each element value.

For more information on BeanUtils
package refer to apache struts framework website.


Here is the call to Ajax request posting the HTML form:


ajaxEngine.request
(
{




"url"
: url,




"title"
:
"Side Menu"
,




"responseFunction"
: receiveLinkResults,




"postBody"
: serializeContentForm(),




"method"
:
"POST"

}
);


function
serializeContentForm()
{



var
url=
""
;



url+=
"filter="
+encodeURIComponent(document.getElem
entById(
"filter"
).value);



url+=
"&selectType=sideMenuContent"
;



url+=
"&namespace="
+
this
.namespace;



return
url;

}


On t
he server, you can retrieve form elements posted as below:


ContentBean contentBean = new ContentBean();

try {


BeanUtils.populate(c
ontentBean,arg0.getParameterMap());

} catch (IllegalAccessException e) {


// TODO Auto
-
generated catch block


e.printStackTrace();

} catch (InvocationTargetException e) {


// TODO Auto
-
generated catch block


e.printStackTrace();

}

System.out.pri
ntln("Filter="+contentBean.getFilter());

System.out.println("SelectType="+contentBean.getSelectType());


We need to make sure that ContentBean has the properties specified in the HTML form.
In our case, we used the same Action Form bean used by the Struts

portlet.


Session sharing

Author:
Kris Vishwanathan

Struts p
ortlets with Ajax in action


Once you define the Servlets in the same portlet application, you can share session
objects among portlets, JSP and Servlets. Only requirement is to make sure that the
session objects are declared with APPLICATION_SCOPE.


About
the sample code


The
sample
code is a downloadable

zip file with
strutsajaxportlet.
war file

in it. You can
install the war file into WebSphere Portal server and place a portlet on any portlet page
to see it working. If you install the war file into Rationa
l Application Developer you will
find the source code
for
client side ajax engine, JavaScript functions for request and
response handling and the server side portlet and servlet for request processing.



Conclusion


Many organizations today want to leverag
e on existing assets to embrace new
technologies. Struts framework is very popular MVC pattern implementation and very
suitable for large enterprise applications. Struts Portlet Framework is an extension to
Struts that is supported in all major releases of

WebSphere Portal. In this article, I
explained the blend of the Struts Portlet framework with Ajax working together.

Ajax
being on the client side you can make it work with any server side framework. There are
several other initiatives to get Ajax working

with JSF (Java Server Faces), JSON
-
RPC
and Java like programming so that frameworks can convert it to client side script for you.


References


Apache Stuts home page

IBM Redbook: IBM Rational Application Developer V6 Portlet Application
Development and Portlet tools
:

Executing Struts actions during t
he render phase of IBM WebSphere Portal
:

Error validation and exception handling in portlets, using the Struts Portlet
Framework

Developing JSR168 Struts portlets


About the author


Kris Vishwanathan is senior software engineer
at the IBM lab in

RTP, NC………..