Sunday, April 29, 2012

STRUTS INTERVIEW QUESTIONS


1. What is Jakarta Struts Framework?
      Jakarta Struts is open source implementation of MVC (Model-View-Controller) pattern for the development of web based applications. Jakarta Struts is robust architecture and can be used for the development of application of any size. Struts framework makes it much easier to design scalable, reliable Web applications with Java.
2. What is ActionServlet?
      The class org.apache.struts.action.ActionServlet is the called the ActionServlet. In the the Jakarta Struts Framework this class plays the role of controller. All the requests to the server goes through the controller. Controller is responsible for handling all the requests.
3. 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.

Example:
          <message-resources parameter="MessageResources" />
4. What is Action Class?
      The Action is part of the controller. The purpose of Action Class is to translate the HttpServletRequest to the business logic. To use the Action, we need to Subclass and overwrite the execute() method. The ActionServlet (commad) passes the parameterized class to Action Form using the execute() method. There should be no database interactions in the action. The action should receive the request, call business objects (which then handle database, or interface with J2EE, etc) and then determine where to go next. Even better, the business objects could be handed to the action at runtime (IoC style) thus removing any dependencies on the model. The return type of the execute method is ActionForward which is used by the Struts Framework to forward the request to the file as per the value of the returned ActionForward object.
5. Write code of any Action Class?
      Here is the code of Action Class that returns the ActionForward object.
TestAction.java

            package chennaisunday.net;
            import javax.servlet.http.HttpServletRequest;
            import javax.servlet.http.HttpServletResponse;
            import org.apache.struts.action.Action;
            import org.apache.struts.action.ActionForm;
            import org.apache.struts.action.ActionForward;
            import org.apache.struts.action.ActionMapping;
            public class TestAction extends Action
            {
            public ActionForward execute(
            ActionMapping mapping,
            ActionForm form,
            HttpServletRequest request,
            HttpServletResponse response) throws Exception{
            return mapping.findForward("testAction");
            }
            }
6. What is ActionForm?
      An ActionForm is a JavaBean that extends org.apache.struts.action.ActionForm. ActionForm maintains the session state for web application and the ActionForm object is automatically populated on the server side with data entered from a form on the client side.
7. What is Struts Validator Framework?
      Struts Framework provides the functionality to validate the form data. It can be use to validate the data on the users browser as well as on the server side. Struts Framework emits the java scripts and it can be used validate the form data on the client browser. Server side validation of form can be accomplished by sub classing your From Bean with DynaValidatorForm class.

     The Validator framework was developed by David Winterfeldt as third-party add-on to Struts. Now the Validator framework is a part of Jakarta Commons project and it can be used with or without Struts. The Validator framework comes integrated with the Struts Framework and can be used without doing any extra settings.
8. Give the Details of XML files used in Validator Framework?
      The Validator Framework uses two XML configuration files validator-rules.xml and validation.xml. The validator-rules.xml defines the standard validation routines, these are reusable and used invalidation.xml. to define the form specific validations. The validation.xml defines the validations applied to a form bean.
9. How you will display validation fail errors on jsp page?
      Following tag displays all the errors:
          <html:errors/>
10. How you will enable front-end validation based on the xml in validation.xml?
      The <html:javascript> tag to allow front-end validation based on the xml in validation.xml. For example the code:
<html:javascript formName="logonForm" dynamicJavascript="true" staticJavascript="true" /> generates the client side java script for the form "logonForm" as defined in the validation.xml file. The <html:javascript> when added in the jsp file generates the client site validation script.
11. What is RequestProcessor and RequestDispatcher?
      The controller is responsible for intercepting and translating user input into actions to be performed by the model. The controller is responsible for selecting the next view based on user input and the outcome of model operations. The Controller receives the request from the browser, invoke a business operation and coordinating the view to return to the client.      The controller is implemented by a java servlet. this servlet is centralized point of control for the web application. In struts framework the controller responsibilities are implemented by several           different components like           The ActionServlet Class           The RequestProcessor Class           The Action Class      The ActionServlet extends the javax.servlet.http.httpServlet class. The ActionServlet class is not abstract and therefore can be used as a concrete controller by your application.
