Question
1: 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. 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 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.
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
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">
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.
Path: The page where the controls are to be followed is case exception occurred.
Question
4: 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>
<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.
Top 10 Interview Questions asked in Struts
Question
5: 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
|
Question
6: 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
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.
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;
}
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.
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 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">
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:
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).
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 may guys can contribute and I will
include it here. If you are looking to find answer of any question asked on Struts
interview then please put it here and I will try to find answer for those
questions.
Read more: http://javarevisited.blogspot.com/2011/11/struts-interview-questions-answer-j2ee.html#ixzz2zmsTvKFs
1.What is MVC?
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 application's 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.
More about Model-View-Controller Architecture >>
2.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.
3.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.
4.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.
5.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.
6.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.
7.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
8.What is the ActionForm?
ActionForm is javabean which represents the form inputs
containing the request parameters from the View referencing the Action bean.
9.What are the important methods of ActionForm?
The important methods of ActionForm are :
validate()
& reset().10.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() {}
11.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.
12.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>
13.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.
14.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
15.What design patterns are used in Struts?
People who read this, also read:- |
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
- What
is the difference between Struts 1 vs Struts 2 ?
http://struts.apache.org/2.1.6/docs/comparing-struts-1-and-2.html - Which
design pattern the Interceptors in Struts2 is based on ?
Interceptors in Struts2 are based on Intercepting Filters. - What
are Pull-MVC and push-MVC based architecture ? Whicharchitecture does
Struts2 follow ?
Pull-MVC and Push-MVC are better understood with how the view layer is getting data i.e. Model to render. In case of Push-MVC the data( Model) is constructed and given to the view layer by the Controllers by putting it in the scoped variables like request or session. Typical example is Spring MVC and Struts1. Pull-MVC on the other hand puts the model data typically constructed in Controllers are kept in a common place i.e. in actions, which then gets rendered by view layer. Struts2 is a Pull-MVC based architecture, in which all data is stored in Value Stack and retrieved by view layer for rendering. - Are
Interceptors in Struts2 thread safe ?
No,Unlike Struts2 action, Interceptors are shared between requests, so thread issues will come if not taken care of. - Are
Interceptors and Filters different ? , If yes then how ?
Apart from the fact that both Interceptors and filters are based on intercepting filter,there are few differences when it comes to Struts2.
Filters: (1)Based on Servlet Specification (2)Executes on the pattern matches on the request.(3) Not configurable method calls
Interceptors: (1)Based on Struts2. (2)Executes for all the request qualifies for a front controller( A Servlet filter ).And can be configured to execute additional interceptor for a particular action execution.(3)Methods in the Interceptors can be configured whether to execute or not by means of excludemethods or includeMethods. ( see tutorial on this Controlling Interceptor Behavior) - In
Struts1, the front-controller was a Servlet but in Struts2, it is a
filter. What is the possible reason to change it to a filter ?
There are two possibilities why filter is designated as front controller in Strtus2
(1)Servlet made as front controller needs developer to provide a right value in <load-on-startup> which lets the framework to initialize many important aspects( viz. struts configuration file)as the container starts.In absense of which the framework gets initialized only as the first request hits.Struts2 makes our life easy by providing front-controller as a filter,and by nature the filters in web.xml gets initialized automatically as the container starts.There is no need of such load-on-startup tag.
(2).The second but important one is , the introduction of Interceptors in Struts2 framework.It not just reduce our coding effort,but helps us write any code which we would have used filters for coding and necessary change in the web.xml as opposed to Struts1.So now any code that fits better in Filter can now moved to interceptors( which is more controllable than filters), all configuration can be controlled in struts.xml file, no need to touch the web.xml file.
(3).The front controller being a filter also helps towards the new feature of Struts ie UI Themes. All the static resources in the Themes now served through the filter - Which
class is the front-controller in Struts2 ?
The class "org.apache.struts2.dispatcher.FilterDispatcher " is the front controller in Struts2. In recent time Struts 2.1.3 this class is deprecated and new classes are introduced to do the job. Refer: http://struts.apache.org/2.1.8/struts2-core/apidocs/org/apache/struts2/dispatcher/FilterDispatcher.html - What
is the role of Action/ Model ?
Actions in Struts are POJO , is also considered as a Model. The role of Action are to execute business logic or delegate call to business logic by the means of action methods which is mapped to request and contains business data to be used by the view layer by means of setters and getters inside the Action class and finally helps the framework decide which result to render - How
does Interceptors help achieve Struts2 a better framework than Struts1
?
> Most of the trivial work are made easier to achieve for example automatic form population.
> Intelligent configuration and defaults for example you can have struts.xml or annotation based configuration and out of box interceptors can provide facilities that a common web application needs
>Now Struts2 can be used anywhere in desktop applications also, with minimal or no change of existing web application,since actions are now POJO.POJO actions are even easier to unit test.Thanks to interceptors
>Easier UI and validation in form of themes and well known DOJO framework.
>Highly plugable,Integrate other technologies like Spring,Hibernate etc at ease.
> Ready for next generation RESTFUL services - What
is the relation between ValueStack and OGNL ?
A ValueStack is a place where all the data related to action and the action itself is stored. OGNL is a mean through which the data in the ValueStack is manipulated.
1. What is MVC?
MVC means
Model, View and Controller. MVC pattern clearly separates the application into
these three layers.
The model
consists of application data, business rules, logic, and functions and it has
no idea of View or Controller. The View is presentation of the Model to the
client and it cannot change the Model and it has no idea of the Controller. The
Controller is responsible for the flow of control of the application and it
acts like an agent between the Model and View.
MVC makes
it possible to develop parallelly each of the layers. Thus it speeds up the
productivity and results in less complexity and easy maintainability.
2. What is the role of a handler in MVC based
applications?
Handlers
use mapping information from configuration files and transfers the requests to
appropriate models as they are part of the controller and a wrapper around the
Model.
3. What is a framework?
A
framework is a skeleton of an application which can be used to build an actual
application following some predefined steps or best practices. A framework
provides a default behavior with control management. Framework provides API to
use the framework and SPI to extend or override the default functionalities. A
framework discourages or does not allow altering some core components so that
the main features or benefits do not go away with that change.
4. What is Struts?
Struts is
an open source web application framework for developing Java based web
applications. It uses and extends the Java Servlet API to encourage developers
to adopt a Model–View–Controller (MVC) architecture.
5. What are advantages of Struts?
- Struts is an implementation MVC pattern which separates the Model, View and Controller layer and a parallel development of each layer is possible. Thus it speeds up the productivity and results in less complexity and easy maintainability.
- Struts implements Front Controller and Service Delegation pattern which gives a better flow management.
- Centralized file-based configuration using struts-config.xml
- Form beans are an encapsulation of the request object so that instead of directly accessing the request object methods it provides getter and setter methods of ActionForm and itsattributes are automatically populated
- Tag libraries enriches the view layer
- Form field validation
6. What are disadvantages of Struts?
- Poor documentation made it difficult to learn and hard to understand.
7. Difference between Struts and Spring MVC
framework?
- Struts framework was very popular and many applications have been already developed using it but Spring is being used in almost all projects in recent days because of some major advantages of it over Struts.
- The central theme of Struts is MVC and the central theme of Spring is IoC and AOP.
- Struts is a whitebox framework and Spring is a black box framework. Whitebox frameworks require deep knowledge of framework for application development and provide a tightly coupled system. On the other hand, black box framework requires less knowledge of framework for application development and they provide loosely coupled software systems. Hence Struts did not seriouslytry to avoid tight coupling but Spring is loosely coupled.
- Struts has a restriction that Action and ActionForm classes should be of certain type (Action and ActionForm) by single class inheritance. Hence Struts Action and ActionFormis tightly coupled with the controller. Spring MVC is entirely based on interfaces and things are configurable. Spring provides a very clean division between controllers, models and views. So Spring is loosely coupled.
- In struts we need to hard code to use backend technologies like hibernate, JDBC but in Spring hibernate and JDBC related features are in build. Spring has plugins to support other technologies.
- Spring has better documentation and community support than Struts.
- Since Spring has lots of features in comparison with struts so it is more complex than struts. So learning Spring needs more effort than Struts.
8. Why you use Struts framework if you have better
Spring MVC framework?
Spring
MVC should be used over Struts.
9. When should be opt for Struts Framework? Why you
have used Struts in your application or project?
Struts is
an implementation MVC pattern which separates the Model, View and Controller
layer and a parallel development of each layer is possible. Thus it speeds up
the productivity and results in less complexity and easy maintainability.
Struts implements Front Controller and Service Delegation pattern which gives a
better flow management.
10. What is a modular application? What does
module-relative mean?
A modular
application is an application that uses more than one module. Module-relative
means that the URI starts at the module levelrather than at the context levelor
the absoluteURL level.
- Absolute URL: http://localhost/myApplication/myModule/myAction.do
- Context-relative: /myModule/myAction.do
- Module-relative: /myAction.do
Struts
supports multiple application modules. All applications have at least one root
or default module. Like the root directory in a file system, the default
application has no name. You can add additional modules to your application
where each module can have their own configuration files, messages resources,
and so forth. Each module is developed in the same way as the default module.
11. Why are some of the class and element names
counter-intuitive?
Those
were not thought well and published immediately as part of nightly build and as
the framework evolved there were very little scope to change it.
12. What is the directory structure of Struts
application?

