Sie sind auf Seite 1von 49

Structs Interview Questions and Answers

What is Struts?
Struts is a web page development framework and an open source software that helps
developers build web applications quickly and easily. Struts combines Java Servlets, Java
Server Pages, custom tags, and message resources into a unified framework. It is a
cooperative, synergistic platform, suitable for development teams, independent
developers, and everyone between.

How is the MVC design pattern used in Struts framework?


In the MVC design pattern, application flow is mediated by a central Controller. The
Controller delegates requests to an appropriate handler. The handlers are tied to a Model,
and each handler acts as an adapter between the request and the Model. The Model
represents, or encapsulates, an application's business logic or state. Control is usually
then forwarded back through the Controller to the appropriate View. The forwarding can
be determined by consulting a set of mappings, usually loaded from a database or
configuration file. This provides a loose coupling between the View and Model, which
can make an application significantly easier to create and maintain.
Controller--Servlet controller which supplied by Struts itself; View --- what you can see
on the screen, a JSP page and presentation components; Model --- System state and a
business logic JavaBeans.

Who makes the Struts?


Struts is hosted by the Apache Software Foundation(ASF) as part of its Jakarta project,
like Tomcat, Ant and Velocity.

Why it called Struts?


Because the designers want to remind us of the invisible underpinnings that hold up our
houses, buildings, bridges, and ourselves when we are on stilts. This excellent description
of Struts reflect the role the Struts plays in developing web applications.

Do we need to pay the Struts if being used in commercial purpose?


No. Struts is available for commercial use at no charge under the Apache Software
License. You can also integrate the Struts components into your own framework just as if
they were written in house without any red tape, fees, or other hassles.

What are the core classes of Struts?


Action, ActionForm, ActionServlet, ActionMapping, ActionForward are basic classes of
Structs.

What is the design role played by Struts?


The role played by Structs is controller in Model/View/Controller(MVC) style. The View
is played by JSP and Model is played by JDBC or generic data source classes. The Struts
controller is a set of programmable components that allow developers to define exactly
how the application interacts with the user.
How Struts control data flow?
Struts implements the MVC/Layers pattern through the use of ActionForwards and
ActionMappings to keep control-flow decisions out of presentation layer.

What configuration files are used in Struts?

ApplicationResources.properties
struts-config.xml
These two files are used to bridge the gap between the Controller and the Model.

What helpers in the form of JSP pages are provided in Struts framework?
--struts-html.tld
--struts-bean.tld
--struts-logic.tld

Is Struts efficient?
The Struts is not only thread-safe but thread-dependent(instantiates each Action once and
allows other requests to be threaded through the original object.
ActionForm beans minimize subclass code and shorten subclass hierarchies
The Struts tag libraries provide general-purpose functionality
The Struts components are reusable by the application
The Struts localization strategies reduce the need for redundant JSPs
The Struts is designed with an open architecture--subclass available
The Struts is lightweight (5 core packages, 5 tag libraries)
The Struts is open source and well documented (code to be examined easily)
The Struts is model neutral

How you will enable front-end validation based on the xml in validation.xml?
The < html:javascript > tag to allow front-end validation based on the xml in
validation.xml. 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 validation.xml file. The < html:javascript > when
added in the jsp file generates the client site validation script.

What is ActionServlet?
The class org.apache.struts.action.ActionServlet 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.

How you will make available any Message Resources Definitions file to the Struts
Framework Environment?
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 / >

What is Action Class?


The Action Class is part of the Model and is a wrapper around the business logic. The
purpose of Action Class is to translate the HttpServletRequest to the business logic. To
use the Action, we need to Subclass and overwrite the execute() method. In the Action
Class all the database/business processing are done. It is advisable to perform all the
database related stuffs in the Action Class. The ActionServlet (commad) passes the
parameterized class to Action Form using the execute() method. The return type of the
execute method is ActionForward which is used by the Struts Framework to forward the
request to the file as per the value of the returned ActionForward object.

Write code of any Action Class?


Here is the code of Action Class that returns the ActionForward object.
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

public class TestAction extends Action


{
public ActionForward execute(
ActionMapping mapping,
ActionForm form,
HttpServletRequest request,
HttpServletResponse response) throws Exception
{
return mapping.findForward(\"testAction\");
}
}

What is ActionForm?
An ActionForm is a JavaBean that extends org.apache.struts.action.ActionForm.
ActionForm maintains the session state for web application and the ActionForm object is
automatically populated on the server side with data entered from a form on the client
side.

What is Struts Validator Framework?


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.

Give the Details of XML files used in Validator Framework?


The Validator Framework uses two XML configuration files validator-rules.xml and
validation.xml. The validator-rules.xml defines the standard validation routines, these are
reusable and used in validation.xml. to define the form specific validations. The
validation.xml defines the validations applied to a form bean. How you will display
validation fail errors on jsp page? - The following tag displays all the errors: <
html:errors/ >

Why do we need Struts?


Java technologies give developers a serious boost when creating and maintaining
applications to meet the demands of today's public Web sites and enterprise intranets.
Struts combines Java Servlets, Java ServerPages, custom tags, and message resources
into a unified framework. The end result is a cooperative, synergistic platform, suitable
for development teams, independent developers, and everyone in between.

How does Struts work?


Java Servlets are designed to handle requests made by Web browsers. Java ServerPages
are designed to create dynamic Web pages that can turn billboard sites into live
applications. Struts uses a special Servlet as a switchboard to route requests from Web
browsers to the appropriate ServerPage. This makes Web applications much easier to
design, create, and maintain.

Is Struts compatible with other Java technologies?


Yes. Struts is committed to supporting industry standards. Struts acts as an integrator of
Java technologies so that they can be used in the "real world".

Who wrote Struts?


There are several active committers to the Struts project, working cooperatively from
around the globe. Dozens of individual developers and committers contributed to the
Struts 1.x codebase. All interested Java developers are invited to contribute to the project.
Struts is a Apache Software Foundation project, with the mission to "provide secure,
enterprise-grade server solutions based on the Java Platform that are developed in an
open and cooperative fashion".
Struts was created by Craig R. McClanahan and donated to The Apache Software
Foundation in May 2000. Craig was the primary developer of both Struts 1.x and Tomcat
4. Tomcat 4 was the basis for the official reference implementation for a servlet 2.3 and
JSP 1.2 container.
Craig's current focus is as architect of the Sun Java Studio Creator (formerly Project
Rave). Craig also serves as the Specification Lead for JavaServer Faces (JSR-127), and is
the Web Layer Architect for the Java2 Enterprise Edition (J2EE) platform as a whole.

Why is it called Struts?


It's a reference to struts in the architectural sense, a reminder of the nearly invisible pieces
that hold up buildings, houses, and bridges.

Do I have to credit Struts on my own website?


You need to credit Struts if you redistribute your own framework based on Struts for
other people to use. (See the Apache License for details.) But you do not need to credit
Struts just because your web application utilizes the framework. It's the same situation as
using the Apache HTTPD server or Tomcat. Not required if its just running your web
site.

Where can I get a copy of Struts?


The best place to download Struts is at struts.apache.org. The nightly builds are very
stable, and recommended as the best place to start today.

How do I install Struts?


To develop applications with Struts, you can usually just add the Struts JAR file to your
Java development environment. You can then start using the Struts classes as part of your
own application. A blank Struts application (in the webapps directory, open struts-
blank.war) is provided, which you can just copy to get a quick-start on your own
brainchild.
Since the full source code for Struts is available, we also provide complete instructions
for compiling your own Struts JAR from scratch. (This is actually easier than it looks!)
Your Struts application can usually be deployed using a standard WAR file. In most
cases, you simply deposit the WAR file on your application server, and it is installed
automatically. If not, step-by-step installation instructions for various servlet containers
are available.

When do I need "struts.jar" on my classpath?


When you are compiling an application that uses the Struts classes, you must have the
"struts.jar" on the classpath your compiler sees -- it does not have to be on your
CLASSPATH environment variable.
Why is that an important distinction? Because if you are using a servlet container on your
development machine to test your application, the "struts.jar" must not be on your
CLASSPATH environment variable when running the container. (This is because each
Web application must also have their own copy of the Struts classes, and the container
will become confused if it is on the environment path as well.)
There are several general approaches to this issue:
* Use ANT for building your projects -- it can easily assemble classpaths for the
compiler. (This is how Struts itself is built, along with Tomcat and most other Java-based
projects).
* Use an IDE where you can configure the "class path" used for compilation independent
of the CLASSPATH environment variable.
* Use a shell script that temporarily adds struts.jar to the classpath just for compilation,
for example javac -classpath /path/to/struts.jar:$CLASSPATH $@

Does Struts include its own unit tests?


Struts currently has two testing environments, to reflect the fact that some things can be
tested statically, and some really need to be done in the environment of a running servlet
container.
For static unit tests, we use the JUnit framework. The sources for these tests are in the
"src/test" hierarchy in the source repository, and are executed via the "test.junit" target in
the top-level build.xml file. Such tests are focused on the low-level functionality of
individual methods, are particularly suitable for the static methods in the
org.apache.struts.util utility classes. In the test hierarchy, there are also some "mock
object" classes (in the org.apache.struts.mock package) so that you can package up things
that look like servlet API and Struts API objects to pass in as arguments to such tests.
Another valuable tool is Struts TestCase which provides a useful harness for Action
classes that can be used with JUnit or Cactus.

If the framework doesn't do what I want, can I request that a feature be added?
First, it's important to remember that Struts is an all-volunteer project. We don't charge
anyone anything to use Struts. Committers and other developers work on Struts because
they need to use it with their own applications. If others can use it too, that's "icing on the
cake". If you submit a patch for a feature that a Committer finds useful, then that
Committer may choose to volunteer his or her time to apply the patch. If you just submit
an idea without a patch, it is much less likely to be added (since first someone else has to
volunteer their time to write the patch).
We are grateful for any patches, and we welcome new ideas, but the best way to see that
something gets added to the framework is to do as much of the work as you can, rather
than rely on the "kindness of strangers". Worst case, you can apply the patch to your copy
of Struts and still use the feature in your own application. (Which is what open source is
~really~ all about.)

Where can I get help with Struts?


The Struts package comes complete with a Users Guide to introduce people to the
framework and its underlying technologies. Various components also have their own in-
depth Developers Guide, to cover more advanced topics. Comprehensive Javadocs are
included along with the full source code. For your convenience, these are bundled
together as a self-installing application. The struts-documentation.war is the same bundle
that is deployed as the Struts Web site.
The Strut's mailing list is also very active, and welcomes posts from new users. Before
posting a new question, be sure to consult the MAILING LIST ARCHIVE and the very
excellent How To Ask Questions The Smart Way by Eric Raymond. Please do be sure to
turn off HTML in your email client before posting.

What's the difference between Struts and Turbine? What's the difference between
Struts and Espresso?
If you are starting from scratch, packages like Turbine and Espresso can be very helpful
since they try to provide all of the basic services that your team is likely to need. Such
services include things like data persistence and logging.
If you are not starting from scratch, and need to hook up your web application to an
existing infrastructure, then "plain vanilla" Struts can be a better choice. The core Struts
framework does not presuppose that you are using a given set of data persistence,
presentation, or logging tools. Anything goes =:0)
Compared to other offerings, Struts endeavors to be a minimalist framework. We try
leverage existing technologies whenever we can and provide only the missing pieces you
need to combine disparate technologies into a coherent application. This is great when
you want to select your own tools to use with Struts. But, if you prefer a more integrated
infrastructure, then packages like Turbine or Espresso (which uses Struts) are perfectly
good ways to go.
See also
* < http://www.mail-archive.com/struts-user@jakarta.apache.org/msg03206.html >
* < http://www.mail-archive.com/general@jakarta.apache.org/msg00495.html >
* < http://jakarta.apache.org/velocity/ymtd/ymtd.html >

