Thursday, August 12, 2021

Top 10 Struts Framework Interview Questions and Answers

This time it's Struts interview questions, After writing Spring interview questions a few weeks back I was thinking about what to pick for my interview series and then I thought about any web framework, and on that struts is my favorite. Struts are open-source frameworks used for web applications. These Struts interview questions are based on my experience as well as collected by friends and colleague and they are not only good for interview practice but also shows a new direction of learning for anyone who is not very familiar with struts. The best way to use these interview questions does revise before going for any Struts interview or any Java or J2EE interview.

Struts Interview Questions Answer

I have also provided answers to these struts interview questions but you can also research more on Google but these answers of struts are sufficient from an interview perspective.

Question 1: What are Struts? Why you have used struts in your application or project.

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


Now why we use Struts? So main reason is if we go with servlet all HTML code which is related to design part mostly will come inside java code which makes code unmaintainable and complex similarly if use JSP, all java code related to 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 were made based on 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. You can read more design pattern interview question on my post 10 Interview question on Singleton Pattern in Java


Question 2: 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 backbone 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.



Question 3: 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 an 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>

The programmatic and Declarative way is sometimes also asked as follow-up questions are given candidate’s response on knowledge on Struts.

Key: The key represents 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.


See Struts in Action for more details:


Struts interview questions and answers





Question 4: How validation is performed in struts application?

Ans: Another classic Struts interview question it’s higher on a level than previous interview questions because it’s related to important validation concept on a 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 files in Struts should be placed somewhere inside the /WEB-INF folder of the application to keep it safe from the 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 created error messages inside the message resource property file which are 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. The answer of this Struts questions gets bit longer but it’s important to touch these important concepts to make it useful.

Top 10 Interview Questions asked in Struts


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

This Struts interview question 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 finds 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




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

Ans: DynaActionForm is a popular topic in Struts interview questions. DynaActionForm is a 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"/>


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

Question 8: 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 contain 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">

Question 9: 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.


Question 10: Explain Struts work Flow?
Ans: Sometime this Struts interview questions asked as first questions but I recall this now J . Here is the answer to this Struts interview questions
Struts flow and architecture
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).

That’s all on Struts interview question answers, for now, there are lots many interview questions on Struts which I have not covered which you guys can contribute and I will include it here. If you are looking to find the answer to any question asked on Struts interview then please put it here and I will try to find an answer to those questions.



15 comments :

Subodh said...

Very common Struts interview question. It looks like anyone who has used Struts for six month can answer these Struts question. You should include tough question which gives some kind of novelty and useful for senior guys who has been working in Struts for more than 2 or 3 years. here are some interview question which I have in my Struts collection :

1) Why you use Struts framework if you have better Spring MVC framework?
2) What are the other MVC web framework have you used apart from Jakarta Struts (Spring, Wicket etc)
3)What is difference between reset() and validate method?
4) What is difference between DispathAction and LookupDispatchAction?
5) Various kind of Action classes in Struts and why they are added like IncludeAction
6)How to forward request to other page using Struts?
7) How to include response from other page using Struts?
8) How to display error page using Struts?
9) Can we change name of Struts-config.xml file as Struts Configuration.
10) Difference between Struts and Spring MVC framework?

Struts said...

my favorite Struts 2 interview questions is "How to you prevent or avoid double submission of form in struts"?
Struts 2 has a tag which can be used along with TokenInterceptor. token can be included in form and than interceptor will be able to check it for uniqueness.

Anonymous said...

can we add multiple config files in struts if yes how?

Anonymous said...

In the web.xml, you can separate multiple Struts configure file by a comma “,“.

java developer said...

Today in the interview i was asked::: difference between servlet filter and struts interceptor?

prasadg said...

What are the different design patterns used in struts, explain them briefly?

Anonymous said...

What is difference between Struts 1 and Struts 2 framework?

How does Struts uses Dependency Injection design principle?

Anonymous said...

These type of interview questions increases confidence level to face interview for beginners like me, So thanks..

Unknown said...

Q. Explain Struts form beans and form-bean mappings.

Ans:

A 'form bean' is a type of Java bean. A form bean is an instance of a subclass of an ActionForm class, which stores HTML form data from a submitted client request or that can store input data from a Struts action link that a user clicked. An HTML form comprises fields in which the user can enter information.

A 'form-bean mapping' is an entry in a Struts configuration file that maps a form bean to an action.

When a browser submits an HTML form, the Struts action servlet does as follows:

1. Looks at the field names from the HTML form
2. Matches them to the properties' names in the form bean
3. Automatically calls the set methods of these variables to put the values retrieved from the HTML form

In addition, if you implement a validate method and set the validate flag in the corresponding action mapping entry in the Struts configuration file, the action servlet invokes the validate method to validate that the data that the servlet receives is of the appropriate type.

Anonymous said...

How to avoid duplicate form submission in struts?

Anonymous said...

Quite good to revise the struts concepts…..would like to see another set for advanced level too...

Anonymous said...

what tag need to use for iterating the list in struts?

Unknown said...

What is the role of RequestProcessor in struts ? Most common Q?

Anonymous said...

suggest any books for struts f/w

Anonymous said...

good helpful

Post a Comment