Showing posts with label Struts. Show all posts
Showing posts with label Struts. Show all posts

Wednesday, August 4, 2010

SPRING Struts2 + Spring + JUnit

Hopefully this entry serves as some search engine friendly documentation on how one might unit test Struts 2 actions configured using Spring, something I would think many, many people want to do. This used to be done using StrutsTestCase in the Struts 1.x days but Webwork/Struts provides enough flexibility in its architecture to accommodate unit testing fairly easily. I’m not going to go over how the Spring configuration is setup. I’m assuming you have a struts.xml file which has actions configured like this:



namespace="/site" extends="struts-default">
name="deletePerson" class="personAction"
method="deletePerson">
name="success">/WEB-INF/pages/person.jsp


...
You also might have an applicationContext.xml file where you might define your Spring beans like this.


id="personAction"
class="com.arsenalist.action.PersonAction"/>
...
Then of course you also need to have an action which you want to test which might look something like:
public class PersonAction extend ActionSupport {


private int id;

public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String deletePerson() {
....
return SUCCESS;
}
}
Remember than in Struts 2, an action is usually called before and after various other interceptors are invoked. Interceptor configuration is usually specified in the struts.xml file. At this point we need to cover three different methods of how you might want to call your actions. 1. Specify request parameters which are translated and mapped to the actions domain objects (id in the PersonAction class) and then execute the action while also executing all configured interceptors. 2. Instead of specifying request parameters, directly specify the values of the domain objects and then execute the action while also executing all configured interceptors. 3. Finally, you just might want to execute the action and not worry about executing the interceptors. Here you’ll specify the values of the actions domain objects and then execute the action. Depending on what you’re testing and what scenario you want to reproduce, you should pick the one that suits the case. There’s an example of all three cases below. The best way I find to test all your action classes is to have one base class which sets up the Struts 2 environment and then your action test classes can extend it. Here’s a class that could be used as one of those base classes. See the comments for a little more detail about whats going on. One point to note is that the class being extended here is junit.framework.TestCase and not org.apache.struts2.StrutsTestCase as one might expect. The reason for this is that StrutsTestCase is not really a well written class and does not provide enough flexibility in how we want the very core Dispatcher object to be created. Also, the interceptor example shown in the Struts documentation does not compile as there seems to have been some sort of API change. It’s been fixed in this example.
public class BaseStrutsTestCase extends TestCase {


private Dispatcher dispatcher;
protected ActionProxy proxy;
protected MockServletContext servletContext;
protected MockHttpServletRequest request;
protected MockHttpServletResponse response;

/**
* Created action class based on namespace and name
*/

protected T createAction(Class clazz, String namespace, String name)
throws Exception {

// create a proxy class which is just a wrapper around the action call.
// The proxy is created by checking the namespace and name against the
// struts.xml configuration
proxy
= dispatcher.getContainer().getInstance(ActionProxyFactory.class).
createActionProxy
(
namespace, name, null, true, false);

// set to true if you want to process Freemarker or JSP results
proxy
.setExecuteResult(false);
// by default, don't pass in any request parameters
proxy
.getInvocation().getInvocationContext().
setParameters
(new HashMap());

// set the actions context to the one which the proxy is using
ServletActionContext.setContext(
proxy
.getInvocation().getInvocationContext());
request
= new MockHttpServletRequest();
response
= new MockHttpServletResponse();
ServletActionContext.setRequest(request);
ServletActionContext.setResponse(response);
ServletActionContext.setServletContext(servletContext);
return (T) proxy.getAction();
}

protected void setUp() throws Exception {
String[] config = new String[] { "META-INF/applicationContext-aws.xml" };

// Link the servlet context and the Spring context
servletContext
= new MockServletContext();
XmlWebApplicationContext appContext = new XmlWebApplicationContext();
appContext
.setServletContext(servletContext);
appContext
.setConfigLocations(config);
appContext
.refresh();
servletContext
.setAttribute(WebApplicationContext.
ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE
, appContext);

// Use spring as the object factory for Struts
StrutsSpringObjectFactory ssf = new StrutsSpringObjectFactory(
null, null, servletContext);
ssf
.setApplicationContext(appContext);
//ssf.setServletContext(servletContext);
StrutsSpringObjectFactory.setObjectFactory(ssf);

// Dispatcher is the guy that actually handles all requests. Pass in
// an empty Map as the parameters but if you want to change stuff like
// what config files to read, you need to specify them here
// (see Dispatcher's source code)
dispatcher
= new Dispatcher(servletContext,
new HashMap());
dispatcher
.init();
Dispatcher.setInstance(dispatcher);
}
}
By extending the above class for our action test classes we can easily simulate any of the three scenarios listed above. I’ve added three methods to PersonActionTest which illustrate how to test the above three cases: testInterceptorsBySettingRequestParameters, testInterceptorsBySettingDomainObjects() and testActionAndSkipInterceptors(), respectively.
public class PersonActionTest extends BaseStrutsTestCase {


/**
* Invoke all interceptors and specify value of the action
* class' domain objects directly.
* @throws Exception Exception
*/

public void testInterceptorsBySettingDomainObjects()
throws Exception {
PersonAction action = createAction(PersonAction.class,
"/site", "deletePerson");
pa
.setId(123);
String result = proxy.execute();
assertEquals
(result, "success");
}

/**
* Invoke all interceptors and specify value of action class'
* domain objects through request parameters.
* @throws Exception Exception
*/

public void testInterceptorsBySettingRequestParameters()
throws Exception {
createAction
(PersonAction.class, "/site", "deletePerson");
Map params = new HashMap();
params.put("id", "123");
proxy
.getInvocation().getInvocationContext().setParameters(params);
String result = proxy.execute();
assertEquals
(result, "success");
}

/**
* Skip interceptors and specify value of action class'
* domain objects by setting them directly.
* @throws Exception Exception
*/

public void testActionAndSkipInterceptors() throws Exception {
PersonAction action = createAction(PersonAction.class,
"/site", "deletePerson");
action
.setId(123);
String result = action.deletePerson();
assertEquals
(result, "success");
}
}
The source code for Dispatcher is probably a good thing to look at if you want to configure your actions more specifically. There are options to specify zero-configuration, alternate XML files and others. Ideally the StrutsTestCaseHelper should be doing a lot more than what it does right now (creating a badly configured Dispatcher) and should allow creation of custom dispatchers and object factories. That’s the reason why I’m not using StrutsTestCase since all that does is make a couple calls using StrutsTestCaseHelper. If you want to test your validation, its pretty easy. Here’s a snippet of code that might do that:
 public void testValidation() throws Exception {

SomeAction action = createAction(SomeAction.class,
"/site", "someAction");
// lets forget to set a required field: action.setId(123);
String result = proxy.invoke();
assertEquals
(result, "input");
assertTrue
("Must have one field error",
action
.getFieldErrors().size() == 1);
}
This example uses Struts 2.0.8 and Spring 2.0.5.

