Struts 2 Tutorial

                                         Struts 1.0


  1. ActionServlet
  • Bundles all the request values into a JavaBean class which extends Struts ActionForm class.
  • Decides which action class to invoke to process the request.Validate the data entered by the user.
  • The action class process the request with the help of the model component. The model interacts with the database and process the request.
  • After completing the request processing the Action class returns an ActionForward to the controller.
  • Based on the ActionForward the controller will invoke the appropriate view.
  • The HTTP response is rendered back to the user by the view component.
  1. ActionForm :  Integretes Jsp form data to getter/Setter methods
  2. Action :       We write bussiness Logic here, and getting the data from ActionForm and Finally mapping forword resultpage.
Method: public ActionForward execute(ActionMappingActionForm,HttpRequest,HttpResponse)


  1. ActionMapping

2.DispatchAction
In prevoius exceute(map,form,req,res) forwards action to one page only.if you want to use diff. Methods use DispactioAction


3.Struts LookupDispatchAction Example
In this tutorial you will learn how to group a set of related functions into a single action using Struts LookupDispatchAction.


LookupDispatchAction provides a mechanism for grouping a set of related functions into a single action, thus eliminating the need to create seperate actions for each functions. In this example we will see how to group a set of user related actions like add user, update user and delete user into a single action called UserAction.


4.Struts DynaActionForm Example


In this tutorial you will see how the DynaActionForm eliminates the need to create a seperate ActionForm for each Action class and allows you to easily define the Form object in the xml declaration file.


DynaActionForm Beans are the extension of Form Beans that allows you to specify the form properties inside the struts configuration file instead of creating a seperate concreate class. It will become tedious to create a seperate form bean for each action class. Using DynaActionForm we can easily create Form Bean in struts-config.xml file. The struts-config.xml file entry for the DyanActionForm Bean is shown below.




                                              Struts 2











1.In the diagram, an initial request goes to the Servlet container which is passed through a filter chain.
2.The chain includes the (optional) ActionContextCleanUp filter, which is useful when integrating technologies such as SiteMesh Plugin.
3.Next, FilterDispatcher is called, which in turn consults the ActionMapper to which action have to call.
4.ActionMapper determines that an Action should be invoked, the FilterDispatcher transfers control to the ActionProxy.
5.The ActionProxy consults the framework Configuration Files manager(struts.xml).
6. Next,ActionProxy creates an ActionInvocation, which is responsible for invoking any Interceptors (the before clause) in advance of invoking the Action itself.
7.Once the Action returns, the ActionInvocation is responsible for looking up the proper result associated with the Action result mapped in struts.xml.
8. The result is then executed, which often (but not always, as is the case for Action Chaining) involves a template written in JSP or FreeMarker to be rendered. While rendering, the templates can use the Struts Tags provided by the framework. Some of those components will work with the ActionMapper to render proper URLs for additional requests.


2.Struts 2 Interceptors
Interceptor is an object that is invoked at the preprocessing and postprocessing of a request. In Struts 2, interceptor is used to perform operations such as validation, exception handling, internationalization, displaying intermediate result etc.


Interceptors are Pluggable If we need to remove any concern such as validation, exception handling, logging etc. from the application, we don't need to redeploy the application. We only need to remove the entry from the struts.xml file.


The struts 2 default interceptors are as follows:
1) alias It converts similar parameters that have different names between requests.
2) autowiring
3) chain If it is used with chain result type, it makes the properties of previous action available in the current action.
4) checkbox It is used to handle the check boxes in the form. By this, we can detect the unchecked checkboxes.
5) cookie It adds a cookie to the current action.
6) conversionError It adds conversion errors to the action's field errors.
7) createSession It creates and HttpSession object if it doesn't exists.
8) clearSession It unbinds the HttpSession object.
9) debugging It provides support of debugging.
10) externalRef
11) execAndWait It sends an intermediate waiting page for the result.
12) exception It maps exception to a result.
13) fileUpload It provides support to file upload in struts 2.
14) i18n It provides support to internationalization and localization.
15) jsonValidation It provides support to asynchronous validation.
16) logger It outputs the action name.
17) store It stores and retrieves action messages, action errors or field errors for action that implements ValidationAware interface.
18) modelDriven It makes other model object as the default object of valuestack.
19) scopedModelDriven It is similar to ModelDriven but works for action that implements ScopedModelDriven.
20) params It populates the action properties with the request parameters.
21) actionMappingParams
22) prepare It performs preparation logic if action implements Preparable interface.
23) profiling It supports action profiling.
24) roles It supports role-based action.
25) scope It is used to store the action state in the session or application scope.
26) servletConfig It provides access to maps representing HttpServletRequest and HttpServletResponse.
27) sessionAutowiring
28) staticParams It maps static properties to action properties.
29) timer It outputs the time needed to execute an action.
30) token It prevents duplication submission of request.
31) tokenSession It prevents duplication submission of request.
32) validation It provides support to input validation.
33) workflow It calls the validate method of action class if action class implements Validateable interface.
34) annotationWorkflow
35) multiselect







