Struts 2
The basic platform requirements are Servlet API 2.4, JSP API 2.0 and Java 5.
The strut-2 framework is designed for the compilation of the entire development cycle including of building, developing and maintaining the whole application. It is very extensible as each class of the framework is based on an Interface and all the base classes are given an extra application and even you can add your own. The basic platform requirements are Servlet API 2.4, JSP API 2.0 and Java 5.
Some of the general features of the current Apache Strut 2 framework are given below.
Architecture: First the web browsers request a resource for which the Filter Dispatcher decides the suitable action. Then the Interceptors use the required functions and after that the Action method executes all the functions like storing and retrieving data from a database. Then the result can be seen on the output of the browser in HTML, PDF, images or any other.
Tags - Tags in Strut 2 allow creating dynamic web applications with less number of coding. Not only these tags contain output data but also provide style sheet driven markup that in turn helps in creating pages with less code. Here the tags also support validation and localization of coding that in turn offer more utilization. The less number of codes also makes it easy to read and maintain.
MVC: The Model View Controller in Strut 2 framework acts as a coordinator between application’s model and web view. Its Controller and View components can come together with other technology to develop the model. The framework has its library and markup tags to present the data dynamically.
Configuration: Provides a deployment descriptor to initialize resources in XML format. The initialization takes place simply by scanning all the classes using Java packages or you can use an application configuration file to control the entire configuration. Its general-purpose defaults allow using struts directly Out of the box.
Configuration files are re-loadable that allows changes without restarting a web container.
Other Features:
Some of the general features of the current Apache Strut 2 framework are given below.
Architecture: First the web browsers request a resource for which the Filter Dispatcher decides the suitable action. Then the Interceptors use the required functions and after that the Action method executes all the functions like storing and retrieving data from a database. Then the result can be seen on the output of the browser in HTML, PDF, images or any other.
Tags - Tags in Strut 2 allow creating dynamic web applications with less number of coding. Not only these tags contain output data but also provide style sheet driven markup that in turn helps in creating pages with less code. Here the tags also support validation and localization of coding that in turn offer more utilization. The less number of codes also makes it easy to read and maintain.
MVC: The Model View Controller in Strut 2 framework acts as a coordinator between application’s model and web view. Its Controller and View components can come together with other technology to develop the model. The framework has its library and markup tags to present the data dynamically.
Configuration: Provides a deployment descriptor to initialize resources in XML format. The initialization takes place simply by scanning all the classes using Java packages or you can use an application configuration file to control the entire configuration. Its general-purpose defaults allow using struts directly Out of the box.
Configuration files are re-loadable that allows changes without restarting a web container.
Other Features:
- All framework classes are based on interfaces and core interfaces are independent from HTTP.
- Check boxes do not require any kind of special application for false values.
- Any class can be used as an action class and one can input properties by using any JavaBean directly to the action class.
- Strut 2 actions are Spring friendly and so easy to Spring integration.
- AJAX theme enables to make the application more dynamic.
- Portal and servlet deployment are easy due to automatic portlet support without altering code.
- The request handling in every action makes it easy to customize, when required.
Struts 2 History
Apache Struts is an open-source framework that is used for developing Java web application. Originally developed by the programmer and author Craig R. McClanahan, this was later taken over by the Apache Software Foundation in 2002.
Struts is a well-organized framework based on MVC architecture. In Model-View-Controller Architecture, Model stands for the business or database code, View represents the page design code and the Controller for navigational code. All these together makes Struts an essential framework for building Java applications. But with the development of new and lightweight MVC based framworks like Spring, Stripes and Tapestry, it becomes necessary to modify the Struts framework. So, the team of Apache Struts and another J2EE framework, WebWork of OpenSymphony joined hand together to develop an advanced framework with all possible developing features that will make it developer and user friendly.
Strut2 contains the combined features of Struts Ti and WebWork 2 projects that advocate’s higher level application by using the architecture of WebWork2 with features including a plug-in framework, a new API, Ajax tags etc.
Request Lifecycle in Struts 2 applications
1. User Sends request: User sends a request to the server for some resource.
2. FilterDispatcher determines the appropriate action: The FilterDispatcher looks at the request and then determines the appropriate Action.
3. Interceptors are applied: Interceptors configured for applying the common functionalities such as workflow, validation, file upload etc. are automatically applied to the request.
4. Execution of Action: Then the action method is executed to perform the database related operations like storing or retrieving data from the database.
5. Output rendering: Then the Result renders the output.
6. Return of Request: Then the request returns through the interceptors in the reverse order. The returning request allows us to perform the clean-up or additional processing.
7. Display the result to user: Finally the control is returned to the servlet container, which sends the output to the user browser.
Struts 2 is a very elegant and flexible front controller framework based on many standard technologies like Java Filters, Java Beans, ResourceBundles, XML etc.
For the Model, the framework can use any data access technologies like JDBC, EJB, Hibernate etc and for the View, the framework can be integrated with JSP, JTL, JSF, Jakarta Velocity Engine, Templates, PDF, XSLT etc.
Exception Handling:
The Struts 2 Framework allows us to define exception handlers and inceptors.
- Exception Handlers:
Exception handlers allows us to define the exception handling procedure on global and local basis. Framework catches the exception and then displays the page of our choice with appropriate message and exception details.
- Interceptors:
The Interceptors are used to specify the "request-processing lifecycle" for an action. Interceptors are configured to apply the common functionalities like workflow, validation etc.. to the request.
- Action ContextCleanUp filter:
The ActionContextCleanUp filter is optional and it is useful when integration has to be done with other technologies like SiteMash Plugin.
- FilterDispatcher:
Next the FilterDispatch is called, which in turn uses the ActionMapper to determine whether to invoke an Action or not. If the action is required to be invoked, the FilterDispatcher delegates the control to the ActionProxy.
- ActionProxy:
The ActionProxy takes help from Configuration Files manager, which is initialized from the struts.xml. Then the ActionProxy creates an ActionInvocation, which implements the command pattern. The ActionInvocation process invokes the Interceptors (if configured) and then invokes the action. The ActionInvocation looks for proper result. Then the result is executed, which involves the rendering of JSP or templates.
Then the Interceptors are executed again in reverse order. Finally the response returns through the filters configured in web.xml file. If the ActionContextCleanUp filter is configured, the FilterDispatcher does not clean the ThreadLocal ActionContext. If the ActionContextCleanUp filter is not present then the FilterDispatcher will cleanup all the ThreadLocals present.
Why Struts 2
- Simplified Design - Programming the abstract classes instead of interfaces is one of design problem of struts1 framework that has been resolved in the struts 2 framework. Most of the Struts 2 classes are based on interfaces and most of its core interfaces are HTTP independent. Struts 2 Action classes are framework independent and are simplified to look as simple POJOs. Framework components are tried to keep loosely coupled.
- Simplified Actions - Actions are simple POJOs. Any java class with execute() method can be used as an Action class. Even we don't need to implement interfaces always. Inversion of Control is introduced while developing the action classes. This make the actions to be neutral to the underlying framework.
- No more ActionForms - ActionForms feature is no more known to the struts2 framework. Simple JavaBean flavored actions are used to put properties directly. No need to use all String properties.
- Simplified testability - Struts 2 Actions are HTTP independent and framework neutral. This enables to test struts applications very easily without resorting to mock objects.
- Intelligent Defaults - Most configuration elements have a default value which can be set according to the need. Even there are xml-based default configuration files that can be overridden according to the need.
- Improved results - Unlike ActionForwards, Struts 2 Results provide flexibility to create multiple type of outputs and in actual it helps to prepare the response.
- Better Tag features - Struts 2 tags enables to add style sheet-driven markup capabilities, so that we can create consistent pages with less code. Struts 2 tags are more capable and result oriented. Struts 2 tag markup can be altered by changing an underlying stylesheet. Individual tag markup can be changed by editing a FreeMarker template. Both JSP and FreeMarker tags are fully supported.
- Annotations introduced : Applications in struts 2 can use Java 5 annotations as an alternative to XML and Java properties configuration. Annotations minimize the use of xml.
- Stateful Checkboxes - Struts 2 checkboxes do not require special handling for false values.
- QuickStart - Many changes can be made on the fly without restarting a web container.
- customizing controller - Struts 1 lets to customize the request processor per module, Struts 2 lets to customize the request handling per action, if desired.
- Easy Spring integration - Struts 2 Actions are Spring-aware. Just need to add Spring beans!
- Easy plugins - Struts 2 extensions can be added by dropping in a JAR. No manual configuration is required!
- AJAX support - The AJAX theme gives interactive applications a significant boost.
The framework provides a set of tags to help you ajaxify your applications, even on Dojo. The AJAX features include:
1. AJAX Client Side Validation
2. Remote form submission support (works with the submit tag as well)
3. An advanced div template that provides dynamic reloading of partial HTML
4. An advanced template that provides the ability to load and evaluate JavaScript remotely
5. An AJAX-only tabbed Panel implementation
6. A rich pub-sub event model
7. Interactive auto complete tag
Struts 1.x Vs Struts 2.x
1. Servlet Dependency:
Actions in Struts1 have dependencies on the servlet API since the HttpServletRequest andHttpServletResponse objects are passed to the execute method when an Action is invoked but in case of Struts 2, Actions are not container dependent because they are made simple POJOs.
2. Action classes
Programming the abstract classes instead of interfaces is one of design issues of struts1 framework that has been resolved in the struts 2 framework.
Struts1 Action classes needs to extend framework dependent abstract base class. But in case of Struts 2 Action class may or may not implement interfaces to enable optional and custom services.
Struts1 Action classes needs to extend framework dependent abstract base class. But in case of Struts 2 Action class may or may not implement interfaces to enable optional and custom services.
3. Validation
Struts1 and Struts 2 both supports the manual validation via a validate method.
Struts1 uses validate method on the ActionForm, or validates through an extension to the Commons Validator. However, Struts 2 supports manual validation via the validate method and the XWork Validation framework. The Xwork Validation Framework supports chaining validation into sub-properties using the validations defined for the properties class type and the validation context.
Struts1 and Struts 2 both supports the manual validation via a validate method.
Struts1 uses validate method on the ActionForm, or validates through an extension to the Commons Validator. However, Struts 2 supports manual validation via the validate method and the XWork Validation framework. The Xwork Validation Framework supports chaining validation into sub-properties using the validations defined for the properties class type and the validation context.
4. Threading Model
In Struts1, Action resources must be thread-safe or synchronized. So Actions are singletons and thread-safe, there should only be one instance of a class to handle all requests for that Action. The singleton strategy places restrictions on what can be done with Struts1 Actions and requires extra care to develop. However in case of Struts 2, Action objects are instantiated for each request, so there are no thread-safety issues. (In practice, servlet containers generate many throw-away objects per request, and one more object does not impose a performance penalty or impact garbage collection.)
5. Testability
Testing Struts1 applications are a bit complex. A major hurdle to test Struts1 Actions is that the execute method because it exposes the Servlet API. A third-party extension, Struts TestCase, offers a set of mock object for Struts1. But the Struts 2 Actions can be tested by instantiating the Action, setting properties and invoking methods. Dependency Injection support also makes testing simpler. Actions in struts2 are simple POJOs and are framework independent hence testability is quite easy in struts2.
6. Harvesting Input
Struts1 uses an ActionForm object to capture input. And all ActionForms needs to extend a framework dependent base class. JavaBeans cannot be used as ActionForms, so the developers have to create redundant classes to capture input.
However Struts 2 uses Action properties (as input properties independent of underlying framework) that eliminates the need for a second input object, hence reduces redundancy. Additionally in struts2, Action properties can be accessed from the web page via the taglibs. Struts 2 also supports the ActionForm pattern, as well as POJO form objects and POJO Actions. Even rich object types, including business or domain objects, can be used as input/output objects.
However Struts 2 uses Action properties (as input properties independent of underlying framework) that eliminates the need for a second input object, hence reduces redundancy. Additionally in struts2, Action properties can be accessed from the web page via the taglibs. Struts 2 also supports the ActionForm pattern, as well as POJO form objects and POJO Actions. Even rich object types, including business or domain objects, can be used as input/output objects.
7. Expression Language
Struts1 integrates with JSTL, so it uses the JSTL-EL. The struts1 EL has basic object graph traversal, but relatively weak collection and indexed property support. Struts 2 can also use JSTL, however it supports a more powerful and flexible expression language called "Object Graph Notation Language" (OGNL).
8. Binding values into views
In the view section, Struts1 uses the standard JSP mechanism to bind objects (processed from the model section) into the page context to access. However Struts 2 uses a "ValueStack" technology so that the taglibs can access values without coupling your view to the object type it is rendering. The ValueStack strategy allows the reuse of views across a range of types which may have the same property name but different property types.
9. Type Conversion
Usually, Struts1 ActionForm properties are all Strings. Struts1 uses Commons-Beanutils for type conversion. These type converters are per-class and not configurable per instance. However Struts 2 uses OGNL for type conversion. The framework includes converters for basic and common object types and primitives.
10. Control of Action Execution
Struts1 supports separate Request Processor (lifecycles) for each module, but all the Actions in a module must share the same lifecycle. However Struts 2 supports creating different lifecycles on a per Action basis via Interceptor Stacks. Custom stacks can be created and used with different Actions as needed.
Example:
Hello.jsp
<%@ taglib prefix="s" uri="/struts-tags" %>
<html>
<head>
<title>Struts 2 Hello Application!</title>
</head>
<body>
<h2><s:property value="message" /></h2>
<p>Current date and time is: <b><s:property value="currentTime" /></b>
</body>
</html>
<html>
<head>
<title>Struts 2 Hello Application!</title>
</head>
<body>
<h2><s:property value="message" /></h2>
<p>Current date and time is: <b><s:property value="currentTime" /></b>
</body>
</html>
Hello.java
Package com.action;
import com.opensymphony.xwork2.ActionSupport;
import java.util.Date;
public class Hello extends ActionSupport {
public static final String MESSAGE = "Struts 2 Hello World Tutorial!";
public String execute() throws Exception { setMessage(MESSAGE); return SUCCESS; }
private String message;
public void setMessage(String message){ this.message = message; }
public String getMessage() { return message; }
public String getCurrentTime(){ return new Date().toString(); }
}
import com.opensymphony.xwork2.ActionSupport;
import java.util.Date;
public class Hello extends ActionSupport {
public static final String MESSAGE = "Struts 2 Hello World Tutorial!";
public String execute() throws Exception { setMessage(MESSAGE); return SUCCESS; }
private String message;
public void setMessage(String message){ this.message = message; }
public String getMessage() { return message; }
public String getCurrentTime(){ return new Date().toString(); }
}
struts.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
"http://struts.apache.org/dtds/struts-2.0.dtd">
<struts>
<constant name="struts.enable.DynamicMethodInvocation" value="false" />
<constant name="struts.devMode" value="true" />
<package name="demo" namespace="/demo" extends="struts-default">
<action name="HelloWorld" class="demo.HelloWorld">
<result>/pages/HelloWorld.jsp</result>
</action>
<!-- Add actions here -->
</package>
<!-- Add packages here -->
</struts>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
"http://struts.apache.org/dtds/struts-2.0.dtd">
<struts>
<constant name="struts.enable.DynamicMethodInvocation" value="false" />
<constant name="struts.devMode" value="true" />
<package name="demo" namespace="/demo" extends="struts-default">
<action name="HelloWorld" class="demo.HelloWorld">
<result>/pages/HelloWorld.jsp</result>
</action>
<!-- Add actions here -->
</package>
<!-- Add packages here -->
</struts>
Steps How to define…………….
1. <filter>
<filter-name>struts2</filter-name>
<filter-class>org.apache.struts2.dispatcher.FilterDispatcher</filter-class>
</filter>
<filter-mapping>
<filter-name>struts2</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<filter-name>struts2</filter-name>
<filter-class>org.apache.struts2.dispatcher.FilterDispatcher</filter-class>
</filter>
<filter-mapping>
<filter-name>struts2</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
2. <action name="Hello" class="com.action.Hello">
<result>/pages/Hello.jsp</result>
</action>
<result>/pages/Hello.jsp</result>
</action>
3. Then the execute method sets the message and returns SUCCESS.
public String execute() throws Exception {
setMessage(MESSAGE);
return SUCCESS;
}
public String execute() throws Exception {
setMessage(MESSAGE);
return SUCCESS;
}
4. Container process the HelloWorld.jsp and generates the output.
5. Then the output in the HTML format is sent to the browser.
Struts2 Action interface : All actions may implement this interface, which exposes the execute() method. If there is no execute method and no other method is specified in the configuration, the framework will throw an exception.
The Action Class usually acts as a Model and executes a particular business logic depending on the Request object and the Input Parameters.
To provide a loosely coupled system, Struts2 uses a technique called dependency injection, or inversion of control. Dependency injection can be implemented by constructor injection, interface injection and setter injection. Struts2 uses setter injection. This means that to have objects available to the action, we need only to provide a setter method. There are also objects such as the HttpServletRequest that can be obtained by asking the ActionContext or implementing ServletRequestAware. Implementing ServletRequestAware is preferred. For each of the non-business objects there is a corresponding interface (known as an ?aware? interface) that the action is required to implement.
Example:
public interface ServletRequestAware {
public void setServletRequest(HttpServletRequest request);
}
public void setServletRequest(HttpServletRequest request);
}
Struts 2 Validation (Int Validator)
Validation Rules
Validation rules are an integral part of Struts 2 applications, where rules to validating particular user inputs are stored. Struts 2 validation framework validates user input against the defined rules.
The validation rules can be specified:
1. Per Action class: ActionName-validation.xml
2. Per Action alias: ActionName-alias-validation.xml
3. Inheritance hierarchy and interfaces are implemented by Action class. The XWork searches up the inheritance tree of the action to find default validations for parent classes of the action and interfaces implemented.
4. Using Java 5 annotations.
Struts 2 default validation functions
Following field validators are part of Struts 2 framework:
1. Conversion Validator
2. Date Validator
3. Double Validator
4. Email Validator
5. Expression Validator
6. Fieldexpression Validator
7. Int Validator
8. Regex Validator
9. Required Validator
10. Requiredstring Validator
11. Stringlength Validator
12. URL Validator
13. Visitor Validator