Tuesday, August 3, 2010

Best practices for Struts development

Struts: A brief introduction

Struts, an open source framework you can use to build Web applications, is based on the popular Model-View-Controller (MVC2) design paradigm. The framework is built upon standard technologies like Java Servlets, JavaBeans, ResourceBundles, and XML, and it provides flexible and extensible components. Struts implements the Controller layer in the form ofActionServlet and recommends building the View layer using JSP tag libraries. Struts also provides a wrapper around the Model layer through Action classes. Figure 1 illustrates the Struts framework based on the Model-View-Controller design.

Figure 1. Struts and MVC
Struts and MVC

Overview of Struts components

First, we’ll explain the Struts components in the context of best practices and the role each one plays in your Web application development.

Action

Every Action of your application extends Struts’ org.apache.struts.action.Action. These Action classes provide an interface to the application’s Model layer, acting as a wrapper around the business logic. Each Action class must provide its case-specific implementation to the perform() method. The perform() method always returns a value of type ActionForward.

ActionForm

Every ActionForm of your application extends Struts’org.apache.struts.action.ActionForm. ActionForms are simple JavaBeans that encapsulate and validate request parameters. To validate your request data, yourActionForm’s validate() method must give a case-specific implementation. ActionForms serve as a carrier of request data to the Action class. A JSP object combines with a respective ActionForm to form your application’s View layer, where almost every form field of the JSP object maps to an attribute of the corresponding ActionForm.