13. What is hierarchy of files in Struts?
Struts
does not use Chain of Responsibility pattern.There is no hierarchy of files in
Struts like some content management frameworks have. For example, in WordPressa
file hierarchy is maintained for view purpose where if one file is not there
then the view is rendered by the next higher level file; if category page is not
present then index page will be used. In Struts all files must be present and
the request is processed using a standard flow.
14. What are the components of Struts?
Struts
components can be categorized into three types: Model, View and Controller.
Model: Application data and business
logic are part of the Model component. Action classes act as a Wrapper around
the Model.
View: HTML, JSP etc. are the part of
the View component.
Controller:ActionServlet is the Front
Controller and RequestProcessor is the Application Controller. ActionServlet
delegates the task of processing the request to RequestProcessor.
15. Which model components are supported by Struts?
Struts
does not provide any built in support for any specific model and developers can
select any model component they want.
16. Explain the flow of Struts application.
- A request is submitted by the client browser.
- Container calls the ActionServlet.service() method as it is configured in the web.xml as the centralized entry point for handling requests from the View layer.
- ActionServlet then delegates the job of serving the request to the Application Controller named as RequestProcessor and calls its process() method.
- RequestProcessor wraps the request with MultipartRequestWrapper if it is a multipart request.
- The path info is read from the request which will later (in Step 11) be used to create the ActionMapping. If the path is null then the request is not processed further.
- Locale is set to the Session.
- Content type is set.
- No-cache header is set.
- RequestProcessor.processPreprocess() is called. This method returns true by default. The subclasses should override this method if some actions must be performed before each and every time a new request is processed.If the method returns false then the request is not processed further.
- Accessible ActionMessages are removed from the Session.
- An ActionMapping instance is created from path info (read on Step 5). If the ActionMapping instance is null then an Error Response with status code 404 (Not Found) is sent.
- The required authorization roles are checked for the Request. If it fails then an Error Response with status code 403 (Forbidden) is sent.
- Create or retrieve ActionForm instance from the ActionMapping instance.
- Populate ActionForm instance.
- Call the ActionForm.validate() method. If it generates ActionErrors then a Success Response is sent. These errors can be viewed using <html:errors /> tag.
- If the action is a Forward Action or an Include Action then it is processed and a Success Response is sent.
- Create or acquire the Action instance to process the Request from the ActionMapping. If the action is null then the request is not processed further.
- Call the Action.execute() method and send a Success Response back to client browser using Response.sendRedirect() method or RequestDispatcher.forward() method.
17. Which design patterns are used in Struts?
- Struts framework implements the Model 2 or MVC architecture.
- Struts controller or RequestProcessor uses the Command Pattern(GoF) and calls the execute() method on Action instances.
- The default Request Processor or ComposableRequestProcessor is composed using Commons Chain which is an implementation of the Chain of Responsibility Pattern (GoF).
- The Action classes use the Adapter Pattern (GoF) and acts as a wrapper around the application data and business logic.
- Struts framework implements Front Controller Pattern(J2EE) where ActionServlet is the Front Controller.
- Struts framework implements Service to Worker Pattern(J2EE) where the Front Controller ActionServlet delegates the task of processing the request to the Application Controller or the RequestProcessor.
- Struts framework implements View Helper Pattern(J2EE) using the tag libraries.
- Struts framework implements Composite View Pattern(J2EE) using Tiles framework.
- The <html:form> tag implements Synchronizer Token Pattern(J2EE) to prevent duplicate form submission. It also uses TokenProcessor for the same.
- Struts framework implements Form-Centric Validation Pattern(J2EE) on client and server side using commons validator framework.
- Struts framework implements Resource Guards Pattern(J2EE) assigning Security Roles to an action for authorization.
18. What are the core classes and interfaces of
Struts Framework?
- ActionServlet
- RequestProcessor
- ActionMapping
- ActionForm
- ActionMessages
- Action
- ActionForward
19. What are the different kinds of actions in
Struts?
- org.apache.struts.action.Action
- org.apache.struts.actions.ForwardAction
- org.apache.struts.actions.IncludeAction
- org.apache.struts.actions.DispatchAction
- org.apache.struts.actions.LookupDispatchAction
- org.apache.struts.actions.EventDispatchAction
- org.apache.struts.actions.MappingDispatchAction
- org.apache.struts.actions.DownloadAction
- org.apache.struts.actions.SwitchAction
- org.apache.struts.actions.LocaleAction
20. What is ActionServlet?
ActionServlet
is the Front Controller in Struts Framework. It provides a centralized entry
point for handling requests from the View layer. ActionServlet then delegates
the job of serving the request to the Application Controller named as
RequestProcessor.
21. Can I have more than one ActionServlet class
file in my application? Why ActionServlet is singleton in Struts?
Theoretically
yes but it gives away all the advantages the Front Controller Pattern
provides.Front Controller Pattern provides a centralized entry point for all
the incoming requests otherwise the request processing logics might get
duplicated. Having more than one ActionServlet configured in web.xml and
identified by the <url-pattern> is likely to duplicate some codes in
those servlets, whereas capturing the request in a single ActionServlet and
then delegate the request processing to multiple workers based on the request
is more handy and known as Service to Worker pattern. Struts uses both these pattern
but with only one worker or RequestProcessor.
ActionServlet
does not implement Singleton Pattern and making more than one
ActionServletgives away all the advantages the Front Controller Pattern
provides. So it is a best practice that developers will not make multiple
ActionServlets.
22. What is RequestProcessor?
ActionServletis
Front Controller and RequestProcessoris the Application Controller.
ActionServletdelegates the task of processing the request to RequestProcessor.
RequestProcessor processes the request and sends response back to the client.
23. What is Action class?
An Action
is an adapter between the contents of an incoming HTTP request and the
corresponding business logic that should be executed to process this request.
The controller (RequestProcessor) will select an appropriate Action for each
request, create an instance (if necessary), and call the execute method.
24. Write code of any Action Class?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
|
package com.roy4j.struts1;
importjava.io.IOException;
importjavax.servlet.ServletException;
importjavax.servlet.http.HttpServletRequest;
importjavax.servlet.http.HttpServletResponse;
importorg.apache.struts.action.Action;
importorg.apache.struts.action.ActionErrors;
importorg.apache.struts.action.ActionForm;
importorg.apache.struts.action.ActionForward;
importorg.apache.struts.action.ActionMapping;
importorg.apache.struts.action.ActionMessage;
public class MyAction extends Action {
publicActionForward execute(ActionMapping mapping,
ActionForm
form, HttpServletRequest request,
HttpServletResponse
response)
throwsIOException,
ServletException {
return (mapping.findForward("success"));
}
}
|
25. In which method of Action class the business
logic is executed?
The
business logic is executed in Action.execute() method.
Post navigation
Leave a Reply
Your
email address will not be published. Required fields are marked *
Name *
Email *
Website
Comment
You may
use these HTML tags and attributes: <a href=""
title=""> <abbr title=""> <acronym
title=""> <b> <blockquote cite="">
<cite> <code> <del datetime=""> <em>
<i> <q cite=""> <strike> <strong>

