What is a framework?

A framework is made up of the set of classes which allow us to use a library in a best possible way for a specific requirement.

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.

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.

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.

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.


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

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>

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

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

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>



What is the directory structure of Struts application?
The directory structure of Struts application :
Struts Directory Structure


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.


What are the important tags of struts-config.xml ?

The five important sections are:
struts-config.xml

What are the different kinds of actions in Struts?
The different kinds of actions in Struts are:
  • ForwardAction
  • IncludeAction
  • DispatchAction
  • LookupDispatchAction
  • SwitchAction

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.


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

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.


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.


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.


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.




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>

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

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"/>

What is the use of <logic:iterate>?
<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> 

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"/>


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.


What is Struts? Why you have used struts in your application or project.


Ans: This is the first interview questions anyone asks in Struts to get the interview rolling. Most commonly asked during less senior level. Struts is nothing but open source framework mostly used for making web application whenever we use the term framework means it comprises JSP ,servlet ,custom tags message resources all in one bundle which makes developer task very easy. Its is based on MVC pattern which is model view Controller pattern.

Now why we use Struts? So main reason is if we go with servlet all HTML code which is related with design part mostly will come inside java code which makes code unmaintainable and complex similarly if use JSP, all java code related with business come inside design part which again make code complex, that’s why MVC pattern come into existence and which separate the business, design and controller and struts was made based upon this pattern and easy to develop web application. The keyword to answer this Struts interview questions is MVC design pattern, Front Controller Pattern and better flow management which mostly interviewer are looking to hear.


What are the main classes which are used in struts application?


Ans 2: This is another beginner’s level Struts interview question which is used to check how familiar candidate is with Struts framework and API. Main classes in Struts Framework are:

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 all the business logic is developed us call model of the application also.
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.


How exceptions are handled in Struts application?

Ans: This is little tough Struts interview question though looks quite basic not every candidate knows about it. Below is my answer of this interview questions on Struts:

There are two ways of handling exception in Struts:

Programmatically 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 handling: There are two ways again either we define <global-Exception> tag inside struts config.xml file

<exception

      key="stockdataBase.error.invalidCurrencyType"

      path="/AvailbleCurrency.jsp"

      type="Stock.account.illegalCurrencyTypeException">
</exception>

Programmatic and Declarative way is some time also asked as followup questions given candidate’s response on knowledge on Struts.

Key: The key represent the key present in MessageResource.properties file to describe the exception.
Type: The class of the exception occurred.
Path: The page where the controls are to be followed is case exception occurred.


How validation is performed in struts application?


Ans: Another classic Struts interview question it’s higher on level than previous interview questions because it’s related to important validation concept on web 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.

These two configuration file in Struts should be place somewhere inside the /WEB-INF folder of the application to keep it safe from client and make it available in Classpath.

<!--  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>
Now the next step towards validation is create error messages inside the message resource property file which is used by validator framework.
Message resource Contain:
1. CurrencyConverterForm.fromCurrency = From Currency
2. CurrencyConverterForm.toCurrency=To currency
3. errors.required={0} is required.

Then validation rules are defined in validation.xml for the fields of form on which we want desire validation

Form bean code that extend DynaValidatorForm
Eg; <form-beans>
<form-bean name="CurrencyConverterForm" type="org.apache.struts.validator.DynaValidatorForm">
<form-property name="fromCurrency" type="java.lang.double" />
<form-property name="toCurrecny" type="java.lang.double" />
</form-bean>
</form-beans>

Validation.xml file contains

<form-validation>
<formset>
<form name=" CurrencyConverterForm ">
<field property=" fromCurrency " depends="required">
<arg key=" CurrencyConverterForm. fromCurrency "/>
</field>
<field property=" toCurrecny " depends="required ">
<arg key=" CurrencyConverterForm.toCurrency "/>
</field>
</form>
</formset>
</form-validation>

To associate more than one validation rule to the property we can specify a comma-delimited list of values. The first rule in the list will be checked first and then the next rule and so on. Answer of this Struts questions gets bit longer but it’s important to touch these important concept to make it useful.



What is the Difference between DispatchAction and LookupDispatchAction in Struts Framework?