5.Struts 2 ActionInvocation
The ActionInvocation represents the execution state of an action. It holds the action and interceptors objects.


1) public ActionContext getInvocationContext() returns the ActionContext object associated with the ActionInvocation.
2) public ActionProxy getProxy() returns the ActionProxy instance holding this ActionInvocation.
3) public ValueStack getStack() returns the instance of ValueStack.
4) public Action getAction() returns the instance of Action associated with this ActionInvocation.
5) public void invoke() invokes the next resource in processing(Intersepotor Invoking) this ActionInvocation.
6) public Result getResult() returns the instance of Result.
6.Struts 2 OGNL(Object Graph Navigation Language )
The Object Graph Navigation Language (OGNL) is an expression language.OGNL is much like EL. It simplifies the accessibility of data stored in the ActionContext. it is an expression language for getting and setting properties of Java objects. You use the same expression for both getting and setting the value of a property


The struts framework sets the ValueStack as the root object of OGNL. Notice that action object is pushed into the ValueStack. We can direct access the action property


Ex: <s:property value="name"/>
              Other (non-root) objects in the ActionContext can be rendered use the # notation.
               <s:property value="#session.mySessionKey"/> or
               <s:property value="#request['myRequestKey']"/>


7.Struts 2 standard flow
  1. User sends a request for the action
  2. Container maps the request in the web.xml file and gets the class name of controller.
  3. Container invokes the controller (StrutsPrepareAndExecuteFilter or FilterDispatcher).
  4. Controller gets the information for the action from the ActionMapper
  5. Controller invokes the ActionProxy
  6. ActionProxy gets the information of action and interceptor stack from the configuration manager which gets the information from the struts.xml file.
  7. ActionProxy forwards the request to the ActionInvocation
  8. ActionInvocation invokes each interceptors and action
  9. A result is generated
  10. The result is sent back to the ActionInvocation
  11. A HttpServletResponse is generated
  12. Response is sent to the user



8.Struts 2 Action class
In Struts2 we implement Action in 3 ways
1.Simple POJO Action
2.Action Interface
3.ActionSupport class


1.Simple POJO Action
In struts 2, action class is POJO (Plain Old Java Object).POJO means you are not forced to implement any interface or extend any class.
Generally, execute method should be specified that represents the business logic.


2.Action Interface
A convenient approach is to implement the com.opensymphony.xwork2.Action interface that defines 5 constants and one execute method.
Contstants: All are Public Static Final String Constants
p s f S SUCCESS = "success";  →action execution is successful &success result should be shown to the user.
p s f S ERROR = "error";   → action execution is failed and a error result should be shown to the user
p s f S LOGIN  = "login";   → indicates user is not logged-in and a login result should be shown to the user
p s f S INPUT = "input";   → indicates validation is failed & a input result should be shown to the user again.
p s f S NONE = "none";   → action execution is successful but no result should be shown to the user.


3.ActionSupport class
It is a convenient class that implements many interfaces such as Action, Validateable, ValidationAware, TextProvider, LocaleProvider and Serializable .
         So it is mostly used instead of Action.

9.struts.xml & Configurations


1.Struts.xml
1.package name : In our app we have no.of modules.each module we can seperate by using this pacakge name
2.package namespace : It is an optional attribute of package. We can separate the jsp's have same name by putting them into folder and giving namespace as folder name. Above /first Is name space and it is in first/multipleXml.jsp folder.Default namespace is '/'
3.<include file=””> : we can separate stuts-xxx.xml files and we put them in struts by using this tag
4.<result type=”chain/dispatcher/freemarker/httpheader/redirect/redirectAction/stream/velocity/plaintext/tiles”                               name=”success/input/error”>
5.we can pass <param-name> &<param-value> in betwwen resulttag while, type is reditect/chain etc.


2.web.xml
3.Propertie.file
  Optional







1.Sample Login Application
  1. Take a input.jsp with fields having names in <s:textfield name=”uname”/>
  2. Take an Action class which implements ActionSupport
  3. write Getter/Setter methods for the Fields which are in input.jsp
  4. write Business logic in public void exceute() which returns a result String
  5. configure Action class in struts.xml with SUCCESS and ERROR pages
  6. the struts.xml must be in src or classes folder
2.Struts2 – with Separate Java Bean
Let us see how to store user input details in the separate bean, actually up to now we stored user input values in Action class by writing setters and getter methods, but there is a chance to store in separate bean class.In bean class we write Setter and getteers for the JavaBean Object in Action class, and me put object.fieldname in input.jsp page
3.Struts2 -Resource Bundle
In struts2, if we want to get labels and error messages from an external file then we need to use resource bundle. in struts 1 we need to configure the resource bundle name in struts-config.xml, but in 2.x we need to configure our bundle name in struts.properties file.Both our Bundle, and struts.properties files need to be store in classes folder only
12.Struts 2 Validation Framework
There are three ways to perform validation in struts 2.


