Struts Framework Interview questions and answers | Real time Questions and Answers

Struts Framework Interview questions and answers | Real time Questions and Answers

Q) Framework?

A) A framework is a reusable, ``semi-complete'' application that can be specialized to produce custom applications

 Q) Why do we need Struts?

A) Struts combines Java Servlets, Java ServerPages, custom tags, and message resources into a unified framework. The end result is a cooperative, synergistic platform, suitable for development teams, independent developers, and everyone in between.

 Q) Diff Struts1.0 & 1.1?

1.RequestProcessor class, 2.Method perform() replaced by execute() in Struts base Action Class

3. Changes to web.xml and struts-config.xml, 4. Declarative exception handling, 5.Dynamic ActionForms, 6.Plug-ins, 7.Multiple Application Modules, 8.Nested Tags, 9.The Struts Validator Change to the ORO package, 10.Change to Commons logging, 11. Removal of Admin actions, 12.Deprecation of the GenericDataSource

 Q) What is the difference between Model2 and MVC models?

In model2, we have client tier as jsp, controller is servlet, and business logic is java bean. Controller and business logic beans are tightly coupled. And controller receives the UI tier parameters. But in MVC, Controller and business logic are loosely coupled and controller has nothing to do with the project/ business logic as such. Client tier parameters are automatically transmitted to the business logic bean, commonly called as ActionForm.

So Model2 is a project specific model and MVC is project independent.

 Q) How to Configure Struts?

Before being able to use Struts, you must set up your JSP container so that it knows to map all appropriate requests with a certain file extension to the Struts action servlet. This is done in the web.xml file that is read when the JSP container starts. When the control is initialized, it reads a configuration file (struts-config.xml) that specifies action mappings for the application while it's possible to define multiple controllers in the web.xml file, one for each application should suffice

 Q) ActionServlet (controller)

The class org.apache.struts.action.ActionServlet is the called the ActionServlet. In 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. The Controller receives the request from the browser, invoke a business operation and coordinating the view to return to the client.

 Q) Action Class

The Action Class is part of the Model and is a wrapper around the business logic. 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. In the Action Class all the database/business processing are done. It is advisable to perform all the database related stuffs in the Action Class. The ActionServlet (commad) passes the parameterized class to Action Form using the execute() method. 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.

 Ex: -

package com.odccom.struts.action;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;

public class BillingAdviceAction extends Action {

     public ActionForward execute(ActionMapping mapping,

                                                    ActionForm form,

                                                  HttpServletRequest request, HttpServletResponse response)

        throws Exception {

        BillingAdviceVO bavo = new BillingAdviceVO();

        BillingAdviceForm  baform = (BillingAdviceForm)form;

        DAOFactory factory = new MySqlDAOFactory();

        BillingAdviceDAO badao = new MySqlBillingAdviceDAO();   

        ArrayList projects = badao.getProjects();

        request.setAttribute("projects",projects);

        return (mapping.findForward("success"));

    }

}

 Q) Action Form

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.

 Ex: -

package com.odccom.struts.form;

 public class BillingAdviceForm extends ActionForm {
               private String projectid;
               private String projectname;   
 
               public String getProjectid() {  return projectid;  }
               public void setProjectid(String projectid) {  this.projectid = projectid;  }    
public ActionErrors validate(ActionMapping mapping, HttpServletRequest request) {
        ActionErrors errors = new ActionErrors();
        if(getProjectName() == null || getProjectName().length() < 1){
               errors.add(“name”, new ActionError(“error.name.required”));
        }         
        return errors;
    }

public void reset(ActionMapping mapping, HttpServletRequest request){

            this.roledesc = "";

            this.currid      = "";

}

}

 Q) Message Resource Definition file

 M.R.D file are simple “.properties” file these files contains the messages that can be used in struts project. The M.R.D can be added in struts-config.xml file through <message-resource> tag

ex: <message-resource parameter=”MessageResource”>

 Q) Reset :-

