Escolar Documentos
Profissional Documentos
Cultura Documentos
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.
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.)
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.
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.
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");
}
}
...
<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
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) {
}
it's work.
it's work.
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.
* 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.
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.
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 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.
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.
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.
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.