1) By Custom Validation:
  • If we want to apply manual validations in struts 2, then we need to extend our Action class from ActionSupport
  • We need to override validate() method in our Action class
  • So in our action class we have execute() and validate() 2 methods, among these 2 validate() method will be executed first, because depends on the validations result execute() method will be executed
  • If we get any  validation error then we can type the error message or we can get the message from a resource bundle(prop.file)
  • If we get any error in validate(), default it will returns string “input“. We have error in validate() method so execute() will not executes.
  • If Error occures in validate(), then add error in this.addActionError(—-) from action class, automatically errors will displays on the top of the input fields.No need to write <s:actionerrors/>
  • Come to execute(), if there is no errors in validate() controller will comes and executes execute() method,if any errors in execute() we need to add errors to addActionError(–), here we need to add <s:actionerrors/> tag in the input page to display the errors
  • If we want to get the error message from the resource bundle we need to call gettext() method


2) By Input Validation (built-in validators) :Struts 2 provides a lot of predefined validations to perform validation.


There are two ways to use bundled validators:
1.Plain-Validator (non-field validator) Syntax:
Plain-validator syntax can be used for action level validator. In such case, a single validator can be applied to many fields.
But disadvantage of this approach is we can't apply many validators to single field.
2.Field-Validator Syntax:The field-validator syntax can be used for field level validator. In such case, multiple validator can be applied to one field. For example, we can apply required and email validators on email field. Moreover, each field can display different messages.






Struts 2 provides following bundled validators.
1.requiredstring
2.stringlength
3.email
4.date
5.int
6.double
7.url
8.regex


















3) By Ajax Validation (built-in validators with ajax) If we don't want to refresh the page, we can use jsonValidation interceptor to perform validation with ajax.







10.Default Interceptors
Struts 2 defaultStack interceptors


1.params interceptor: The params interceptor also known as parameters interceptor is used to set all parameters on the valuestack.
The params interceptor is found in the default stack. You don't need to specify interceptors found in the default-stack.


Declaring param-interceptor manually




If you specify any interceptor for the action explicitely, default interceptors will not be available for the action class.


2.execAndWait interceptor
  • The execAndWait interceptor also known as execute and wait interceptor is used to display the intermediate result.
  • It is recommended to use for long running action.
  • It is not found in the default stack bydefault. So you need to specify it explicitely.
  • For the custom intermediate result, you need to define "wait" result in struts.xml file.
  • In your page, you can display processing image etc. So, it is better to specify the custom result.
3.prepare interceptor


The prepare interceptor calls prepre() method on the action if it implements Preparable interface. It calls prepare() method before the execute() method.
To use the prepare interceptor, you need to implement Preparable interface in your action class and override its method prepare.
It is found in the default stack bydefault. So you don't need to specify it explicitely.
4.modelDriven interceptor
  • The modelDriven interceptor makes other model object as the default object of valuestack.
  • Bydefault, action object is the default object of valuestack.
  • To use the modelDriven interceptor, you need to implement ModelDriven interface in your action class and override its method getModel().
It is found in the default stack bydefault. So you don't need to specify it explicitely.
Here our Bean Object is makes as Default Object of valueStack



11.Custom Interceptors
  1. For Creating userdefined Interseptors we must implement Interceptor interface
  2. It contains public void init(),public String intercept(ActionInvocation),public void destroy()
  3. in intercept(ai) method we must define Pre-proccing/ post-processing Logic and return ai.invoke() reutrns String
  4. the ai.invoke() calls the next Action
  5. configure/ intilize interseptor in struts.xml using <interceptors> tag
  6. declare the interceptor in which servlet you want to run using <interceptor-ref name="upper"> Tag
13.Aware Interfaces


  • In struts2 we don’t have any http specific objects by default just like in servlets.  
  • If at all we want any http related objects in our Action class then we need to implement our Action class from Aware Interfaces
  • Every Aware interface provides a setter method,so we must override that setter method while implementing the  Aware interface,
  • At run time struts 2 controller will automatically calls that setter method and injects the required object into that Action class


Struts 2 provided total of 5 Aware Interfaces
1.ApplicationAware Interface:  
when ever our Action class need to get context behavior, means we can share our data across all the files of the web application by putting in a global object that’s context


When we implement our Action class from ApplicationAware interface then the controller doesn’t inject exactly servlet context object, instead it will injects a map object and this will created once by the controller and the same object will be injected to all files of the struts application.
1.Setting : Override public void setApplication(Map m),method in Action class implementns ApplicationAware
   put values m.put("a",uname);
2.Getting : <s:property value="#application.a" />


2.SessionAware Interface: If we implement from SessionAware interface we need to override the method setSession() by SessionAware in our action class.  If we implement our action class from SessionAware interface then struts 2 controller doesn’t inject exactly session object, but it will injects a Map object with similar behavior.
For each Action class or a jsp visited by the same client, the controller injects the same map object, the controller creates a new map object for each client, it means one map object per session ( browser )
No. of clients = No. of map objects created by controller
3.ServletRequestAware Interface : For request Object
4.ServletResponseAware Interface : For response Object
5.ParameterAware Interface


14.Struts 2 Tiles
A web page can contain many parts (known as tile) such as header, left pane, right pane, body part, footer etc. In tiles framework, we manage all the tile by our Layout Manager page.