Why aren't the Struts tags maintained as part of the Jakarta Taglibs project ?
Development of both products began about the same time. Leading up to the release of
1.0, it was thought better to continue to develop the taglibs alongside the controller. Now
that 1.0 is out, the JavaServer Pages Standard Taglib is in active development. Once work
on JSTL stabilizes, the Struts taglibs will be revisited. Tags which are not linked directly
to the framework may be hosted at Jakarta Taglibs instead.

Are the Struts tags XHTML compliant ?


If you use an <html:html xhtml="true> or <html:xhtml/> element on your page, the tags
will render as XHTML (since Struts 1.1).

Will the Struts tags support other markup languages such as WML ?
Struts itself is markup neutral. The original Struts taglibs are only one example of how
presentation layer components can access the framework. The framework objects are
exposed through the standard application, session, and request contexts, where any Java
component in the application can make use of them.
Markup extensions that use Struts are available for Velocity and XLST, among others. A
new Struts tag library for Java Server Faces is also in development.
For more about using WAP/WML with Struts see the article WAP up your EAserver.

What about JSTL and JavaServer Faces ?


JSTL, the JavaServer Standard Tag Library, is a set of JSP tags that are designed to make
it easier to develop Web applications. JavaServer Faces (JSF) is a specification for a new
technology that promises to make it easier to write MVC applications, both for the Web
and for the desktop.
The inventor of Struts, Craig McClanahan, is the specification co-lead for JavaServer
Faces (JSR 127), and architect of the reference implemenation as well as Java Studio
Creator. Both JSTL and JSF are complementary to Struts.
The mainstay of the Struts framework is the controller components, which can be used
with any Java presentation technology. As new technologies become available, it is
certain that new "glue" components will also appear to help these technologies work as
well with Struts.
Struts originally came bundled with a set of custom JSP tags. Today, several extensions
are available to help you use Struts with other popular presentation technologies, like
XSLT and Velocity. Likewise, extensions for JSTL and JSF are now available as well.
The JSTL reference implementation is available through the Jakarta Taglibs site. A JSTL
taglibs for Struts, Struts-El , is available and distributed with Struts beginning with the
1.1 release.
The JSF specification and reference implementation is available through Sun's The JSF
specification and reference implementation is available through Sun's Java ServerFaces
page. An early-release JavaServer Faces taglib for Struts, Struts-Faces, is also in early
release and available through the nightly build. The Struts Faces taglib is expected to
work with any compliant JSF implementation, including MyFaces.

Is there a particularly good IDE to use with Struts


Struts should work well with any development environment that you would like to use, as
well as with any programmers editor. The members of the Struts development team each
use their own tools such as Emacs, IDEA, Eclipse, and NetBeans.

Why was reload removed from Struts (since 1.1)?


The problem with ReloadAction was that Struts was trying to act like a container, but it
couldn't do a proper job of it. For example, you can't reload classes that have been
modified, or (portably) add new classes to a running web application (even if the
container supported it).
Meanwhile, as Struts 1.1 was being developed, work progressed on things like Tomcat's
reload command via the Manager webapp. This feature allows you to quickly reload-on-
demand, complete with saving and restoring your session). It started to make even less
sense for Struts to half-implement a feature that containers are implementing fully.
A more minor point is that freezing the configuration information at application startup
time allows Struts to safely access the mapping information without bothering with
synchronization. The "startup-only" strategy creates a modest but real improvement in
performance for all users.
So, ReloadAction is not supported since Struts 1.1 for two reasons:
* It never did let you reload everything that you would really want to -- particularly
changed classes -- so many people ended up having to reload the webapp anyway.
* Containers are starting to offer reload-on-demand features which does the same thing as
the Struts ReloadAction, only better.
* Not supporting ReloadAction lets Struts avoid doing synchronization locks around all
the lookups (like figuring out which action to use, or the destination of an
ActionForward) so applications can run a little faster.
Of course, if someone came up with an implementation that solved these problems
without creating any others, we would not be opposed to including a new ReloadAction.

What is a modular application? What does module-relative mean?


Since Struts 1.1, the framework 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. (Or is named with an empty string, depending your
viewpoint.) Developing an application with only a default module is no different from
how applications were developed under Struts 1.0. Since Struts 1.1, you can add
additional modules to your application, each of which can have their own configuration
files, messages resources, and so forth. Each module is developed in the same way as the
default module. Applications that were developed as a single module can added to a
multiple module application, and modules can promoted to a standalone application
without change. For more about configuring your application to support multiple
modules, see Configuring Applications in the User Guide.
But to answer the question =:0), a modular application is a Struts application that uses
more than one module. Module-relative means that the URI starts at the module level,
rather than at the context level, or the absolute-URL level.
* Absolute URL: http://localhost/myApplication/myModule/myAction.do
* context-relative: /myModule/myAction.do
* module-relative: /myAction.do
The Struts Examples application is a modular application that was assembled from
several applications that were created independently.

Why are some of the class and element names counter-intuitive?


The framework grew in the telling and, as it evolved, some of the names drifted.
The good thing about a nightly build, is that everything becomes available to the
community as soon as it is written. The bad thing about a nightly build is that things like
class names get locked down early and then become difficult to change.

Why is ActionForm a base class rather than an interface?


The MVC design pattern is very simple to understand but much more difficult to live
with. You just need this little bit of Business Logic in the View logic or you need just that
little bit of View logic in the Business tier and pretty soon you have a real mess.
Making ActionForm a class takes advantage of the single inheritance restriction of Java
to it makes it more difficult for people to do things that they should not do.
ActionForms implemented as interfaces encourage making the property types match the
underlying business tier instead of Strings, which violates one of the primary purposes for
ActionForms in the first place (the ability to reproduce invalid input, which is a
fundamental user expectation). ActionForms as an interface would also encourage using
existing DAO objects as ActionForms by adding ‘implements ActionForm’ to the
class. This violates the MVC design pattern goal of separation of the view and business
logic.
Since the goal of struts is to enforce this separation, it just makes more sense for Struts to
own the ActionForm.
DynaActionForms relieve developers of maintaining simple ActionForms. For near zero
maintenance, try Niall Pemberton's LazyActionForm

Do ActionForms have to be true JavaBeans?


The utilities that Struts uses (Commons-BeanUtils since 1.1) require that ActionForm
properties follow the JavaBean patterns for mutators and accessors (get*,set*,is*). Since
Struts uses the Introspection API with the ActionForms, some containers may require that
all the JavaBean patterns be followed, including declaring "implements Serializable" for
each subclass. The safest thing is to review the JavaBean specification and follow all the
prescribed patterns.
Since Struts 1.1, you can also use DynaActionForms and mapped-backed forms, which
are not true JavaBeans. For more see ActionForm classes in the User Guide and Using
Hashmaps with ActionForms in this FAQ.

Can I use multiple HTML form elements with the same name?
Yes. Define the element as an array and Struts will autopopulate it like any other.
private String[] id= {};
public String[] getId() { return this.id; }
public void setItem(String id[]) {this.id = id;}
And so forth

Can I use multiple HTML form elements with the same name?
Yes. The issue is that only one action class can be associated with a single form. So the
real issue is how do I decode multiple submit types to a single Action class. There is
more than one way to achieve this functionality.
The way that is suggested by struts is right out of the javadoc for
LookupDispatchAction . Basically, LookupDispatchAction is using the keys from
ApplicationProperties.resources as keys to a map of actions available to your Action
class. It uses reflection to decode the request and invoke the proper action. It also takes
advantage of the struts <html:submit> tags and is straight forward to implement.
You can roll your own with JavaScript events and javascript:void
(document.forms["myform"].submit) on any html element. This gives you control of how
you want your page to look. Again you will have to decode the expected action in the
execute method of your action form if you choose this route.

Why doesn't the focus feature on the <html:form> tag work in every circumstance?
Unfortunately, there is some disagreement between the various browsers, and different
versions of the same browser, as to how the focus can be set. The <html:form> tag
provides a quick and easy JavaScript that will set the focus on a form for most versions of
most browsers. If this feature doesn't work for you, then you should set the focus using
your own JavaScript. The focus feature is a convenient "value-add" -- not a core
requirement of the tag. If you do come up with a JavaScript that provides the final
solution to this project, please post your patch to this Bugzilla ticket.

Why are my checkboxes not being set from ON to OFF?


A problem with a checkbox is that the browser will only include it in the request when it
is checked. If it is not checked, the HTML specification suggests that it not be sent (i.e.
omitted from the request). If the value of the checkbox is being persisted, either in a
session bean or in the model, a checked box can never unchecked by a HTML form --
because the form can never send a signal to uncheck the box. The application must
somehow ascertain that since the element was not sent that the corresponding value is
unchecked.
The recommended approach for Struts applications is to use the reset method in the
ActionForm to set all properties represented by checkboxes to null or false. The checked
boxes submitted by the form will then set those properties to true. The omitted properties
will remain false. Another solution is to use radio buttons instead, which always submit a
value.
It is important to note that the HTML specification recommends this same behavior
whenever a control is not "successful". Any blank element in a HTML form is not
guaranteed to submitted. It is therefor very important to set the default values for an
ActionForm correctly, and to implement the reset method when the ActionForm might
kept in session scope.

Can't I just create some of my JavaBeans in the JSP using a scriptlet?


Struts is designed to encourage a Model 2/MVC architecture. But there is nothing that
prevents you from using Model 1 techniques in your JavaServer Pages, so the answer to
the question is "Yes, you can".
Though, using Model 1 techniques in a Struts application does go against the grain. The
approach recommended by most Struts developers is to create and populate whatever
objects the view may need in the Action, and then forward these through the request.
Some objects may also be created and stored in the session or context, depending on how
they are used.
Likewise, there is nothing to prevent you from using scriptlets along with JSP tags in
your pages. Though, many Struts developers report writing very complex scriplet-free
applications and recommend the JSP tag approach to others.
For help with Model 1 techniques and scriptlets, you might consider joining the Javasoft
JSP-interest mailing list, where there are more people still using these approaches.

