Tuesday, September 25, 2007

Sruts 2 for dummies
Sruts 2 for dummies

Requests:

Struts 2 uses OpenSymphony's WebWorks and XWorks frameworks. XWorks frameworks implements IOC (Inversion Of Control) framework, thus decoupling
command receivers from originators. Its an extension to the Command Pattern from Struts 1.x to additionally allow the Action objects to be independent of
the HTTPServletRequest/Response. It all looks rather complex initially but it is very trivial... Just following two tips would help.

1) When using command pattern instead of receivers requiring to implement interface with execute(param1, param2, ....), let them
implement just execute() without any arguments. Now send these arguments to the receiver via hashmap. in global visibility.

Receiver if interested in request parameters can request them using singleton object ActionContext.

2) Now if ActionContext is a singleton, how to chain ActionContext. For this the framework, uses concept similar to Stack.
Every ActionProxy (not exactly Action, to remove burden from us) saves its ActionContext (or caches locally) in a local variable before calling a next Action. At the end of the Action,
it restores its ActionContext. This is not tough, just ...

Save ActionContext;
try {
ActionInvocation.Action...
} catch () {}
Finally
{
restore ActionContext;
}


Two direct advantages of this IOC approach are:

1) Filters as per Aspect Oriented Programming (AOP) need not require to implement the delegation model where they dispatch the request using chain pattern.
Similary while receiving response.

2) Unit testing of the actions is simplified as they are independent of container related parameters.


Return Values from Actions.

Earlier in Struts 1.x all actions used to explicitly add results to request,session ( for pull model of Model 2 Architecture ) to allow view to access the return values or access to the model objects
But if there is no direct access to HTTPRequest for Action objects, how can they access them. Well they can still get them using the ActionContext right. Struts 2 also uses OGNL notation to allow to retrieve
responses or model objects using stack. As Actions are being executed in a chain pattern (like I said earlier the stack model), the responses will also be available in the stack model. The last action in the ActionChain
will save the objects at the bottom of the stack (or at the top ?). OGNL allows objects to be retrieved using a notation convenient to use in templates/views. such as top, indexed notation etc.