The controller is implemented by the ActionServlet class. All incoming requests are mapped to the central controller in the deployment descriptor as follows.

          <servlet>
           <servlet-name>action</servlet-name>
           <servlet-class>org.apache.struts.action.ActionServlet</servlet-class>
          </servlet>


All request URIs with the pattern *.do are mapped to this servlet in the deployment descriptor as follows.

          <servlet-mapping>
          <servlet-name>action</servlet-name>
           <url-pattern>*.do</url-pattern>
           <url-pattern>*.do</url-pattern>


A request URI that matches this pattern will have the following form.
http://www.my_site_name.com/mycontext/actionName.do
The preceding mapping is called extension mapping, however, you can also specify path mapping where a pattern ends with /* as shown below.

          <servlet-mapping>
           <servlet-name>action</servlet-name>
           <url-pattern>/do/*</url-pattern>
          <url-pattern>*.do</url-pattern>


A request URI that matches this pattern will have the following form.
http://www.my_site_name.com/mycontext/do/action_Name

     The class org.apache.struts.action.requestProcessor process the request from the controller. You can sublass the RequestProcessor with your own version and modify how the request is processed.

     Once the controller receives a client request, it delegates the handling of the request to a helper class. This helper knows how to execute the business operation associated with the requested action. In the Struts framework this helper class is descended of org.apache.struts.action.Action class. It acts as a bridge between a client-side user action and business operation. The Action class decouples the client request from the business model. This decoupling allows for more than one-to-one mapping between the user request and an action. The Action class also can perform other functions such as authorization, logging before invoking business operation. the Struts Action class contains several methods, but most important method is the execute() method.

public ActionForward execute(ActionMapping mapping,
      ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception;      The execute() method is called by the controller when a request is received from a client. The controller creates an instance of the Action class if one doesn?t already exist. The strut framework will create only a single instance of each Action class in your application.

Action are mapped in the struts configuration file and this configuration is loaded into memory at startup and made available to the framework at runtime. Each Action element is represented in memory by an instance of the org.apache.struts.action.ActionMapping class . The ActionMapping object contains a path attribute that is matched against a portion of the URI of the incoming request.

          <action>
           path= "/somerequest"
           type="com.somepackage.someAction"
           scope="request"
           name="someForm"
           validate="true"
           input="somejsp.jsp"
           <forward name="Success" path="/action/xys" redirect="true"/>
           <forward name="Failure" path="/somejsp.jsp" redirect="true"/>
           </action>

     Once this is done the controller should determine which view to return to the client. The execute method signature in Action class has a return type org.apache.struts.action.ActionForward class. The ActionForward class represents a destination to which the controller may send control once an action has completed. Instead of specifying an actual JSP page in the code, you can declaratively associate as action forward through out the application. The action forward are specified in the configuration file.

           <action>
           path= "/somerequest"
           type="com.somepackage.someAction"
           scope="request"
           name="someForm"
           validate="true"
           input="somejsp.jsp"
           <forward name="Success" path="/action/xys" redirect="true"/>
           <forward name="Failure" path="/somejsp.jsp" redirect="true"/>
           </action>

The action forward mappings also can be specified in a global section, independent of any specific action mapping.
          <global-forwards>
           <forward name="Success" path="/action/somejsp.jsp" />
           <forward name="Failure" path="/someotherjsp.jsp" />
          </global-forwards>

public interface RequestDispatcher
     Defines an object that receives requests from the client and sends them to any resource (such as a servlet, HTML file, or JSP file) on the server. The servlet container creates the RequestDispatcher object, which is used as a wrapper around a server resource located at a particular path or given by a particular name.

This interface is intended to wrap servlets, but a servlet container can create RequestDispatcher objects to wrap any type of resource.
getRequestDispatcher

public RequestDispatcher getRequestDispatcher(java.lang.String path) Returns a RequestDispatcher object that acts as a wrapper for the resource located at the given path. A RequestDispatcher object can be used to forward a request to the resource or to include the resource in a response. The resource can be dynamic or static.
The pathname must begin with a "/" and is interpreted as relative to the current context root. Use getContext to obtain a RequestDispatcher for resources in foreign contexts. This method returns null if the ServletContext cannot return a RequestDispatcher.
Parameters:

path - a String specifying the pathname to the resource Returns:
a RequestDispatcher object that acts as a wrapper for the resource at the specified path See Also:
RequestDispatcher, getContext(java.lang.String)

getNamedDispatcher

public RequestDispatcher getNamedDispatcher(java.lang.String name) Returns a RequestDispatcher object that acts as a wrapper for the named servlet. Servlets (and JSP pages also) may be given names via server administration or via a web application deployment descriptor. A servlet instance can determine its name using ServletConfig.getServletName(). This method returns null if the ServletContext cannot return a RequestDispatcher for any reason.

Parameters:

name - a String specifying the name of a servlet to wrap Returns:
a RequestDispatcher object that acts as a wrapper for the named servlet See Also:
RequestDispatcher, getContext(java.lang.String), ServletConfig.getServletName() 
12. Why cant we overide create method in StatelessSessionBean?
      From the EJB Spec : - A Session bean's home interface defines one or morecreate(...) methods. Each create method must be named create and must match one of the ejbCreate methods defined in the enterprise Bean class. The return type of a create method must be the enterprise Bean's remote interface type. The home interface of a stateless session bean must have one create method that takes no arguments.
13. Is struts threadsafe?Give an example?
      Struts is not only thread-safe but thread-dependant. The response to a request is handled by a light-weight Action object, rather than an individual servlet. Struts instantiates each Action class once, and allows other requests to be threaded through the original object. This core strategy conserves resources and provides the best possible throughput. A properly-designed application will exploit this further by routing related operations through a single Action.
14. Can we Serialize static variable?
      Serialization is the process of converting a set of object instances that contain references to each other into a linear stream of bytes, which can then be sent through a socket, stored to a file, or simply manipulated as a stream of data. Serialization is the mechanism used by RMI to pass objects between JVMs, either as arguments in a method invocation from a client to a server or as return values from a method invocation. In the first section of this book, There are three exceptions in which serialization doesnot necessarily read and write to the stream.

These are

     1. Serialization ignores static fields, because they are not part of any particular object's state.
     2. Base class fields are only handled if the base class itself is serializable.
     3. Transient fields. There are four basic things you must do when you are making a class serializable. They are:
           1. Implement the Serializable interface.
           2. Make sure that instance-level, locally defined state is serialized properly.
           3. Make sure that superclass state is serialized properly.
          4. Override equals( )and hashCode( ).
it is possible to have control over serialization process. The class should implement Externalizable interface. This interface contains two methods namely readExternal and writeExternal. You should implement these methods and write the logic for customizing the serialization process ....
15. What are the uses of tiles-def.xml file, resourcebundle.properties file, validation.xml file?
         tiles-def.xml is is an xml file used to configure tiles with the struts application. You can define the layout / header / footer / body content for your View.
   The resourcebundle.properties file is used to configure the message (error/ other messages) for the struts applications.
   The file validation.xml is used to declare sets of validations that should be applied to Form Beans.
16. What is the difference between perform() and execute() methods?
      Perform method is the method which was deprecated in the Struts Version 1.1. In Struts 1.x, Action.perform() is the method called by the ActionServlet. This is typically where your business logic resides, or at least the flow control to your JavaBeans and EJBs that handle your business logic. As we already mentioned, to support declarative exception handling, the method signature changed in perform. Now execute just throws Exception. Action.perform() is now deprecated; however, the Struts v1.1 ActionServlet is smart enough to know whether or not it should call perform or execute in the Action, depending on which one is available.
17. What are the various Struts tag libraries?
      Struts is very rich framework and it provides very good and user friendly way to develop web application forms. Struts provide many tag libraries to ease the development of web applications. These tag libraries are:

     * Bean tag library - Tags for accessing JavaBeans and their properties.
     * HTML tag library - Tags to output standard HTML, including forms, text boxes, checkboxes, radio
      buttons etc..
     * Logic tag library - Tags for generating conditional output, iteration capabilities and flow management
     * Tiles or Template tag library - For the application using tiles
     * Nested tag library - For using the nested beans in the application 
18. What do you understand by DispatchAction?
      DispatchAction is an action that comes with Struts 1.1 or later, that lets you combine Struts actions into one class, each with their own method. The org.apache.struts.action.DispatchAction class allows multiple operation to mapped to the different functions in the same Action class.

For example:

A package might include separate RegCreate, RegSave, and RegDelete Actions, which just perform different operations on the same RegBean object. Since all of these operations are usually handled by the same JSP page, it would be handy to also have them handled by the same Struts Action.
A very simple way to do this is to have the submit button modify a field in the form which indicates which operation to perform.

     <html:hidden property="dispatch" value="error"/>
     <SCRIPT>unction set(target) {document.forms[0].dispatch.value=target;}</SCRIPT>
     <html:submit onclick="set('save');">SAVE</html:submit>
     <html:submit onclick="set('create');">SAVE AS NEW</html:submitl>
     <html:submit onclick="set('delete);">DELETE</html:submit>

Then, in the Action you can setup different methods to handle the different operations, and branch to one or the other depending on which value is passed in the dispatch field.

     String dispatch = myForm.getDispatch();
     if ("create".equals(dispatch)) { ...
     if ("save".equals(dispatch)) { ...

     The Struts Dispatch Action [org.apache.struts.actions] is designed to do exactly the same thing, but without messy branching logic.
The base perform method will check a dispatch field for you, and invoke the indicated method. The only catch is that the dispatch methods must use the same signature as perform. This is a very modest requirement, since in practice you usually end up doing that anyway.
To convert an Action that was switching on a dispatch field to a DispatchAction, you simply need to create methods like this
     public ActionForward create(
      ActionMapping mapping,
      ActionForm form,
      HttpServletRequest request,
      HttpServletResponse response)
      throws IOException, ServletException { ...
     public ActionForward save(
      ActionMapping mapping,
      ActionForm form,
      HttpServletRequest request,
      HttpServletResponse response)      throws IOException, ServletException { ...

Cool. But do you have to use a property named dispatch? No, you don't. The only other step is to specify the name of of the dispatch property as the "parameter" property of the action-mapping. So a mapping for our example might look like this:

     <action
      path="/reg/dispatch"
      type="app.reg.RegDispatch"
      name="regForm"
      scope="request"
      validate="true"
      parameter="dispatch"/>

If you wanted to use the property "o" instead, as in o=create, you would change the mapping to
     <action
      path="/reg/dispatch"
      type="app.reg.RegDispatch"
      name="regForm"
      scope="request"
      validate="true"
      parameter="o"/>
Again, very cool. But why use a JavaScript button in the first place? Why not use several buttons named "dispatch" and use a different value for each?
You can, but the value of the button is also its label. This means if the page designers want to label the button something different, they have to coordinate the Action programmer. Localization becomes virtually impossible. 
19. How Struts relates to J2EE?
      Struts framework is built on J2EE technologies (JSP, Servlet, Taglibs), but it is itself not part of the J2EE standard.
20. What is Struts actions and action mappings?
      A Struts action is an instance of a subclass of an Action class, which implements a portion of a Web application and whose perform or execute method returns a forward.

An action can perform tasks such as validating a user name and password.

     An action mapping is a configuration file entry that, in general, associates an action name with an action. An action mapping can contain a reference to a form bean that the action can use, and can additionally define a list of local forwards that is visible only to this action.

     An action servlet is a servlet that is started by the servlet container of a Web server to process a request that invokes an action. The servlet receives a forward from the action and asks the servlet container to pass the request to the forward's URL. An action servlet must be an instance of an org.apache.struts.action.ActionServlet class or of a subclass of that class. An action servlet is the primary component of the controller.
21. Can I setup Apache Struts to use multiple configuration files?
      Yes Struts can use multiple configuration files. Here is the configuration example:

          <servlet>
           <servlet-name>banking</servlet-name>
           <servlet-class>org.apache.struts.action.ActionServlet
           </servlet-class>
           <init-param>
           <param-name>config</param-name>
           <param-value>/WEB-INF/struts-config.xml,
                 /WEB-INF/struts-authentication.xml,
                 /WEB-INF/struts-help.xml
                 </param-value>
           </init-param>
            <load-on-startup>1</load-on-startup>
          </servlet>
22. What are the disadvantages of Struts?
      Struts is very robust framework and is being used extensively in the industry. But there are some disadvantages of the Struts:

a) High Learning Curve
Struts requires lot of efforts to learn and master it. For any small project less experience developerscould spend more time on learning the Struts.

b) Harder to learn
Struts are harder to learn, benchmark and optimize.
23. What is Struts Flow?
      Struts Flow is a port of Cocoon's Control Flow to Struts to allow complex workflow, like multi-form wizards, to be easily implemented using continuations-capable JavaScript. It provides the ability to describe the order of Web pages that have to be sent to the client, at any given point in time in an application. The code is based on a proof-of-concept Dave Johnson put together to show how the Control Flow could be extracted from Cocoon.
24. What are the difference between <bean:message> and <bean:write>?
      <bean:message>: This tag is used to output locale-specific text (from the properties files) from a MessageResources bundle.

     <bean:write>: This tag is used to output property values from a bean. is a commonly used tag which enables the programmers to easily present the data.
25. What is 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..
26. What are the components of Struts?
      Struts is based on the MVC design pattern. Struts components can be categories into Model, View and Controller.
Model: Components like business logic / business processes and data are the part of Model.
View: JSP, HTML etc. are part of View
Controller: Action Servlet of Struts is part of Controller components which works as front controller to handle all the requests.
27. What are Tag Libraries provided with Struts?
      Struts provides a number of tag libraries that helps to create view components easily. These tag libraries are:
a) Bean Tags: Bean Tags are used to access the beans and their properties.
b) HTML Tags: HTML Tags provides tags for creating the view components like forms, buttons, etc..
c) Logic Tags: Logic Tags provides presentation logics that eliminate the need for scriptlets.
d) Nested Tags: Nested Tags helps to work with the nested context.
28. What are the core classes of the Struts Framework?
      Core classes of Struts Framework are ActionForm, Action, ActionMapping, ActionForward, ActionServlet etc.
29. What are difference between ActionErrors and ActionMessage?
      ActionMessage: A class that encapsulates messages. Messages can be either global or they are specific to a particular bean property.
Each individual message is described by an ActionMessage object, which contains a message key (to be looked up in an appropriate message resources database), and up to four placeholder arguments used for parametric substitution in the resulting message.

     ActionErrors: A class that encapsulates the error messages being reported by the validate() method of an ActionForm. Validation errors are either global to the entire ActionForm bean they are associated with, or they are specific to a particular bean property (and, therefore, a particular input field on the corresponding form).
30. How you will handle exceptions in Struts?
      In Struts you can handle the exceptions in two ways:

a) Declarative Exception Handling: You can either define global exception handling tags in your struts-config.xml or define the exception handling tags within <action>..</action> tag.
Example:
          <exception
           key="database.error.duplicate"
           path="/UserExists.jsp"
           type="mybank.account.DuplicateUserException"/>

b) Programmatic Exception Handling: Here you can use try{}catch{} block to handle the exception.
31.What is MVC?
     A Model-View-Controller (MVC) is a design pattern put together to help control change. MVC decouples interface from business logic and data.

* Model : The model contains the core of the applications functionality. The model encapsulates the state of the application. Sometimes the only functionality it contains is state. It knows nothing about the view or controller.
View: The view provides the presentation of the model. It is the look of the application. The view can access the model getters, but it has no knowledge of the setters. In addition, it knows nothing about the controller. The view should be notified when changes to the model occur.
* Controller:The controller reacts to the user input. It creates and sets the model.
33.What is Struts framework?
      Struts framework is an open-source framework for developing the web applications in java EE, based on MVC-2 architecture. It uses and extends the Java Servlet API. Struts is robust architecture and can be used for the development of application of any size. Struts framework makes it much easier to design scalable, reliable Web applications with Java.
34.What are the components of Struts?
      Struts components can be categorize into Model, View and Controller:

      * Model: Components like business logic /business processes and data are the part of model.
      * View: HTML,JSP are the view components.
      * Controller: Action Servlet of Struts is part of Controller components which works as front controller to handle all the requests.
35.What are the core classes of the Struts Framework?
      Struts is a set of cooperating classes, servlets, and JSP tags that make up a reusable MVC 2 design.

* JavaBeans components for managing application state and behavior.
* Event-driven development (via listeners as in traditional GUI development).
* Pages that represent MVC-style views; pages reference view roots via the JSF component tree.
36.What is ActionServlet?
      ActionServlet is a simple servlet which is the backbone of all Struts applications. It is the main Controller component that handles client requests and determines which Action will process each received request. It serves as an Action factory – creating specific Action classes based on user’s request.
37.What is role of ActionServlet?
      ActionServlet performs the role of Controller:

* Process user requests
* Determine what the user is trying to achieve according to the request
* Pull data from the model (if necessary) to be given to the appropriate view,
* Select the proper view to respond to the user
* Delegates most of this grunt work to Action classes
* Is responsible for initialization and clean-up of resources
38.What is the ActionForm?
      ActionForm is javabean which represents the form inputs containing the request parameters from the View referencing the Action bean.
39.What are the important methods of ActionForm?
      The important methods of ActionForm are : validate() & reset().
40.Describe validate() and reset() methods ?
      validate() : Used to validate properties after they have been populated; Called before FormBean is handed to Action. Returns a collection of ActionError as ActionErrors. Following is the method signature for the validate() method.

public ActionErrors validate(ActionMapping mapping,HttpServletRequest request)

reset(): reset() method is called by Struts Framework with each request that uses the defined ActionForm. The purpose of this method is to reset all of the ActionForm's data members prior to the new request values being set.

public void reset() {}
41.What is ActionMapping?
      Action mapping contains all the deployment information for a particular Action bean. This class is to determine where the results of the Action will be sent once its processing is complete.
42.How is the Action Mapping specified ?
      We can specify the action mapping in the configuration file called struts-config.xml. Struts framework creates ActionMapping object from <ActionMapping> configuration element of struts-config.xml file

          <action-mappings>
          <action path="/submit"
           type="submit.SubmitAction"
           name="submitForm"
           input="/submit.jsp"
           scope="request"
           validate="true">
           <forward name="success" path="/success.jsp"/>
           <forward name="failure" path="/error.jsp"/>
          </action>
          </action-mappings>
43.What is role of Action Class?
      An Action Class performs a role of an adapter between the contents of an incoming HTTP request and the corresponding business logic that should be executed to process this request.
44.In which method of Action class the business logic is executed ?
      In the execute() method of Action class the business logic is executed.

          public ActionForward execute(
           ActionMapping mapping,
           ActionForm form,
           HttpServletRequest request,
           HttpServletResponse response)
           throws Exception ;
     execute() method of Action class:
      * Perform the processing required to deal with this request
      * Update the server-side objects (Scope variables) that will be used to create the next page of the
     user interface
      * Return an appropriate ActionForward object
45.What design patterns are used in Struts?
      Struts is based on model 2 MVC (Model-View-Controller) architecture. Struts controller uses the command design pattern and the action classes use the adapter design pattern. The process() method of the RequestProcessor uses the template method design pattern. Struts also implement the following J2EE design patterns.

           * Service to Worker
           * Dispatcher View
           * Composite View (Struts Tiles)
           * Front Controller
           * View Helper
          * Synchronizer Token
46.Can we have more than one struts-config.xml file for a single Struts application?
      Yes, we can have more than one struts-config.xml for a single Struts application. They can be configured as follows:

          <servlet>
          <servlet-name>action</servlet-name>
           <servlet-class>

      org.apache.struts.action.ActionServlet

           </servlet-class>
          <init-param>
           <param-name>config</param-name>
           <param-value>
           /WEB-INF/struts-config.xml,
          /WEB-INF/struts-admin.xml,
          /WEB-INF/struts-config-forms.xml
           </param-value>
          </init-param>
          .....
          <servlet>
47.What is the directory structure of Struts application?
     The directory structure of Struts application :
Struts Directory Structure
48.What is the difference between session scope and request scope when saving formbean ?
      when the scope is request,the values of formbean would be available for the current request.
     when the scope is session,the values of formbean would be available throughout the session.
49.What are the important tags of struts-config.xml ?
     The directory structure of Struts application :
struts-config.xml
50.What are the different kinds of actions in Struts?
      The different kinds of actions in Struts are:

          * ForwardAction
          * IncludeAction
          * DispatchAction
          * LookupDispatchAction
          * SwitchAction
51.What is DispatchAction?
      The DispatchAction class is used to group related actions into one class. Using this class, you can have a method for each logical action compared than a single execute method. The DispatchAction dispatches to one of the logical actions represented by the methods. It picks a method to invoke based on an incoming request parameter. The value of the incoming parameter is the name of the method that the DispatchAction will invoke.
52.How to use DispatchAction?
      To use the DispatchAction, follow these steps :

 * Create a class that extends DispatchAction (instead of Action)
 * In a new class, add a method for every function you need to perform on the service – The   method has the same signature as the execute() method of an Action class.
 * Do not override execute() method – Because DispatchAction class itself provides execute() method.
 * Add an entry to struts-config.xml
53.What is the use of ForwardAction?
      The ForwardAction class is useful when you’re trying to integrate Struts into an existing application that uses Servlets to perform business logic functions. You can use this class to take advantage of the Struts controller and its functionality, without having to rewrite the existing Servlets. Use ForwardAction to forward a request to another resource in your application, such as a Servlet that already does business logic processing or even another JSP page. By using this predefined action, you don’t have to write your own Action class. You just have to set up the struts-config file properly to use ForwardAction.
54.What is IncludeAction?
      The IncludeAction class is useful when you want to integrate Struts into an application that uses Servlets. Use the IncludeAction class to include another resource in the response to the request being processed.
55.What is the difference between ForwardAction and IncludeAction?
      The difference is that you need to use the IncludeAction only if the action is going to be included by another action or jsp. Use ForwardAction to forward a request to another resource in your application, such as a Servlet that already does business logic processing or even another JSP page.
56.What is LookupDispatchAction?
      The LookupDispatchAction is a subclass of DispatchAction. It does a reverse lookup on the resource bundle to get the key and then gets the method whose name is associated with the key into the Resource Bundle.
57.What is the use of LookupDispatchAction?
      LookupDispatchAction is useful if the method name in the Action is not driven by its name in the front end, but by the Locale independent key into the resource bundle. Since the key is always the same, the LookupDispatchAction shields your application from the side effects of I18N.
58.What is difference between LookupDispatchAction and DispatchAction?
      The difference between LookupDispatchAction and DispatchAction is that the actual method that gets called in LookupDispatchAction is based on a lookup of a key value instead of specifying the method name directly.
59.What is SwitchAction?
      The SwitchAction class provides a means to switch from a resource in one module to another resource in a different module. SwitchAction is useful only if you have multiple modules in your Struts application. The SwitchAction class can be used as is, without extending.
60.What if <action> element has <forward> declaration with same name as global forward?
      In this case the global forward is not used. Instead the <action> element’s <forward> takes precendence.
61.What is DynaActionForm?
      A specialized subclass of ActionForm that allows the creation of form beans with dynamic sets of properties (configured in configuration file), without requiring the developer to create a Java class for each type of form bean.
62.What are the steps need to use DynaActionForm?
      Using a DynaActionForm instead of a custom subclass of ActionForm is relatively straightforward. You need to make changes in two places:

* In struts-config.xml: change your <form-bean> to be an org.apache.struts.action.DynaActionForm instead of some subclass of ActionForm
     <form-bean name="loginForm"type="org.apache.struts.action.DynaActionForm" >
      <form-property name="userName" type="java.lang.String"/>
      <form-property name="password" type="java.lang.String" />
     </form-bean>
* In your Action subclass that uses your form bean:
          »  import org.apache.struts.action.DynaActionForm
          »  downcast the ActionForm parameter in execute() to a DynaActionForm
           »  access the form fields with get(field) rather than getField()
          import javax.servlet.http.HttpServletRequest;
          import javax.servlet.http.HttpServletResponse;
          import org.apache.struts.action.Action;
          import org.apache.struts.action.ActionForm;
          import org.apache.struts.action.ActionForward;
          import org.apache.struts.action.ActionMapping;
          import org.apache.struts.action.ActionMessage;
          import org.apache.struts.action.ActionMessages;
          import org.apache.struts.action.DynaActionForm;
          public class DynaActionFormExample extends Action {
          public ActionForward execute(ActionMapping mapping, ActionForm form,
          HttpServletRequest request, HttpServletResponse response)
           throws Exception {
           DynaActionForm loginForm = (DynaActionForm) form;
            ActionMessages errors = new ActionMessages();
           if (((String) loginForm.get("userName")).equals("")) {
           errors.add("userName", new ActionMessage(
           "error.userName.required"));
           }
           if (((String) loginForm.get("password")).equals("")) {
           errors.add("password", new ActionMessage(
           "error.password.required"));
           }
63.How to display validation errors on jsp page?
      <html:errors/> tag displays all the errors.
     <html:errors/> iterates over ActionErrors request attribute.
64.What are the various Struts tag libraries?
      The various Struts tag libraries are:

          * HTML Tags
          * Bean Tags
          * Logic Tags
          * Template Tags
          * Nested Tags
          * Tiles Tags
65.What is the use of ?
      <logic:iterate> repeats the nested body content of this tag over a specified collection.

          <table border=1>
           <logic:iterate id="customer" name="customers">
           <tr>
           <td><bean:write name="customer" property="firstName"/></td>
           <td><bean:write name="customer" property="lastName"/></td>
           <td><bean:write name="customer" property="address"/></td>
           </tr>
           </logic:iterate>
          </table>
66.What are differences between <bean:message> and <bean:write>
      <bean:message>: is used to retrive keyed values from resource bundle. It also supports the ability to include parameters that can be substituted for defined placeholders in the retrieved string.

<bean:message key="prompt.customer.firstname"/>
<bean:write>: is used to retrieve and print the value of the bean property. <bean:write> has no body.
<bean:write name="customer" property="firstName"/>
67.How the exceptions are handled in struts?
      Exceptions in Struts are handled in two ways:

* Programmatic exception handling :
Explicit try/catch blocks in any code that can throw exception. It works well when custom value (i.e., of variable) needed when error occurs.
* Declarative exception handling :You can either define <global-exceptions> handling tags in your struts-config.xml or define the exception handling tags within <action></action> tag. It works well when custom page needed when error occurs. This approach applies only to exceptions thrown by Actions.

          <global-exceptions>
           <exception key="some.key"
           type="java.lang.NullPointerException"
           path="/WEB-INF/errors/null.jsp"/>
          </global-exceptions>
               or
          <exception key="some.key"
           type="package.SomeException"
           path="/WEB-INF/somepage.jsp"/>
68.What is difference between ActionForm and DynaActionForm?
      * An ActionForm represents an HTML form that the user interacts with over one or more pages. You will provide properties to hold the state of the form with getters and setters to access them. Whereas, using DynaActionForm there is no need of providing properties to hold the state. Instead these properties and their type are declared in the struts-config.xml

* The DynaActionForm bloats up the Struts config file with the xml based definition. This gets annoying as the Struts Config file grow larger.

* The DynaActionForm is not strongly typed as the ActionForm. This means there is no compile time checking for the form fields. Detecting them at runtime is painful and makes you go through redeployment.

* ActionForm can be cleanly organized in packages as against the flat organization in the Struts Config file.

ActionForm were designed to act as a firewall between HTTP and the Action classes, i.e. isolate and encapsulate the HTTP request parameters from direct use in Actions. With DynaActionForm, the property access is no different than using request.getParameter( .. ).

DynaActionForm construction at runtime requires a lot of java Reflection (Introspection) machinery that can be avoided.
69.How can we make message resources definitions file available to the Struts framework environment?
      We can make message resources definitions file (properties file) available to Struts framework environment by adding this file to struts-config.xml.

            <message-resources parameter="com.login.struts.ApplicationResources"/>
70.What is the life cycle of ActionForm?
      The lifecycle of ActionForm invoked by the RequestProcessor is as follows:

        * Retrieve or Create Form Bean associated with Action
        * "Store" FormBean in appropriate scope (request or session)
        * Reset the properties of the FormBean * Populate the properties of the FormBean
        * Validate the properties of the FormBean * Pass FormBean to Action

No comments:

Post a Comment