Professional Documents
Culture Documents
* Struts 2 Framework was implemented on MVC architecture and Front Controller Design Pattern.
* Struts 2 offers two different style to implement application (1) XML based Configuration (2) Annotation based Configuration
* Struts 2 required – Servlet API 2.4, JSP API 2.0, JAVA 5
* Struts Features :
Simple POJO based Actions
Simplified testability
Thread Safe
AJAX Support
jQuery Plugin
Dojo Plugin (deprecated)
AJAX Client Side Validation
Template Support
Support for different result types
Easy to extend with Plugins
REST Plugin (REST based Actions, Extension-less URLs)
Convention Plugin (Action Configuration via Conventions and Annotations)
Spring Plugin (Dependency Injection)
Hibernate Plugin
support in Design
JFreechart Plugin (Charts)
jQuery Plugin (AJAX Support, UI Widgets, Dynamic Table, Charts)
Rome Plugin (RSS Feeds)
* Struts 1 used a Servlet Controller such as the ActionServlet class while Struts 2 used Filter to perform same task.
* Struts 1 provided several tag libraries like Html, bean, logic etc that allow using custom tag in JSP while Struts 2
provides single Tag library that covers all.
* In Struts 1 all the tasks are done by a single component called RequestProcessor. There are some limitations with this
RequestProcessor while in the case of Struts 2 all the tasks are done by Interceptors. There are various interceptors implemented in
Struts 2 for various tasks.
* Struts 1 uses Form bean class but Struts 2 does not use Form bean class.
struts.xml :
<struts>
<constant name=”struts.devMode” value=”true”/>
<package name=”” namespace=”” extends=”” abstract=””>
<action name=”” class=”” method=””>
<result name=”” type=””></result>
</action>
</package>
<include file=”student-config.xml”/>
<bean type=”” name=”” class=”” scope=”” static=”” optional=””>
</struts>
ActionContext : ActionContext is the centralized object which contains ValueStack, Web Container objects like Request, Response,
Session, Application, ServletContext etc. related to the request currently under Processing.
ValueStack : ValueStack is the centralized object which contains one or more Action Class instances.
OGNL (Open Graph Navigation Language) helps us to access the data from ActionContext inside JSP’s.
OGNL is a powerful expression language that is used to reference and manipulate data on the ValueStack. OGNL also helps in data
transfer and type conversion. The OGNL is very similar to the JSP Expression Language. OGNL is based on the idea of having a root or
default object within the context. The properties of the default or root object can be referenced using the markup notation, which is the
pound symbol.
The ActionSupport class implements Action interface which exposes the execute() method.
The execute() method and following constants are declared in the Action interface which can be used as return values in the execute()
method.
public static final String ERROR = "error"
public static final String INPUT = "input"
public static final String LOGIN = "login"
public static final String NONE = "none"
public static final String SUCCESS = "success"
ERROR is returned when the action execution fails.
INPUT is returned when the action requires more input from the user.
LOGIN is returned when the user is not logged into the system.
NONE is returned when the action execution is successfull and there are no views to display.
SUCCESS is returned when the action executed successfully and the corresponding result is displayed to the user.
Now lets see the roles played by the different interceptors.
# params interceptor helps in transfering the request data onto the action object.
# workflow interceptor controls the flow of cotrol.
The workflow interceptor checks whether the action implements the Validateable interface , if it does, the workflow interceptor will
invoke the validate() method of the Action class.
Note : validate() method available in Validateable Interface.
Struts 2 Interceptors :
* Interceptors are responsible for most of the request processing.
* Interceptors help inject custom logic into the request processing pipeline.
* They are invoked by the controller (FilterDispatcher) before and after invoking action, thus they sit between the controller and action.
* Interceptors perform tasks such as Logging, Validation, File Upload, Exception Handling, Double-submit guard etc.
* Struts2 comes with default list of Interceptors already configured in the application in struts-default.xml file which is available in
struts2-core-2.0.11.2.jar file.
* Struts2 Interceptors are conceptually very similar to Servlet Filter.
* We can create our own custom Interceptors and plugin into a Struts2 based web application.
* Framework creates an object of ActionInvocation that encapsulates the action and all the interceptors configured for that action. Each
interceptors are called before the action gets called. Once the action is called and result is generated, each interceptors are again called in
reverse order to perform post processing work. Interceptors can alter the workflow of action. It may prevent the execution of action.
void init() - called after an interceptor is created, but before any requests are processed using intercept, giving the Interceptor a
chance to initialize any needed resources.
void destroy() - Called to let an interceptor clean up any resources it has allocated.
* If we are extending the AbstractInterceptor class, then we only need to override the method :
String intercept(ActionInvocation invocation) throws Exception method to provide our own implementation
Strusts 2 provides two types of Validations : 1. Basic Validations 2. Validation Framework Validations.
Basic Validation: Steps to use Basic Validation :
We have to override the validate() method in the Action Class.
Our Action Class must implement Interface called Validateable.
Workflow Interceptor should be invoked.
We should specify the result with name “input”.
Validation Framework Validations :
[i] XML based Validations [ii] Annotations based Validations
# XML based Validations : required, requiredString, int, double, date, expression, fieldExpression, email, url, Conversion, Stringlength, Regex
<validators>
<field name="username">
<field-validator type="requiredstring">
<message>Username is Required</message>
</field-validator>
<field-validator type="stringlength">
<param name="minLength">5</param>
<param name="maxLength">15</param>
<message> ${username} is Invalid. Username length must be between
${minLength} and ${maxLength} Characters long.
</message>
</field-validator>
</field>
</validators>
import com.opensymphony.xwork2.validator.validators.FieldValidatorSupport;
public class MyEmailValidator extends FieldValidatorSupport{
public void validate(Object obj)throws ValidationException{
String fieldName=getFieldName();
String fieldValue=(String)getFieldValue(FieldName, obj);
// Our logic goes here………
}
}
public abstract class FieldValidatorSupport extends ValidatorSupport implements FieldValidator
@CustomValidator (type="passwordstrategy", fieldName="password", message="Your password must contains one letter, one
number, and one of the following special Character--$!@#?")
@Validation
public class AnnotedTest extends ActionSupport{
public String username;
@RequiredStringValidator(message=”Username is Required”)
@StringLengthFieldValidator(message=”Username must contain minimum of ${minLength} to Maximum
of ${maxLength} Characters”, trim=true, minLength=”5”, maxLength=”8”)
Public String getUsername(){
return username;
}
Public void setUsername(String username){
this.username=username;
}
}
3. We should specify with name “input”.
* To integrate Tiles 2 Framework with Struts 2 we have to add the following <listener> in web.xml
<listener>
<listener-class> org.apache.struts2.tiles.StrutsTilesListener </listener-class>
</listener>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/springConfig.xml</param-value>
</context-param>
<listener>
<listener-class>
org.springframework.web.context.ContextLoaderListener
</listener-class>
</listener>
<listener>
<listener-class>
org.springframework.web.context.request.RequestContextListener
</listener-class>
</listener>