Struts2.0

Major Point of Concern of Struts2.0:-

Struts1.x vs 2.x
http://www.java4s.com/struts-tutorials/struts-1-x-vs-struts-2-x-main-differences/

1:-Namespace:-
Struts 2 Namespace is a new concept to handle the multiple modules by given a namespace to each module. In addition, it can used to avoid conflicts between same action names located at different modules.

http://www.mkyong.com/struts2/struts-2-namespace-configuration-example-and-explanation/
https://www.youtube.com/watch?v=BlFHGscURC4

----------------------------------------------------------------------------------------
How Does ActionClass interact To Jsp:-
Actually in servlet-jsp we use Request,Session Scope, then how things work out here:
--
Since Servlet has single object(Singlton) it's based on MultiThread:
Whereas Strts2.0:'
Action object are created for each and every request
servlet object are not created for each and every request

------
So 4 four there you will have for instance of your action class
now Question is how to reterive the value inside action to jsp:
here is the concept of ValueStack
ValueStack play very important role lot of component access it for there use
it's not a tradition stack. actually for accessing member variable of action object.
it comes in picture, Struts2 make action object availability in ValueStack, so that
using Struts tage we can directly access instance of action.


very important:-
it behave like virtual object,
so accessing the member variable you can directly acess ,no need to fetch first action object then . member

variable, this is what power of struts and value stack.
but there may be problem. two member same name.. then how to acess. it use concept of top-down since
it's stack and workout
----------------------------------------------------
Accessing Input Parameters:-
passing parameter in request like www.udi.com?language=hi
now in servlet you need to fetch the value using getParam..
but in struts no need it does automatically you need to create member variable as parameter name in actionand getter setter,
and it will work out
---
this is done by interceptor ,while request time it picks the value from url or your request parameter
and set in value stack action object member variable which we have created..
and then action class use it.
-----------
The above case remain same either it is GET request or Post,
We can have multiple .xml configuration and we can include all of them together. using include tag
--------------------
you can have Action Wildcards like action=log*

----------------------
Action vs ActionSupport
There are lot difference ,anyway if you extends from actionSupport it's intreanlly implmetning Action
we have validate method inside ActionSuppport addFieldError etc..
---------------\
Configuring methods in Action mappings:-
We have here method attribute which value we can set ...by default struts call to execute method
---------------------------------------------

ActionContext:-
From anywhere within an Struts 2 application, you can obtain a reference to the ActionContext by calling

ActionContext context = ActionContext.getContext();
For example, if a helper class is called from an Action, and if it happens to need access to ServletContext
(maybe it is writing a file and needs ServletContext to get a path to it),
the helper can obtain the ActionContext directly. Nothing needs to be passed from the Action.
---
The ActionContext is a container of objects in which action is executed. The values stored in the ActionContext are unique per thread (i.e. ThreadLocal).
So we don't need to make our action thread safe.
We can get the reference of ActionContext by calling the getContext() method of ActionContext class.
It is a static factory method. For example:
ActionContext context = ActionContext.getContext();

--------------------
ActionInvocation:-
The ActionInvocation represents the execution state of an action. It holds the action and interceptors objects.
The struts framework provides ActionInvocation interface to deal with ActionInvocation. It provides many methods, some of them can be used to get the instance of ValueStack, ActionProxy, ActionContext, Result etc.

Mehods of ActionInvocation Interface

The commonly used methods of ActionInvocation interface are as follows:
No.MethodDescription
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 this ActionInvocation.
6)public Result getResult()returns the instance of Result.
The entire. architecture of the struts2.0; request to end:-
http://java.dzone.com/articles/struts2-tutorial-part-17
--------------------

http://java.dzone.com/articles/struts2-tutorial-part-17
complete flow for struts2 Arch:-
http://www.javatpoint.com/struts-2-architecture-and-flow

StrutsPrepareAndExecuteFilter vs FilterDispatcher
Deprecated. Since Struts 2.1.3, use StrutsPrepareAndExecuteFilter instead or
StrutsPrepareFilter and StrutsExecuteFilter
if needing using the ActionContextCleanUp filter in addition to this one
 ----------------------------------------

extending class by TokenInterceptor.
actually we already have token interceptor how ever we are extending TokenInterceptor because if we use
default one. only double submittion will stop but .extending from TokenInterceptor. we can give our fuctionality
as well to TokenInterceptor
  --------------------------