This is called by the struts framework with each request, purpose of this method is to reset all of the forms data members and allow the object to be pooled for rescue.

 public class TestAction extends ActionForm{

  public void reset(ActionMapping mapping, HttpServletRequest request request)

}

 Q) execute

Is called by the controller when a request is received from a client. The controller creates an instance of the Action class if one does not already exist. The frame work will create only a single instance of each Action class.

  public ActionForward execute( ActionMapping mapping, ActionForm form, HttpServletRequest request,    HttpServletResponse response)

 Q) Validate: -

This method is called by the controller after the values from the request has been inserted into the ActionForm. The ActionForm should perform any input validation that can be done and return any detected errors to the controller.

 Public ActionErrors validate(ActionMapping mapping, HttpServletRequest request)

 Q) What is Validator? Why will you go for Validator?

Validator is an independent framework, struts still comes packaged with it.

            Instead of coding validation logic in each form bean’s validate() method, with validator you use an xml configuration file to declare the validations that should be applied to each form bean. Validator supports both “server-side and client-side” validations where form beans only provide “server-side” validations.

 Flowing steps: -

1. Enabling the Validator plug-in: This makes the Validator available to the system.

2. Create Message Resources for the displaying the error message to the user.

3. Developing the Validation rules We have to define the validation rules in the validation.xml for the address form. Struts Validator Framework uses this rule for generating the JavaScript for validation.

4. Applying the rules: We are required to add the appropriate tag to the JSP for generation of JavaScript.

 Using Validator Framework

                Using the Validator framework involves enabling the Validator plug-in, configuring Validator's two configuration files, and creating Form Beans that extend the Validator's ActionForm subclasses.

 Enabling the Validator Plug-in

Validator framework comes packaged with Struts; Validator is not enabled by default. To enable Validator, add the following plug-in definition to your application's struts-config.xml file.

 <plug-in className="org.apache.struts.validator.ValidatorPlugIn">

<set-property property="pathnames" value="/technology/WEB-INF/validator-rules.xml,

 /WEB-INF/validation.xml"/>

</plug-in>

This definition tells Struts to load and initialize the Validator plug-in for your application. Upon initialization, the plug-in loads the comma-delimited list of Validator config files specified by the pathnames property.

 Validator-rules.xml

<form-validation>

  <global>

    <Validator name="required" classname="org.apache.struts.validator.FieldChecks" method="validateRequired"

       methodParams="java.lang.Object,

                     org.apache.commons.validator.ValidatorAction,

                     org.apache.commons.validator.Field,

                     org.apache.struts.action.ActionErrors,

                     javax.servlet.http.HttpServletRequest"

                msg="errors.required">

      <javascript>

        <![CDATA[

                    function validateRequired(form) {

        ]]>

      </javascript>

    </validator>

  </global>

</form-validation>

 Q) How struts validation is working?

Validator uses the XML file to pickup the validation rules to be applied to a form. In XML validation requirements are defined applied to a form. In case we need special validation rules not provided by the validator framework, we can plug in our own custom validations into Validator.

 The Validator Framework uses two XML configuration files validator-rules.xml & validation.xml. The validator-rules.xml defines the standard validation routines; such as Required, Minimum Length, Maximum length, Date Validation, Email Address validation and more. These are reusable and used in validation.xml. To define the form specific validations. The validation.xml defines the validations applied to a form bean.

 Q) What is Tiles?

A) Tiles is a framework for the development user interface, Tiles is enables the developers to develop the web applications by assembling the reusable tiles.

  1. Add the Tiles Tag Library Descriptor (TLD) file to the web.xml.
  2. Create layout JSPs.
  3. Develop the web pages using layouts.

Q) How to call ejb from Struts?

    1…use the Service Locator patter to look up the ejbs.

    2…Or you can use InitialContext and get the home interface.

 Q) What are the various Struts tag libraries?

Struts-html tag library -> used for creating dynamic HTML user interfaces and forms.

Struts-bean tag library -> provides substantial enhancements to the basic capability provided by .

Struts-logic tag library -> can manage conditional generation of output text, looping over object collections for repetitive generation of output text, and application flow management.

