Professional Documents
Culture Documents
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.
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 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'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.
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.
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.
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 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 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
<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>
<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>
< 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>
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.
/* com/AAction.java */
...
return mapping.findForward("success");
}
}
/* com/BAction.java */
...
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.
int i=1;
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
it's work.
it's work.
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.
* 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".
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.
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.
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.)
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" />
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 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.
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{
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.
Server side validation of form data can be accomplished by subclassing your “form”
Bean with DynaValidatorForm class.
The Validator framework comes integrated with the Struts Framework and
can be used without any making any additional settings.
1) validator-rules.xml and
2) validation.xml.
These are reusable and used in validation.xml to define the form specific validations.
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.
When a client request is sent to the servlet container, how does the container
choose which servlet to invoke?
The servlet container determines which servlet to invoke based on the configuration
of its servlets, and calls it with objects representing the request and response.
Given the request path below, which are context path, servlet path and path
info?
/bookstore/education/index.html
When using servlets to build the HTML, you build a DOCTYPE line, why do
you do that?
I know all major browsers ignore it even though the HTML 3.2 and 4.0 specifications
require it. But building a DOCTYPE line tells HTML validators which version of
HTML you are using so they know which specification to check your document
against. These validators are valuable debugging services, helping you catch HTML
syntax errors.
How can I send user authentication information while making URL Connection?
How can a servlet refresh automatically if some new data has entered the
database?
You can use a client-side Refresh or Server Push
The code in a finally clause will never fail to execute, right?
Using System.exit(1); in try block will not allow finally code to execute.
In POST Your name/value pairs inside the body of the HTTP request, which makes
for a cleaner URL and imposes no size limitations on the form's output. It is used to
send a chunk of data to the server to be processed, more versatile, most secure.
What is session?
The session is an object used by a servlet to track a user's interaction with a Web
application across multiple HTTP requests.
Loaded(by the container for first request or on start up if config file suggests load-on-
startup), initialized( using init()), service(service() or doGet() or doPost()..),
destroy(destroy()) and unloaded.
When is the servlet instance created in the life cycle of servlet? What is the
importance of configuring a servlet?
An instance of servlet is created when the servlet is loaded for the first time in the
container. Init() method is used to configure this servlet instance. This method is
called only once in the life time of a servlet, hence it makes sense to write all those
configuration details about a servlet which are required for the whole life of a servlet
in this method.
When we don't write any constructor for the servlet, how does container create
an instance of servlet?
Container creates instance of servlet by calling
Class.forName(className).newInstance().
Once the destroy() method is called by the container, will the servlet be
immediately destroyed? What happens to the tasks(threads) that the servlet
might be executing at that time?
Yes, but Before calling the destroy() method, the servlet container waits for the
remaining threads that are executing the servlet’s service() method to finish.
Example :
<hibernate-mapping>
<class name=”com.test.User” table=”user”>
<property column=”USER_NAME” length=”255″
name=”userName” not-null=”true” type=”java.lang.String”/>
<property column=”USER_PASSWORD” length=”255″
name=”userPassword” not-null=”true” type=”java.lang.String”/>
</class>
</hibernate-mapping>
load() :-
Only use the load() method if you are sure that the object exists.
load() method will throw an exception if the unique id is not found in the database.
load() just returns a proxy by default and database won’t be hit until the proxy is
first invoked.
get():-
If you are not sure that the object exists, then use one of the get() methods.
get() method will return null if the unique id is not found in the database.
get() will hit the database immediately.
Q) Define HibernateTemplate?
A) org.springframework.orm.hibernate.HibernateTemplate is a helper class which
provides different methods for querying/retrieving data from the database. It also
converts checked HibernateExceptions into unchecked DataAccessExceptions.
Q) If you want to see the Hibernate generated SQL statements on console, what
should we do?
A) In Hibernate configuration file set as follows:
<property name=”show_sql”>true</property>
order collection :-
Order collection is sorting a collection by specifying the order-by clause for sorting
this collection when retrieval.
If your collection is very large, it will be more efficient way to sort it .