Tuesday, November 5, 2013

Struts Related Question and answer

1. What are the main classes which are used in struts application?
------------------------------------------------------------------
Action servlet: it’s a back-bone of web application it’s a controller class responsible for handling the entire request.

Action class: using Action classes where all the business logic implemented.

Action Form: it’s a java bean which represents our forms and associated with action mapping. And it also maintains the session state its object is
automatically populated on the server side with data entered from a form on the client side.

Action Mapping: using this class we do the mapping between object and Action.

ActionForward: this class in Struts is used to forward the result from controller to destination.

2. How exceptions are handled in Struts application?
----------------------------------------------------
There are two ways of handling exception in Struts:

Pro grammatically handling: using try {} catch block in code where exception can come and flow of code is also decided by programmer .its a normal java language
concept.

Declarative Exception Handling: we can either define global exception handling tags in your struts-config.xml or define the exception handling tags within <action>..</action> tag.

example:
        <global-exception-mappings>
            <exception-mapping exception="java.sql.SQLException" result="SQLException"/>
            <exception-mapping exception="java.lang.Exception" result="Exception"/>
        </global-exception-mappings>
        ...
        <action name="DataAccess" class="com.company.DataAccess">
            <exception-mapping exception="com.company.SecurityException" result="login"/>
            <result name="SQLException" type="chain">SQLExceptionAction</result>
            <result>/DataAccess.jsp</result>
        </action>
        ...
3. How validation is performed in struts application?
------------------------------------------------------
 In struts validation is performed using validator framework, Validator Framework in Struts consist of two XML configuration files.

1. validator-rules.xml file: which contains the default struts pluggable validator definitions. You can add new validation rules by adding an entry in this file.

This was the original beauty of struts which makes it highly configurable.

2. Validation.xml files which contain details regarding the validation routines that are applied to the different Form Beans.



4. Dispatch Action , LookupDispatch Action , EventDispatchAction
------------------------------------------------
Dispatch Action:An abstract Action that dispatches to a public method that is named by the request parameter whose name is specified by the parameter property of the corresponding ActionMapping. This Action is useful for developers who prefer to combine many similar actions into a single Action class, in order to simplify their application design.

Example :
<action path="/saveSubscription" type="org.apache.struts.actions.DispatchAction" name="subscriptionForm" scope="request" input="/subscription.jsp" parameter="method"/>

LookupDispatchAction : An abstract Action that dispatches to the subclass mapped execute method. This is useful in cases where an HTML form has multiple submit buttons with the same name. The button name is specified by the parameter property of the corresponding ActionMapping. To configure the use of this action in your struts-config.xml file, create an entry like this:

   <action path="/test"
           type="org.example.MyAction"
           name="MyForm"
          scope="request"
          input="/test.jsp"
      parameter="method"/>

EventDispatchAction: An Action that dispatches to to one of the public methods that are named in the parameter attribute of the corresponding ActionMapping and matches a submission parameter. This is useful for developers who prefer to use many submit buttons, images, or submit links on a single form and whose related actions exist in a single Action class.

<action path="/saveSubscription"
           type="org.example.SubscriptionAction"
           name="subscriptionForm"
          scope="request"
          input="/subscription.jsp"
      parameter="save,back,recalc=recalculate,default=save"/>

5. How you can retrieve the value which is set in the JSP Page in case of DynaActionForm?
--------------------------------------------------------------------------------------------
DynaActionForm is a popular topic in Struts interview questions. DynaActionForm is subclass of ActionForm that allows the creation of form beans with dynamic sets of properties, without requiring the developer to create a Java class for each type of form bean. DynaActionForm eliminates the need of FormBean class and now the form bean definition can be written into the struts-config.xml file. So, it makes the FormBean declarative and this helps the programmer to reduce the development time.

6. what the Validate () and reset () method does?
----------------------------------------------------
validate() : validate method is Used to validate properties after they have been populated, and this ,method is  Called before FormBean is passed  to Action.
Returns a collection of ActionError as ActionErrors.

reset() : The purpose of this method is to reset all of the ActionForm's data


7. How you will make available any Message Resources Definitions file to the Struts Framework Environment?
----------------------------------------------------------------------------------------------------------
Message Resources Definitions file are simple .properties files and these files contains the messages that can be used in the struts project. Message Resources
Definitions files can be added to the struts-config.xml file through < message-resources / > tag and also using web.xml

