Explain Struts navigation flow?
Struts Navigation flow.
1) A request is made from previously displayed view.
2) The request reaches the ActionServlet which acts as the controller .The ActionServlet
Looksup the requested URI in an XML file ([Link]) and determines the name
of the Action class that has to perform the requested business logic.
3) The Action Class performs its logic on the Model Components associated with the
Application.
4) Once Action has been completed its processing it returns the control to the Action
[Link] part of its return the Action Class provides a key to determine where the
results should be forwarded for presentation.
5)The request is complete when the Action Servlet responds by forwarding the request to
the view, and this view represents the result of the action.
There are two versions of Struts : Struts 1 and Struts 2.
**These two are different frameworks.
Struts 1 is based on Servlets. It has one ActionServlet that acts as its controller.
Whereas in Struts 2 we have Filters. In this we can have Filter like FilterDispatcher or
StrutsPrepareAndExecuteFilter that acts as our Controller.
What is difference between LookupDispatchAction and DispatchAction?
The difference between LookupDispatchAction and DispatchAction is that the actual method that
gets called in LookupDispatchAction is based on a lookup of a key value instead of specifying the
method name directly.
Details :
LookupDispatchAction is subclass of DispatchAction.
In case of DispatchAction, you have to declare the method name in the JSP page.
For Example :
[Link] // IN CASE OF DispatchAction
here step=add , we are delaring method name in JSP.
or
<html:submit property="step">Add</html:submit> //IN CASE OF DispatchAction
so we can't use localization for button.
To over come both the issues below
a)method name declaration in JSP
b)can't use localization for button
We will go for LookupDispatchAction.
In the LookupDispatchAction :
For example :
If there are three operation like add, delete, update employee.
You can create three different Actions ?
AddEmpAction, DeleteEmpAction and UpdateEmpAction.
This is a valid approach, although not elegant since there might be duplication of code across
the Actions since they are related. LookupDispatchAction is the answer to this
problem. With LookupDispatchAction, you can combine all three Actions into one.
Example :
Step 1.
three buttons might be
<html:submit property="step">
<bean:message key="[Link]"/>
</html:submit>
<html:submit property="step">
<bean:message key="[Link]"/>
</html:submit>
<html:submit property="step">
<bean:message key="[Link]"/>
</html:submit>
//No need method name declaration in JSP . Button name from resource bundle.
Step 2.
In the the Resource Bundle. //Here you can add localization.
[Link]=Add
[Link]=Delete
[Link]=Update
Step 3.
Implement a method named getKeyMethodMap() in the subclass of the
LookupDispatchAction. The method returns a [Link]. The
keys used in the Map should be also used as keys in Message Resource
Bundle.
public class EmpAction extends LookupDispatchAction {
public Map getKeyMethodMap()
{
Map map = new HashMap();
[Link]("[Link]", "add");
[Link]("[Link]", "delete");
[Link]("[Link]", "update");
}
public ActionForward add(ActionMapping mapping,
ActionForm form, HttpServletRequest request,
HttpServletResponse response) throws Exception
{
//your logic
[Link]("add-success");
}
public ActionForward delete(ActionMapping mapping,
ActionForm form, HttpServletRequest request,
HttpServletResponse response) throws Exception
{
//your logic
[Link]("delete-success");
}
public ActionForward update(ActionMapping mapping,
ActionForm form, HttpServletRequest request,
HttpServletResponse response) throws Exception
{
//your logic
[Link]("update-success");
}
In [Link]
<action path="/empaction"
input="/[Link]"
type="[Link]"
parameter="step"
scope="request"
validate="false">
<forward name="add-success"
path="[Link]"
redirect="true"/>
<forward name="delete-success"
path="[Link]"
redirect="true"/>
<forward name="update-success"
path="[Link]"
redirect="true"/>
</action>
for every form submission, LookupDispatchAction does the
reverse lookup on the resource bundle to get the key and then gets the method
whose name is associated with the key from
getKeyMethodmap().
Flow of LookupDispatchAction:
a) Form the button name "Add" get the key "[Link]" fro resource bundle.
b) then in the Map getKeyMethodMap() find the value associated with the key "[Link]".
c) value from the Map is "add" . then call add() method of the same action class.
.
Actions in struts2 are simple POJOs and are framework independent
In Struts1, Action resources must be thread-safe or synchronized. So Actions are
singletons and thread-safe, there should only be one instance of a class to handle all
requests for that Action
Programming the abstract classes instead of interfaces is one of design issues of struts1
framework that has been resolved in the struts 2 framework.
Struts1 Action classes needs to extend framework dependent abstract base class. But in
case of Struts 2 Action class may or may not implement interfaces to enable optional and
custom services. In case of Struts 2 , Actions are not container dependent because they
are made simple POJOs. Struts 2 provides a base ActionSupport class to implement
commonly used interfaces. Albeit, the Action interface is not required. Any POJO object
with an execute signature can be used as an Struts 2 Action object.
What is the difference between a normal servlet and action servlet?
Normal Servlet and Action servlet are same but Action servlet consists of logic for
forwarding the request to corresponding action class
the ActionServlet instance also is responsible for initialization and clean-up of resources.
When the controller initializes, it first loads the application config
Struts 1 Actions are singletons and must be thread-safe since there will only be one
instance of a class to handle all requests for that Action. The singleton strategy places
restrictions on what can be done with Struts 1 Actions and requires extra care to develop.
Action resources must be thread-safe or synchronized.
Struts 2 Action objects are instantiated for each request, so there are no thread-safety
issues.(In practice, servlet containers generate many throw-away objects per request, and
one more object does not impose a performance penalty or impact
garbage collection.)
What is the difference between bean:write and bean:message
<bean:message> : this tag is used to output local-specific text from
[Link] file
<bean:message key=""[Link]>
<bean:write> : this tag is used to output bean property value from bean property
<jsp:useBean id="beanName" class="className">
<bean:write name="beanName" property="propertyName">
MappingDispatchAction class is much like the DispatchAction class except that it uses a
unique action corresponding to a new request , to dispatch the methods .
At run time, this class manages to delegate the request to one of the methods of the
derived Action class. Selection of a method depends on the value of the parameter
passed from the incoming request. MappingDispatchAction uses this request parameter
value and selects a corresponding action from the different action-mappings defined.
This eliminates the need of creating an instance of ActionForm class.
What design pattern are used in struts?
Struts uses model MVC architecture,
Struts controller uses Command design pattern,
Action classes uses Adapter design pattern,
Process method of the underlying RequestProcessor class uses template design pattern.
Can I have an Action without a form?
[Link] your action does not need any data and it does not need to make any data available
to the view or controller component
that it forwards to, it doesn't need a form.
E.g LogOff action.
Q: What is Struts?
A: The core of the Struts framework is a flexible control layer based on standard
technologies like Java Servlets, JavaBeans, ResourceBundles, and XML, as well as
various Jakarta Commons packages. Struts encourages application architectures
based on the Model 2 approach, a variation of the classic Model-View-Controller
(MVC) design paradigm.
Struts provides its own Controller component and integrates with other
technologies to provide the Model and the View. For the Model, Struts can interact
with standard data access technologies, like JDBC and EJB, as well as most any
third-party packages, like Hibernate, iBATIS, or Object Relational Bridge. For the
View, Struts works well with JavaServer Pages, including JSTL and JSF, as well as
Velocity Templates, XSLT, and other presentation systems.
The Struts framework provides the invisible underpinnings every professional web
application needs to survive. Struts helps you create an extensible development
environment for your application, based on published standards and proven
design patterns.
[ Received from Ramakrishna Potluri ] TOP
Q:What is Jakarta Struts Framework?
A: Jakarta Struts is open source implementation of MVC (Model-View-Controller)
pattern for the development of web based applications. Jakarta Struts is robust
architecture and can be used for the development of application of any size. Struts
framework makes it much easier to design scalable, reliable Web applications with
Java.
[ Received from Dhiraj Sharma] TOP
Q:What is ActionServlet?
A: The class [Link] is the called the ActionServlet. In
the the Jakarta Struts Framework this class plays the role of controller. All the
requests to the server goes through the controller. Controller is responsible for
handling all the requests.
[ Received from Dhiraj Sharma] TOP
Q:How you will make available any Message Resources Definitions file to
the Struts Framework Environment?
A: The 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 [Link] file through
<message-resources /> tag.
Example:
<message-resources parameter=\"MessageResources\" />.
[ Received from Dhiraj Sharma] TOP
Q:What is Action Class?
A: The Action Class is part of the Model and is a wrapper around the business logic.
The purpose of Action Class is to translate the HttpServletRequest to the business
logic. To use the Action, we need to Subclass and overwrite the execute() method.
In the Action Class all the database/business processing are done. It is advisable to
perform all the database related stuffs in the Action Class. The ActionServlet
(commad) passes the parameterized class to Action Form using the execute()
method. The return type of the execute method is ActionForward which is used by
the Struts Framework to forward the request to the file as per the value of the
returned ActionForward object.
[ Received from Dhiraj Sharma] TOP
Q:What is ActionForm?
A: An ActionForm is a JavaBean that extends [Link].
ActionForm maintains the session state for web application and the ActionForm
object is automatically populated on the server side with data entered from a form
on the client side.
[ Received from Dhiraj Sharma] TOP
Q:What is Struts Validator Framework?
A: Struts Framework provides the functionality to validate the form data. It can be
use to validate the data on the users browser as well as on the server side. Struts
Framework emits the java scripts and it can be used validate the form data on the
client browser. Server side validation of form can be accomplished by sub classing
your From Bean with DynaValidatorForm class.
The Validator framework was developed by David Winterfeldt as third-party add-on
to Struts. Now the Validator framework is a part of Jakarta Commons project and it
can be used with or without Struts. The Validator framework comes integrated with
the Struts Framework and can be used without doing any extra settings.
[ Received from Dhiraj Sharma] TOP
Q:Give the Details of XML files used in Validator Framework?
A: The Validator Framework uses two XML configuration files [Link] and
[Link]. The [Link] defines the standard validation routines,
these are reusable and used in [Link]. to define the form specific
validations. The [Link] defines the validations applied to a form bean.
[ Received from Dhiraj Sharma] TOP
Q:How you will display validation fail errors on jsp page?
A: Following tag displays all the errors:
<html:errors/>
[ Received from Dhiraj Sharma] TOP
Q:How you will enable front-end validation based on the xml in
[Link]?
A: The <html:javascript> tag to allow front-end validation based on the xml in
[Link]. For example the code: <html:javascript formName=\"logonForm\"
dynamicJavascript=\"true\" staticJavascript=\"true\" /> generates the client side
java script for the form \"logonForm\" as defined in the [Link] file. The
<html:javascript> when added in the jsp file generates the client site validation
script.
[ Received from Dhiraj Sharma] TOP
Q:How to get data from the velocity page in a action class?
A: We can get the values in the action classes by using [Link](\"variable
name defined in the velocity page\");
What are the design pattern used in Struts?
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
What is the difference between bean:write and bean:message?
In Jakarta Struts - you may be knowing that - both are custom tags defined in HTML Tag
library.
Both are used for accessing Java beans.
Bean:Message - is to access a java bean that will display a message such as “ For more
details on the product displayed in this web site please contact a phone number 12345..”
Bean: write - is to display a data from the model; example “Number of People visited this
site is: 1234”
Bean does not directly write. the Tag is used to take help of these Beans for the above
mentioned purposes
<bean: message> : this tag is used to output local-specific text from
[Link] file
<bean: message key=””[Link]>
<bean: write> : this tag is used to output bean property value fron bean property
<jsp:useBean id=”beanName” class=”className”>
<bean: write name=”beanName” property=”propertyName”>
What is the difference between Struts 1.0 and Struts 1.1?
The new features added to Struts 1.1 are
1. RequestProcessor class
2. Method perform() replaced by execute() in Struts base Action Class
3. Changes to [Link] and [Link]
[Link] exception handling
[Link] ActionForms
[Link]-ins
[Link] Application Modules
[Link] Tags
[Link] Struts Validator
[Link] to the ORO package
[Link] to Commons logging
[Link] of Admin actions
13. Deprecation of the GenericDataSource.
What is the difference between ActionForm and DynaActionForm
# 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 b cleanly organized in packages as against the flat organization in
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
[Link]( .. ).
# DynaActionForm construction at runtime requires a lot of Java Reflection
(Introspection) machinery that can be avoided.
# Time savings from DynaActionForm is insignificant. It doesn t take long for today s
IDEs to generate getters and setters for the ActionForm attributes. (Let us say that you
made a silly typo in accessing the DynaActionForm properties in the Action instance. It
takes less time to generate the getters and setters in the IDE than fixing your Action code
and redeploying your web application)
Explain about token feature in Struts?
Use the Action Token methods to prevent duplicate submits:
There are methods built into the Struts action to generate one-use tokens. A token is
placed in the session when a form is populated and also into the HTML form as a hidden
property. When the form is returned, the token is validated. If validation fails, then the
form has already been submitted, and the user can be apprised.
saveToken(request)
on the return trip,
isTokenValid(request)
resetToken(request)
What is Action Class. What are the methods in 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.
Actions must be programmed in a thread-safe manner, because the controller will share
the same instance for multiple simultaneous requests. This means you should design with
the following items in mind:
Instance and static variables MUST NOT be used to store information related to the state
of a particular request. They MAY be used to share global resources across requests for
the same action.
Access to other resources (JavaBeans, session variables, etc.) MUST be synchronized if
those resources require protection. (Generally, however, resource classes should be
designed to provide their own protection where necessary.
When an Action instance is first created, the controller will call setServlet with a non-null
argument to identify the servlet instance to which this Action is attached. When the
servlet is to be shut down (or restarted), the setServlet method will be called with a null
argument, which can be used to clean up any allocated resources in use by this Action.
action class implemented by [Link]
public ActionForwad execute(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse)
{
return [Link](“”);
}
In struts how can i validate the values filled into the text boxes or
else using DynaValidatorForm,without using javascript. Actually
with javascript it is working perfect but not without javascript, and
i want without javascript?
Using the validate() method of the ActionForm class, the values filled in the form will be
validated in the case there is no JavaScript for validating the form.
In struts why we use jsp as presentation layer? can we use servlet
as presentation layer?
1. We can seperate the business logic from presentation logic
[Link] facilitates to write the java code inside a html environment
if we use servlets then we need to write the html tags inside [Link]() number of
times. it is not possible in all cases and it combines the businesslogic and
presentation logic which reduces security
What is the difference between ActionErrors and ActionMessages?
There is no differnece between these two [Link] the behavior of ActionErrors was
copied into ActionMessages and vice versa. This was done in the attempt to clearly signal
that these classes can be used to pass any kind of messages from the controller to the
view—where as errors being only one kind of message.
The difference between saveErrors(...) and saveMessages(...) is simply the attribute name
under which the ActionMessages object is stored, providing two convenient default
locations for storing controller messages for use by the view. If you look more closely at
the html:errors and html:messages tags, you can actually use them to get an
ActionMessages object from any arbitrary attribute name in any scope.
Who will run the execute method in struts?
RequestProcessor class run the execute method inside this class.
What are the drawbacks of Struts
In struts, their is no facility of backward flow.
Suppose we are in page 1 and when we submit it calls action mapping [Link] may
be lot of variable stored in session , which is available to [Link] we wish to go page1
from page 2, for this we have to call the action mapping of page1. But struts flow is
always in forward direction. So when we call page 1, values stored in session never get
[Link] it reduces the performance.
To resolve this problem of struts, Their is a framework called Web Flow Nevigation
Manager(WFNM) of [Link] framework can be integrated with struts.
What are the core classes of Struts?
Action,
ActionForm,
ActionServlet,
ActionMapping,
ActionForward
How you will save the data across different pages for a particular
client request using Struts
Several ways. The similar to the ways session tracking is enabled. Using cookies, URL-
rewriting, SSLSession, and possibilty threw in the database.
What part of MVC does Struts represent ?
Struts is mainly famous for its Action Controller - which is nothing but the
CONTROLLER part of MVC Pattern.
To add up, Struts is the framework which started mainly using the MVC-2 Pattern where
in the Business logic is STRICTLY SEPARATED from the Presentation logic (mainly in
JSPs).
Does Struts provide support for Validator & Tiles by default ?
NO.
Struts does not provide default support for Validator and Tiles.
Additional plugins are required for the purpose.
In struts what happens if made any changes in ActionServlet?
The ActionServlet plays the role of controller which is responsible for handling the
request and selecting the correct Application Module and storing ApplicationConfig and
MessageResource bundle in the request object.
If we modify the ActionServlet the Controller may or may not work what happens that
depends on your modification, You have not specify whether you want to create your
own custom ActionServlet by extending ActionServlet and overriding the methods in it
or what exactly you want to modify.
Is struts threadsafe?Give an example?
Struts is not only thread-safe but thread-dependant. The response to a request is
handled by a light-weight Action object, rather than an individual servlet. Struts
instantiates each Action class once, and allows other requests to be threaded through the
original object. This core strategy conserves resources and provides the best possible
throughput. A properly-designed application will exploit this further by routing related
operations through a single Action.
Can I setup Apache Struts to use multiple configuration files?
Yes Struts can use multiple configuration files. Here is the configuration example:
<servlet>
<servlet-name>banking</servlet-name>
<servlet-class>[Link]
</servlet-class>
<init-param>
<param-name>config</param-name>
<param-value>/WEB-INF/[Link],
/WEB-INF/[Link],
/WEB-INF/[Link]
</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
What are the components of Struts?
Struts is based on the MVC design pattern. Struts components can be categories into
Model, View and Controller.
Model: Components like business logic / business processes and data are the part of
Model.
View: JSP, HTML etc. are part of View
Controller: Action Servlet of Struts is part of Controller components which works as
front controller to handle all the requests.