In our web application, there might occur exception at any point.
To overcome this problem, struts 2 provides a mechanism of global exception handling where we can display a global result to the user.
Struts 2 automatically log the uncaught exceptions and redirects the user to the error handler page
Struts 2 Exception Handling - exception interceptor

<global-results>
<result name="myresult">globalresult.jsp</result>
</global-results>

<global-exception-mappings>
<exception-mapping result="myresult" exception="java.lang.Exception"></exception-mapping>
</global-exception-mappings>
------------------------------------------------------

XML Based Validation:

The second method of doing validation is by placing an xml file next to the action class. Struts2 XML based validation provides more options of validation like email validation, integer range validation, form validation field, expression validation, regex validation, required validation, requiredstring validation, stringlength validation and etc.
The xml file needs to be named '[action-class]'-validation.xml. So, in our case we create a file calledEmployee-validation.xml with the following contents:
<!DOCTYPE validators PUBLIC 
"-//OpenSymphony Group//XWork Validator 1.0.2//EN"
"http://www.opensymphony.com/xwork/xwork-validator-1.0.2.dtd">

<validators>
   <field name="name">
      <field-validator type="required">
         <message>
            The name is required.
         </message>
      </field-validator>
   </field>

   <field name="age">
     <field-validator type="int">
         <param name="min">29</param>
         <param name="max">64</param>
         <message>
            Age must be in between 28 and 65
         </message>
      </field-validator>
   </field>
</validators>
Above XML file would be kept in your CLASSPATH ideally along with class file. Let us have our Employee action class as follows without having validate() method:
package com.tutorialspoint.struts2;

import com.opensymphony.xwork2.ActionSupport;

public class Employee extends ActionSupport{
   private String name;
   private int age;
   
   public String execute() 
   {
       return SUCCESS;
   }
   public String getName() {
       return name;
   }
   public void setName(String name) {
       this.name = name;
   }
   public int getAge() {
       return age;
   }
   public void setAge(int age) {
       this.age = age;
   }
}
Rest of the setup will remain as it is i the previous example, now if you will run the application, it will produce same result what we recieved in previous example.
The advantage of having an xml file to store the configuration allows the separation of the validation from the application code. You could get a developer to write the code and a business analyst to create the validation xml files. Another thing to note is the validator types that are available by default. There are plenty more validators that come by default with Struts. Common validators include Date Validator, Regex validator and String Length validator. Check following link for more detail Struts - XML Based Validators.

---------\
The syntax of the FieldValidator is given below and it's recomanded by the Apache

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.
But disadvantage of this approach is we can't apply common validator to many field like plain-validator.
Let's see simple example of field-validator.
  1. <validators>  
  2.     <!-- Field-Validator Syntax -->  
  3.     <field name="username">  
  4.           <field-validator type="requiredstring">  
  5.             <param name="trim">true</param>  
  6.             <message>username is required</message>  
  7.        </field-validator>  
  8.     </field>  
  9.   
  10. </validators>  
  11. ------------------------------------
Struts2 - Writing custom validator


go and check above link .. you will find best resul
-----------------------------------------------------------
Tiles Framwork:-
e can customize the layout of the struts 2 application by integrating with tiles framework.
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.

Advantage of tiles framework

There are following advantages of tiles framework:
  • Customization by centralized page We can customize the layout of all the pages by single page (centralized page) only.
  • Code reusability A single part e.g. header or footer can be used in many pages. So it saves coding.
  • Easy to modify If any part (tile) is modified, we don't need to change many pages.
  • Easy to remove If any part (tile) of the page is removed, we don't need to remove the code from all the pages. We can remove the tile from our layout manager page.
struts 2 with tiles example
add tiles jar,
add listener in web.xml



   <listener>
   <listener-class>
      org.apache.struts2.tiles.StrutsTilesListener
   </listener-class>
   </listener>
create tiles.xml..
http://www.tutorialspoint.com/struts_2/struts_tiles.htm  more you can find here

---------------------------------------------------------------------------------------

SessionAware Interface:-

Struts 2 Aware interfaces are used to put information into the request, response, context or session object.

The action class must implement these interfaces to store information 
so that it can be retrieved from other action class.

The four aware interfaces are:

org.apache.struts2.interceptor.SessionAware
org.apache.struts2.util.ServletContextAware
org.apache.struts2.interceptor.ServletRequestAware
org.apache.struts2.interceptor.ServletResponseAware

for more details: log in here
http://www.javatpoint.com/struts-2-aware-interfaces-tutorial
----------------------------------------------------
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.

http://www.javatpoint.com/struts-2-interceptors-tutorial


No comments:

Post a Comment