Can I use JavaScript to submit a form?


You can submit a form with a link as below. BTW, the examples below assume you are
in an block and 'myForm' is picked up from the struts-config.xml name field of the
action.
<a href='javascript:void(document.forms["myForm"].submit()>My Link</a>
Now the trick in the action is to decode what action you intend to perform. Since you are
using JavaScript, you could set a field value and look for it in the request or in the form.
... html/javascript part ...
<input type='hidden' value='myAction' />
<input type='button' value='Save Meeeee'
onclick='document.forms["myForm"].myAction.value="save";
document.forms["myForm"].submit();' />
<input type='button' value='Delete Meeeee'
onclick='document.forms["myForm"].myAction.value="delete";
document.forms["myForm"].submit();' />
... the java part ...
class MyAction extends ActionForm implements Serializable {

public ActionForward execute (ActionMapping map, ActionForm form,


HttpServletRequest req, HttpServletResponse) {
String myAction = req.getParameter("myAction");

if (myAction.equals("save") {
// ... save action ...
} else if (myAction.equals("delete") {
// ... delete action ...
}
}
}
}
This is just one of many ways to achieve submitting a form and decoding the intended
action. Once you get used to the framework you will find other ways that make more
sense for your coding style and requirements. Just remember this example is completely
non-functional without JavaScript.

How do I use JavaScript to ...


Struts is mainly a server-side technology. We bundled in some JSP tags to expose the
framework components to your presentation page, but past that, the usual development
process applies.
Interactive pages require the use of JavaScript. (That's why it was invented.) If you want
things popping up or doing this when they click that, you are outside the scope of Struts
and back into the web development mainstream.
You use JavaScript with Struts the same way you use with any presentation page. Since
JavaScript is a client-side technology, you can use simple relative references to your
scripts. If you need to fire a JavaScript from a HTML control, the Struts HTML tags have
properties for the JavaScript events.
A very good JavaScript resource is Matt Kruse's site at
http://www.mattkruse.com/javascript/ Do I need to implement reset and set all my form
properties to their initial values?
No. You need to set checkbox properties to false if the ActionForm is being retained in
session scope. This is because an unchecked box does not submit an attribute. Only
checked boxes submit attributes. If the form is in session scope, and the checkbox was
checked, there is no way to turn it back off without the reset method. Resetting the
properties for other controls, or for a request scope form, is pointless. If the form is in
request scope, everything already just started at the initial value.

Can I use other beans or hashmaps with ActionForms?


Yes. There are several ways that you can use other beans or hashmaps with ActionForms.

* ActionForms can have other beansor hashmaps as properties


* "Value Beans" or "Data Transfer Objects" (DTOs) can be used independently of
ActionForms to transfer data to the view
* ActionForms can use Maps to support "dynamic" properties (since Struts 1.1)
ActionForms (a.k.a. "form beans") are really just Java beans (with a few special methods)
that Struts creates and puts into session or request scope for you. There is nothing
preventing you from using other beans, or including them in your form beans. Here are
some examples:
Collections as properties Suppose that you need to display a pulldown list of available
colors on an input form in your application. You can include a string-valued
colorSelected property in your ActionForm to represent the user's selection and a
colorOptions property implemented as a Collection (of strings) to store the available
color choices. Assuming that you have defined the getters and setters for the
colorSelected and colorOptions properties in your orderEntryForm form bean, you can
render the pulldown list using:
<html:select property="colorSelected">
<html:options property="colorOptions" name="orderEntryForm"/>
</html:select>
The list will be populated using the strings in the colorOptions collection of the
orderEntryForm and the value that the user selects will go into the colorSelected property
that gets posted to the subsequent Action. Note that we are assuming here that the
colorOptions property of the orderEntryForm has already been set.
See How can I prepopulate a form? for instructions on how to set form bean properties
before rendering edit forms that expect properties to be pre-set.
Independent DTO An Action that retrieves a list of open orders (as an ArrayList of Order
objects) can use a DTO independently of any form bean to transfer search results to the
view. First, the Action's execute method performs the search and puts the DTO into the
request:
ArrayList results = businessObject.executeSearch(searchParameters);
request.setAttribute("searchResults",results);
Then the view can iterate through the results using the "searchResults" request key to
reference the DTO:
` <logic:iterate id="order" name="searchResults" type="com.foo.bar.Order">
<tr><td><bean:write name="order" property="orderNumber"/><td>
<td>..other properties...</td></tr>
</logic:iterate>

How can I scroll through list of pages like the search results in google?
Many Struts developers use the Pager from the JSPTags site.
http://jsptags.com/tags/navigation/pager/

Why do the Struts tags provide for so little formatting?


The Struts tags seem to provide only the most rudimentary functionality. Why is there not
better support for date formatting and advanced string handling?
Three reasons:
First, work started on the JSTL and we didn't want to duplicate the effort.
Second, work started on Java Server Faces, and we didn't want to duplicate that effort
either.
Third, in a Model 2 application, most of the formatting can be handled in the
ActionForms (or in the business tier), so all the tag has to do is spit out a string. This
leads to better reuse since the same "how to format" code does not need to be repeated in
every instance. You can "say it once" in a JavaBean and be done with it. Why don't the
Struts taglibs offer more layout options?
Since the Struts tags are open source, you can extend them to provide whatever additional
formatting you may need. If you are interested in a pre-written taglib that offers more
layout options, see the struts-layout taglib.
In the same arena, there is a well regarded contributor taglib that can help you create
Menus for your Struts applications.

Why does the <html:link> tag URL-encode javascript and mailto links?
The <html:link> tag is not intended for use with client-side references like those used to
launch Javascripts or email clients. The purpose of link tag is to interject the context (or
module) path into the URI so that your server-side links are not dependent on your
context (or module) name. It also encodes the link, as needed, to maintain the client's
session on the server. Neither feature applies to client-side links, so there is no reason to
use the <html:link> tag. Simply markup the client-side links using the standard tag.

Why does the option tag render selected=selected instead of just selected?
Attribute minimization (that is, specifying an attribute with no value) is a place where
HTML violates standard XML syntax rules. This matters a lot for people writing to
browsers that support XHTML, where doing so makes the page invalid. It's much better
for Struts to use the expanded syntax, which works the same on existing browsers
interpreting HTML, and newer browsers that expect XHTML-compliant syntax. Struts is
following the behavior recommended by the XHTML specification

Do I have to use JSPs with my application?


The short answer to this question is: No, you are not limited to JavaServer Pages.
The longer answer is that you can use any type of presentation technology which can be
returned by a web server or Java container. The list includes but is not limited to:
* JavaServer Pages,
* HTML pages,
* WML files,
* Java servlets,
* Velocity templates, and
* XML/XLST
Some people even mix and match apparently unrelated technologies, like PHP, into the
same web application.

Do ActionForms have to be true JavaBeans?


ActionForms are added to a servlet scope (session or request) as beans. What this means
is that, for certain functionality to be available, your ActionForms will have to follow a
few simple rules.
First, your ActionForm bean must have a zero-arguments constructor. This is required
because Struts must be able to dynamically create new instances of your form bean class,
while knowing only the class name. This is not an onerous restriction, however, because
Struts will also populate your form bean's properties (from the request parameters) for
you.
Second, the fields of your form bean are made available to the framework by supplying
public getter and setter methods that follow the naming design patterns described in the
JavaBeans Specification. For most users, that means using the following idiom for each
of your form bean's properties:
private {type} fieldName;
public {type} getFieldName() {
return (this.fieldName);
}

public void setFieldName({type} fieldName) {


this.fieldName = fieldName;
}
NOTE - you MUST obey the capitalization conventions shown above for your
ActionForm properties to be recognized. The property name in this example is
"fieldName", and that must also be the name of the input field that corresponds to this
property. A bean property may have a "getter" method and a "setter" method (in a form
bean, it is typical to have both) whose name starts with "get" or "set", followed by the
property name with the first character capitalized. (For boolean properties, it is also legal
to use "is" instead of "get" as the prefix for the getter method.)
Advanced JavaBeans users will know that you can tell the system you want to use
different names for the getter and setter methods, by using a java.beans.BeanInfo class
associated with your form bean. Normally, however, it is much more convenient to
follow the standard conventions.
WARNING - developers might be tempted to use one of the following techniques, but
any of them will cause your property not to be recognized by the JavaBeans introspection
facilities, and therefore cause your applications to misbehave:
* Using getter and setter method names that do not match - if you have a getFoo()
method for your getter, but a setBar() method for your setter, Java will not recognize
these methods as referring to the same property. Instead, the language will think you have
a read-only property named "foo" and a write-only property named "bar".
* Using more than one setter method with the same name - The Java language lets you
"overload" methods, as long as the argument types are different. For example, you could
have a setStartDate(java.util.Date date) method and a setStartDate(String date) method in
the same class, and the compiled code would know which method to call based on the
parameter type being passed. However, doing this for form bean properties will prevent
Java from recognizing that you have a "startDate" property at all.
There are other rules to follow if you want other features of your form beans to be
exposed. These include indexed attributes and mapped attributes. They are covered in
detail in other areas of the Struts documentation, in particular: indexedprops.html

Do I have to have a separate ActionForm bean for every HTML form?


This is an interesting question. As a newbie, it is a good practice to create a new
ActionForm for each action sequence. You can use DynaActionForms to help reduce the
effort required, or use the code generation facilities of your IDE.
Some issues to keep in mind regarding reuse of form beans are as follows:
* Validation - You might need to use different validation rules depending upon the action
that is currently being executed.
* Persistence - Be careful that a form populated in one action is not unexpectedly reused
in a different action. Multiple entries in struts-config.xml for the same ActionForm
subclass can help (especially if you store your form beans in session scope).
Alternatively, storing form beans in request scope can avoid unexpected interactions (as
well as reduce the memory footprint of your application, because no server-side objects
will need to be saved in between requests.
* Checkboxes - If you do as recommended and reset your boolean properties (for fields
presented as checkboxes), and the page you are currently displaying does not have a
checkbox for every boolean property on the form bean, the undisplayed boolean
properties will always appear to have a false value.
* Workflow - The most common need for form bean reuse is workflow. Out of the box,
Struts has limited support for workflow, but a common pattern is to use a single form
bean with all of the properties for all of the pages of a workflow. You will need a good
understanding of the environment (ActionForms, Actions, etc.) prior to being able to put
together a smooth workflow environment using a single form bean.
As you get more comfortable, there are a few shortcuts you can take in order to reuse
your ActionForm beans. Most of these shortcuts depend on how you have chosen to
implement your Action / ActionForm combinations.

How can I prepopulate a form?


The simplest way to prepopulate a form is to have an Action whose sole purpose is to
populate an ActionForm and forward to the servlet or JSP to render that form back to the
client. A separate Action would then be use to process the submitted form fields, by
declaring an instance of the same form bean name.
The struts-example example application that is shipped with Struts illustrates this design
pattern nicely. Note the following definitions from the struts-config.xml file:
...
<form-beans>
...
<-- Registration form bean -->
<form-bean name="registrationForm"
type="org.apache.struts.webapp.example.RegistrationForm"/>
...
</form-beans>
...
<action-mappings>
...
<-- Edit user registration -->
<action path="/editRegistration"
type="org.apache.struts.webapp.example.EditRegistrationAction"
name="registrationForm"
scope="request"
validate="false"/>
...
<-- Save user registration -->
<action path="/saveRegistration"
type="org.apache.struts.webapp.example.SaveRegistrationAction"
name="registrationForm"
input="registration"
scope="request"/>
...
</action-mappings>

Note the following features of this approach:


* Both the /editRegistration and /saveRegistration actions use the same form bean.
* When the /editRegistration action is entered, Struts will have pre-created an empty form
bean instance, and passed it to the execute() method. The setup action is free to
preconfigure the values that will be displayed when the form is rendered, simply by
setting the corresponding form bean properties.
* When the setup action completes configuring the properties of the form bean, it should
return an ActionForm that points at the page which will display this form. If you are
using the Struts JSP tag library, the action attribute on your <html:form> tag will be set to
/saveRegistration in order for the form to be submitted to the processing action.
* Note that the setup action (/editRegistration) turns off validation on the form that is
being set up. You will normally want to include this attribute in the configuration of your
setup actions, because you are not planning to actually process the results -- you simply
want to take advantage of the fact that Struts will precreate a form bean instance of the
correct class for you.
* The processing action (/saveRegistration), on the other hand, leaves out the validate
attribute, which defaults to true. This tells Struts to perform the validations associated
with this form bean before invoking the processing action at all. If any validation errors
have occurred, Struts will forward back to your input page (technically, it forwards back
to an ActionForward named "registration" in this case, because the example webapp uses
the inputForward attribute in the element -- see the documentation describing struts-
config.xml for more information) instead of calling your processing action.

Can I have an Action without a form?


Yes. If 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. A good example of an Action with no ActionForm is
the LogoffAction in the struts example application:

<action path="/logoff"
type="org.apache.struts.webapp.example.LogoffAction">
<forward name="success" path="/index.jsp"/>
</action>

This action needs no data other than the user's session, which
it can get from the Request, and it doesn't need to prepare any
view elements for display, so it does not need a form.

However, you cannot use the <html:form> tag without


an ActionForm. Even if you want to use the <html:form>
tag with a simple Action that does not require input,
the tag will expect you to use some type of ActionForm,
even if it is an empty subclass without any properties.

Can you give me a simple example of using the requiredif Validator rule?
First off, there's an even newer Validator rule called
validwhen, which is almost certainly what you want to use,
since it is much easier and more powerful.
It will be available in the first release after 1.1 ships.
The example shown below could be coded with validwhen as:

<form name="medicalStatusForm">

<field
property="pregnancyTest" depends="validwhen">
<arg0 key="medicalStatusForm.pregnancyTest.label"/>
<var>
<var-name>test</var-name>
<var-value>((((sex == 'm') OR (sex == 'M'))
AND (*this* == null)) OR (*this* != null))</test>
</var>
</field>

Let's assume you have a medical information form


with three fields,
sex, pregnancyTest, and testResult. If sex is 'f' or 'F',
pregnancyTest is required. If pregnancyTest is not blank,
testResult is required. The entry in your validation.xml
file would look like this:

<form name="medicalStatusForm">

<field
property="pregnancyTest" depends="requiredif">
<arg0 key="medicalStatusForm.pregnancyTest.label"/>
<var>
<var-name>field[0]</var-name>
<var-value>sex</var-value>
</var>
<var>
<var-name>fieldTest[0]</var-name>
<var-value>EQUAL</var-value>
</var>
<var>
<var-name>fieldValue[0]</var-name>
<var-value>F</var-value>
</var>
<var>
<var-name>field[1]</var-name>
<var-value>sex</var-value>
</var>
<var>
<var-name>fieldTest[1]</var-name>
<var-value>EQUAL</var-value>
</var>
<var>
<var-name>fieldValue[1]</var-name>
<var-value>f</var-value>
</var>
<var>
<var-name>fieldJoin</var-name>
<var-value>OR</var-value>
</var>
</field>

<field
property="testResult" depends="requiredif">
<arg0 key="medicalStatusForm.testResult.label"/>
<var>
<var-name>field[0]</var-name>
<var-value>pregnancyTest</var-value>
</var>
<var>
<var-name>fieldTest[0]</var-name>
<var-value>NOTNULL</var-value>
</var>
</field>
</form>

When is the best time to validate input?


This is an excellent question. Let's step back a second and think about a typical mid to
large size application. If we start from the back end and work toward the view we have:
1) Database: Most modern databases are going to validate for required fields, duplicate
records, security constraints, etc.
2) Business Logic: Here you are going to check for valid data relationships and things
that make sense for the particular problem you are triing to solve.
... This is where struts comes into the picture, by now the system should be pretty well
bulletproof. What we are going to do is make validation friendlier and informative.
Rember it is OK to have duplicate validations...
3) ActionErrors validate(ActionMapping map, HttpServletRequest req) is where you can
do your validation and feed back to the view, information required to correct any errors.
validate is run after the form has been reset and after the ActionForm properties have
been set from corresponding view based input. Also remember you can turn validation
off with validate="false" in the action mapping in the struts-config.xml. This is done by
returning an ActionErrors collection with messages from your
ApplicationResources.properties file.
Here you have access to the request so you can see what kinds of action is being
requested to fine tune your validations. The <html:error> tag allows you to dump all
errors on your page or a particular error associated with a particular property. The input
attribute of the struts-config.xml action allows you to send validation errors to a
particular jsp / html / tile page.
4) You can have the system perform low level validations and client side feedback using
a ValidatorForm or its derivatives. This will generate javascript and give instant feedback
to the user for simple data entry errors. You code your validations in the validator-
rules.xml file. A working knowledge of regular expressions is necessary to use this
feature effectively.

How can I avoid validating a form before data is entered?


The simplest way is to have two actions. The first one has the job of setting the form data,
i.e. a blank registration screen. The second action in our writes the registration data to the
database. Struts would take care of invoking the validation and returning the user to the
correct screen if validation was not complete.
The EditRegistration action in the struts example application illustrates this:
< action path="/editRegistration">
type="org.apache.struts.webapp.example.EditRegistrationAction"
attribute="registrationForm"
scope="request"
validate="false">
<forward name="success path="/registration.jsp"/>
</action>
When the /editRegistration action is invoked, a registrationForm is created and added to
the request, but its validate method is not called. The default value of the validate
attribute is true, so if you do not want an action to trigger form validation, you need to
remember to add this attribute and set it to false.

How can I create a wizard workflow?


The basic idea is a series of actions with next, back, cancel and finish actions with a
common bean. Using a LookupDispatchAction is reccomended as it fits the design
pattern well and can be internationalized easily. Since the bean is shared, each choice
made will add data to the wizards base of information. A sample of struts-config.xml
follows:

< form-beans>
<form-bean name="MyWizard"
type="forms.MyWizard" />
</form-beans>

<!-- the first screen of the wizard (next action only available) -->
<!-- no validation, since the finish action is not available -->
<actions>
<action path="/mywizard1"
type="actions.MyWizard"
name="MyWizard"
validate="false"
input="/WEB-INF/jsp/mywizard1.jsp">
<forward name="next"
path="/WEB-INF/jsp/mywizard2.jsp" />
<forward name="cancel"
path="/WEB-INF/jsp/mywizardcancel.jsp" />
</action>

<!-- the second screen of the wizard (back, next and finish) -->
<!-- since finish action is available, bean should validated, note
validation should not necessarily validate if back action requested, you
might delay validation or do conditional validation -->
<action path="/mywizard2"
type="actions.MyWizard"
name="MyWizard"
validate="true"
input="/WEB-INF/jsp/mywizard2.jsp">
<forward name="back"
path="/WEB-INF/jsp/mywizard1.jsp" />
<forward name="next"
path="/WEB-INF/jsp/mywizard3.jsp" />
<forward name="finish"
path="/WEB-INF/jsp/mywizarddone.jsp" />
<forward name="cancel"
path="/WEB-INF/jsp/mywizardcancel.jsp" />
</action>

<!-- the last screen of the wizard (back, finish and cancel only) -->
<action path="/mywizard3"
type="actions.MyWizard"
name="MyWizard"
validate="true"
input="/WEB-INF/jsp/mywizard3.jsp">
<forward name="back"
path="/WEB-INF/jsp/mywizard2.jsp" />
<forward name="finish"
path="/WEB-INF/jsp/mywizarddone.jsp" />
<forward name="cancel"
path="/WEB-INF/jsp/mywizardcancel.jsp" />
</action>

The pieces of the wizard are as follows:


forms.MyWizard.java - the form bean holding the information required
actions.MyWizard.java - the actions of the wizard, note the use of LookupDispatchAction
allows for one action class with several methods. All the real work will be done in the
'finish' method.
mywizard[x].jsp - the data collection jsp's
mywizarddone.jsp - the 'success' page
mywizardcancel.jsp - the 'cancel' page

What's the best way to deal with migrating a large application from Struts to JSF?
Is there any tool support that can help?
Answer: This is a complicated task depending on your Struts application. Because the
two frameworks have different goals, there are some challenges. Migrate your response
pages first. Keep the Struts controller and place and forward to JSF pages. Then you can
configure Struts forwards to go through the Faces servlet. Consider looking at the Struts-
Faces framework from Apache. See the framework chapter in JSF in Action.

How can I 'chain' Actions?


Chaining actions can be done by simply using the
proper mapping in your forward entries in the struts-config.xml file.
Assume you had the following two classes:

/* com/AAction.java */
...

public class AAction extends Action


{
public ActionForward
execute(ActionMapping mapping,
ActionForm form,
HttpServletRequest request,
HttpServletResponse response) throws
Exception
{
// Do something

return mapping.findForward("success");
}
}
/* com/BAction.java */
...

public class BAction extends Action


{
public ActionForward
execute(ActionMapping mapping,
ActionForm form,
HttpServletRequest request,
HttpServletResponse response) throws
Exception
{
// Do something else

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

Then you can chain together these two actions with


the Struts configuration as shown in the following excerpt:

...
<action-mappings type="org.apache.struts.action.ActionMapping">
<action path="/A"
type="com.AAction"
validate="false">
<forward name="success" path="/B.do" />
</action>
<action path="/B"
type="com.BAction"
scope="session"
validate="false">
<forward name="success" path="/result.jsp" />
</action>
</action-mappings>
...

Here we are assuming you are using a suffix-based (.do) servlet mapping, which is
recommended since module support requires it. When you send your browser to the web
application and name the action A.do (i.e. http://localhost:8080/app/A.do) it will execute
AAction.execute(), which will then forward to the "success" mapping.
This causes the execution of BAction.execute() since the entry for "success" in the
configuration file uses the .do suffix.
Of course it is also possible to chain actions programmatically, but the power and ease of
being able to "reroute" your web application's structure using the XML configuration file
is much easier to maintain.
As a rule, chaining Actions is not recommended. If your business classes are properly
factored, you should be able to call whatever methods you need from any Action, without
splicing them together into a cybernetic Rube Goldberg device.
If you must chain Actions, be aware of the following: calling the second Action from the
first Action has the same effect as calling the second Action from scratch. If both of your
Actions change the properties of a formbean, the changes made by the first Action will be
lost because Struts calls the reset() method on the formbean when the second Action is
called.

Declarative Exception Handling


If you have developed web applications long enough, you will realize a recurring pattern
emerges: when the backend (e.g. the EJB tier) throws you an exception, you nearly
always need to display an error page corresponding to the type of that exception. Sooner
or later, you will come up with a mechanism to use a lookup table (e.g. an HashMap) to
lookup an error page from the exception class.
Struts 1.1 now provides a similar but more powerful mechanism to declare exception
handling. In Struts 1.1, you can declare in the struts-config.xml the associations between
an exception class and an exception handler. Using the default exception handler
included in Struts, you can also specify the path of the error pages. With this information,
Struts will automatically forward to the specified pages when an uncaught exception is
thrown from an Action.
Like other facilities in Struts, the exception handlers are pluggable. You can write and
define your own handler classes if needed.

Struts GenericDataSource Just a general question - I'm building an application that


will run stand-alone, not in an application server. I need to manage some database
connections. Is the struts GenericDataSource a good candidate to do this for me? I
basicly just need a connection pool from where I can get connections and then
return them to optimize performance.
If this struts class is not a good candidate, can someone recommend a similar pool-
manager that is lean and mean and easy to use?
Answer 1
The Struts 1.0 GenericDataSource is not a good candidate for a production server. In
Struts 1.1, the Commons DBCP is used istead, which is a good candidate for a production
server. (You can also use the DBCP in Struts 1.0 by specifying the type and including the
Commons JARs.)
Another popular choice is Poolman. It's not under active development, but I believe you
can still download it from SourceForge. Poolman is also very easy to use outside of
Struts.
Many containers also offer support for connection pools. The one that ships with Resin is
quite good. The later versions of Tomcat bundle the Commons DBCP.
Regardless of what pool you use, a good practice is to hide it behind some type of adaptor
class of your own (often a singleton), to make it easy to change later. So your classes call
your adaptor, and your adaptor calls whichever pool you are using.
A neat and often-overlooked aspect of the Struts DataSource manager is that it supports
loading multiple connection pools and giving each a name. So you might have one pool
for internal use and another for public use. This way, the public connections can't swap
your administrative access to the application. Each pool could also have its own login,
and therefore different rights to the underlying database.
Answer 2

int i=1;

with Struts 1.0 and jdbc i'am use GenericDataSource


not in struts-xml, but in Client.properties

my Client.properties
instanceBd=oraID
userPasswd=xxx/yyyy
maxCount=20
minCount=19
port=1521
driver=oracle.jdbc.driver.OracleDriver
url=jdbc:oracle:thin:@serverName:port:instanceBd

then, on my code i have init (struts 1.0 or struts 1.1):

GenericDataSource ng = new GenericDataSource ();

ng.setUser (mprop.getUserBd());
ng.setPassword (mprop.getPasswdBd());
ng.setUrl (mprop.getUrl());
ng.setDriverClass(mprop.getDriverClass());
ng.setMaxCount(mprop.getMaxCount());
ng.setMinCount (mprop.getMinCount());
ng.setDescription("jdbc OracleDriver");
ng.setAutoCommit(true);
try { ng.open(); } catch (java.sql.SQLException e) {
}

in business logic (or pool) :


Connect cn = ng.getConnection();

it's work.
with struts 1.1 , struts-legacy.jar is necessy for this codes.

it's work.

Dynamic pages using struts


Is it possible to create the elements of a page(jsp) dynamically based on the results
of a data base query, when using struts framework?
If you are talking about rendering a report, then sure. The Action iteracts with the
business layer/data access objects to acquire the data, and then passes it to the
presentation page bundled up as a JavaBean or a collection of JavaBeans. The JSP tags
(and other systems) all use reflection, so you can use whatever JavaBean you like.
If you are talking about creating a dynamic data-entry form, then "not so much".
Struts 1.1 supports map-backed ActionForms, but the page still needs to know what input
fields are going to be needed. For a truly dynamic input form, I guess the key would be
some type of tag that took a map and then generated a column of input fields. (Wouldn't
work for everyone, since a lot of forms must be designed just so.) For extra credit, the
entry names could (optionally) be resource keys that were used to find the label text.
Text fields would be easy. Others would need some type of JavaBean with properties to
tell the tag what to output. A bit of work, but obviously doable.
Of course, you'd probably want to validate the form before passing it back to the
database. I imagine it's possible to use the validator in a non-declarative way, but I don't
know anyone whose doing that. If you can do a db query to get the information about the
form, I imagine you could also do a query to get the information about validations for the
form. It would probably be easier to write your own engine than adopt the validator. (It's
not really that complicated to do.)
People often ask about "dynamic input forms", but most of us just can't get our head
around the use case. It's hard to understand what you do with the dynamic data when it
comes back. Most application don't allow you to input or update an arbitrary (e.g.
dynamic) set of fields.

Both JSF and Struts will continue to exist for a while. The Struts community is
aware of JSF and is positioning itself to have strong support for JSF. See What
about JSTL and JavaServer faces?
From a tools perspective, if you look at the support for JSF versus Struts in WebSphere
Studio, the Struts tools are focused around the controller aspects. The Web Diagram
editor helps build your Struts configuration and the wizards/editors build Struts artifacts.
The JSF tools are geared towards building pages, and in essence, hide the JSF framework
from you. Expect WebSphere Studio to support both frameworks for a while. As JSF
matures, expect to see some of the controller aspects in JSF to become toolable.

Can you compare the advantages and disadvantages of JSF vs. Struts. Both now,
and from what you may know of futures, how and if JSF will evolve into a superior
technology vs. Struts? Include how WSAD plays into the comparison if it will help
differentiate the two.
This is a very popular question these days. In general, JSF is still fairly new and will take
time to fully mature. However, I see JSF being able to accomplish everything Struts can,
plus more. Struts evolved out of necessity. It was created by developers who were tired of
coding the same logic again and again. JSF emerged both from necessity and
competition.
Struts has several benefits:
* Struts is a mature and proven framework. It has been around for a few years and
deployed successfully on many projects. The WebSphere Application Server admin
console is a Struts application.
* Struts uses the Front Controller and Command patterns and can handle sophisticated
controller logic.
* In addition to the core controller function, it has many add-on benefits such as layouts
with Tiles, declarative exception handling, and internationalization.

There are disadvantages:

* Struts is very JSP-centric and takes other frameworks to adapt to other view
technologies.
* Although Struts has a rich tag library, it is still geared towards helping the controller
aspect of development and does not give a sense that you are dealing with components on
a page. Therefore, it is not as toolable from a view perspective.
* Struts requires knowledge of Java™. Its goal was to aid Java developers, but not to hide
Java. It does not hide details of the Java language to Web developers that well.
* ActionForms are linked programmatically to the Struts framework. Therefore, to
decouple the model, you need to write transfer code or use utilities to move data from
Action Forms to the Model on input.

JSF is an evolution of a few frameworks, including Struts. The creator of Struts, Craig
McClanahan, is one of the JSF specification leads. Therefore, it is not by accident to see
some overlap between Struts and JSF. However, one of JSF's major goals is to help J2EE
Web applications to be easily developed using RAD tools. As such, it introduces a rich
component model. JSF has several advantages:
* JSF is a specification from Sun® and will be included in future versions of the J2EE
specification. All major vendors are pledging strong support for JSF.
* JSF uses the Page Controller Pattern and therefore aids in Page rich applications.
Components can respond to event from components on a page.
* JSF has a well-defined request lifecycle allowing for plugability at different levels.
* One powerful example of plugability is building your own render toolkit. The ability to
separate the rendering portion from the controller portion of the framework allows for
wonderful opportunities of extensibility. Component providers can write their own
toolkits to render different markup languages, such as XML or WML. In addition, the
render toolkit is not tied to JSP.
* Because JSF has a rich component model, it favors a RAD style of development. I can
now build my Web pages using drag and drop technology. In addition, JSF gives me a
way to link visual components to back model components without breaking the layering.
JSF has disadvantages:
* JSF is still quite new and evolving. It will take some time to see successful
deployments and wide usage. In addition, as vendors write components, they may not do
everything you want them to.
* JSF by hand is not easier than Struts. Its goal was more oriented to RAD. Those who
prefer to do things by hand (for example, the vi type guy who does not like IDEs) may
find Struts easier to develop.
* Struts navigation may be a bit more flexible and adhere to more complex controller
logic.

Multiple Sub-applications
One of the shortcomings in Struts 1.0 is manageability of the configuration file
(commonly known as struts-config.xml) when the development of the application
involves a sizable team. This problem arises because a Struts-based application must run
under one controller servlet, the ActionServlet, and the ActionServlet can use only one
struts-config.xml. It is not an issue when the project is relatively small and the team
consists of a couple of developers; however, when the project size becomes significant
and the project involves a large number of developers, maintaining all the mapping
information in a single file becomes increasingly problematic.
Struts 1.1 solves this problem nicely by introducing multiple sub-applications. In Struts
1.1, each sub-application has its own struts-config.xml file. A large Struts-based
application can thus be easily partitioned into largely independent modules, i.e. sub-
applications, and each sub-team can maintain their struts-config.xml independently.
The sub-application scheme is a natural extension of the servlet context mapping scheme
of the URI paths used by servlet containers. According to the Servlet standard, when the
servlet container receives a request with a URL, the servlet container will try to match the
prefix of the URI path to a deployed web-application in the container. What Struts 1.1
does is it maps the second prefix of the path to a sub-application. In effect, this prefix
mapping scheme creates another level of namespace for each sub-application. For
example, for the URI,
http://some-host.com/myApp/module2/editSubscription.do
/myApp is the context path for a web-application called "myApp" and /module2 is the
sub-app prefix for a Struts sub-application called "module2".

DynaBean and BeanUtils


Another major complaint usually heard amongst Struts 1.0 users is the extensive effort
involved in writing the FormBean (a.k.a. ActionForm) classes.
Struts provides two-way automatic population between HTML forms and Java objects,
the FormBeans. To take advantage of this however, you have to write one FormBean per
HTML form. (In some use cases, a FormBean can actually be shared between multiple
HTML forms. But those are specific cases.) Struts' FormBean standard follows faithfully
the verbose JavaBean standard to define and access properties. Besides, to encourage a
maintainable architecture, Struts enforces a pattern such that it is very difficult to 'reuse' a
model-layer object (e.g. a ValueObject from the EJB tier) as a FormBean. Combining all
these factors, a developer has to spend a significant amount of time to write tedious
getters/setters for all the FormBean classes.
Struts 1.1 offers an alternative, Dynamic ActionForms, which are based on DynaBeans.
Simply put, DynaBeans are type-safe name-value pairs (think HashMaps) but behave like
normal JavaBeans with the help of the BeanUtils library. (Both the DynaBeans and the
BeanUtils library were found to be useful and generic enough that they have been
'promoted' into Jakarta's Commons project.) With Dynamic ActionForms, instead of
coding the tedious setters/getters, developers can declare the required properties in the
struts-config.xml files. Struts will instantiate and initialize Dynamic ActionForm objects
with the appropriate metadata. From then onwards, The Dynamic ActionForm instance is
treated as if it is an ordinary JavaBean by Struts and the BeanUtils library.

Validator
The Validator is not exactly a new feature. The Validator has been in the contrib package
in the distribution since Struts 1.0.1. Since then, part of it has now been refactored and
moved into the Jakarta-Commons subproject and renamed the Commons-Validator and
the Struts specific portion is now called the Struts-Validator. However, since it is in the
contrib package, people may overlook it and it is worthwhile to mention it here.
The Validator provides an extensible framework to define validation rules to validate user
inputs in forms. What is appealing in the Validator is that it generates both the server-side
validation code and the client-side validation code (i.e. Javascript) from the same set of
validation rules defined in an XML configuration file. The Validator performs the
validation based on regular-expression pattern matching. While a handful of commonly
used validators are shipped with the framework (e.g. date validator, range validator), you
can always define your own ones to suit your need.

Default Sub-application
To maintain backward compatibility, Struts 1.1 allows one default sub-application per
application. The URI of the resources (i.e. JSPs, HTMLs, etc) in the default sub-
application will have an empty sub-app prefix. This means when an existing 1.0
application is "dropped" into Struts 1.1, theoretically, it will automatically become the
default sub-application.

Direct Requests to JSPs


To take the full advantage of sub-application support, Struts 1.1 stipulates the
requirement that all requests must flow through the controller servlet, i.e. the
ActionServlet. Effectively, this means all JSPs must be fronted by Actions. Instead of
allowing direct requests to any of the JSPs, all requests must go through an Action and let
the Action forward to the appropriate JSP.
This is perhaps the biggest impact of migration to Struts 1.1 if you have not followed this
idiom in your applications. This restriction is required because without going through the
ActionServlet, Struts navigation taglibs (e.g. <html:form> and <html:link>) used in the
JSPs will not have the correct sub-app context to work with.

ActionServlet Configurations
With the introduction of sub-applications, a more flexible way is introduced to configure
each sub-application independently. Many of the configuration entries (e.g. resource
bundle location, maximum upload file size, etc) that used to be defined in web.xml have
now been moved to struts-config.xml. The original entries in web.xml are deprecated but
will still be effective.

Action.execute() and Action.getResources()


In Struts 1.0, request handling logic is coded in Action.perform(); however,
Action.perform() throws only IOException and SevletException. To facilitate the new
declarative exception handling , the request handling method needs to throw Exception,
the superclass of all the checked exceptions. Therefore, to both maintain backward
compatibility and facilitate declarative exception handling, Action.perform() is now
deprecated in favour of Action.execute().
You also have to be careful if you use DispatchAction in your existing applications. At
the time of writing, the DispatchAction in Struts 1.1 beta has not yet been updated to use
execute(). (A bug report has been filed in Struts' bug database.) Therefore, without
modifying the DispatchAction class yourself, declarative exception handling will not
work with DispatchAction subclasses.
In addition, Action.getResources() is now deprecated. Instead, you should call
Action.getResources(HttpServletRequest) instead. This allows Struts to return to you the
sub-application specific message resources. Otherwise, the message resources for the
default sub-app will be used.

Library Dependency
Struts 1.1 now depends on a handful of libraries from other Jakarta subprojects (e.g.
Commons-Logging, Commons-Collections, etc.). Some of these libraries may cause
classloading conflicts in some servlet containers. So far, people have reported in the
mailing list the classloading problem of commons-digester/jaxp1.1, and commons-
logging causing deployment difficulties in Struts 1.1 applications running on Weblogic
6.0. (The problems have been corrected in Weblogic 6.1 and 7.0.)

Resources under WEB-INF


According to the Servlet specification, resources (e.g. JSP files) stored under WEB-INF
are protected and cannot be accessed directly by the browsers. One design idiom for
Struts 1.0 is to put all the JSP files under WEB-INF and front them by Actions so that
clients cannot illegally access the JSPs. With the introduction of sub-application prefixes
in Struts 1.1, mapping resources under WEB-INF gets complicated. Extra configuration
steps utilizing the pagePattern and forwardPattern attributes of the element in struts-
config.xml is required to inform Struts to construct the paths correctly. More specifically,
you need to set these attributes to the pattern "/WEB-INF/$A$P".

What is the Jakarta Struts Framework?


Jakarta Struts is an open source implementation of MVC
(Model-View-Controller) pattern for the development of web based applications.
Jakarta Struts is a robust architecture and can be used for the development of applications
of any size.
The “Struts framework” makes it easier to design scalable, reliable Web applications.

What is an ActionServlet?
The class org.apache.struts.action.ActionServlet is called the ActionServlet.
In the Jakarta Struts Framework this class plays the role of controller.
All the requests to the server go through the “Controller”.
The “Controller” is responsible for handling all the requests.

How can one make any “Message Resources” definitions file available to the “Struts
Framework” environment?
Answer: “Message Resources” definitions file are simple .properties files and
these files contain the messages that can be used in the struts project.
“Message Resources” definition files can be added to the struts-config.xml file
through <message-resources /> tag. Example:
<message-resources parameter="MessageResources" />

What is an “Action Class”?


The “Action Class” is part of the “Model” and is a wrapper around the business logic.

The purpose of the “Action Class” is to translate the HttpServletRequest to the business
logic.

To use the “Action”, we need to subclass and overwrite the execute() method.

All the database and business processing is done in the “Action” class.

It is advisable to perform all the database related work in the “Action” class.

The ActionServlet (command) passes the parameterized class to ActionForm 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 according to the value of the returned
ActionForward object.

Write code of any Action Class?


Here is the code of Action Class that returns the ActionForward object.

package j2eeonline.jdj.com;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
public class TestAction extends Action{

public ActionForward execute(ActionMapping mapping, ActionForm form,


HttpServletRequest request,
HttpServletResponse response) throws Exception{
return mapping.findForward("testAction");
}
}

What is an “ActionForm”?
An “ActionForm” is a JavaBean that extends org.apache.struts.action.ActionForm.
ActionForm maintains the session state for web application and the “ActionForm” object
is automatically populated on the server side with data entered from a form on the client
side.

What is Struts Validator Framework?


The “Struts Framework” provides the functionality to validate the form data.
It can be used to validate the data in the user’s browser as well as on the server side.
Struts Framework checks the JavaScript code and it can be used to validate the form data
on the client browser.

Server side validation of form data can be accomplished by subclassing your “form”
Bean with DynaValidatorForm class.

The “Validator” framework was developed by David Winterfeldt as a third-party “add-


on” to Struts.
Now the Validator framework is part of the “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 any making any additional settings.

Describe the details of XML files used in the “Validator Framework”?


The Validator Framework uses two XML configuration files

1) validator-rules.xml and

2) validation.xml.

The validator-rules.xml defines the standard validation routines.

These are reusable and used in validation.xml to define the form specific validations.

The validation.xml defines the validations applied to a form bean.


How would you display “validation fail” errors on a JSP page?
Following tag displays all the errors:
<html:errors/>

How can one enable front-end validation based on the xml in validation.xml?
The
<html:javascript>
tag allows front-end validation based on the xml in validation.xml.

For example the code:

generates the client side JavaScript for the form "logonForm" as defined in the
validation.xml file.
The <html:javascript> when added in the JSP file generates the client side validation
script.

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.

Q: What is ActionServlet?
A: The class org.apache.struts.action.ActionServlet 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.

Q: How you will make available any Message Resources Definitions file to the Struts
Framework Environment?
A: 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" />

Q: What is Action Class?


A: The Action is part of the controller. 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. The ActionServlet (commad) passes the parameterized
class to Action Form using the execute() method. There should be no database
interactions in the action. The action should receive the request, call business objects
(which then handle database, or interface with J2EE, etc) and then determine where to go
next. Even better, the business objects could be handed to the action at runtime (IoC
style) thus removing any dependencies on the model. 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.

Q: Write code of any Action Class?


A: Here is the code of Action Class that returns the ActionForward object.
TestAction.java

package roseindia.net;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

public class TestAction extends Action


{
public ActionForward execute(
ActionMapping mapping,
ActionForm form,
HttpServletRequest request,
HttpServletResponse response) throws Exception{
return mapping.findForward("testAction");
}
}

Q: What is ActionForm?
A: An ActionForm is a JavaBean that extends
org.apache.struts.action.ActionForm. ActionForm maintains the session state for
web application and the ActionForm object is automatically populated on the server side
with data entered from a form on the client side.

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.

Q. Give the Details of XML files used in Validator Framework?


A: The Validator Framework uses two XML configuration files validator-rules.xml and
validation.xml. The validator-rules.xml defines the standard validation routines, these
are reusable and used in validation.xml. to define the form specific validations. The
validation.xml defines the validations applied to a form bean.

Q. How you will display validation fail errors on jsp page?


A: Following tag displays all the errors:
<html:errors/>

Q. How you will enable front-end validation based on the xml in validation.xml?
A: The <html:javascript> tag to allow front-end validation based on the xml in
validation.xml. 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 validation.xml file. The <html:javascript>
when added in the jsp file generates the client site validation script.

Question: What is RequestProcessor and RequestDispatcher?


Answer: The controller is responsible for intercepting and translating user input into
actions to be performed by the model. The controller is responsible for selecting the next
view based on user input and the outcome of model operations. The Controller receives
the request from the browser, invoke a business operation and coordinating the view to
return to the client.

The controller is implemented by a java servlet, this servlet is centralized point of control
for the web application. In struts framework the controller responsibilities are
implemented by several different components like
The ActionServlet Class
The RequestProcessor Class
The Action Class

The ActionServlet extends the javax.servlet.http.httpServlet class. The ActionServlet


class is not abstract and therefore can be used as a concrete controller by your
application.
The controller is implemented by the ActionServlet class. All incoming requests are
mapped to the central controller in the deployment descriptor as follows.
<servlet>
<servlet-name>action</servlet-name>
<servlet-class>org.apache.struts.action.ActionServlet</servlet-class>
</servlet>
All request URIs with the pattern *.do are mapped to this servlet in the deployment
descriptor as follows.

<servlet-mapping>
<servlet-name>action</servlet-name>
<url-pattern>*.do</url-pattern>
<url-pattern>*.do</url-pattern>
A request URI that matches this pattern will have the following form.
http://www.my_site_name.com/mycontext/actionName.do

The preceding mapping is called extension mapping, however, you can also specify path
mapping where a pattern ends with /* as shown below.
<servlet-mapping>
<servlet-name>action</servlet-name>
<url-pattern>/do/*</url-pattern>
<url-pattern>*.do</url-pattern>
A request URI that matches this pattern will have the following form.
http://www.my_site_name.com/mycontext/do/action_Name
The class org.apache.struts.action.requestProcessor process the request from the
controller. You can sublass the RequestProcessor with your own version and modify how
the request is processed.

Once the controller receives a client request, it delegates the handling of the request to a
helper class. This helper knows how to execute the business operation associated with the
requested action. In the Struts framework this helper class is descended of
org.apache.struts.action.Action class. It acts as a bridge between a client-side user action
and business operation. The Action class decouples the client request from the business
model. This decoupling allows for more than one-to-one mapping between the user
request and an action. The Action class also can perform other functions such as
authorization, logging before invoking business operation. the Struts Action class
contains several methods, but most important method is the execute() method.
public ActionForward execute(ActionMapping mapping,
ActionForm form, HttpServletRequest request, HttpServletResponse response)
throws Exception;
The execute() method is called by the controller when a request is received from a client.
The controller creates an instance of the Action class if one doesn’t already exist. The
strut framework will create only a single instance of each Action class in your
application.

Action are mapped in the struts configuration file and this configuration is loaded into
memory at startup and made available to the framework at runtime. Each Action element
is represented in memory by an instance of the org.apache.struts.action.ActionMapping
class . The ActionMapping object contains a path attribute that is matched against a
portion of the URI of the incoming request.
<action>
path= "/somerequest"
type="com.somepackage.someAction"
scope="request"
name="someForm"
validate="true"
input="somejsp.jsp"
<forward name="Success" path="/action/xys" redirect="true"/>
<forward name="Failure" path="/somejsp.jsp" redirect="true"/>
</action>
Once this is done the controller should determine which view to return to the client. The
execute method signature in Action class has a return type
org.apache.struts.action.ActionForward class. The ActionForward class represents a
destination to which the controller may send control once an action has completed.
Instead of specifying an actual JSP page in the code, you can declaratively associate as
action forward through out the application. The action forward are specified in the
configuration file.
<action>
path= "/somerequest"
type="com.somepackage.someAction"
scope="request"
name="someForm"
validate="true"
input="somejsp.jsp"
<forward name="Success" path="/action/xys" redirect="true"/>
<forward name="Failure" path="/somejsp.jsp" redirect="true"/>
</action>
The action forward mappings also can be specified in a global section, independent of
any specific action mapping.
<global-forwards>
<forward name="Success" path="/action/somejsp.jsp" />
<forward name="Failure" path="/someotherjsp.jsp" />
</global-forwards>

public interface RequestDispatcher

Defines an object that receives requests from the client and sends them to any resource
(such as a servlet, HTML file, or JSP file) on the server. The servlet container creates the
RequestDispatcher object, which is used as a wrapper around a server resource located at
a particular path or given by a particular name.
This interface is intended to wrap servlets, but a servlet container can create
RequestDispatcher objects to wrap any type of resource.

getRequestDispatcher

public RequestDispatcher getRequestDispatcher(java.lang.String path)


Returns a RequestDispatcher object that acts as a wrapper for the resource located at the
given path. A RequestDispatcher object can be used to forward a request to the resource
or to include the resource in a response. The resource can be dynamic or static.
The pathname must begin with a "/" and is interpreted as relative to the current context
root. Use getContext to obtain a RequestDispatcher for resources in foreign contexts.
This method returns null if the ServletContext cannot return a RequestDispatcher.

Parameters:
path - a String specifying the pathname to the resource
Returns:
a RequestDispatcher object that acts as a wrapper for the resource at the
specified path
See Also:
RequestDispatcher, getContext(java.lang.String)

getNamedDispatcher

public RequestDispatcher getNamedDispatcher(java.lang.String name)

Returns a RequestDispatcher object that acts as a wrapper for the named servlet.
Servlets (and JSP pages also) may be given names via server administration or via a web
application deployment descriptor. A servlet instance can determine its name using
ServletConfig.getServletName().
This method returns null if the ServletContext cannot return a RequestDispatcher for any
reason.

Parameters:
name - a String specifying the name of a servlet to wrap
Returns:
a RequestDispatcher object that acts as a wrapper for the named servlet
See Also:
RequestDispatcher, getContext(java.lang.String), ServletConfig.getServletName()

Question: Why cant we overide create method in StatelessSessionBean?


Answer: From the EJB Spec : - A Session bean's home interface defines one or
morecreate(...) methods. Each create method must be named create and must match one
of the ejbCreate methods defined in the enterprise Bean class. The return type of a create
method must be the enterprise Bean's remote interface type. The home interface of a
stateless session bean must have one create method that takes no arguments.
Question: Is struts threadsafe?Give an example?
Answer: 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.

Question: Can we Serialize static variable?


Answer: Serialization is the process of converting a set of object instances that contain
references to each other into a linear stream of bytes, which can then be sent through a
socket, stored to a file, or simply manipulated as a stream of data. Serialization is the
mechanism used by RMI to pass objects between JVMs, either as arguments in a method
invocation from a client to a server or as return values from a method invocation. In the
first section of this book, There are three exceptions in which serialization doesnot
necessarily read and write to the stream. These are
1. Serialization ignores static fields, because they are not part of any particular
object's state.
2. Base class fields are only handled if the base class itself is serializable.
3. Transient fields. There are four basic things you must do when you are making a class
serializable. They are:

1. Implement the Serializable interface.


2. Make sure that instance-level, locally defined state is serialized properly.
3. Make sure that superclass state is serialized properly.
4. Override equals( )and hashCode( ).
it is possible to have control over serialization process. The class should
implement Externalizable interface. This interface contains two methods namely
readExternal and writeExternal. You should implement these methods and write
the logic for customizing the serialization process .... (Source:
http://www.oreilly.com/catalog/javarmi/chapter/ch10.html)

Question: What are the uses of tiles-def.xml file, resourcebundle.properties file,


validation.xml file?
Answer: tiles-def.xml is is an xml file used to configure tiles with the struts application.
You can define the layout / header / footer / body content for your View. See more at
http://www.roseindia.net/struts/using-tiles-defs-xml.shtml.

The resourcebundle.properties file is used to configure the message (error/ other


messages) for the struts applications.

The file validation.xml is used to declare sets of validations that should be applied to
Form Beans. Fpr more information please visit
http://www.roseindia.net/struts/address_struts_validator.shtml.

Question: What is the difference between perform() and execute() methods?


Answer: Perform method is the method which was deprecated in the Struts Version 1.1.
In Struts 1.x, Action.perform() is the method called by the ActionServlet. This is
typically where your business logic resides, or at least the flow control to your JavaBeans
and EJBs that handle your business logic. As we already mentioned, to support
declarative exception handling, the method signature changed in perform. Now execute
just throws Exception. Action.perform() is now deprecated; however, the Struts v1.1
ActionServlet is smart enough to know whether or not it should call perform or execute
in the Action, depending on which one is available.

Question: What are the various Struts tag libraries?


Answer: Struts is very rich framework and it provides very good and user friendly way
to develop web application forms. Struts provide many tag libraries to ease the
development of web applications. These tag libraries are:
* Bean tag library - Tags for accessing JavaBeans and their properties.
* HTML tag library - Tags to output standard HTML, including forms, text boxes,
checkboxes, radio buttons etc..
* Logic tag library - Tags for generating conditional output, iteration capabilities and
flow management
* Tiles or Template tag library - For the application using tiles
* Nested tag library - For using the nested beans in the application

Question: What do you understand by DispatchAction?


Answer: DispatchAction is an action that comes with Struts 1.1 or later, that lets you
combine Struts actions into one class, each with their own method. The
org.apache.struts.action.DispatchAction class allows multiple operation to mapped to the
different functions in the same Action class.
For example:
A package might include separate RegCreate, RegSave, and RegDelete Actions, which
just perform different operations on the same RegBean object. Since all of these
operations are usually handled by the same JSP page, it would be handy to also have
them handled by the same Struts Action.

A very simple way to do this is to have the submit button modify a field in the form
which indicates which operation to perform.

<html:hidden property="dispatch" value="error"/>


<SCRIPT>function set(target)
{document.forms[0].dispatch.value=target;}</SCRIPT>
<html:submit onclick="set('save');">SAVE</html:submit>
<html:submit onclick="set('create');">SAVE AS NEW</html:submitl>
<html:submit onclick="set('delete);">DELETE</html:submit>
Then, in the Action you can setup different methods to handle the different operations,
and branch to one or the other depending on which value is passed in the dispatch field.

String dispatch = myForm.getDispatch();


if ("create".equals(dispatch)) { ...
if ("save".equals(dispatch)) { ...

The Struts Dispatch Action [org.apache.struts.actions] is designed to do exactly the same


thing, but without messy branching logic. The base perform method will check a dispatch
field for you, and invoke the indicated method. The only catch is that the dispatch
methods must use the same signature as perform. This is a very modest requirement,
since in practice you usually end up doing that anyway.

To convert an Action that was switching on a dispatch field to a DispatchAction, you


simply need to create methods like this

public ActionForward create(


ActionMapping mapping,
ActionForm form,
HttpServletRequest request,
HttpServletResponse response)
throws IOException, ServletException { ...

public ActionForward save(


ActionMapping mapping,
ActionForm form,
HttpServletRequest request,
HttpServletResponse response)
throws IOException, ServletException { ...

Cool. But do you have to use a property named dispatch? No, you don't. The only other
step is to specify the name of of the dispatch property as the "parameter" property of the
action-mapping. So a mapping for our example might look like this:

<action
path="/reg/dispatch"
type="app.reg.RegDispatch"
name="regForm"
scope="request"
validate="true"
parameter="dispatch"/>

If you wanted to use the property "o" instead, as in o=create, you would change the
mapping to

<action
path="/reg/dispatch"
type="app.reg.RegDispatch"
name="regForm"
scope="request"
validate="true"
parameter="o"/>

Again, very cool. But why use a JavaScript button in the first place? Why not use several
buttons named "dispatch" and use a different value for each?

You can, but the value of the button is also its label. This means if the page designers
want to label the button something different, they have to coordinate the Action
programmer. Localization becomes virtually impossible. (Source:
http://husted.com/struts/tips/002.html).

Question: How Struts relates to J2EE?


Answer: Struts framework is built on J2EE technologies (JSP, Servlet, Taglibs), but it is
itself not part of the J2EE standard.

Question: What is Struts actions and action mappings?


Answer: A Struts action is an instance of a subclass of an Action class, which
implements a portion of a Web application and whose perform or execute method returns
a forward.

An action can perform tasks such as validating a user name and password.

An action mapping is a configuration file entry that, in general, associates an action name
with an action. An action mapping can contain a reference to a form bean that the action
can use, and can additionally define a list of local forwards that is visible only to this
action.

An action servlet is a servlet that is started by the servlet container of a Web server to
process a request that invokes an action. The servlet receives a forward from the action
and asks the servlet container to pass the request to the forward's URL. An action servlet
must be an instance of an org.apache.struts.action.ActionServlet class or of a subclass of
that class. An action servlet is the primary component of the controller.

Question: Can I setup Apache Struts to use multiple configuration files?


Answer: Yes Struts can use multiple configuration files. Here is the configuration
example:
<servlet>
<servlet-name>banking</servlet-name>
<servlet-class>org.apache.struts.action.ActionServlet
</servlet-class>
<init-param>
<param-name>config</param-name>
<param-value>/WEB-INF/struts-config.xml,
/WEB-INF/struts-authentication.xml,
/WEB-INF/struts-help.xml
</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>

Question: What are the disadvantages of Struts?


Answer: Struts is very robust framework and is being used extensively in the industry.
But there are some disadvantages of the Struts:
a) High Learning Curve
Struts requires lot of efforts to learn and master it. For any small project less experience
developers could spend more time on learning the Struts.

b) Harder to learn
Struts are harder to learn, benchmark and optimize.

Question: What is Struts Flow?


Answer: Struts Flow is a port of Cocoon's Control Flow to Struts to allow complex
workflow, like multi-form wizards, to be easily implemented using continuations-capable
JavaScript. It provides the ability to describe the order of Web pages that have to be sent
to the client, at any given point in time in an application. The code is based on a proof-of-
concept Dave Johnson put together to show how the Control Flow could be extracted
from Cocoon. (Ref: http://struts.sourceforge.net/struts-flow/index.html )

Question: What are the difference between <bean:message> and <bean:write>?


Answer: <bean:message>: This tag is used to output locale-specific text (from the
properties files) from a MessageResources bundle.

<bean:write>: This tag is used to output property values from a bean. <bean:write> is a
commonly used tag which enables the programmers to easily present the data.

Question: What is LookupDispatchAction?


Answer: An abstract Action that dispatches to the subclass mapped execute 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. (Ref.
http://struts.apache.org/1.2.7/api/org/apache/struts/actions/LookupDispatchAction.html).

Question: What are the components of Struts?


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

Question: What are Tag Libraries provided with Struts?


Answer: Struts provides a number of tag libraries that helps to create view components
easily. These tag libraries are:
a) Bean Tags: Bean Tags are used to access the beans and their properties.
b) HTML Tags: HTML Tags provides tags for creating the view components like forms,
buttons, etc..
c) Logic Tags: Logic Tags provides presentation logics that eliminate the need for
scriptlets.
d) Nested Tags: Nested Tags helps to work with the nested context.

Question: What are the core classes of the Struts Framework?


Answer: Core classes of Struts Framework are ActionForm, Action, ActionMapping,
ActionForward, ActionServlet etc.

Question: What are difference between ActionErrors and ActionMessage?


Answer: ActionMessage: A class that encapsulates messages. Messages can be either
global or they are specific to a particular bean property.
Each individual message is described by an ActionMessage object, which contains a
message key (to be looked up in an appropriate message resources database), and up to
four placeholder arguments used for parametric substitution in the resulting message.

ActionErrors: A class that encapsulates the error messages being reported by the
validate() method of an ActionForm. Validation errors are either global to the entire
ActionForm bean they are associated with, or they are specific to a particular bean
property (and, therefore, a particular input field on the corresponding form).

Question: How you will handle exceptions in Struts?


Answer: In Struts you can handle the exceptions in two ways:
a) Declarative Exception Handling: You can either define global exception handling
tags in your struts-config.xml or define the exception handling tags within
<action>..</action> tag.
Example:
<exception

key="database.error.duplicate"

path="/UserExists.jsp"

type="mybank.account.DuplicateUserException"/>

b) Programmatic Exception Handling: Here you can use try{}catch{} block to handle
the exception.
Question: What do you understand by JSP Actions?
Answer: JSP actions are XML tags that direct the server to use existing components or
control the behavior of the JSP engine. JSP Actions consist of a typical (XML-based)
prefix of "jsp" followed by a colon, followed by the action name followed by one or more
attribute parameters.

There are six JSP Actions:

<jsp:include/>

<jsp:forward/>

<jsp:plugin/>

<jsp:usebean/>

<jsp:setProperty/>

<jsp:getProperty/>

Question: What is the difference between <jsp:include page = ... > and
<%@ include file = ... >?.
Answer: Both the tag includes the information from one page in another. The differences
are as follows:
<jsp:include page = ... >: This is like a function call from one jsp to
another jsp. It is executed ( the included page is executed and the
generated html content is included in the content of calling jsp) each
time the client page is accessed by the client. This approach is useful
to for modularizing the web application. If the included file changed
then the new content will be included in the output.

<%@ include file = ... >: In this case the content of the included file
is textually embedded in the page that have <%@ include file="..">
directive. In this case in the included file changes, the changed
content will not included in the output. This approach is used when the
code from one jsp file required to include in multiple jsp files.

Question: What is the difference between <jsp:forward page = ... > and
response.sendRedirect(url),?.
Answer: The <jsp:forward> element forwards the request object containing the client
request information from one JSP file to another file. The target file can be an HTML
file, another JSP file, or a servlet, as long as it is in the same application context as the
forwarding JSP file.
sendRedirect sends HTTP temporary redirect response to the browser, and browser
creates a new request to go the redirected page. The response.sendRedirect kills the
session variables.

Question: Identify the advantages of JSP over Servlet.

a) Embedding of Java code in HTML pages


b) Platform independence
c) Creation of database-driven Web applications
d) Server-side programming capabilities

Answer :- Embedding of Java code in HTML pages

Write the following code for a JSP page:


<%@ page language = "java" %>

<HTML>
<HEAD><TITLE>RESULT PAGE</TITLE></HEAD>
<BODY>
<%

PrintWriter print = request.getWriter();


print.println("Welcome");

%>
</BODY>
</HTML>
Suppose you access this JSP file, Find out your answer.
a) A blank page will be displayed.
b) A page with the text Welcome is displayed
c) An exception will be thrown because the implicit out object is not used
d) An exception will be thrown because PrintWriter can be used in servlets only

Answer :- A page with the text Welcome is displayed

Question: What are implicit Objects available to the JSP Page?


Answer: Implicit objects are the objects available to the JSP page. These objects are
created by Web container and contain information related to a particular request, page, or
application. The JSP implicit objects are:

Variable Class Description


The context for the JSP page's servlet and any Web
application javax.servlet.ServletContext
components contained in the same application.
config javax.servlet.ServletConfig Initialization information for the JSP page's servlet.
exception java.lang.Throwable Accessible only from an error page.
out javax.servlet.jsp.JspWriter The output stream.
The instance of the JSP page's servlet processing the
page java.lang.Object
current request. Not typically used by JSP page authors.
The context for the JSP page. Provides a single API to
pageContext javax.servlet.jsp.PageContext
manage the various scoped attributes.
Subtype of
request The request triggering the execution of the JSP page.
javax.servlet.ServletRequest
Subtype of The response to be returned to the client. Not typically
response
javax.servlet.ServletResponse used by JSP page authors.
session javax.servlet.http.HttpSession The session object for the client.

Question: What are all the different scope values for the <jsp:useBean> tag?
Answer:<jsp:useBean> tag is used to use any java object in the jsp page. Here are the
scope values for <jsp:useBean> tag:
a) page
b) request
c) session and
d) application

Question: What is JSP Output Comments?


Answer: JSP Output Comments are the comments that can be viewed in the HTML
source file.
Example:
<!-- This file displays the user login screen -->
and
<!-- This page was loaded on
<%= (new java.util.Date()).toLocaleString() %> -->

Question: What is expression in JSP?


Answer: Expression tag is used to insert Java values directly into the output. Syntax for
the Expression tag is:
<%= expression %>
An expression tag contains a scripting language expression that is evaluated, converted to
a String, and inserted where the expression appears in the JSP file. The following
expression tag displays time on the output:
<%=new java.util.Date()%>
Question: What types of comments are available in the JSP?
Answer: There are two types of comments are allowed in the JSP. These are hidden and
output comments. A hidden comments does not appear in the generated output in the
html, while output comments appear in the generated output.
Example of hidden comment:
<%-- This is hidden comment --%>
Example of output comment:
<!-- This is output comment -->

Question: What is JSP declaration?


Answer: JSP Decleratives are the JSP tag used to declare variables. Declaratives are
enclosed in the <%! %> tag and ends in semi-colon. You declare variables and functions
in the declaration tag and can use anywhere in the JSP. Here is the example of
declaratives:

<%@page contentType="text/html" %>

<html>

<body>

<%!
int cnt=0;
private int getCount(){
//increment cnt and return the value
cnt++;
return cnt;
}
%>

<p>Values of Cnt are:</p>

<p><%=getCount()%></p>

</body>

</html>

Question: What is JSP Scriptlet?


Answer: JSP Scriptlet is jsp tag which is used to enclose java code in the JSP pages.
Scriptlets begins with <% tag and ends with %> tag. Java code written inside scriptlet
executes every time the JSP is invoked.
Example:
<%
//java codes
String userName=null;
userName=request.getParameter("userName");
%>

Question: What are the life-cycle methods of JSP?


Answer: Life-cycle methods of the JSP are:
a) jspInit(): The container calls the jspInit() to initialize the servlet instance. It is called
before any other method, and is called only once for a servlet instance.
b)_jspService(): The container calls the _jspservice() for each request and it passes the
request and the response objects. _jspService() method cann't be overridden.
c) jspDestroy(): The container calls this when its instance is about to destroyed.
The jspInit() and jspDestroy() methods can be overridden within a JSP page.

Das könnte Ihnen auch gefallen