8. Explain Struts work Flow?
---------------------------------
 1) A request comes in from a Java Server Page into the ActionServlet.

2) The ActionServlet having already read the struts-config.xml file, knows which form bean relates to this JSP, and delegates work to the validate method of  that form bean.

3) The form bean performs the validate method to determine if all required fields have been entered, and performs whatever other types of field validations that  need to be performed.

4) If any required field has not been entered, or any field does not pass validation, the form bean generates ActionErrors, and after checking all fields  returns back to the ActionServlet.

5) The ActionServlet checks the ActionErrors that were returned from the form beans validate method to determine if any errors have occurred. If errors have  occurred, it returns to the originating JSP displaying the appropriate errors.

6) If no errors occurred in the validate method of the form bean, the ActionServlet passes control to the appropriate Action class.

7) The Action class performs any necessary business logic, and then forwards to the next appropriate action (probably another JSP).


9. How can I create a wizard work flow?
-------------------------------------------------
The basic idea is a series of actions with next, back, cancel and finish actions with a common bean. Using a LookupDispatchAction is recommended as it fits the design pattern well and can be internationalized easily.

10. How to do 'chain' Actions?
-----------------------------------------
Chaining actions can be done by simply using the proper mapping in your forward entries in the struts-config.xml file.

example :
<forward name="success" path="/xyz.do" />

11. diff detween Struts 1 and Struts 2
---------------------------------------
Action classes :

In struts 1 Action classes extend an abstract base class.

An Struts 2 Action may implement an Action interface, along with other interfaces to enable optional and custom service,Struts 2 provides a base ActionSupport  class to implement commonly used interfaces.

Servlet dependency :
Struts 1 is completely dependent on servlet api. where as Struts 2 action is not its execute() method doesn't required Servlet API. can use simple   POJO

Threading Model :
Struts 1 Actions are singletons and must be thread-safe.
   
Struts 2 Action objects are instantiated for each request, so there are no thread-safety issues.

Validation :
Struts 1 supports manual validation via a validate method on the ActionForm, or through an extension to the Commons Validator.

Struts 2 supports manual validation via the validate method and the XWork Validation framework.
   
Type Conversion :
 Struts 1 ActionForm properties are usually all Strings. Struts 1 uses Commons-Beanutils for type conversion.

Struts 2 uses OGNL for type conversion.
   
Binding values into views :
Struts 1 uses the standard JSP mechanism for binding objects into the page context for access.
Struts 2 uses a "ValueStack" technology so that the taglibs can access values without coupling your view to the object type it is rendering.

 Expression Language :
 Struts 1 integrates with JSTL, so it uses the JSTL EL.
 Struts 2 can use JSTL, but the framework also supports a more powerful and flexible expression language called "Object Graph Notation Language" (OGNL).
   
12. Which design pattern the Interceptors in Struts2 is based on ?
    Interceptors in Struts2 are based on Intercepting Filters.   

13 : Are Interceptors and Filters different ? , If yes then how ?
---------------------------------------------------------------------------
Interceptors and filters are based on intercepting filter,there are few differences when it comes to Struts2.

Filters:
         (1) Based on Servlet Specification
         (2) Executes on the pattern matches on the request.
         (3) Not configurable method calls
       
Interceptors:
         (1) Based on Struts2.
         (2) Executes for all the request qualifies for a front controller( A Servlet filter ).And can be  
              configured to execute additional interceptor for a  particular action execution.
         (3)Methods in the Interceptors can be configured whether to execute or not by means of
             exclude  methods or include Methods.    
       
14. In Struts1, the front-controller was a Servlet but in Struts2, it is a filter. What is the possible reason to change it to a filter ?
-------------------------------------------------------------------------------------------------------------------
There are two possibilities why filter is designated as front controller in Strtus2       

1. Servlet madel as front controller needs developer to provide a right value in <load-on-startup> which lets the framework to initialize many important aspects.

Struts2 makes our life easy by providing front-controller as a filter,and by nature the filters in web.xml gets initialized automatically as the container starts

2. The second but important one is , the introduction of Interceptors in Struts2 framework.

14. Which class is the front-controller in Struts2 ?
    org.apache.struts2.dispatcher.FilterDispatcher


