Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.
Comment: Migrated to Confluence 5.3

A striking difference in SAF2 attribute of the framework is the brevity of its signatures. For example:

SAF1 S1 Action

Code Block
ActionForward execute(ActionMapping, ActionForm, ServletRequest, ServletResponse)

SAF2 S2 Action

Code Block
String execute()

...

To keep signatures brief, and methods useful, SAF2 the framework uses two techniques: Dependency Injection and Thread Local, both of which, in turn, rely on the ActionContext.

Dependency Injection

Many Interceptors are used to populate propertes on an Action. For example, the Servlet Config Interceptor can set Map properties representing the HTTP Request, Session, and Appplication objects.

...

Code Block
String intercept(ActionInvocation invocation)

Looking through ActionInvocation, there are several interesting properties, but nothing that reveals the HTTP contexts. (Good thing! since it is a web-independant XWork class.)

So how does an Interceptor obtain the HTTP contexts to inject?

ThreadLocal

The ThreadLocal class is not a new kid on the block. It's been available to developers since Java 1.2. In effect, each thread has its own copy of the variables on a ThreadLocal class.

SAF2 The framework uses ThreadLocal in connection with the ActionContext class to make servlet configuration and other runtime details available.

ActionContext

From anywhere within an SAF2 Struts 2 application, you can obtain a reference to the ActionContext by calling

Code Block
ActionContext context = ActionContext.getContext();

For example, if a helper class is called from an Action, and if it happens to need access to ServletContext (maybe it is writing a file and needs ServletContext to get a path to it), the helper can obtain the ActionContext directly. Nothing needs to be passed from the Action.

In SAF1frameworks like Struts 1, details like the runtime request and response are passed around like hot potatoes. In SAF2Struts 2, such details are bundled together in the ActionContext. In SAF1S1, Actions are bound to HTTP through the execute signature. In SAF2S2, Actions can be a plain old Java object, and each bound to HTTP only to the extent required.

...

The darker side is that classes that depend heavily on ThreadLocal can be diffcult to unit test. A cleaner design centralizes access to ThreadLocal variables, so that other classes are easier to test.

Back to

...

FAQs

...

This material originally adopted from http://wiki.apache.org/struts/ActionContext?action=edit.