Struts-template tag library -> contains tags that are useful in creating dynamic JSP templates for pages which share a common format.

Struts-tiles tag library -> This will allow you to define layouts and reuse those layouts with in our site.

Struts-nested tag library ->

 Q) How you will handle errors & exceptions using Struts?

-To handle “errors” server side validation can be used using ActionErrors classes can be used. 
-The “exceptions” can be wrapped across different layers to show a user showable exception. 
- Using validators

 Q) What are the core classes of struts?

A) ActionForm, Action, ActionMapping, ActionForward etc.

 Q) How you will save the data across different pages for a particular client request using Struts?

A) If the request has a Form object, the data may be passed on through the Form object across pages. Or within the Action class, call request.getSession and use session.setAttribute(), though that will persist through the life of the session until altered.

(Or) Create an appropriate instance of ActionForm that is form bean and store that form bean in session scope. So that it is available to all the pages that for a part of the request

 Q) How would struts handle “messages” required for the application?

A) Messages are defined in a “.properties” file as name value pairs. To make these messages available to the application, You need to place the .properties file in WEB-INF/classes folder and define in struts-config.xml

 <message-resource parameter=”title.empname”/>

 and in order to display a message in a jsp would use this

 <bean:message key=”title.empname”/>

 Q) What is the difference between ActionForm and DynaActionForm?

A) 1. In struts 1.0, action form is used to populate the html tags in jsp using struts custom tag.when the java code changes, the change in action class is needed. To avoid the chages in struts 1.1 dyna action form is introduced.This can be used to develop using xml. The dyna action form bloats up with the struts-config.xml based definetion.

2. There is no need to write actionform class for the DynaActionForm and all the variables related to the actionform class will be specified in the struts-config.xml. Where as we have to create Actionform class with getter and setter methods which are to be populated from the form

3.if the formbean is a subclass of ActionForm, we can provide reset(),validate(),setters(to hold the values),gettters whereas if the formbean is a subclass to DynaActionForm we need not provide setters, getters but in struts-config.xml we have to configure the properties in using .basically this simplifies coding

 DynaActionForm which allows you to configure the bean in the struts-config.xml file. We are going to use a subclass of DynaActionForm called a DynaValidatorForm which provides greater functionality when used with the validation framework.

 <struts-config>

    <form-beans>

        <form-bean name="employeeForm" type="org.apache.struts.validator.DynaValidatorForm">

            <form-property name="name" type="java.lang.String"/>

            <form-property name="age" type="java.lang.String"/>

            <form-property name="department" type="java.lang.String" initial="2" />

            <form-property name="flavorIDs" type="java.lang.String[]"/>

            <form-property name="methodToCall" type="java.lang.String"/>

        </form-bean>

    </form-beans>

</struts-config>

 This DynaValidatorForm is used just like a normal ActionForm when it comes to how we define its use in our action mappings. The only 'tricky' thing is that standard getter and setters are not made since the DynaActionForms are backed by a HashMap. In order to get fields out of the DynaActionForm you would do: 

String age = (String)formBean.get("age");
Similarly, if you need to define a property:
formBean.set("age","33");

Q) Struts how many “Controllers” can we have?

A) You can have multiple controllers, but usually only one is needed

Q) Can I have more than one struts-config.xml?

A) Yes you can I have more than one.

<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</param-value>

    </init-param>

   <! — module configurations -- >

   <init-param>

            <param-name>config/exercise</param-name>

<param-value>/WEB-INF/exercise/struts-config.xml</param-value>

    </init-param>

  </servlet>

Q) Can you write your own methods in Action class other than execute() and call the user method directly?

A) Yes, we can create any number of methods in Action class and instruct the action tag in struts-config.xml file to call that user methods.

Public class StudentAction extends DispatchAction