Search
for:
Categories
- Ant
- Core Java
- CSS
- Database
- GoF Design Patterns
- Hibernate
- HTML
- Interview Questions
- JavaScript
- JDBC
- JSP
- Log4j
- Miscellaneous
- SEO
- Spring
- Struts 1
- Web Services
- WordPress
- XML
Archives
- July 2013
- June 2013
- May 2013
- April 2013
- March 2013
- February 2013
- January 2013
- December 2012
- November 2012
- October 2012
- September 2012
- August 2012
- July 2012
- June 2012
- May 2012
- April 2012
- March 2012
- February 2012
- January 2012
- December 2011
- November 2011
- October 2011
- September 2011
- August 2011
- July 2011
- June 2011
- May 2011
- April 2011
April 2014
|
||||||
M
|
T
|
W
|
T
|
F
|
S
|
S
|
|
|
|||||
|
1
|
2
|
3
|
4
|
5
|
6
|
7
|
8
|
9
|
10
|
11
|
12
|
13
|
14
|
15
|
16
|
17
|
18
|
19
|
20
|
21
|
22
|
23
|
24
|
25
|
26
|
27
|
28
|
29
|
30
|
|
Questions 1 What're the types of controllers?
Answer There are two types of Controllers in Strus.
1.Main Controller/FrontController
Ex: ActionServlet
2.Application Controller
Ex:Action Class
Questions 2 What is the Struts 2.0 flow?
Answer Struts and webwork has joined together to develop the Struts 2 Framework. Struts 2 Framework is very extensible and elegant for the development of enterprise web application of any size. In this section we are going to explain you the architecture of Struts 2 Framework.
Request Lifecycle in Struts 2 applications
User Sends request: User sends a request to the server for some resource.
FilterDispatcher determines the appropriate action: The FilterDispatcher looks at the request and then determines the appropriate Action.
Interceptors are applied: Interceptors configured for applying the common functionalities such as workflow, validation, file upload etc. are automatically applied to the request.
Execution of Action: Then the action method is executed to perform the database related operations like storing or retrieving data from the database.
Output rendering: Then the Result renders the output.
Return of Request: Then the request returns through the interceptors in the reverse order. The returning request allows us to perform the clean-up or additional processing.
Display the result to user: Finally the control is returned to the servlet container, which sends the output to the user browser.
The Flow of a Struts 2.0 Application
The following are the sequence of steps that will happen when a Html Client makes a request to a Web Application built on top of Struts 2.0
The Client (which is usually a Html Browser) makes a Request to the Web Application.
The Web Server will search for the Configuration Information that is very specific to the Web Application (taken from the web.xml file), and will identity which Boot-strap Component has to be loaded to serve the Client's Request.
In Struts 2.0, this Component is going to be a Servlet Filter (whereas in Struts 1.0, the component is an Action Servlet).
The Filter Servlet then finds out the Action Class for this Request that is mapped in the Configuration File. File.
Before passing the Request to the Action class, the Controller passes the Request to a series of Interceptor Stack (explained later).
Then the Request Object is passed on to the corresponding Action Class.
The Action Class then executes the Appropriate Business Logic based on the Request and the Request Parameters.
After the execution of the Business Logic, a Result ("success" or "error") is returned either in the form of String or in the form of Result Object back to the Controller.
The Controller uses the Return Result to choose which View to be rendered back to the Client Application.
Questions 3 How do we config struts config file in spring configuration file?
Answer To use the Struts Spring plugin, add the ContextLoaderPlugIn to your Struts config file (usually struts-config.xml):
<plug-in className="org.springframework.web.struts.ContextLoaderPlugIn">
<set-property property="contextConfigLocation"
value="/WEB-INF/applicationContext.xml"/>
</plug-in>
The "contextConfigLocation" property is the location of the Spring beans configuration file.
For each action that uses Spring, you need to define the action mapping to use org.springframework.web.struts.DelegatingActionProxy and declare a matching (action "path" == bean "name") Spring bean for the actual Struts action. This is an example of an action that requires an instance of UserDatabase:
<action path="/logon"
type="org.springframework.web.struts.DelegatingActionProxy">
<forward name="success" path="/logon.jsp"/>
</action>
The corresponding Spring bean configuration:
<bean id="userDatabase" class="org.apache.struts.webapp.example.memory.MemoryUserDatabase" destroy-method="close" />
<bean name="/logon" class="org.apache.struts.webapp.example.LogonAction">
<property name="userDatabase"><ref bean="userDatabase" /></property>
</bean>
For more information on the Spring configuration file format, see the Spring beans DTD.
The Struts action org.apache.struts.webapp.example.LogonAction will automatically receive a reference to UserDatabase without any work on its part or references to Spring by adding a standard JavaBean setter:
private UserDatabase database = null;
public void setUserDatabase(UserDatabase database) {
this.database = database;
}
Questions 4 Is actionform belongs to the model or view or controller in struts?
Answer ActionForm class is used to capture user-input data from an HTML form and transfer it to the Action Class. ActionForm plays the role of Transport Vehicle between the presentation Tire & Business Tier.
Life Cycle :
1. Request received by Controller
2. Create or recycle ActionForm
3. Call reset()
4. store ActionForm in proper scope
5. populate ActionForm from Request
6. Validate the ActionForm
7. If errors found then forward back to input attribute page(configured in Action mapping in struts-config.xml) with ActionForm in scope. If no errors found then call execute() with the ActionForm.
The steps would be like this (in terms of the diagram)
A. Client will point to the controller
B. Controller would point to action form
C. Actionform would point to action class
D. Action class would point to JSP?
E. JSP would point to client
Answer Yes, actionform belongs to controller. But not sure about whether it belongs to model or view.
Questions 5 what are responsibilities of a struts action class?which responsibility is view related aspect of boundary component?Does it provide any facilities for separating these view related aspects for the controller related action classes?
Answer An Action class in the struts application extends Struts 'org.apache.struts.action.Action" Class. Action class acts as wrapper around the business logic and provides an inteface to the application's Model layer. It acts as glue between the View and Model layer. It also transfers the data from the view layer to the specific business process layer and finally returns the procssed data from business layer to the view layer.
An Action works as an adapter between the contents of an incoming HTTP request and the business logic that corresponds to it. Then the struts controller (ActionServlet) slects an appropriate Action and creates an instance if necessary, and finally calls execute method.
To use the Action, we need to Subclass and overwrite the execute() method. In the Action Class don't add the business process logic, instead move the database and business process logic to the process or dao layer.
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.
Core Java questions:
1. What is the difference between abstract class and interface?
2. Explain about OOPs?
3. Differnce between Hashtable VS HashMap?
4. How will you provide thread safety in ArrayList?
5. Explain about Object class? what are the methods it can have? tell me about tostring()?
6. what are the types of the exceptions?
7. what is immediate super class of RuntimException?
8. can you write one predefined exception code in real time manner?
9. put vs get?
10. Vector vs Array list?
11. what are concepts in 1.5 java?
12. can you write one multi threading programme?
JDBC questions:
1. write DataSource code?
2. what are drivers available? which driver you use in your project?
Servlets question
1. Explain about servlet life cycle?
2. Explain about init() method?
3. if we call destroy() from service() what will happen?
4. Differentiate include file Vs include page?
5. Session management techniques?
Spring questions:
1)What is IOC?
2)What is Method injection?
3)What are interfaces available in spring?
4)What is meant by spring?
EJB questions:
1)what are ejb sessions in ejb?
2)who do you know your ejb application can have stateful or stateless?
3)what is jndi?
4)what is ejb?
Hibernate questions:
1)Hibernate Assction mappings tell me ? can you give real time examples?
2)what is meant by component mapping?2)what is meant by component mapping?
3)what is meant by inheritance mapping in hibernate?
4)what are the problems you get doing hibernate projects?
Struts questions:
1)what are actions in struts?
2)what is include action?
3)how to declare exceptions in struts?
Project Manager questions:
1)Can you draw your project architecture?
2)What are issues you got in your projects?
1. What is the difference between abstract class and interface?
2. Explain about OOPs?
3. Differnce between Hashtable VS HashMap?
4. How will you provide thread safety in ArrayList?
5. Explain about Object class? what are the methods it can have? tell me about tostring()?
6. what are the types of the exceptions?
7. what is immediate super class of RuntimException?
8. can you write one predefined exception code in real time manner?
9. put vs get?
10. Vector vs Array list?
11. what are concepts in 1.5 java?
12. can you write one multi threading programme?
JDBC questions:
1. write DataSource code?
2. what are drivers available? which driver you use in your project?
Servlets question
1. Explain about servlet life cycle?
2. Explain about init() method?
3. if we call destroy() from service() what will happen?
4. Differentiate include file Vs include page?
5. Session management techniques?
Spring questions:
1)What is IOC?
2)What is Method injection?
3)What are interfaces available in spring?
4)What is meant by spring?
EJB questions:
1)what are ejb sessions in ejb?
2)who do you know your ejb application can have stateful or stateless?
3)what is jndi?
4)what is ejb?
Hibernate questions:
1)Hibernate Assction mappings tell me ? can you give real time examples?
2)what is meant by component mapping?2)what is meant by component mapping?
3)what is meant by inheritance mapping in hibernate?
4)what are the problems you get doing hibernate projects?
Struts questions:
1)what are actions in struts?
2)what is include action?
3)how to declare exceptions in struts?
Project Manager questions:
1)Can you draw your project architecture?
2)What are issues you got in your projects?
Question
1) What is difference between Vector and ArrayList in Java?
Answer : One of the most popular Java question at 2
years experience level which aims to check your knowledge on Java collection
API. key point to mention is synchronization and speed, since ArrayList is not synchronized its fast compare to
Vector. See Vector vs ArrayList in Java for
more difference between both of them.
Question
2) What is difference in LinkedList and ArrayList in Java?
Answer : If you don't get previous Java question
then you are likely to get this question at 2 to 3 years experience level Java
interview. Unlike synchronization, key point to mention here is underlying data
structure. See LinkedList vs ArrayList in Java for
detail answer of this java question.
3) What is
difference between fail-fast and fail-safe Iterator in Java?
This is relatively new Java question compare to
previous ones but increasingly getting popular into 2 to 3 years level Java
interviews. key difference here is that fail-fast Iterator throw ConcurrentModificationException while
fail-safe doesn't. See fail-safe vs fail-fast Iterator in Java for
more differences between two.
4)
Difference between throw and throws in Java?
This Java question belongs to Exception handling
category which is another popular category for 2 to 4 years experienced Java
programmer. Main difference between these two is that one declares exception
thrown by a Java method while other is actually used to throw Exception. See Difference between throw and throws in Java for
full answer of this Java exception handling question.
5) What
is difference between checked and unchecked Exception in Java.
Another java interview question for 2 to 4 years
experienced Java programmer from Exception handling. key point to mention here
is that checked Exception requires mandatory exception handling code while
unchecked doesn't. See checked vs unchecked Exception in Java for
more differences.
6) Write
code to print Fibonacci series in Java?
You are bound to expect some coding interview question in
Java interview for 2 to 4 years experience. Though Fibonacci series is one of
the most classical and popular question not every Java programmer is able to do
it correctly in interview, things get more complicated if interviewer ask to do
this by using recursion. So better to prepare for approach, See how to write Java program for Fibonacci series using
recursion for details and code example.
7) Write
Java program to reverse String in Java without using StringBuffer?
Another Java coding interview question asked on 2 ot
4 years experienced Java developer. Many times interviewer specifically
mentioned that you can not use StringBuffer because it has reverse() method
which makes this taks trivial. So you must know how to do this by using
iteration as well as recursion to perform well. Look at Java program to reverse String in Java for
full code sample and explanation.
8) What
is difference between Runnable and Thread in Java ?
Frequently asked Java interview question on 2 to 4
years experienced level from Threading fundamentals. there are two ways to implement Thread in Java, in
fact three e..g extending java.lang.Thread class or implementing java.lang.Runnable or
Callable interface. See Thread vs Runnable in Java for exact
differences on following each approach.
9) What
happens if you don't call wait and notify from synchronized block?
Another common Java interview question from
multi-threding and inter thread communication. As I said earlier you must know
concept of wait and notify in Java if you have worked for 2 to 3 years in Java.
Check why wait and notify needs to call from synchronized
block for exact reason to answer this Java question.
10) Write
code to solve producer consumer problem in Java.
A good java question in my opinion which is mix of
threading, synchronization, inter-thread
communication and coding abilities. This particular java question can make any
body's list at any day, not just 2 to 4 years experienced programmer. despite
being so common it has something on it which confuse average programmer and
allow you to differentiate between good and average programmer. See Producer consumer problem solving using
BlockingQueue in Java for full code example.
These were 10
frequently asked Core Java interview question for 2 to 3 years experienced Java
programmers. If you want to increase
numbers there are lot many questions floating around web for 2 to 3 or 2 to 4
years experienced Java developers but key things it to remember topics e.g.
Collection, Exception handling, Coding, Threading and OOPS principles are the main areas from
which most of 2 to 3 years experienced Java programmer interview question
appear. Just get them right and you can crack any Java interview upto 2 to 4
years experienced Java programmer.
No comments:
Post a Comment