This Struts interview questions is pretty straight forward and I have put the differences in tabular format to make it easy to read.


Dispatch Action
LookupDispatchAction

It’s a parent class of  LookupDispatchAction
Subclass of Dispatch Action
DispatchAction provides a mechanism for grouping a set of related functions into a single action, thus eliminating the need to create separate actions for each function.
An abstract Action that dispatches to the subclass mapped executes 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.
If not using Internalization functionality then dispatch action is more useful.

Lookup Dispatch Action is useful when we are using Internalization functionality

DispatchAction selects the method to execute depending on the request parameter value which is configured in the xml file.
LookupDispatchAction looks into the resource bundle file and find out the corresponding key name. We can map this key name to a method name by overriding the getKeyMethodMap() method. 
DispatchAction is not useful for I18N

LookupDispatchAction is used for I18N


How you can retrieve the value which is set in the JSP Page in case of DynaActionForm?

Ans: 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.

For Example: we have a CurrencyConverterForm and we don't want a java class.
CurrencyConverterForm has properties fromCurrency, toCurrency

in the struts-config.xml file, declare the form bean
<form-bean name=" CurrencyConverterForm "
type="org.apache.struts.action.DynaActionForm">
<form-property name=" fromCurrency " type="java.lang.String"/>
<form-property name=" toCurrency " type="java.lang. String "/>
</form-bean> 

Add action mapping in the struts-config.xml file:
<action path="/convertCurrency" type="com.techfaq.action.ConvertCurrencyAction"
name=" CurrencyConverterForm "
scope="request"
validate="true"
input="/pages/ currencyConverterform.jsp">

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

</action> 

In the Action class.

public class ConvertCurrencyAction extends Action
{
public ActionForward execute(
ActionMapping mapping,
ActionForm form,
HttpServletRequest request,
HttpServletResponse response) throws Exception{

DynaActionForm currencyConverterForm = (DynaActionForm)form;

// by this way we can retrieve the value which is set in the JSP Page

String fromCurrency = (String) currencyConverterForm.get("fromCurrency ");
String toCurrency = (String) currencyConverterForm.get("toCurrency ");
return mapping.findForward("success");
}
}

In the JSP page

<html:text property=" fromCurrency " size="30" maxlength="30"/>
<html:text property=" toCurrency " size="30" maxlength="30"/>

what the Validate () and reset () method does?

Ans: This is one of my personal favorite Struts interview questions. 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. Following is the method signature for the validate() method.public ActionErrors validate(ActionMapping mapping, HttpServletRequest request) {
                       
ActionErrors errors = new ActionErrors();
if ( StringUtils.isNullOrEmpty(username) && StringUtils.isNullOrEmpty(password)){
     errors.add(ActionErrors.GLOBAL_ERROR, new ActionError("error.usernamepassword.required"));
}
return errors;
}

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.

Example : 
public void reset(ActionMapping mapping, HttpServletRequest request) {
this.password = null;
this.username = null;

Set null for every request.

How you will make available any Message Resources Definitions file to the Struts Framework Environment?

Ans: 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 / >

Message resource definition files can available to the struts environment in two ways
1. using web.xml as
<servlet>
<servlet-name>action<servlet-name>
servlet-class>org.apache.struts.action.ActionServlet<servlet-class>
<init-param>
<param-name>application<param-name>
<param-value>resource.Application<param-value>
</servlet>

2.
<message-resource key="myResorce" parameter="resource.Application" null="false">

What configuration files are used in Struts?
Ans: ApplicationResources.properties and struts-config.xml these two files are used to between the Controller and the Model.

Explain Struts work Flow?


Ans: Some time this Struts interview questions asked as first questions but I recall this now J . Here is the answer of this Struts interview questions
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).

Leave a Reply

Subscribe to Posts | Subscribe to Comments

About This Site

Howdy! My name is Suersh Rohan and I am the developer and maintainer of this blog. It mainly consists of my thoughts and opinions on the technologies I learn,use and develop with.

Blog Archive

Powered by Blogger.

- Copyright © My Code Snapshots -Metrominimalist- Powered by Blogger - Designed by Suresh Rohan -