JSP custom tag libraries

The JSP custom tag libraries are a collection of actions presented as tags. This is a powerful feature of the JSP Specification 1.1; it allows you to separate presentation from other application tiers. The libraries are easy to use and you can read them in XML-like fashion. You can easily maintain the JSP components by minimizing the use of Java scriptlets in them. The JSP tags that Struts provides include HTML, logic, and bean tags.

ActionErrors

You use ActionErrors to support exception handling. An ActionError traps and propagates an application exception to the View layer. Each one is a collection ofActionError instances. ActionErrors encapsulate error messages, while the in the Presentation layer renders all error messages in the ActionErrorcollection.

Best Practice 1. Reuse data across multiple ActionForms

Now that you are familiar with the Struts components, we will continue by showing you ways to get the most out of the framework. First, Struts recommends that you associate every JSP object with an ActionForm, which encapsulates data represented in the screen. You access the form data in the JSP object using accessory methods found in ActionForm. Listing 1 shows the conventional use of ActionForm tag in the View layer.

Listing 1. Using ActionForm in JSP

              

The ActionForm called “BP1AForm” includes the attribute attrib1, as well as its getter and setter methods. In the configuration file struts-config.xml, the action “/bp1” maps to bp1AForm using the name attribute. This facilitates data display in the JSP.

To implement this best practice, Struts recommends you do two things:

  1. Create a JavaBean (BP1BForm) with attributes that form an attribute subset in BP1AForm, along with the attributes’ getter and setter methods.
  2. Replace the attributes in BP1AForm with the bean BP1BForm by associating the bean withBP1AForm. Now you can access this attribute subset in BP1AForm through BP1BForm. Listing 2 shows you how.

Listing 2. Accessing form attributes in JSP

                   

Points to remember

This practice’s main advantage is that you can use it when you need multipleActionForms to access a set of attributes. When following this best practice, you’ll want to keep in mind the following:

  • Struts implements the tag.
  • When the code <%@ taglib uri="struts-bean.tld" prefix="bean" %> points to struts-bean.tld, the tag starts to work in the JSP components.
  • BP1AForm’s validation framework, which extends ActionForm, must validate BP1BForm’s data.

When creating Action classes in your application, instead of directly extendingorg.apache.struts.action.Action, create an Action class (IntermediateAction) by extending org.apache.struts.action.Action to handle common things in your application. All other Action classes extend this IntermediateAction class.

Best Practice 2. Use Action class to handle requests

Typically when using the Struts framework, for every action the JSP component requests your application to execute, the application must extend Struts’org.apache.struts.action.Action to create an Action class. This individual Actionclass interfaces with the application’s Model layer while processing the request.

