28
Struts 2.0 1) Introduction This article provides an introduction to Struts 2.0 and its new Validation Features. Since Struts 2.0 is new, the first few sections of the article discusses in brief about the basics of Struts 2.0, its architecture and its various New Features. The rest of the article is dedicated towards explaining about the new Validation Features available. Struts is an Open-Source Web Application Framework that simplifies the creation of a Java Web Application. It is based on the Model-View-Controller 2 (MVC 2) Architecture which was originally found in a language called SmallTalk. The recent version of Struts is Struts 2.0 and it has borrowed most of the concepts in terms of architecture and functionality from two frameworks namely WebWork and XWork. 2) Struts 2.0 - MVC Architecture Struts 2.0 is based on MVC 2 Architecture. MVC is mainly concentrated in splitting the whole set of logic that happens in an Application into three different layers namely the Model, View and the Controller. In Struts 2.0, the Controller acts as a mediator between the View and the Model components. Whenever a request comes from a client, it is this Controller component who intercepts the request before being passed to Appropriate Handler. Model represents the application data as well as the business logic that operates on the Data. Whenever the Framework routes the request to some Action class, the Action Class will do the Business Processing Logic which results in the State of the Application getting affected. After the application's state is affected, the control is returned back to the Controller which determines which View to be Rendered to the Client Application . View is the Display Surface given as a response back to the Client populated with values. Struts 2.0 is not restricted in having JSP as its only View. Any View Technolgy can be chosen to render the Client Surface. It can be JSP, Velocity, Freemaker, or even XSLT. Even a brand new View technology can be plugged-in easily to the Struts Framework. 3) The Flow of a Struts 2.0 Application The following are the sequence of steps that will happen when a Html Client makes a request to a Web Application built on top of Struts 2.0 The Client (which is usually a Html Browser) makes a Request to the Web Application. The Web Server will search for the Configuration Information that is very specific to the Web Application (taken from the web.xml file), and will identity which Boot-strap Component has to be loaded to serve the Client's Request. In Struts 2.0, this Component is going to be a Servlet Filter (whereas in Struts 1.0, the component is an Action Servlet).

Struts 2

  • Upload
    tlad

  • View
    11

  • Download
    3

Embed Size (px)

Citation preview

Page 1: Struts 2

Struts 2.0

1) Introduction

This article provides an introduction to Struts 2.0 and its new Validation Features. Since Struts 2.0 is new, the first few sections of the article discusses in brief about the basics of Struts 2.0, its architecture and its various New Features. The rest of the article is dedicated towards explaining about the new Validation Features available. Struts is an Open-Source Web Application Framework that simplifies the creation of a Java Web Application. It is based on the Model-View-Controller 2 (MVC 2) Architecture which was originally found in a language called SmallTalk. The recent version of Struts is Struts 2.0 and it has borrowed most of the concepts in terms of architecture and functionality from two frameworks namely WebWork and XWork.

2) Struts 2.0 - MVC Architecture

Struts 2.0 is based on MVC 2 Architecture. MVC is mainly concentrated in splitting the whole set of logic that happens in an Application into three different layers namely the Model, View and the Controller. In Struts 2.0, the Controller acts as a mediator between the View and the Model components. Whenever a request comes from a client, it is this Controller component who intercepts the request before being passed to Appropriate Handler.

Model represents the application data as well as the business logic that operates on the Data. Whenever the Framework routes the request to some Action class, the Action Class will do the Business Processing Logic which results in the State of the Application getting affected. After the application's state is affected, the control is returned back to the Controller which determines which View to be Rendered to the Client Application.

View is the Display Surface given as a response back to the Client populated with values. Struts 2.0 is not restricted in having JSP as its only View. Any View Technolgy can be chosen to render the Client Surface. It can be JSP, Velocity, Freemaker, or even XSLT. Even a brand new View technology can be plugged-in easily to the Struts Framework.

3) The Flow of a Struts 2.0 Application

The following are the sequence of steps that will happen when a Html Client makes a request to a Web Application built on top of Struts 2.0

The Client (which is usually a Html Browser) makes a Request to the Web Application. The Web Server will search for the Configuration Information that is very specific to

the Web Application (taken from the web.xml file), and will identity which Boot-strap Component has to be loaded to serve the Client's Request.

In Struts 2.0, this Component is going to be a Servlet Filter (whereas in Struts 1.0, the component is an Action Servlet).

The Filter Servlet then finds out the Action Class for this Request that is mapped in the Configuration File. File.

Before passing the Request to the Action class, the Controller passes the Request to a series of Interceptor Stack (explained later).

Then the Request Object is passed on to the corresponding Action Class. The Action Class then executes the Appropriate Business Logic based on the Request

and the Request Parameters. After the execution of the Business Logic, a Result ("success" or "error") is returned

either in the form of String or in the form of Result Object back to the Controller. The Controller uses the Return Result to choose which View to be rendered back to the

Client Application.

Let us look into the details of the major steps that was listed above.

Page 2: Struts 2

3.1) Filter Servlet Loaded and Invoked by the Framework

A client makes a Web Request by typing the URL of the Web Application that is hosted in the Web Server something like the following, where localhost is the Machine Name where the Web Server is running, 8080 is the Port Number and hello is the Application Context for the Web Application.

http://localhost:8080/hello