15. How does Interceptors help achieve Struts2 a better framework than Struts1 ?
--------------------------------------------------------------------------------
> Most of the trivial work are made easier to achieve for example automatic form population.

> Intelligent configuration and defaults for example you can have struts.xml or annotation based configuration and out of box interceptors can provide facilities that a common web application needs

>Now Struts2 can be used anywhere in desktop applications also, with minimal or no change of existing web application,since actions are now POJO.POJO actions are even easier to unit test

>Easier UI and validation in form of themes and well known DOJO framework.

>Highly plugable,Integrate other technologies like Spring,Hibernate etc at ease.

> Ready for next generation RESTFUL services

16. What is the relation between ValueStack and OGNL ?
-------------------------------------------------------
A ValueStack is a place where all the data related to action and the action itself is stored. OGNL is a mean through which the data in the ValueStack is manipulated.

17. What is the difference between empty default namespace and root name space ?
--------------------------------------------------------------------------------
If the namespace attribute is not defined in the package tag or assigned "" value then it is called empty default namespace.While if "/" is assigned as value to the namespace attribute then it is called as root namespace. The root namespace is treated as all other explicit namespaces and must be matched. It’s important to distinguish between the empty default namespace, which can catch all request patterns as long as the action name matches, and the root namespace, which is an actual namespace that must be matched.

18. Which interceptor is responsible for setting action's JavaBean properties ?
--------------------------------------------------------------------------------
com.opensymphony.xwork2.interceptor.ParametersInterceptor is the interceptor class who sets the action's JavaBean properties from request.

19. What is the difference between Action and ActionSupport ?
--------------------------------------------------------------------------------
Action is interface defines some string like SUCCESS,ERROR etc  and an execute() method. For convenience Developer implement this interface to have access to String field in action methods.

ActionSupport on other hand implements Action and some other interfaces and provides some feature like data validation and localized error messaging  when extended in the action classes by developers.

20. Does the order in which interceptors execute matters ? If yes then why ?
-----------------------------------------------------------------------------------------
Well, the answer is yes and no.Some Interceptors are designed to be independent so the order doesn't matter,but some interceptors are totally dependent on the previous interceptors execution.For example the validation and workflow interceptors,the validation interceptors checks if there is any error in the form being submitted to the action, then comes the workflow interceptor who checks if validation ( occured in the last) has any error,in presence of error it will not let the rest of the interceptors ( if any ) in the stack to execute.So this is very important that the validation interceptors execute first before the workflow. On the other hand lets say you wrote an interceptors who is doing the authentication and you have the user credential provided ( by the time this executes) it doesn't matter where this interceptors is placed( It is a different fact that you would like to keep it in the top ).

21. What is the difference between RequestAware and ServletRequestAware interface ?
---------------------------------------------------------------------------------------------------------
RequestAware and ServletRequestAware both makes your action to deals with the servlet request, but in a different ways,RequestAware gives you the attributes in the servlet request as a map( key as attribute name and value is the object added),But ServletRequestAware gives you the  HttpServletRequest object

22.What is the difference between EL and OGNL ?
----------------------------------------------------------------
OGNL is much like EL in JSPs,a language to traverse or manupulate objects like request , session or application in web context.OGNL stands for Object graph navigation language,

23. What are the difference between ActionContext and ServletActionContext ?
----------------------------------------------------------------------------
ActionContext represents the context in which Action is executed, which itself doesn't hold any web parameters like session, request etc. ServletActionContext, extends the ActionContext and provides the web parameters  to the Action

24. What is the DispatchAction (Struts1) equivalent in Strtus2 ? 
------------------------------------------------------------------
Struts1 provided the facility of having related action methods in a Single Action class,depending on the method parameter, the mapped methods were executed.To achieve this we have to extend the DispatchAction class in Struts1.But this comes as default in Struts2, We need to provide the qualified methods in the action class( no need to inherit any class), and provide the mapping of action path/name to the method attribute in action tag(struts.xml) and proper code in view layer.

25. What is the role of Action/ Model ?
--------------------------------------------------
Actions in Struts are POJO , is also considered as a Model. The role of Action are to execute business logic or delegate call to business logic by the means of action methods which is mapped to request and contains business data to be used by the view layer by means of setters and getters inside the Action class and finally helps the framework decide which result to render

1 comment:

AWS Services

      1.         Identity Access Management (IAM): Used to control Identity (who) Access (what AWS resources).                   1....