To implement this practice, Struts recommends you follow these steps:

  1. Create an Action class, say BP2Action, by extending org.apache.struts.action.Action.
  2. Create all other Action classes in your Web application by extending BP2Action.
  3. In BP2Action, create a method performTask(), as in public abstract ActionForward performTask(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException.
  4. In BP2Action add one or more generic methods to the application, for exampleserverSideValidate(). You can decide on the method’s access modifier by considering the following factors:
    • If all Action classes must implement this method, make it abstract.
    • If some Action classes will provide a case-specific implementation, declare the method protected and give it a default implementation.
  5. In BP2Action, declare method perform() as final. Invoke the above generic method, which must always be called before processing the request. Now call the method performTask()created in step 3.
  6. In every Action class extending BP2Action, add method performTask() with a case-specific implementation.

Advantages

This practice has two main advantages. First, it helps you avoid redundant code in everyAction class of your Web application. Second, it gives the application more control over generic tasks by centralizing the behavior in one Action class.

Best Practice 3. Use ActionForm to work on session data

In a Struts-based Web application, each ActionForm extendsorg.apache.struts.action.ActionForm. These ActionForms encapsulate page data and provide a validation framework to validate request parameters.

Most Web applications maintain data in session to make them available throughout the application. This best practice addresses this Web application feature. It allows methodstoSession() and fromSession() to move session data to and from the form data. Thus, it addresses session data maintenance in a Web application.

To adhere to this practice, follow these steps:

  1. Create an abstract class named BP3Form by extendingorg.apache.struts.action.ActionForm.
  2. In BP3Form, add methods with access modifiers as in public abstract void toSession(SessionData sessionData) and void fromSession(SessionData sessionData).
  3. In every ActionForm, extend BP3Form and implement the abstract methods in which the form data is transported to and from the session.
  4. The corresponding Action class may determine the order in which these methods are called. For example, you could invoke method toSession() on the ActionForm just beforeactionForward is determined.

When to use this practice

This practice is most useful when session data is maintained as a single object and/or every page manipulates or uses session data.

Best Practice 4. Handle exceptions effectively

Conventionally, when an application exception occurs in an Action class, the exception is first logged. Then the class creates an ActionError and stores it in the appropriate scope. This Action class then forwards control to the appropriate ActionForward. Listing 3 shows how Action class handles exceptions.

Listing 3. Exception handling in an Action class

   try {    //Code in Action class    }    catch (ApplicationException e) {    //log exception    ActionErrors actionErrors = new ActionErrors();    ActionError actionError = new ActionError(e.getErrorCode());    actionErrors.add(ActionErrors.GLOBAL_ERROR, actionError);    saveErrors(request, actionErrors);    } 

While conventional exception handling procedures save exception information in everyAction class, best practice 4 aims to avoid redundant code while handling exceptions.

To use this practice, Struts recommends following these steps:

  1. Create an Action class, say BP4Action, by extending org.apache.struts.action.Action.
  2. Create all other Action classes in your Web application by extending BP4Action.
  3. In BP4Action, declare variable ActionErrors actionErrors = new ActionErrors();.
  4. In BP4Action, create a method performTask() as in public abstract ActionForward performTask(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response, ActionErrors actionErrors) throws IOException, ServletException.
  5. In BP4Action, declare method perform() as final. Then invoke generic methods, which must always be called before processing the request. Now you can call the method performTask()created in the previous step.
  6. While implementing method performTask() in every Action class (by extending BP4Action), handle application exceptions as shown in Listing 4.

Listing 4. Using ActionErrors effectively

   try   {    //Code in Action class    }    catch(ApplicationException appException) {    //Log exception    //Add error to actionErrors    actionErrors.add(ActionErrors.GLOBAL_ERROR,       new ActionError(appException.getErrorCode()));    }

In BP4Action, after invoking the method performTask(), save the ActionErrors usingsaveErrors(request, errors).

Advantages

This practice’s main advantage is that it avoids code redundancy in every Action class that handles ActionErrors.

In conclusion

Building an easily maintainable Web application can be one of the most challenging tasks for a development team. Using a mature framework like Struts helps you implement the infrastructure code normally associated with building an application. The Struts framework provides a set of standard interfaces for plugging business logic into the application, a consistent mechanism across development teams for performing tasks such as user data validation, screen navigation, and so forth, as well as a set of custom tag libraries to simplify developing screens.

These four best practices are important for you to extract more from the framework’s features. You, as a developer, can benefit from these lessons to increase your code modularity and application reusability, plus minimize code redundancy. These are all critical to building an extensible Web application.

Resources

  • Find out more about Struts at the Jakarta Struts Home page.

  • Download the Struts source code.
  • Read “Struts, An Open-Source MVC Implementation” for an introduction to Struts (developerWorks, February 2001).
  • Discover the “Struts Adoption” discussion of pertinent Struts issues.
  • Explore a useful reference on Struts, Mastering Jakarta Struts by James Goodwill (Wiley Publishers, 2002).
  • Read about changes to Struts, including the Tiles library in “Struts and tiles aid component-based development” (developerWorks, June 2002).
  • Browse for books on these and other technical topics.
  • Visit developerWorks Web Architecture and Java technology zones for a range of articles on the topics of Web architecture, usability, and Java.