Whenever a Request comes to a Web Application that is Struts 2.0 Enabled, the Web Server will search and load the Configuration Related Information that is very specific to the Application. In the case of a Struts 2.0 enabled Application, the Boot-Strap Component is going to a Filter Servlet. The Configuration Information about the Web Application will be maintained separately in web.xml file. Following is the Xml snippet taken from the web.xml file,

web.xml

<filter> <filter-name>Struts2FilterServlet</filter-name> <filter-class> org.apache.struts.action2.dispatcher.FilterDispatcher </filter-class></filter> <filter-mapping> <filter-name>Struts2FilterServlet</filter-name> <url-pattern>/*</url-pattern></filter-mapping>

The above Xml Code tells that whatever be the Request URI Pattern (which is indicated by /*) that comes from the Client, identify the Component named by Struts2FilterServlet which happens to be the class org.apache.struts.action2.dispatcher.FilterDispatcher. The Identified Component is then instantiated and then passed with the Request Information.

3.2) Request Intercepted by Interceptors

Interceptors provide Pre-processing and Post-processing functionality for a Request or a Response object in a Web Application. For general information about Interceptors, readers can go through this section on JavaBeat. A Request Object usually passes through a Series of Interceptors before actually reaching the Framework. Assume that some kind of Authentication and Authorization related stuffs have to be done before a Request Object is being passed to a particular Module. In such a case, we can have the Core Business Logic that does the functionality of authorizing the Client Request in an Interceptor called AuthenticationInterceptor which does the Pre-processing works. Implementing a Custom Interceptor like this is very simple in Struts 2.0. The class structure may look like this,

AuthenticationInterceptor.java

package myinterceptors;

import com.opensymphony.xwork2.interceptor.*;

Page 3: Struts 2

class AuthenticationInterceptor implements Interceptor{

public void init(){}

public void destroy(){}

public String intercept(ActionInvocation invocation) throws Exception{

// Get the value of user credentials from the Request and Validate it.

}}

As we can see, writing a Custom Interceptor is as simple as writing a class that implements the Interceptor interface which is found in the com.opensymphony.xwork2.interceptor package. The method of interest is Interceptor.intercept() which has to be overriden along with the the appropriate business logic. Then the Custom Interceptor has to be made available to the framework by adding information in the Configuration File (struts.xml) as shown below,

struts.xml

<struts>

... <interceptors> <interceptor name = "authentication" class = "myinterceptors.AuthenticationInterceptor"> </interceptor> <interceptors> ... </struts>

Interceptors are configured into the Web Application in the struts.xml file with the help of <interceptors> and <interceptor> entries. The name attribute is the alias name of the interceptor and it must be unique among the other set of Interceptor names. The class attribute identifies the actual implementation class for an Interceptor. The advantages of interceptors is not only limited to this. Interceptors can participate in so many different activities, to name a few - providing Logging Information to an Application, providing Encryption Facilities for the user input that used to get transmitted across layers, etc.. . Struts 2.0 already comes with a bunch of Built-in Useful Interceptors.

3.3) Performing some Action for a Request

After passing through a series of Interceptors, now it is time for the Framework to determine what Action has to be done for the Request. The Mapping between a Request and its Corresponding Action is configurable in the Xml Configuration File. Assume that in a Web Application, Regitration, Login and Logout represents the different set of actions. Let us have an assumptions that the operations are fairly complex, so that we tend to have individual classes for each of the operation. These things are configured in the struts.xml like the following,

struts.xml

Page 4: Struts 2

<struts>

<action name = "Registration" class = "hello.RegistrationAction"> <action name = "Login" class = "hello.LoginAction"> <action name = "Logout" class = "hello.LogoutAction">

</struts>

The Action Class usually acts as a Model and executes a particular business logic depending on the Request object and the Input Parameters. In earlier versions of Struts (before Struts 2.0), an Action class is supposed to extend the org.apache.struts.Action class and has to override the Action.execute() method which takes four parameters. Following is the code snippet of an Action class before Struts 2.0,

MyAction.java

package myactions;

import java.servlet.http.*;import org.apache.struts.*;

class MyAction extends Action{

public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws java.lang.Exception {

// Do some business logic here.

}}

In Struts 2.0, an Action class is made flexible as it can be a simple POJO Class. It means that the Action Class doesn't need to extend some class or implement an interface. It can be as simple as possible, and the following code snippet proves the same,

MyAction.java

package myactions;

import com.opensymphony.xwork2.*;

class MyAction extends Action{

public String execute(){ // Some logic here. }

}

Here comes the big question!. Then how can an Action class is supposed to access the HttpServletRequest and the HttpServletResponse objects to get the needed information!!! At this stage it is worth to mention about the Aware-Related Interfaces here. Suppose that an

Page 5: Struts 2

Action class wants to access the HttpServletRequest object. For this, it has to implement a special Aware Interface called ServletRequestAware and has to override the method setServletRequest(HttpServletRequest request) thereby storing it in an instance variable. So, the new modified action class becomes like this,

MyAction.java

package myactions;

import javax.servlet.http.*;

import com.opensymphony.xwork2.*;import org.apache.struts2.interceptor.*;

class MyAction extends Action implements ServletRequestAware{

private HttpServletRequest request;

public String execute(){ }

public void setServletRequest(HttpServletRequest request){ this.request = request; }}

This above technique is basically an Inversion of Control. Inversion of Control is generally a Push Model which means that the data needed by the Application will be pushed by the Container or the Framework. In our case, we are making the Struts 2.0 Framework to call the method ServletRequestAware.setServletRequest(HttpServletRequest request) thereby populating the Request Object. Similar to this, there are Aware-Related Interfaces for Application, Servlet Request, Servlet Response, Parameters etc namely ApplicationAware, HttpServletRequestAware, HttpServletResponseAware, ParameterAware respectively.

3.4) Rendering the Result back to the Client

As we can see from the method signature, the return type of the Action.excute() method is just a String. This return type defines the Logical Outcome of the Action or the Page. Actual Outcome or the Response of a Page is configurable in the Struts Configuration File. Say the Action class can return a logical 'success' which tells that the action has be successfully processed or 'failure' which sadly tells that some thing wrong has happened in the Application. Some Predefined Constants have been defined in the Action interface for the logical outcomes namely, Action.SUCCESS, Action.ERROR, Action.LOGIN, Action.INPUT and Action.NONE. Consider the following code snippet,

MyAction.java

package myactions;

public class MyAction{

public String execute(){

Page 6: Struts 2

if (createOperation()){ return "create"; }else if (deleteOperation()){ return "delete"; }else if( readOperation()){ return "read"; }else if (writeOperation()){ return "write"; } return "error"; }}

The above method returns a bunch of Logical Outputs namely "create", "delete", "read" and "write". The logical outcomes should have their Corresponding Mappings defined in the struts.xml like the following,

struts.xml

<struts> … <action name = "MyAction" class = "myactions.MyAction"> <result name = "create">/myApp/create.jsp</result> <result name = "delete">/myApp/delete.jsp</result> <result name = "read">/myApp/read.jsp</result> <result name = "write">/myApp/write.jsp</result> </action> …</struts>

4) Struts.xml Configuration File

All the Configuration Related Information are externalized from a Web Application by maintaining them in a Xml File. The new Struts 2.0 Configuration Xml File is very Simple and Modular when compared with its older versions. Let us look into the structure of the Struts 2.0 Configuration File and the Core Elements within them in detail in the following sections.

4.1) Modularization of Configuration Files

The first nice feature is the File Inclusion Faciltity. Assume that in a very complex Web Application, there are multiple modules and each module is designated to be developed by a particular team. Similar to the Modularization of Work, the configuration file can also be made modular using the File Inclusion Facility. For the sake of simplicity, let the assume that there are three modules namely "admin", "customer", "employer" in a Web Application. We can define the three modules in three different Configuration Files, and using the File Inclusion Facility, the three files can be directly included in the Main Configuration File. A Main Configuration File is nothing but a File that includes other Configuration Files. Examine the following code snippet,

Admin-Config.xml

Page 7: Struts 2

<struts> <!-- Configuration Information Related to Admin Module --></struts>

Customer-Config.xml

<struts> <!-- Configuration Information Related to Customer Module --></struts>

Employee-Config.xml

<struts> <!-- Configuration Information Related to Employee Module --></struts>

All the above separate Configuration Files can be directly referenced or included in the Root Configuration File with the help of <include> tag like the following,

Struts.xml

<struts>

<!-- Other information goes here --> <include file = "Admin-Config.xml"/> <include file = "Customer-Config.xml"/> <include file = "Employer-Config.xml"/> <!-- Other information goes here -->

</struts>

4.2) Grouping of Similar Actions inside a Package

Packages in Java are logically used to group similar Classes or Interfaces. Similary, there is a <package> tag in Struts 2.0, which is used to Group Similar Actions along with Interceptors, Results, Exceptions etc. Following is the structure of the package element,

Struts.xml

<struts>

<package name = "MyPackage1">

<interceptors> </interceptors>

<global-results> <global-results>

Page 8: Struts 2

<action name = "MyAction1"> </action>

<action name = "MyAction2"> </action>

</package>

<package name = "MyPackage2">

<interceptors> </interceptors>

<global-results> <result name = "common-error"> /myApp/commons/commonError.jsp </result> <global-results>

<action name = "MyAction3"> <result name = "result1"> /myApp/myResult1.jsp </result> </action>

<action name = "MyAction4"> </action>

</package>

</stuts>

Assuming that MyAction1 and MyAction2 are someway related, they are grouped under a package called MyPackage1. All the declaration of Interceptors, Results and Exceptions within the Package MyPackage1 will be availabe only within the actions MyAction1 and MyAction2. Similarly all the definition of the Interceptors, Results and Exceptions within the package MyPackage2 will be applicable only for MyAction3 and MyAction4 action elements. Packages can also be extended through the means of extends attribute like the following,

Struts.xml

<struts> ... <package name = "MySubPackage" extends = "MyBasePackage"> ... </package> ...</struts>

Let us define what a Package Extension is and their advantages. Assume that there is a Package called P1 with interceptors I1 and I2, Results R1 and R2 and Exceptions E1 and E2. If we say some Package called P2 extends P1, then all the elements that are available in P1 becomes visible to Package P2. Package Extension is very similar to Class Inheritance which we normally see in any kind of Object Oriented Language.

Page 9: Struts 2

4.3) Interceptors and Stack

As previously discussed, Custom Interceptors can be written and made immediately available in Application by configuring them in the Configuration File with the help of <interceptor> tag. An Interceptor defined can be applied to a particlur Action (or a set of Actions) through the help of <intercept-ref> tag. Following Xml snippet will show this,

Struts.xml

<struts>

<package name = "MyPackage">

<interceptors> <interceptor name="logger-interceptor" class="myinterceptors.LoggingInterceptor"> </interceptor>

<action name = "MyAction"> <result name = "MyResult"> /myApp/Result1.jsp </result> <interceptor-ref name = "logger-interceptor"/> </action>

</package>

</struts>

The above code defines an Interceptor called logger-interceptor identified by the class myinterceptors.LoggingInterceptor and the same is included for an action called MyAction with the help of <interceptor-ref> tag. It is very common that a Set of Interceptors (often called Interceptor Stack) to be applied as a whole for one or more actions. Such a piece of functionality can be easily achieved with the help of <interceptor-stack> element.

struts.xml

<struts>

<package name = "MyPackage">

<interceptors> <!--Some set of common interceptors for a particular action--> <interceptor name = "A_I1" class = "MyA_I1"> <interceptor name = "A_I2" class = "MyA_I2"> <interceptor name = "A_I3" class = "MyA_I3"> <interceptor name = "A_I4" class = "MyA_I4">

<!--Another set of common interceptors --> <interceptor name = "B_I1" class = "MyB_I1"> <interceptor name = "B_I2" class = "MyB_I2"> <interceptor name = "B_I3" class = "MyB_I3"> <interceptor name = "B_I4" class = "MyB_I4"> </interceptors>

Page 10: Struts 2

<interceptor-stack name = "A"> <interceptor-ref name = "A_I1"> <interceptor-ref name = "A_I2"> <interceptor-ref name = "A_I3"> <interceptor-ref name = "A_I4"> </interceptor-stack>

<interceptor-stack name = "B"> <interceptor-ref name = "B_I1"> <interceptor-ref name = "B_I2"> <interceptor-ref name = "B_I3"> <interceptor-ref name = "B_I4"> </interceptor-stack>

<action name = "MyAction1"> <interceptor-ref name = "A"/> </action>

<action name = "MyAction2"> <interceptor-ref name = "B"/> </action>

</package>

</struts>

The above Xml snippet defines a series of interceptors with the help of <interceptors> tag. Related Set of Interceptors to be added to an action element is then categorized with the help of <interceptor-stack> element. The categorized Interceptor Stack is then bound to an action element using the same sensible <interceptor-ref> tag. The framework is sensible here, it will find out the value for the name attribute. If the value is an interceptor name, then the corresponding intercept() method will be invoked, else if the value is an Interceptor-Stack, then all the interceptors within the stack are iterated in the same order as their definition and their intercept() method will be invoked.

5) Validation using Configuration Files and Annotations

Struts 2.0 comes with new set of Robust Validation Features. Most of the common Validation Activities related to a Web Application are taken care by the Framework itself which means that only less burden lies on the shoulders of a Developer. Following lists the most commonly used Validations in Struts 2.0,

1. Integer Validation - Checks whether the value for a field is an integer and it falls within the integer range.

2. Double Validation - Checks whether the value for a field is a double and it falls within the double range.

3. Date Validation - Checks whether the value of the field is a Date value. 4. Email Validation - Validates whether the input string is in appropriate email format (Eg:

[email protected]). 5. Url Validation - Ensures whether the value for a field is in appropriate URL Format. 6. Required Validation - Checks for the emptiness of a field value. 7. Required String Validation - Checks for the emptiness of a trimmed String value (not

null) 8. String Length Validation - Checks whether the given field value is of the specified

length.

Page 11: Struts 2

9. Regex Validation - Ensures whether the field Value given matches the Regular Expression.

5.1) Validations Types based on Scope

Validation comes in two different flavors based on its Scope. A Scope defines whether a Validation is dedicated to a Single Field in a Page or it corresponds to a particular Action which may involve more than one fields along with some other constraints. Based on this, the following types are available.

Field Validation Non-Field Validation

5.1.1) Field Validation

Validating a Field in a Page for correctness is a common situation for almost any Web Application. As mentioned this type of Validation is restricted to a particular field. Common cases may be validating the username and password field for emptiness. Both Xml-Based Validation or Annotation-Based Validation can be mentioned for the field elements. The following snippet code is an example of Field-Level Validation.

validation.xml

<field name="username"> <field-validator type="required"> <message>User name cannot be empty.</message> </field-validator><field-name="username">

<field name="email_address"> <field-validator type="required"> <message>Email Address cannot be empty.</message> </field-validator>

<field-validator type="email"> <message> Enter the email id in proper format (eg: [email protected]) </message> </field-validator></field>

The above Xml snippet essentially applies one Validation Rule to the username field and two Validation Rules to the email-address field. The type of the validation rule is specified by the attribute called type. In our case, the types represent the Required Validation (required) and the EMail Validation (email). Any number of validation rules can be attached to a field element with the help of <field-validator> tag.

Annotation-Based Validation for a field is also possible. The only requirement for the class is that the class that contains the fields representing the page (it can be an Action class too) must be marked with the @Validation annotation. Assume the Validation has to take place when the user submits the form. It is known that the Action.execute() method will be invoked as a result of this. So we can perform the field validations by marking the necessary Annotations against the method.

Page 12: Struts 2

MyAction.java

package myactions;

import com.opensymphony.xwork2.validator.annotations.*; @Validationpublic class MyAction{ @Validations( emails = { @EmailValidator(type = ValidatorType.SIMPLE, fieldName = "email_address", message = "Enter the email id in proper format (eg: [email protected])") }

requiredFields = { @RequiredFieldValidator(type = ValidatorType.SIMPLE, fieldName = "email_address", message = "Email Address cannot be empty.")},

@RequiredFieldValidator(type = ValidatorType.SIMPLE, fieldName = "username", message = "User name cannot be empty.")} } ) public String execute(){ // Other Logic goes here.. }

}

Instead of marking the whole Bunch of Validations on the Action.execute method(), there is another alternate way wherein which the Annotation-Based Validation can be applied on a Field-by-Field basis. Assume that username and password are the two properties inside the Action class, then the following type of Annotation is also possible.

MyAction.java

package myactions;

import com.opensymphony.xwork2.validator.annotations.*;

public class MyAction{

private String username; private String emailAddress;

@RequiredFieldValidator(type = ValidatorType.SIMPLE, fieldName = "username", message = "User name cannot be empty.") public String getUsername(){ return username; }

Page 13: Struts 2

...

@RequiredFieldValidator(type = ValidatorType.SIMPLE, fieldName = "email_address", message = "Email Address cannot be empty.") @EmailValidator(type = ValidatorType.SIMPLE, fieldName = "email_address", message = "Enter the email id in app. format(eg: [email protected])") public String getEmailAddress(){ return emailAddress; }}

5.1.2) Non-Field Validation

Non-Field Validations are generally Application specific and they will be given implementation by the Application Developers. Example may be performing validations based one or more fields in a form along with some Application specific Business Logic. The only availabe Validation that comes along with Struts 2.0 in this category is the Expression Validation. Assume that in some Application an Employee is asked to enter his Dirth of Birth and the Joining Date. For sure, the Birth Date will be logically lesser than the Joining Date. We can enforce this kind of Validation Rule using Expression Validation as follows.

validation.xml

<field name = "date_of_birth"></field>

<field name = "joining_date"> </field>

<validator type = "expression"> <param name="expression"> date_of_birth lt joining_date </param> <message> Warning: DOB(${date_of_birth}) is greater than Joining Date(${joining_date}) </message></validator>

The first noticeable thing in the above Xml snippet is that the type of the Validation is identified as expression. The param tag is used to specify the constraint to be applied for the Validation. Here the constraint is very simple which tells that the Date of Birth for an Employee must be lesser that his Joining Date in the Organisation. Also notice, how actually the value of the field is taken to display error messages ($field_name). If the user enters 10/10/2000 for the DOB field and 10/10/1960 in the Joining Date Field, then the message "Warning: DOB(10/10/2000) is greater than the Joining Date(10/10/1960)" will be flashed in the User Browser.

5.2) Validation Types based on Implementation

If we look at another angle based on how Validations are Configured or Implemented, they can be classified into two categories namely,

Page 14: Struts 2

Declarative Validation Programmtic Validation.

5.2.1) Declarative Validation

If the Validation Logic for a particular Field or for an Entire Action is specified either in the Xml File or through Annotations, then it is called Declarative Validation. Whatever Validation we are seeing till now are Declarative Validations only. The idea behind Declarative Validation is that during the Deployment time of the Web Application itself, the Framework or the Container will be in a suitable position to map the set of fields participating in Validations against their Validation Rules.

5.2.2) Programmatic Validation

Not at all times, the Built-in Validations provided by the Framework will be sufficient. At times, there will be a situation to perform a Complex Validation Logic that is very specific to an application. For example situation may occur wherein, a single value of a field can be validated based on the content of some other text-fields along with some values fetched from the Database. In such a case, we can implement the Validation Logic directly into the Code. The following code snippet shows that,

MyAction.java

package myactions;

import com.opensymphony.xwork2.*;

public class MyAction extends ActionSupport{ public void validate(){ String stockSymbol = getStockFieldValue();

if ((stockSymbol == null) || (stockSymbol.trim().length == 0) ){ addFieldError("stock_field", "Stock Symbol cannot be empty"); }

boolean result = validateStockSymbolFromDb(stockSymbol); if (!result){ addActionError("Invalid Stock Symbol"); } // Other Code goes here. }}

If an Application is going to provide Manual Validation, then it has to implement two interfaces namely Validateable and ValidationAware interfaces in the com.opensymphony.xwork2 package. The core logic for the Custom Validation must be done within the Validateable.validate() method. ValidationAware Interface is used to collect the Error Messages that are related to fields or to a general Action. Fortunately, as expected, Struts 2.0 provides Default Implementation for both these interfaces in the ActionSupport class. So it is wise to extend this class for performing any Validation Logic without redefining every methods available in the Validation Interfaces.

Page 15: Struts 2

Our sample Action class extends ActionSupport class to get all the Basic functionality for Storing and Retrieving Error Messages. Two types of Error Messages are available in the ValidationAware interface. One is the Field-level Messages and the other thing is the Action-Level Messages. Convinient methods are available for populating and retreiving both these messages. Methods addActionError(String message) and addFieldMessage(String fieldName, String message) are used to populate the error messages to an internal Collection. To retrive the Error Messages getActionErrors() and getFieldErrors() are used. To check whether errors have occured in a page use hasActionErrors() and hasFieldErrors() methods.

The sample code essentially checks the value of the stock symbol obtained from the field and checks for its emptiness. If not, it is populating the field-level error message by calling the addFieldMessage("..."). It then make Database Calls to ensure whether the Stock Symbol is valid. If not, an Action Level Error message is populated in the code by calling addActionEror("...");

6) Conclusion

Though Struts 2.0 has more new features to its credit, this article just provides only the basic piece of information. It walked-through about how Struts 2.0 fits into the Bigger MVC2 Architecture. Then the Flow of the Client Request into the Struts Framework is explained in detail. Following that, some samples regarding the structure of a Struts Configuration File. Then the second section primarily focusses on the new Struts Validation Features with the various types of Validations that can be performed on field components.

Introduction

Struts is more established and more stable MVC2 framework at this time so if your application is based on Struts framework you may forget about thinking to move to some other framework. But at the same time you must have heard about the buzz created by Inversion of Control (IOC) design pattern. This design pattern is implemented by Spring framework. Besides there are some more amazing features of Spring like AOP. So if you like to take advantage of these features of Spring you do not have to rebuild the application, but you can integrate your existing Struts application with Spring without much hassle. More about that latter but first we would like to have a look at new features of Spring and how they work.

What's new in Spring?

Spring implements the IOC design pattern. It is a lightweight container and the objects are managed using an external XMl configuration file. Reference to a dependent object is obtained by exposing a JavaBean property. You just have to enter the properties in the external XML file.

Spring and IOC

IOC is a design pattern that externalizes application logic so that it can be injected into client code rather than written into it. Use of IOC in Spring framework separates the implementation logic from the client.

Spring framework offers more than this. The transaction handling is done beautifully in Spring. It can integrate major persistence frameworks and offer a consistent exception hierarchy. The best part of Spring is the mechanism of aspect-oriented code instead of the usual object-oriented code.

Spring AOP provides us with interceptors which are used to intercept the application logic at any execution point and then apply some methods at the interceptors. They are widely used for logging resulting in a more readable and functional code.

Page 16: Struts 2

Advantages of integrating Struts with Spring:

The advantages of integrating a Struts application into the Spring framework are:

1. Spring framework is based on new design approach and was designed to resolve the existing problems of existing Java applications such as performance.

2. Spring framework lets you apply AOP (aspect-oriented programming technique) rather than object-oriented code.

3. Spring provides more control on struts actions. That may depend on the method of integration you choose.

Integrating Struts and Spring

If you have decided to integrate your Struts application into Spring, we are ready to begin. There are three ways of doing this and based on the scenarios in your application you can select the way you want to do it.

1. Using Spring’s ActionSupport class to integrate Struts. 2. Using ContextLoaderPlugin.

1) Using Spring’s ActionSupport class to integrate Struts.

Integrating Struts with Spring doesn’t sound to be easy but if you follow this method you will find it quite simple and to add to this Spring provides you with org.springframework.web.struts.ActionSupport class. This class provides a method getWebApplicationContext() which you can use to obtain the Spring context. So you just have to extend Spring’s ActionSupport from your strut’s actions.

Using ActionSupport to integrate Struts

package net.javabeat.example1.actions;

import java.io.IOException;import javax.servlet.*;import org.apache.struts.action.*;import org.springframework.context.ApplicationContext;import org.springframework.web.struts.ActionSupport;

import net.javabeat.example1.beans.Employee;import net.javabeat.example1.business.EmpSearchService;

public class SubmitSearch extends ActionSupport {

public ActionForward execute( ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {

DynaActionForm searchEmpForm = (DynaActionForm) form; String empId = (String) searchEmpForm.get("empId");

ApplicationContext ctx = getWebApplicationContext();

Page 17: Struts 2

EmpSearchService empSearchService = EmpSearchService) ctx.getBean("EmpSearchSercvice"); Employee employee = empSearchService.find(empId.trim());

if (null == employee) { ActionErrors errors = new ActionErrors(); errors.add(ActionErrors.GLOBAL_ERROR,new ActionError("message.empnotfound")); saveErrors(request, errors); return mapping.findForward("failure") ; } request.setAttribute("employee", employee); return mapping.findForward("success"); }}

Explanation:

The trick here is to extend your Action from the Spring ActionSupport and not from the Struts Action class. The Spring ActionSupport provides you with the method getWebApplicationContext() to obtain an ApplicationContext and from the ApplicationContext you can access the business service layer.

ApplicationContext ctx = getWebApplicationContext();//getWebApplicationContext provided by the Spring ActionSupport class

EmpSearchService empSearchService = (EmpSearchService) ctx.getBean("EmpSearchSercvice");

// From the ApplicationContext get the business service bean

Disadvantages:

This method involves changes in the java files of your application, which is not desirable because if you want to move your application back to Struts framework you will have to redo the changes in the java files. And in this method the Struts actions are not in complete control of Spring.

2) Using ContextLoaderPlugin provided with Spring.

ContextLoaderPlugin is provided with Spring's 1.0.1 release. This plug-in loads the Spring application context for Strut's applications ActionServlet.There are two methods of integrating Struts with Spring using this plug-in and these two methods are:

A) Overriding the Struts RequestProcessor with Spring’s DelegatingRequestProcessor. B) Delegate Struts Action management to the Spring framework.

To use the ContextLoaderPlugin loads the Spring context file for the Struts ActionServlet. To use this plug-in you have to add following to your struts config file:

<plug-in className="org.springframework.web.struts.ContextLoaderPlugIn"/>

The location of the context config file can be set through contextConfigLocation property.

<plug-in className="org.springframework.web.struts.ContextLoaderPlugIn"> <set-property property="contextConfigLocation"

Page 18: Struts 2

value="/WEB-INF/actionname-servlet.xml” /></plug-in>

The default location for the Context config file is /WEB-INF/actionname-servlet.xml.

A)Overriding the Struts RequestProcessor with Spring’s DelegatingRequestProcessor.

One way of using ContextLoaderPlugIn is to override the Struts RequestProcessor with Spring’s DelegatingRequestProcessor class. The Spring's DelegatingRequestProcessor will lookup the Struts Actions defined in ContextLoaderPlugIn's WebApplicationContext. You can either use a single ContexLoaderPlugIn for all your Struts modules and then load the context in all your Struts modules or you can also define seperate ContextLoaderPlugIn for each of your Struts modules and then use the contextConfigLocation parameter to load the appropriate XML file.Let us have a look at it.

Integration via Spring's DelegatingRequestProcessor

<?xml version="1.0" encoding="ISO-8859-1" ?><!DOCTYPE struts-config PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 1.1//EN" "http://jakarta.apache.org/struts/dtds/struts-config_1_1.dtd"><struts-config> <form-beans> <form-bean name="searchEmpForm" type="org.apache.struts.validator.DynaValidatorForm"> <form-property name="empId" type="java.lang.String"/> </form-bean> </form-beans> <global-forwards type="org.apache.struts.action.ActionForward"> <forward name="welcome” path="/index.do"/> <forward name="searchEmployee" path="/searchEmp.do"/> <forward name="submitSearch" path="/submitSearch.do"/> </global-forwards> <action-mappings> <action path="/welcome" forward="/WEB-INF/views/welcome.htm"/> <action path="/searchEmployee" forward="/WEB-INF/views/search.jsp"/> <action path="/submitSearch" type="net.javabeat.example1.books.actions.SubmitSearch" input="/searchEmployee.do" validate="true" name="searchEmpForm"> <forward name="success" path="/WEB-INF/views/empDetail.jsp"/> <forward name="failure" path="/WEB-INF/views/search.jsp"/> </action> </action-mappings> <message-resources parameter="ApplicationResources"/> <controller processorClass="org.springframework.web.struts.DelegatingRequestProcessor"/> <plug-in className="org.apache.struts.validator.ValidatorPlugIn"> <set-property property="pathnames" value="/WEB-INF/validator-rules.xml,/WEB-INF/validation.xml"/> </plug-in> <plug-in className="org.springframework.web.struts.ContextLoaderPlugIn"> <set-property property="csntextConfigLocation" value="/WEB-INF/beans.xml"/> </plug-in></struts-config>

Page 19: Struts 2

Explanation:

Here we have overridden the Struts RequestProcessor with Spring’s DelegatingRequestProcessor using the controller tag. Now our Spring's DelegatingRequestProcessor will lookup the Struts Actions so we need to register the action in our Spring config file as shown below:

<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-beans.dtd"><beans> <bean id="empSearchService" class="net.javabeat.example1.employee.business.EmpSearchImpl"/> <bean name="/submitSearch" class="net.javabeat.example1.employee.actions.SubmitSearch"> <property name="empSearchService"> <ref bean="empSearchService"/> </property> </bean></beans>

Explanation:

This part is same as registering the Spring beans but here we register Struts actions as Spring's beans, the names of the beans must be same as in struts config file. This will allow Spring to populate our beans at the run time.

Package net.javabeat.example1.employee.actions; import java.io.IOException;import javax.servlet.*;import org.apache.struts.action.*;

import net.javabeat.example1.employee.beans.Employee;import net.javabeat.example1.employee.business.EmpSearchService;

public class SubmitSearch extends Action {

private EmpSearchService empSearchService; public EmpSearchService getEmpSearchService () { return empSearchService; } public void setEmpSearchService(EmpSearchService empSearchService) { this.empSearchService = empSearchService; } public ActionForward execute( ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {

DynaActionForm searchEmpForm = (DynaActionForm) form; String empId = (String) searchEmpForm.get("empId"); Employee employee = getEmpSearchService().find(empId.trim());

if (null == employee) {

Page 20: Struts 2

ActionErrors errors = new ActionErrors(); errors.add(ActionErrors.GLOBAL_ERROR,new ActionError("message.notfound")); saveErrors(request, errors); return mapping.findForward("failure") ; } request.setAttribute("employee", employee); return mapping.findForward("success"); }}

Explanation:

Now here we are using Struts action but the beans are managed by Spring. In the above code we create a javaBean which is populated by Spring and then use it to run our business logic.

Disadvantages:

This method is definitely better then the previous one but still here the Spring beans are dependent on the RequestProcessor, this reduces the flexibility of the application.

B) Delegate Struts Action management to the Spring framework.

A much better solution is to delegate Struts action management to the Spring framework. You can do this by registering a proxy in the struts-config action mapping. The proxy is responsible for looking up the Struts action in the Spring context. Because the action is under Spring's control, it populates the action's JavaBean properties and leaves the door open to applying features such as Spring's AOP interceptors.

The delegation method of Spring integration

<?xml version="1.0" encoding="ISO-8859-1" ?><!DOCTYPE struts-config PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 1.1//EN" "http://jakarta.apache.org/struts/dtds/struts-config_1_1.dtd"><struts-config> <form-beans> <form-bean name="searchEmpForm" type="org.apache.struts.validator.DynaValidatorForm"> <form-property name="empId" type="java.lang.String"/> </form-bean> </form-beans> <global-forwards type="org.apache.struts.action.ActionForward"> <forward name="welcome” path="/index.do"/> <forward name="searchEmployee" path="/searchEmp.do"/> <forward name="submitSearch" path="/submitSearch.do"/> </global-forwards> <action-mappings> <action path="/welcome" forward="/WEB-INF/views/welcome.htm"/> <action path="/searchEmployee" forward="/WEB-INF/views/search.jsp"/> <action path="/submitSearch" type="org.springframework.web.struts.DelegatingActionProxy" (1) input="/searchEmployee.do" validate="true" name="searchEmpForm"> <forward name="success" path="/WEB-INF/views/empDetail.jsp"/> <forward name="failure" path="/WEB-INF/views/search.jsp"/>

Page 21: Struts 2

</action> </action-mappings> <message-resources parameter="ApplicationResources"/> <plug-in className="org.apache.struts.validator.ValidatorPlugIn"> <set-property property="pathnames" value="/WEB-INF/validator-rules.xml,/WEB-INF/validation.xml"/> </plug-in> <plug-in className="org.springframework.web.struts.ContextLoaderPlugIn"> <set-property property="contextConfigLocation" value="/WEB-INF/beans.xml"/> </plug-in></struts-config>

Explaination:

This is simply a struts config file, but here we do not declare the action’s class name but we set the Spring’s DelegatingActionProxy. The DelegatingActionProxy will lookup context for the action name in the spring’s config and map it to its class. The context is declared in the ContextLoaderPlugIn.

Now just register the Struts action as a bean in the Spring config file. The properties for this action’s bean will be automatically populated just like any other Spring bean.

Register a Struts action in the Spring context

<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-beans.dtd"><beans> <bean id="empSearchService" class="net.javabeat.example1.employee.business.EmpServiceImpl"/> <bean name="/submitSearch" class="net.javabeat.example1.employee.actions.SubmitSearch"> <property name="empSearchService"> <ref bean="empSearchService"/> </property> </bean></beans>

Disadvantages:

If you have the option to choose a method then this is the best method the only disadvantage here is this method leaves your code less readable because the dependencies are not clear.

Using Spring’s AOP with your Struts Application:

To tackle cross-cutting you can use Spring interceptors

To use Spring’s AOP in your Struts Applications you need to :

1. Create the interceptor. 2. Registor the interceptor. 3. Delclare interceptors.

Page 22: Struts 2

For example

A sample logging interceptor

package net.javabeat.example1.employee.interceptors;

import org.springframework.aop.MethodBeforeAdvice;import java.lang.reflect.Method;

public class LoggingInterceptor implements MethodBeforeAdvice {

public void beforeMethod(Method method, Object[] objects, Object o) throws Throwable { System.out.println("logging before intersection"); }}

This interceptor will execute the beforeMethod() before every intersection (We are using MethodBeforeAdvice). Here we are just printing a line but we can use it for anything we like. Next let us register the interceptor.

Registering the interceptor in the Spring config file

<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-beans.dtd"><beans> <bean id="empSearchService" class="net.javabeat.example1.employee.business.EmpSearchServiceImpl"/> <bean name="/submitSearch" class="net.javabeat.example1.employee.actions.SubmitSearch"> <property name="empSearchService"> <ref bean="empSearchService"/> </property> </bean> <!-- Interceptors --> <bean name="logger" class="net.javabeat.example1.employee.interceptors.LoggingInterceptor"/> <!-- AutoProxies --> <bean name="loggingAutoProxy" class="org.springframework.aop.framework.autoproxy.BeanNameAutoProxyCreator"> <property name="beanNames"> <value>/submitSearch>/values> </property> <property name="interceptorNames"> <list> <value>logger>/value> </list> </property> </bean></beans>

Explanation:

Page 23: Struts 2

First we have to register the interceptor:

<bean name="logger" class="net.javabeat.example1.employee.interceptors.LoggingInterceptor"/>

Now we need to define the intersections, we will use autoproxy:

<bean name="loggingAutoProxy" class="org.springframework.aop.framework.autoproxy.BeanNameAutoProxyCreator">

Now we have to register the Struts action’s that will be intercepted.

<property name="beanNames"> <value>/submitSearch>/values> // <value>/otherBeans>/values> </property>Apply interceptors to the beanNames: <property name="interceptorNames"> <list> <value>logger>/value> </list> </property>

Conclusion

All the three methods provide good integrating of Struts with Spring and you can select any method that suits your project. The Action-delegation method seems to be better of the three because you have to make fewer changes in the code and you can take advantages of other features of Spring like AOP (discussed latter). This method gives Spring more control over Struts action. You can make the strut’s actions (or beans in Spring) threadsafe through Spring. You can also use Spring’s lifecycle methods.