Beruflich Dokumente
Kultur Dokumente
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.
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.
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.
with struts 1.1 , struts-legacy.jar is necessy for this codes.
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.
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" />
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.
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.
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.
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" />
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;
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. 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.
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
<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>
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
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
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()
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.
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.
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).
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.
b) Harder to learn
Struts are harder to learn, benchmark and optimize.
<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.
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).
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.
<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.
<HTML>
<HEAD><TITLE>RESULT PAGE</TITLE></HEAD>
<BODY>
<%
%>
</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
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
<html>
<body>
<%!
int cnt=0;
private int getCount(){
//increment cnt and return the value
cnt++;
return cnt;
}
%>
<p><%=getCount()%></p>
</body>
</html>