Struts Interview Questions with Answers Page II
From freshersonline.com
1. 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.
2. 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.
3. 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".
4. 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.
5. 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.
6. 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.
7. 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.
8. 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.
9. 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
$@
10. 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.
11. 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.)
12. 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.
13. What's the difference between Struts and Turbine? What's the difference between Struts and Expresso?
If you are starting from scratch, packages like Turbine and Expresso 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 Expresso (which uses Struts) are perfectly good ways to go.
See also
14. 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.
15. 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).
16. 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.
17. 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 implementation 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.
18. 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.
19. 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.
20.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.
21. 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.
22. 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
23. 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.
24. 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
25. 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.
26. 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.
27. 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.
28. 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.
Here is a link which utilizes the LookupDispatch action to submit forms with multiple actions without javascript: http://husted.com/struts/tips/003.html
29. 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.
30. 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.