{

      public ActionForward read(ActionMapping mapping, ActionForm form,

                                                  HttpServletRequest request, HttpServletResponse response) throws Exceptio

      {

            Return some thing;

      }

      public ActionForward update(ActionMapping mapping, ActionForm form,

                                                  HttpServletRequest request, HttpServletResponse response) throws Exceptio

      {

            Return some thing;

      }

If the user want to call any methods, he would do something in struts-config.xml file.

<action path="/somepage"

            type="com.odccom.struts.action.StudentAction"

            name="StudentForm"

            <b>parameter=”methodToCall”</b>

            scope="request"

            validate="true">                                   

<forward name="success" path="/Home.jsp" />

</action>

 Q) Struts-config.xml

 <struts-config>

     <data-sources>

        <data-source>

               <set-property property=”key” value=”” url=”” maxcount=”” mincount=””  user=”” pwd=”” >                 

        </data-source>

    <data-sources>

     <!— describe the instance of the form bean-- >

    <form-beans>

        <form-bean name="employeeForm" type="net.reumann.EmployeeForm"/>

    </form-beans>

     <!— to identify the target of an action class when it returns results -- >

    <global-forwards>

        <forward name="error" path="/error.jsp"/>

    </global-forwards>

     <!— describe an action instance to the action servlet-- >

    <action-mappings>

        <action path="/setUpEmployeeForm" type="net.reumann.SetUpEmployeeAction"

            name="employeeForm" scope="request" validate="false">

          <forward name="continue" path="/employeeForm.jsp"/>

        </action> 

        <action path="/insertEmployee" type="net.reumann.InsertEmployeeAction"

            name="employeeForm" scope="request" validate="true"

            input="/employeeForm.jsp">

         <forward name="success" path="/confirmation.jsp"/>

        </action>

    </action-mappings>

        <!— to modify the default behaviour of the struts controller-- >

    <controller processorClass=”” bufferSize=” ” contentType=””  noCache=””   maxFileSize=””/>

       <!— message resource properties -- >

    <message-resources parameter="ApplicationResources" null="false" />

    <!—Validator plugin à

   <plug-in className="org.apache.struts.validator.ValidatorPlugIn">
          <set-property property="pathnames" value="/WEB-INF/validator-rules.xml, /WEB-INF/validation.xml"/>
   </plug-in>

    <!—Tiles plugin à

   <plug-in className="org.apache.struts.tiles.TilesPlugIn">
          <set-property property="definitions-config" value="/WEB-INF/tiles-defs.xml "/>
   </plug-in>

 </struts-config>

 Q) Web.xml: -   Is a configuration file describe the deployment elements.

<web-app>

    <servlet>

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

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

      <!—Resource Properties -->

      <init-param>

            <param-name>application</param-name>

            <param-value>ApplicationResources</param-value>

      </init-param>

                  <init-param>

         <param-name>config</param-name>

         <param-value>/WEB-INF/struts-config.xml</param-value>

      </init-param>

    <load-on-startup>1</load-on-startup>

  </servlet>

   <!-- Action Servlet Mapping -->

  <servlet-mapping>

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

<url-pattern>/do/*</url-pattern>

  </servlet-mapping>

   <!-- The Welcome File List -->

  <welcome-file-list>

            <welcome-file>index.jsp</welcome-file>

  </welcome-file-list>

   <!-- tag libs -->

  <taglib>

<taglib-uri>struts/bean-el</taglib-uri>

<taglib-location>/WEB-INF/struts-bean-el.tld</taglib-location>

  </taglib>

   <taglib>

            <taglib-uri>struts/html-el</taglib-uri>

            <taglib-location>/WEB-INF/struts-html-el.tld</taglib-location>

  </taglib>

   <!—Tiles tag libs -->

  <taglib>
            <taglib-uri>/tags/struts-tiles</taglib-uri>
            <taglib-location>/WEB-INF/struts-tiles.tld</taglib-location>
  </taglib>

 <!—Using Filters -->

  <filter>

<filter-name>HelloWorldFilter</filter-name>

            <filter-class>HelloWorldFilter</filter-class>

  </filter>

   <filter-mapping>

            <filter-name>HelloWorldFilter</filter-name>

            <url-pattern>ResponseServlet</ url-pattern >

  </filter-mapping> 

</web-app>