SlideShare une entreprise Scribd logo
1  sur  35
CP237
Java Programming II
Jakarta Struts
•   Introduction
•   Struts Architecture
•   Installing Struts
•   Action Form
•   Action Servlet
•   struts_config.xml
•   Custom tags
What is Struts?
There are several different ways of looking at Struts. The three main ways are
that Struts is:

An MVC Framework.
Struts provides a unified framework for deploying servlet and JSP applications
that use the MVC architecture.

A Collection of Utilities.
Struts provides utility classes to handle many of the most common tasks in Web
application development

A Set of JSP Custom Tag Libraries.
Struts provides custom tag libraries for outputting bean properties, generating
HTML forms, iterating over various types of data structures, and conditionally
outputting HTML.
Struts Framework
Installing Struts
Download the Struts zip file.
Start at http://jakarta.apache.org/site/binindex.cgi, or follow the link from http://
jakarta.apache.org/struts/.

Unzip into a directory of your choice.
For example, unzip into C:jakarta-struts. This is refered to as the
struts_install_dir.

Update your CLASSPATH.
Add struts_install_dir/lib/struts.jar to the CLASSPATH used by your compiler or
IDE (not your server). Here are three possible ways of setting it:

Set it in your autoexec.bat file. E.g., on Windows if you unzipped into
C:jakarta-struts-1.1, you would add the following to C:autoexec.bat:

set CLASSPATH=C:jakarta-strutslibstruts.jar;%CLASSPATH%
On Unix/Linux, use your .cshrc, .bashrc, or .profile instead.
Installing Struts
Set it using the system settings. On WinXP, go to the Start menu and select
Control Panel, then System, then the Advanced tab, then the Environment
Variables button. On Win2K/WinNT, go to the Start menu and select Settings,
then Control Panel, then System, then Environment. Either way, enter the
CLASSPATH value from the previous bullet.

Set it in your editor or IDE. Most IDEs have a way of specifying the JAR files
needed to compile projects. Or, you could make a small .bat file (Windows) or
shell script (Unix/Linux) that supplies the struts.jar file as the argument to
-classpath for javac.

Install an XML parser.
If you have JDK 1.4 or Apache Tomcat, this step is not necessary, since they
already come with an XML parser. But, if you use JDK 1.2 or 1.3 with another
server, you might need to obtain the XML parsing libraries. Here are two good
sources:
http://xml.apache.org/
http://java.sun.com/xml/
Installing Struts
• Download from jakarta web site
• Get the appropriate operating system
  download
• Uncompress the downloaded file
• Copy all of the *.war files from the
  downloaded directory to your Tomcat
  webapps directory
• Start tomcat
• Enter: http://localhost:8080/struts_blank
Struts *.war files
Found in the following installation directory:
      struts-1.2.7webapps
•   struts-blank.war
•   struts-documentation.war
•   struts-examples.war
•   struts-mailreader.war
•   tiles-documentation.war
Struts.jar
• Be sure to place the struts.jar into your
  JS2E_HOMEjrelibext directory
Testing Struts
Install struts-blank.war.
Install the Web application from struts_install_dir/webapps/struts-blank.war on
your server. For example, with Apache Tomcat, copy struts_install_dir/webapps/
struts-blank.war to tomcat_install_dir/webapps/.

Start or restart the server.
Most servers only recognize new Web apps when the server is started.

Access http://localhost/struts-blank/.
This URL assumes you are running the server on your desktop and are using
port 80. In general, access http://hostname:port/struts-blank/. You should see
something like the following.
Struts Install Successful
Setting Up Struts Applications
To make your own Struts application, you need to create a Web application that
has the appropriate JAR files, TLD files, and web.xml entries. You almost
always do this by starting with the struts-blank application and modifying it. You
have three options for doing this:

Option 1 (Good): Copy/rename the struts-blank directory to your
development directory.
When you tested your Struts installation, you ran the struts-blank Web app.
When you did so, Tomcat and most other servers unpacked the struts-blank.war
file into the struts-blank directory. So, copy that directory to whatever location
you use for developing custom Web applications, and rename it to whatever app
name you choose. For example, if you are using Tomcat and devel_dir is the
location you use for development, copy the tomcat_install_dir/webapps/struts-
blank directory to devel_dir, rename it to struts-test, resulting in devel_dir/struts-
test.
Setting Up Struts Applications
Option 2 (Good): Unjar struts-blank.war into your development directory.
If your server doesn't automatically unpack WAR files, then even if you ran the
struts-blank test described above, you have no regular directory to work with.
Besides, some people prefer to unpack the WAR file themselves anyhow. To
do so:
     Copy struts_install_dir/webapps/struts-blank.war to your development
     directory.
     Make a new directory (e.g., called struts-test).
     Unjar struts-blank.war into that directory You can use jar -xvf or a
     standard zip tool like WinZip or the Windows XP explorer.
     Whenever you want to test your application, copy struts-test to the
     server's Web application autodeploy directory (e.g., onto the shortcut to
     tomcat_install_dir/webapps).
Setting Up Struts Applications
Option 3 (Bad): Rename struts-blank and leave it in the server's
deployment directory.
It is quite common to work directly in server's deployment directory (e.g., to
work directly in tomcat_install_dir/webapps/struts-test). However, this
approach scales poorly to real applications, makes it harder to test changes
(you have no stable working version), and doesn't support your "real"
deployment server anyhow (which is almost certainly not your desktop
machine). If you don't have a good deployment system using your IDE or ant
scripts, you can easily make a shortcut (Windows) or symbolic link (Unix/Linux)
to the server's autodeploy directory, and just copy the Web app onto the
shortcut each time. For example, suppose you are using Tomcat on Windows.
To easily develop in one directory and then deploy in another, just do this:
Grab tomcat_install_dir/webapps with your right mouse, drag it into devel_dir,
release, and choose "Create Shortcut Here".
Create struts-test or other applications as subdirectories within devel_dir, as
described above.
Deploy by using the right mouse to drag struts-test onto the shortcut from step
1, releasing, and choosing "Copy".
Adding Struts to an Existing Web
             Application
By far the easiest way to develop a Struts application is to start with struts-blank, rename
it, and work from there. if you already have an existing Web application and want to add
Struts capabilities to it, starting with struts-blank won't work. Adding Struts capabilities to
existing Web apps is a huge pain in the neck, and will probably require several attempts
to get it right. Here is a quick summary:
Copy JAR files from struts-blank/WEB-INF/lib to your_web_app/WEB-INF/lib.
Copy TLD files from struts-blank/WEB-INF to your_web_app/WEB-INF.
Copy struts-config.xml from struts-blank/WEB-INF to your_web_app/WEB-INF.
Copy the application properties file from struts-blank/WEB-INF/classes/resources to
your_web_app/WEB-INF/classes/resources.
If you plan on using the automatic validator (see Section 5, Validating User Input), copy
validation.xml and validator-rules.xml from struts-blank/WEB-INF to your_web_app/WEB-
INF.
If you plan on using Tiles (see Section 6, Composing Pages with Tiles), copy struts-
tiles.xml from struts-blank/WEB-INF to your_web_app/WEB-INF.
Copy declarations out of struts-blank/WEB-INF/web.xml into your_web_app/WEB-
INF/web.xml. Most importantly, copy the servlet and servlet-mapping entries that map
blah.do to org.apache.struts.action.ActionServlet. Be sure you keep the entries in the
same locations: the order of elements in web.xml matters.
Accessing Struts Documentation
You probably already have bookmarked the APIs for standard Java, servlets,
and JSP. But you will also want to frequently refer to the Apache Struts
documentation. You can do this two ways:

Read a local copy.
This is fastest, but the documentation can get a bit out of date. To read a local
copy, install the struts-documentation.war Web app. For example, if you are
using Apache Tomcat on port 80 on your local machine, copy struts_install_dir/
webapps/struts-documentation.war to tomcat_install_dir/webapps, restart
server, and use the URL http://localhost/struts-documentation/.
Read it from the Apache site.

This option is slower, but guarantees that you get the latest versions of the
documentation. To read the online version of the documentation, start at http://
jakarta.apache.org/struts/learning.html. The documentation includes FAQs,
user guides, tutorials, and the API in Javadoc format.
The Six Basic Steps in Using
              Jakarta Struts
With Struts, the normal processing flow is that a form submits data to a URL of
the form blah.do. That address is mapped by struts-config.xml to an Action
object, whose execute method handles the request.
One of the arguments to execute is a form bean that is automatically created
and whose properties are automatically populated with the incoming form data.
The Action object then invokes business logic and data-access logic, placing
the results in normal beans stored in request, session, or application scope.
The Action uses mapping.findForward to return a condition, and the conditions
are mapped by struts-config.xml to various JSP pages. The system forwards
the request to the appropriate JSP page, where the bean:write tag is used to
output properties of the form bean and results beans.
Optionally, both the input form and the final JSP pages can use bean:message
to output standard messages and labels as defined in a system property file.
The Six Basic Steps in Using
               Jakarta Struts
Here are the minimum steps needed to create an application that follows this
   process. This set of slides will focus on the basic flow and the Action
   objects; the next set of slides will show how to use beans.

Modify struts-config.xml.
   Use WEB-INF/struts-config.xml to:
    Designate Action classes to handle requests for blah.do.
    Specify the URLs that apply in various situations.
    Declare any form beans that are being used.
Be sure to restart the server after modifying struts-config.xml; the file is read
   only when the Web application is first loaded.

Define a form bean.
   This bean is a class the extends ActionForm and will represent the data
   submitted by the user. It is automatically populated when the input form is
   submitted. Beans will be discussed in the next set of slides.
The Six Basic Steps in Using
               Jakarta Struts
Create results beans.
In the MVC architecture, the business-logic and data-access code create the
results and the JSP pages present them. To transfer the results from one layer to
the other, they are stored in beans. These beans differ from form beans in that
they need extend no particular class, and they represent the output of the
computational process, not the input to the process. Beans will be discussed in
the next set of slides

Create an Action object to handle requests.
The struts-config.xml file designates the Action object that handles requests for
various URLs. The Action objects themselves need to do the real work: invoke
the appropriate business- and data-access-logic, store the results in beans, and
designate the type of situation (missing data, database error, success category
         1, success category

         2, etc.) that is appropriate for the results. The struts-config.xml file then
         decides which JSP page should apply to that situation.
The Six Basic Steps in Using
                Jakarta Struts
Create form that invokes blah.do.
You need to create an input form whose ACTION corresponds to one of the *.do addresses
listed in struts-config.xml. At a minimum, the input form should look like this:
    <FORM ACTION=".../blah.do" ...>...</FORM>
However, in future slides we will discuss the advantages of using the Struts html:form tag
to build this input form.

Display results in JSP.
Since Struts is built around the MVC architecture, these JSP pages should avoid JSP
scripting elements whenever possible. For basic Struts, these JSP pages usually use the
Struts bean:write tag, but in JSP 2.0 the JSP 2.0 expression language is a viable
alternative. In complex cases, the JSP pages also use the JSP Standard Tag Library
(JSTL) or the Struts looping/logic tags.

In most cases, the JSP pages only make sense when the request is funneled through the
Action, since it is the Action that invokes the logic that creates the data that the JSP pages
will display. So, the JSP pages are placed in WEB-INF, where RequestDispatcher can
forward to them but where clients cannot access them directly. If the JSP pages makes
sense independently of the Action (e.g., if they display session data), then the JSP pages
should be placed in a regular subdirectory of the Web application, and the forward entries
in struts-config.xml should say <forward ... redirect="true"/>.
Let’s do a simple example…
In this example, the URL http://hostname/struts-test/actions/register1.do
should be handled by the class RegisterAction1 (which extends Action
class). RegisterAction1 always returns "success", and this return value
results in the JSP page /WEB-INF/results/result1.jsp being displayed to
the client.
Registration Example
Modify struts-config.xml.
Use WEB-INF/struts-config.xml to:
Designate Action classes to handle requests for blah.do. In this case, we designate that
RegisterAction1 should handle requests for /actions/register1.do (notice that .do is implied
automatically). To accomplish this, we add an action entry to action-mappings, where action has the
following attributes.

     path: the relative path that should be mapped to the Action, minus the .do extension. Thus,
     path="/actions/register1" refers to http://hostname/webAppName/actions/register1.do. See
     this section for a discussion of why it is useful to use /actions/register1 instead of just register1 in
     the path.

     type: the fully qualified class name of the Action object that should be invoked when a request for
     the specified path is received.

       name, scope, and input: these attributes are omitted in this example, but are used in later
       examples when beans are used.
In this case, the action element looks like this:
<action path="/actions/register1"
      type="coreservlets.RegisterAction1">
  ...
</action>
Specify the URLs that apply in various situations. In this case, we use the forward element to say that
result1.jsp applies when RegisterAction1 returns "success", as follows:
<forward name="success"
       path="/WEB-INF/results/result1.jsp"/>
Modify struts-config.xml
Modify struts-config.xml.
Use WEB-INF/struts-config.xml to:
Designate Action classes to handle requests for blah.do. In this case, we
designate that RegisterAction1 should handle requests for /actions/register1.do
(notice that .do is implied automatically). To accomplish this, we add an action
entry to action-mappings, where action has the following attributes.

    path: the relative path that should be mapped to the Action, minus the .do
    extension. Thus, path="/actions/register1" refers to
    http://hostname/webAppName/actions/register1.do. See this section for a
    discussion of why it is useful to use /actions/register1 instead of just
    register1 in the path.

    type: the fully qualified class name of the Action object that should be
    invoked when a request for the specified path is received.

    name, scope, and input: these attributes are omitted in this example, but
    are used in later examples when beans are used.
Modify struts-config.xml
Register example
Define a form bean.
Beans are postponed, so this step is omitted for now.


Create results beans.
Beans are postponed, so this step is omitted for now.
Create an Action object to
             handle requests
In general, your Action subclass should:

Use a package. In this case, we have
package coreservlets;
This means that the class file should go in your_web_app/WEB-
INF/classes/coreservlets/.

Add Struts-specific import statements to whatever imports are otherwise
needed. In this case, we have
import javax.servlet.http.*;
import org.apache.struts.action.*; (this is why you need to be sure that you
have the struts.jar file in your J2SEjrelibext directory

Extend the Action class. In this case, we have
public class RegisterAction1 extends Action {...}
Create an Action object to
             handle requests
Override the execute method. This method is defined as follows.
 public ActionForward execute(ActionMapping mapping,
                 ActionForm form,
                 HttpServletRequest request,
                 HttpServletResponse response)
    throws Exception {
  ...
  }

Return mapping.findForward. The execute method should have one or more return
values. These values will then be mapped to specific JSP pages by forward entries
in struts-config.xml. In this case, we simply return "success" in all situations.
 public ActionForward execute(ActionMapping mapping,
                   ActionForm form,
                   HttpServletRequest request,
                   HttpServletResponse response)
    throws Exception {
   return(mapping.findForward("success"));
 }
RegisterAction1.java
register1.jsp
Create form that invokes blah.do.


In this case, we need an HTML form that invokes http://hostname/struts-test/
actions/register1.do. We place the HTML form in the forms subdirectory and
use a relative URL for the ACTION as follows.
                    register1.jsp (Excerpt)
URL Design Strategy
Display results in JSP
In general, there can be several possible JSP pages corresponding to the
various possible return values of the execute method of the Action. In struts-
config.xml, each JSP page is declared in a forward entry within the appropriate
action. In this simple case, the only return value is "success", so /WEB-
INF/results/result1.jsp is used in all cases. This JSP page displays a simple
message, as shown below In general, there can be several possible JSP pages
corresponding to the various possible return values of the execute method of the
Action. In struts-config.xml, each JSP page is declared in a forward entry within
the appropriate action. In this simple case, the only return value is "success", so /
WEB-INF/results/result1.jsp is used in all cases. This JSP page displays a simple
message, as shown on the next slide.
result1.jsp
Executing the Form
Executing the Form

This form is then filled in and submitted, with the form's ACTION resulting in the
URL http://localhost/struts-test/actions/register1.do. This address is mapped by
struts-config.xml to the RegisterAction1 class, whose execute method is
invoked. This method returns a mapping.findForward with a value of "success",
and that value is mapped by struts-config.xml to /WEB-INF/results/result1.jsp,
which is the final result displayed to the user. However, since the JSP page is
invoked with RequestDispatcher.forward, not response.sendRedirect, the URL
displayed to the user is register1.do, not result1.jsp. See the following screen
shot.
Final Result

Contenu connexe

En vedette

Dual Gravitons in AdS4/CFT3 and the Holographic Cotton Tensor
Dual Gravitons in AdS4/CFT3 and the Holographic Cotton TensorDual Gravitons in AdS4/CFT3 and the Holographic Cotton Tensor
Dual Gravitons in AdS4/CFT3 and the Holographic Cotton TensorSebastian De Haro
 
3 hendy ifa prague - older drivers and rights
3 hendy ifa prague - older drivers and rights3 hendy ifa prague - older drivers and rights
3 hendy ifa prague - older drivers and rightsifa2012_2
 
Mobile Lessons From Around The World | Somo Webinar
Mobile Lessons From Around The World | Somo WebinarMobile Lessons From Around The World | Somo Webinar
Mobile Lessons From Around The World | Somo WebinarSomo
 
Monica andrea recetor1
Monica andrea recetor1Monica andrea recetor1
Monica andrea recetor1klaumilenitha
 
Mobile, have you clicked you clicked yet?
Mobile, have you clicked you clicked yet?Mobile, have you clicked you clicked yet?
Mobile, have you clicked you clicked yet?Textlocal Ltd
 
SHARON GOMEZ MI SUPER HISTORIA
SHARON GOMEZ  MI SUPER HISTORIASHARON GOMEZ  MI SUPER HISTORIA
SHARON GOMEZ MI SUPER HISTORIAklaumilenitha
 
2 szeman-family strategies-role of ict eng
2 szeman-family strategies-role of ict eng2 szeman-family strategies-role of ict eng
2 szeman-family strategies-role of ict engifa2012_2
 
3 cheallaigh--new-older learners & lll ifa300512
3  cheallaigh--new-older learners & lll ifa3005123  cheallaigh--new-older learners & lll ifa300512
3 cheallaigh--new-older learners & lll ifa300512ifa2012_2
 
“Man Can be destroy not defeated”- How it proved Wrong in mourning becomes E...
“Man Can be destroy not defeated”-  How it proved Wrong in mourning becomes E...“Man Can be destroy not defeated”-  How it proved Wrong in mourning becomes E...
“Man Can be destroy not defeated”- How it proved Wrong in mourning becomes E...bhavnabaraiya
 
INTEGRATE 2016 - Julie Link & Greg Stroud
INTEGRATE 2016 - Julie Link & Greg Stroud INTEGRATE 2016 - Julie Link & Greg Stroud
INTEGRATE 2016 - Julie Link & Greg Stroud IMCWVU
 
Tito, marina, carlos and maira (1)
Tito, marina, carlos and maira (1)Tito, marina, carlos and maira (1)
Tito, marina, carlos and maira (1)Amos Shacham
 
AHNS- Soroush Zaghi- Dysphagia
AHNS- Soroush Zaghi- DysphagiaAHNS- Soroush Zaghi- Dysphagia
AHNS- Soroush Zaghi- Dysphagiaszaghi
 
3 celdrán-generatividad ifa praga
3 celdrán-generatividad ifa praga3 celdrán-generatividad ifa praga
3 celdrán-generatividad ifa pragaifa2012_2
 
Duality in AdS/CFT, Chicago 7 Nov. 2014
Duality in AdS/CFT, Chicago 7 Nov. 2014Duality in AdS/CFT, Chicago 7 Nov. 2014
Duality in AdS/CFT, Chicago 7 Nov. 2014Sebastian De Haro
 
3 fadayvatan-easy care in iran, prague 2012
3  fadayvatan-easy care in iran, prague 20123  fadayvatan-easy care in iran, prague 2012
3 fadayvatan-easy care in iran, prague 2012ifa2012_2
 

En vedette (20)

Dual Gravitons in AdS4/CFT3 and the Holographic Cotton Tensor
Dual Gravitons in AdS4/CFT3 and the Holographic Cotton TensorDual Gravitons in AdS4/CFT3 and the Holographic Cotton Tensor
Dual Gravitons in AdS4/CFT3 and the Holographic Cotton Tensor
 
3 hendy ifa prague - older drivers and rights
3 hendy ifa prague - older drivers and rights3 hendy ifa prague - older drivers and rights
3 hendy ifa prague - older drivers and rights
 
Mobile Lessons From Around The World | Somo Webinar
Mobile Lessons From Around The World | Somo WebinarMobile Lessons From Around The World | Somo Webinar
Mobile Lessons From Around The World | Somo Webinar
 
Hb Services .net ieee project 2015 - 16
Hb Services .net ieee project 2015 - 16Hb Services .net ieee project 2015 - 16
Hb Services .net ieee project 2015 - 16
 
Thu thuat seo
Thu thuat seoThu thuat seo
Thu thuat seo
 
Monica andrea recetor1
Monica andrea recetor1Monica andrea recetor1
Monica andrea recetor1
 
Mobile, have you clicked you clicked yet?
Mobile, have you clicked you clicked yet?Mobile, have you clicked you clicked yet?
Mobile, have you clicked you clicked yet?
 
SHARON GOMEZ MI SUPER HISTORIA
SHARON GOMEZ  MI SUPER HISTORIASHARON GOMEZ  MI SUPER HISTORIA
SHARON GOMEZ MI SUPER HISTORIA
 
Brayan piñeros2
Brayan piñeros2Brayan piñeros2
Brayan piñeros2
 
2 szeman-family strategies-role of ict eng
2 szeman-family strategies-role of ict eng2 szeman-family strategies-role of ict eng
2 szeman-family strategies-role of ict eng
 
3 cheallaigh--new-older learners & lll ifa300512
3  cheallaigh--new-older learners & lll ifa3005123  cheallaigh--new-older learners & lll ifa300512
3 cheallaigh--new-older learners & lll ifa300512
 
Hb services .net application 2015 16
Hb services .net application 2015 16Hb services .net application 2015 16
Hb services .net application 2015 16
 
Dagoberto lara
Dagoberto laraDagoberto lara
Dagoberto lara
 
“Man Can be destroy not defeated”- How it proved Wrong in mourning becomes E...
“Man Can be destroy not defeated”-  How it proved Wrong in mourning becomes E...“Man Can be destroy not defeated”-  How it proved Wrong in mourning becomes E...
“Man Can be destroy not defeated”- How it proved Wrong in mourning becomes E...
 
INTEGRATE 2016 - Julie Link & Greg Stroud
INTEGRATE 2016 - Julie Link & Greg Stroud INTEGRATE 2016 - Julie Link & Greg Stroud
INTEGRATE 2016 - Julie Link & Greg Stroud
 
Tito, marina, carlos and maira (1)
Tito, marina, carlos and maira (1)Tito, marina, carlos and maira (1)
Tito, marina, carlos and maira (1)
 
AHNS- Soroush Zaghi- Dysphagia
AHNS- Soroush Zaghi- DysphagiaAHNS- Soroush Zaghi- Dysphagia
AHNS- Soroush Zaghi- Dysphagia
 
3 celdrán-generatividad ifa praga
3 celdrán-generatividad ifa praga3 celdrán-generatividad ifa praga
3 celdrán-generatividad ifa praga
 
Duality in AdS/CFT, Chicago 7 Nov. 2014
Duality in AdS/CFT, Chicago 7 Nov. 2014Duality in AdS/CFT, Chicago 7 Nov. 2014
Duality in AdS/CFT, Chicago 7 Nov. 2014
 
3 fadayvatan-easy care in iran, prague 2012
3  fadayvatan-easy care in iran, prague 20123  fadayvatan-easy care in iran, prague 2012
3 fadayvatan-easy care in iran, prague 2012
 

Similaire à Java Struts Framework

Struts2 tutorial
Struts2 tutorialStruts2 tutorial
Struts2 tutorializdihara
 
Apache Tomcat 8 Application Server
Apache Tomcat 8 Application ServerApache Tomcat 8 Application Server
Apache Tomcat 8 Application Servermohamedmoharam
 
Spring Live Sample Chapter
Spring Live Sample ChapterSpring Live Sample Chapter
Spring Live Sample ChapterSyed Shahul
 
StreamSets DataOps Platform Fundamentals.pptx
StreamSets DataOps Platform Fundamentals.pptxStreamSets DataOps Platform Fundamentals.pptx
StreamSets DataOps Platform Fundamentals.pptxssuser4c04eb
 
Development Setup of B-Translator
Development Setup of B-TranslatorDevelopment Setup of B-Translator
Development Setup of B-TranslatorDashamir Hoxha
 
Exploit Frameworks
Exploit FrameworksExploit Frameworks
Exploit Frameworksphanleson
 
C# and Borland StarTeam Connectivity
C# and Borland StarTeam ConnectivityC# and Borland StarTeam Connectivity
C# and Borland StarTeam ConnectivityShreesha Rao
 
[xp2013] Narrow Down What to Test
[xp2013] Narrow Down What to Test[xp2013] Narrow Down What to Test
[xp2013] Narrow Down What to TestZsolt Fabok
 
Creating your own AtoM demo data set for re-use with Vagrant
Creating your own AtoM demo data set for re-use with VagrantCreating your own AtoM demo data set for re-use with Vagrant
Creating your own AtoM demo data set for re-use with VagrantArtefactual Systems - AtoM
 
Orangescrum In App Chat Add-on User Manual
Orangescrum In App Chat Add-on User ManualOrangescrum In App Chat Add-on User Manual
Orangescrum In App Chat Add-on User ManualOrangescrum
 
Selenium-Browser-Based-Automated-Testing-for-Grails-Apps
Selenium-Browser-Based-Automated-Testing-for-Grails-AppsSelenium-Browser-Based-Automated-Testing-for-Grails-Apps
Selenium-Browser-Based-Automated-Testing-for-Grails-Appschrisb206 chrisb206
 
Web Applications and Deployment
Web Applications and DeploymentWeb Applications and Deployment
Web Applications and DeploymentBG Java EE Course
 
Apache Traffic Server
Apache Traffic ServerApache Traffic Server
Apache Traffic Serversupertom
 
Building a Gateway Server
Building a Gateway ServerBuilding a Gateway Server
Building a Gateway ServerDashamir Hoxha
 

Similaire à Java Struts Framework (20)

Struts2 tutorial
Struts2 tutorialStruts2 tutorial
Struts2 tutorial
 
Struts2 tutorial
Struts2 tutorialStruts2 tutorial
Struts2 tutorial
 
Mc sl54 051_ (1)
Mc sl54 051_ (1)Mc sl54 051_ (1)
Mc sl54 051_ (1)
 
Apache Tomcat 8 Application Server
Apache Tomcat 8 Application ServerApache Tomcat 8 Application Server
Apache Tomcat 8 Application Server
 
Spring Live Sample Chapter
Spring Live Sample ChapterSpring Live Sample Chapter
Spring Live Sample Chapter
 
StreamSets DataOps Platform Fundamentals.pptx
StreamSets DataOps Platform Fundamentals.pptxStreamSets DataOps Platform Fundamentals.pptx
StreamSets DataOps Platform Fundamentals.pptx
 
Team lab install_en
Team lab install_enTeam lab install_en
Team lab install_en
 
Development Setup of B-Translator
Development Setup of B-TranslatorDevelopment Setup of B-Translator
Development Setup of B-Translator
 
Exploit Frameworks
Exploit FrameworksExploit Frameworks
Exploit Frameworks
 
C# and Borland StarTeam Connectivity
C# and Borland StarTeam ConnectivityC# and Borland StarTeam Connectivity
C# and Borland StarTeam Connectivity
 
bjhbj
bjhbjbjhbj
bjhbj
 
[xp2013] Narrow Down What to Test
[xp2013] Narrow Down What to Test[xp2013] Narrow Down What to Test
[xp2013] Narrow Down What to Test
 
Creating your own AtoM demo data set for re-use with Vagrant
Creating your own AtoM demo data set for re-use with VagrantCreating your own AtoM demo data set for re-use with Vagrant
Creating your own AtoM demo data set for re-use with Vagrant
 
Orangescrum In App Chat Add-on User Manual
Orangescrum In App Chat Add-on User ManualOrangescrum In App Chat Add-on User Manual
Orangescrum In App Chat Add-on User Manual
 
Selenium-Browser-Based-Automated-Testing-for-Grails-Apps
Selenium-Browser-Based-Automated-Testing-for-Grails-AppsSelenium-Browser-Based-Automated-Testing-for-Grails-Apps
Selenium-Browser-Based-Automated-Testing-for-Grails-Apps
 
Tomcat tutorail
Tomcat tutorailTomcat tutorail
Tomcat tutorail
 
Web Applications and Deployment
Web Applications and DeploymentWeb Applications and Deployment
Web Applications and Deployment
 
Apache Traffic Server
Apache Traffic ServerApache Traffic Server
Apache Traffic Server
 
Gwt portlet
Gwt portletGwt portlet
Gwt portlet
 
Building a Gateway Server
Building a Gateway ServerBuilding a Gateway Server
Building a Gateway Server
 

Dernier

Virtual-Orientation-on-the-Administration-of-NATG12-NATG6-and-ELLNA.pdf
Virtual-Orientation-on-the-Administration-of-NATG12-NATG6-and-ELLNA.pdfVirtual-Orientation-on-the-Administration-of-NATG12-NATG6-and-ELLNA.pdf
Virtual-Orientation-on-the-Administration-of-NATG12-NATG6-and-ELLNA.pdfErwinPantujan2
 
What is Model Inheritance in Odoo 17 ERP
What is Model Inheritance in Odoo 17 ERPWhat is Model Inheritance in Odoo 17 ERP
What is Model Inheritance in Odoo 17 ERPCeline George
 
How to Add Barcode on PDF Report in Odoo 17
How to Add Barcode on PDF Report in Odoo 17How to Add Barcode on PDF Report in Odoo 17
How to Add Barcode on PDF Report in Odoo 17Celine George
 
How to do quick user assign in kanban in Odoo 17 ERP
How to do quick user assign in kanban in Odoo 17 ERPHow to do quick user assign in kanban in Odoo 17 ERP
How to do quick user assign in kanban in Odoo 17 ERPCeline George
 
Earth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice greatEarth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice greatYousafMalik24
 
Global Lehigh Strategic Initiatives (without descriptions)
Global Lehigh Strategic Initiatives (without descriptions)Global Lehigh Strategic Initiatives (without descriptions)
Global Lehigh Strategic Initiatives (without descriptions)cama23
 
Transaction Management in Database Management System
Transaction Management in Database Management SystemTransaction Management in Database Management System
Transaction Management in Database Management SystemChristalin Nelson
 
Food processing presentation for bsc agriculture hons
Food processing presentation for bsc agriculture honsFood processing presentation for bsc agriculture hons
Food processing presentation for bsc agriculture honsManeerUddin
 
GRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTS
GRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTSGRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTS
GRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTSJoshuaGantuangco2
 
4.16.24 21st Century Movements for Black Lives.pptx
4.16.24 21st Century Movements for Black Lives.pptx4.16.24 21st Century Movements for Black Lives.pptx
4.16.24 21st Century Movements for Black Lives.pptxmary850239
 
USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...
USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...
USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...Postal Advocate Inc.
 
Field Attribute Index Feature in Odoo 17
Field Attribute Index Feature in Odoo 17Field Attribute Index Feature in Odoo 17
Field Attribute Index Feature in Odoo 17Celine George
 
Keynote by Prof. Wurzer at Nordex about IP-design
Keynote by Prof. Wurzer at Nordex about IP-designKeynote by Prof. Wurzer at Nordex about IP-design
Keynote by Prof. Wurzer at Nordex about IP-designMIPLM
 
Concurrency Control in Database Management system
Concurrency Control in Database Management systemConcurrency Control in Database Management system
Concurrency Control in Database Management systemChristalin Nelson
 
Activity 2-unit 2-update 2024. English translation
Activity 2-unit 2-update 2024. English translationActivity 2-unit 2-update 2024. English translation
Activity 2-unit 2-update 2024. English translationRosabel UA
 
Karra SKD Conference Presentation Revised.pptx
Karra SKD Conference Presentation Revised.pptxKarra SKD Conference Presentation Revised.pptx
Karra SKD Conference Presentation Revised.pptxAshokKarra1
 
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptx
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptxINTRODUCTION TO CATHOLIC CHRISTOLOGY.pptx
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptxHumphrey A Beña
 
Music 9 - 4th quarter - Vocal Music of the Romantic Period.pptx
Music 9 - 4th quarter - Vocal Music of the Romantic Period.pptxMusic 9 - 4th quarter - Vocal Music of the Romantic Period.pptx
Music 9 - 4th quarter - Vocal Music of the Romantic Period.pptxleah joy valeriano
 
AUDIENCE THEORY -CULTIVATION THEORY - GERBNER.pptx
AUDIENCE THEORY -CULTIVATION THEORY -  GERBNER.pptxAUDIENCE THEORY -CULTIVATION THEORY -  GERBNER.pptx
AUDIENCE THEORY -CULTIVATION THEORY - GERBNER.pptxiammrhaywood
 

Dernier (20)

Virtual-Orientation-on-the-Administration-of-NATG12-NATG6-and-ELLNA.pdf
Virtual-Orientation-on-the-Administration-of-NATG12-NATG6-and-ELLNA.pdfVirtual-Orientation-on-the-Administration-of-NATG12-NATG6-and-ELLNA.pdf
Virtual-Orientation-on-the-Administration-of-NATG12-NATG6-and-ELLNA.pdf
 
What is Model Inheritance in Odoo 17 ERP
What is Model Inheritance in Odoo 17 ERPWhat is Model Inheritance in Odoo 17 ERP
What is Model Inheritance in Odoo 17 ERP
 
How to Add Barcode on PDF Report in Odoo 17
How to Add Barcode on PDF Report in Odoo 17How to Add Barcode on PDF Report in Odoo 17
How to Add Barcode on PDF Report in Odoo 17
 
How to do quick user assign in kanban in Odoo 17 ERP
How to do quick user assign in kanban in Odoo 17 ERPHow to do quick user assign in kanban in Odoo 17 ERP
How to do quick user assign in kanban in Odoo 17 ERP
 
Earth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice greatEarth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice great
 
Global Lehigh Strategic Initiatives (without descriptions)
Global Lehigh Strategic Initiatives (without descriptions)Global Lehigh Strategic Initiatives (without descriptions)
Global Lehigh Strategic Initiatives (without descriptions)
 
Transaction Management in Database Management System
Transaction Management in Database Management SystemTransaction Management in Database Management System
Transaction Management in Database Management System
 
Food processing presentation for bsc agriculture hons
Food processing presentation for bsc agriculture honsFood processing presentation for bsc agriculture hons
Food processing presentation for bsc agriculture hons
 
FINALS_OF_LEFT_ON_C'N_EL_DORADO_2024.pptx
FINALS_OF_LEFT_ON_C'N_EL_DORADO_2024.pptxFINALS_OF_LEFT_ON_C'N_EL_DORADO_2024.pptx
FINALS_OF_LEFT_ON_C'N_EL_DORADO_2024.pptx
 
GRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTS
GRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTSGRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTS
GRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTS
 
4.16.24 21st Century Movements for Black Lives.pptx
4.16.24 21st Century Movements for Black Lives.pptx4.16.24 21st Century Movements for Black Lives.pptx
4.16.24 21st Century Movements for Black Lives.pptx
 
USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...
USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...
USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...
 
Field Attribute Index Feature in Odoo 17
Field Attribute Index Feature in Odoo 17Field Attribute Index Feature in Odoo 17
Field Attribute Index Feature in Odoo 17
 
Keynote by Prof. Wurzer at Nordex about IP-design
Keynote by Prof. Wurzer at Nordex about IP-designKeynote by Prof. Wurzer at Nordex about IP-design
Keynote by Prof. Wurzer at Nordex about IP-design
 
Concurrency Control in Database Management system
Concurrency Control in Database Management systemConcurrency Control in Database Management system
Concurrency Control in Database Management system
 
Activity 2-unit 2-update 2024. English translation
Activity 2-unit 2-update 2024. English translationActivity 2-unit 2-update 2024. English translation
Activity 2-unit 2-update 2024. English translation
 
Karra SKD Conference Presentation Revised.pptx
Karra SKD Conference Presentation Revised.pptxKarra SKD Conference Presentation Revised.pptx
Karra SKD Conference Presentation Revised.pptx
 
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptx
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptxINTRODUCTION TO CATHOLIC CHRISTOLOGY.pptx
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptx
 
Music 9 - 4th quarter - Vocal Music of the Romantic Period.pptx
Music 9 - 4th quarter - Vocal Music of the Romantic Period.pptxMusic 9 - 4th quarter - Vocal Music of the Romantic Period.pptx
Music 9 - 4th quarter - Vocal Music of the Romantic Period.pptx
 
AUDIENCE THEORY -CULTIVATION THEORY - GERBNER.pptx
AUDIENCE THEORY -CULTIVATION THEORY -  GERBNER.pptxAUDIENCE THEORY -CULTIVATION THEORY -  GERBNER.pptx
AUDIENCE THEORY -CULTIVATION THEORY - GERBNER.pptx
 

Java Struts Framework

  • 2. Jakarta Struts • Introduction • Struts Architecture • Installing Struts • Action Form • Action Servlet • struts_config.xml • Custom tags
  • 3. What is Struts? There are several different ways of looking at Struts. The three main ways are that Struts is: An MVC Framework. Struts provides a unified framework for deploying servlet and JSP applications that use the MVC architecture. A Collection of Utilities. Struts provides utility classes to handle many of the most common tasks in Web application development A Set of JSP Custom Tag Libraries. Struts provides custom tag libraries for outputting bean properties, generating HTML forms, iterating over various types of data structures, and conditionally outputting HTML.
  • 5. Installing Struts Download the Struts zip file. Start at http://jakarta.apache.org/site/binindex.cgi, or follow the link from http:// jakarta.apache.org/struts/. Unzip into a directory of your choice. For example, unzip into C:jakarta-struts. This is refered to as the struts_install_dir. Update your CLASSPATH. Add struts_install_dir/lib/struts.jar to the CLASSPATH used by your compiler or IDE (not your server). Here are three possible ways of setting it: Set it in your autoexec.bat file. E.g., on Windows if you unzipped into C:jakarta-struts-1.1, you would add the following to C:autoexec.bat: set CLASSPATH=C:jakarta-strutslibstruts.jar;%CLASSPATH% On Unix/Linux, use your .cshrc, .bashrc, or .profile instead.
  • 6. Installing Struts Set it using the system settings. On WinXP, go to the Start menu and select Control Panel, then System, then the Advanced tab, then the Environment Variables button. On Win2K/WinNT, go to the Start menu and select Settings, then Control Panel, then System, then Environment. Either way, enter the CLASSPATH value from the previous bullet. Set it in your editor or IDE. Most IDEs have a way of specifying the JAR files needed to compile projects. Or, you could make a small .bat file (Windows) or shell script (Unix/Linux) that supplies the struts.jar file as the argument to -classpath for javac. Install an XML parser. If you have JDK 1.4 or Apache Tomcat, this step is not necessary, since they already come with an XML parser. But, if you use JDK 1.2 or 1.3 with another server, you might need to obtain the XML parsing libraries. Here are two good sources: http://xml.apache.org/ http://java.sun.com/xml/
  • 7. Installing Struts • Download from jakarta web site • Get the appropriate operating system download • Uncompress the downloaded file • Copy all of the *.war files from the downloaded directory to your Tomcat webapps directory • Start tomcat • Enter: http://localhost:8080/struts_blank
  • 8. Struts *.war files Found in the following installation directory: struts-1.2.7webapps • struts-blank.war • struts-documentation.war • struts-examples.war • struts-mailreader.war • tiles-documentation.war
  • 9. Struts.jar • Be sure to place the struts.jar into your JS2E_HOMEjrelibext directory
  • 10. Testing Struts Install struts-blank.war. Install the Web application from struts_install_dir/webapps/struts-blank.war on your server. For example, with Apache Tomcat, copy struts_install_dir/webapps/ struts-blank.war to tomcat_install_dir/webapps/. Start or restart the server. Most servers only recognize new Web apps when the server is started. Access http://localhost/struts-blank/. This URL assumes you are running the server on your desktop and are using port 80. In general, access http://hostname:port/struts-blank/. You should see something like the following.
  • 12. Setting Up Struts Applications To make your own Struts application, you need to create a Web application that has the appropriate JAR files, TLD files, and web.xml entries. You almost always do this by starting with the struts-blank application and modifying it. You have three options for doing this: Option 1 (Good): Copy/rename the struts-blank directory to your development directory. When you tested your Struts installation, you ran the struts-blank Web app. When you did so, Tomcat and most other servers unpacked the struts-blank.war file into the struts-blank directory. So, copy that directory to whatever location you use for developing custom Web applications, and rename it to whatever app name you choose. For example, if you are using Tomcat and devel_dir is the location you use for development, copy the tomcat_install_dir/webapps/struts- blank directory to devel_dir, rename it to struts-test, resulting in devel_dir/struts- test.
  • 13. Setting Up Struts Applications Option 2 (Good): Unjar struts-blank.war into your development directory. If your server doesn't automatically unpack WAR files, then even if you ran the struts-blank test described above, you have no regular directory to work with. Besides, some people prefer to unpack the WAR file themselves anyhow. To do so: Copy struts_install_dir/webapps/struts-blank.war to your development directory. Make a new directory (e.g., called struts-test). Unjar struts-blank.war into that directory You can use jar -xvf or a standard zip tool like WinZip or the Windows XP explorer. Whenever you want to test your application, copy struts-test to the server's Web application autodeploy directory (e.g., onto the shortcut to tomcat_install_dir/webapps).
  • 14. Setting Up Struts Applications Option 3 (Bad): Rename struts-blank and leave it in the server's deployment directory. It is quite common to work directly in server's deployment directory (e.g., to work directly in tomcat_install_dir/webapps/struts-test). However, this approach scales poorly to real applications, makes it harder to test changes (you have no stable working version), and doesn't support your "real" deployment server anyhow (which is almost certainly not your desktop machine). If you don't have a good deployment system using your IDE or ant scripts, you can easily make a shortcut (Windows) or symbolic link (Unix/Linux) to the server's autodeploy directory, and just copy the Web app onto the shortcut each time. For example, suppose you are using Tomcat on Windows. To easily develop in one directory and then deploy in another, just do this: Grab tomcat_install_dir/webapps with your right mouse, drag it into devel_dir, release, and choose "Create Shortcut Here". Create struts-test or other applications as subdirectories within devel_dir, as described above. Deploy by using the right mouse to drag struts-test onto the shortcut from step 1, releasing, and choosing "Copy".
  • 15. Adding Struts to an Existing Web Application By far the easiest way to develop a Struts application is to start with struts-blank, rename it, and work from there. if you already have an existing Web application and want to add Struts capabilities to it, starting with struts-blank won't work. Adding Struts capabilities to existing Web apps is a huge pain in the neck, and will probably require several attempts to get it right. Here is a quick summary: Copy JAR files from struts-blank/WEB-INF/lib to your_web_app/WEB-INF/lib. Copy TLD files from struts-blank/WEB-INF to your_web_app/WEB-INF. Copy struts-config.xml from struts-blank/WEB-INF to your_web_app/WEB-INF. Copy the application properties file from struts-blank/WEB-INF/classes/resources to your_web_app/WEB-INF/classes/resources. If you plan on using the automatic validator (see Section 5, Validating User Input), copy validation.xml and validator-rules.xml from struts-blank/WEB-INF to your_web_app/WEB- INF. If you plan on using Tiles (see Section 6, Composing Pages with Tiles), copy struts- tiles.xml from struts-blank/WEB-INF to your_web_app/WEB-INF. Copy declarations out of struts-blank/WEB-INF/web.xml into your_web_app/WEB- INF/web.xml. Most importantly, copy the servlet and servlet-mapping entries that map blah.do to org.apache.struts.action.ActionServlet. Be sure you keep the entries in the same locations: the order of elements in web.xml matters.
  • 16. Accessing Struts Documentation You probably already have bookmarked the APIs for standard Java, servlets, and JSP. But you will also want to frequently refer to the Apache Struts documentation. You can do this two ways: Read a local copy. This is fastest, but the documentation can get a bit out of date. To read a local copy, install the struts-documentation.war Web app. For example, if you are using Apache Tomcat on port 80 on your local machine, copy struts_install_dir/ webapps/struts-documentation.war to tomcat_install_dir/webapps, restart server, and use the URL http://localhost/struts-documentation/. Read it from the Apache site. This option is slower, but guarantees that you get the latest versions of the documentation. To read the online version of the documentation, start at http:// jakarta.apache.org/struts/learning.html. The documentation includes FAQs, user guides, tutorials, and the API in Javadoc format.
  • 17. The Six Basic Steps in Using Jakarta Struts With Struts, the normal processing flow is that a form submits data to a URL of the form blah.do. That address is mapped by struts-config.xml to an Action object, whose execute method handles the request. One of the arguments to execute is a form bean that is automatically created and whose properties are automatically populated with the incoming form data. The Action object then invokes business logic and data-access logic, placing the results in normal beans stored in request, session, or application scope. The Action uses mapping.findForward to return a condition, and the conditions are mapped by struts-config.xml to various JSP pages. The system forwards the request to the appropriate JSP page, where the bean:write tag is used to output properties of the form bean and results beans. Optionally, both the input form and the final JSP pages can use bean:message to output standard messages and labels as defined in a system property file.
  • 18. The Six Basic Steps in Using Jakarta Struts Here are the minimum steps needed to create an application that follows this process. This set of slides will focus on the basic flow and the Action objects; the next set of slides will show how to use beans. Modify struts-config.xml. Use WEB-INF/struts-config.xml to: Designate Action classes to handle requests for blah.do. Specify the URLs that apply in various situations. Declare any form beans that are being used. Be sure to restart the server after modifying struts-config.xml; the file is read only when the Web application is first loaded. Define a form bean. This bean is a class the extends ActionForm and will represent the data submitted by the user. It is automatically populated when the input form is submitted. Beans will be discussed in the next set of slides.
  • 19. The Six Basic Steps in Using Jakarta Struts Create results beans. In the MVC architecture, the business-logic and data-access code create the results and the JSP pages present them. To transfer the results from one layer to the other, they are stored in beans. These beans differ from form beans in that they need extend no particular class, and they represent the output of the computational process, not the input to the process. Beans will be discussed in the next set of slides Create an Action object to handle requests. The struts-config.xml file designates the Action object that handles requests for various URLs. The Action objects themselves need to do the real work: invoke the appropriate business- and data-access-logic, store the results in beans, and designate the type of situation (missing data, database error, success category 1, success category 2, etc.) that is appropriate for the results. The struts-config.xml file then decides which JSP page should apply to that situation.
  • 20. The Six Basic Steps in Using Jakarta Struts Create form that invokes blah.do. You need to create an input form whose ACTION corresponds to one of the *.do addresses listed in struts-config.xml. At a minimum, the input form should look like this: <FORM ACTION=".../blah.do" ...>...</FORM> However, in future slides we will discuss the advantages of using the Struts html:form tag to build this input form. Display results in JSP. Since Struts is built around the MVC architecture, these JSP pages should avoid JSP scripting elements whenever possible. For basic Struts, these JSP pages usually use the Struts bean:write tag, but in JSP 2.0 the JSP 2.0 expression language is a viable alternative. In complex cases, the JSP pages also use the JSP Standard Tag Library (JSTL) or the Struts looping/logic tags. In most cases, the JSP pages only make sense when the request is funneled through the Action, since it is the Action that invokes the logic that creates the data that the JSP pages will display. So, the JSP pages are placed in WEB-INF, where RequestDispatcher can forward to them but where clients cannot access them directly. If the JSP pages makes sense independently of the Action (e.g., if they display session data), then the JSP pages should be placed in a regular subdirectory of the Web application, and the forward entries in struts-config.xml should say <forward ... redirect="true"/>.
  • 21. Let’s do a simple example… In this example, the URL http://hostname/struts-test/actions/register1.do should be handled by the class RegisterAction1 (which extends Action class). RegisterAction1 always returns "success", and this return value results in the JSP page /WEB-INF/results/result1.jsp being displayed to the client.
  • 22. Registration Example Modify struts-config.xml. Use WEB-INF/struts-config.xml to: Designate Action classes to handle requests for blah.do. In this case, we designate that RegisterAction1 should handle requests for /actions/register1.do (notice that .do is implied automatically). To accomplish this, we add an action entry to action-mappings, where action has the following attributes. path: the relative path that should be mapped to the Action, minus the .do extension. Thus, path="/actions/register1" refers to http://hostname/webAppName/actions/register1.do. See this section for a discussion of why it is useful to use /actions/register1 instead of just register1 in the path. type: the fully qualified class name of the Action object that should be invoked when a request for the specified path is received. name, scope, and input: these attributes are omitted in this example, but are used in later examples when beans are used. In this case, the action element looks like this: <action path="/actions/register1" type="coreservlets.RegisterAction1"> ... </action> Specify the URLs that apply in various situations. In this case, we use the forward element to say that result1.jsp applies when RegisterAction1 returns "success", as follows: <forward name="success" path="/WEB-INF/results/result1.jsp"/>
  • 23. Modify struts-config.xml Modify struts-config.xml. Use WEB-INF/struts-config.xml to: Designate Action classes to handle requests for blah.do. In this case, we designate that RegisterAction1 should handle requests for /actions/register1.do (notice that .do is implied automatically). To accomplish this, we add an action entry to action-mappings, where action has the following attributes. path: the relative path that should be mapped to the Action, minus the .do extension. Thus, path="/actions/register1" refers to http://hostname/webAppName/actions/register1.do. See this section for a discussion of why it is useful to use /actions/register1 instead of just register1 in the path. type: the fully qualified class name of the Action object that should be invoked when a request for the specified path is received. name, scope, and input: these attributes are omitted in this example, but are used in later examples when beans are used.
  • 25. Register example Define a form bean. Beans are postponed, so this step is omitted for now. Create results beans. Beans are postponed, so this step is omitted for now.
  • 26. Create an Action object to handle requests In general, your Action subclass should: Use a package. In this case, we have package coreservlets; This means that the class file should go in your_web_app/WEB- INF/classes/coreservlets/. Add Struts-specific import statements to whatever imports are otherwise needed. In this case, we have import javax.servlet.http.*; import org.apache.struts.action.*; (this is why you need to be sure that you have the struts.jar file in your J2SEjrelibext directory Extend the Action class. In this case, we have public class RegisterAction1 extends Action {...}
  • 27. Create an Action object to handle requests Override the execute method. This method is defined as follows. public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { ... } Return mapping.findForward. The execute method should have one or more return values. These values will then be mapped to specific JSP pages by forward entries in struts-config.xml. In this case, we simply return "success" in all situations. public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { return(mapping.findForward("success")); }
  • 29. register1.jsp Create form that invokes blah.do. In this case, we need an HTML form that invokes http://hostname/struts-test/ actions/register1.do. We place the HTML form in the forms subdirectory and use a relative URL for the ACTION as follows. register1.jsp (Excerpt)
  • 31. Display results in JSP In general, there can be several possible JSP pages corresponding to the various possible return values of the execute method of the Action. In struts- config.xml, each JSP page is declared in a forward entry within the appropriate action. In this simple case, the only return value is "success", so /WEB- INF/results/result1.jsp is used in all cases. This JSP page displays a simple message, as shown below In general, there can be several possible JSP pages corresponding to the various possible return values of the execute method of the Action. In struts-config.xml, each JSP page is declared in a forward entry within the appropriate action. In this simple case, the only return value is "success", so / WEB-INF/results/result1.jsp is used in all cases. This JSP page displays a simple message, as shown on the next slide.
  • 34. Executing the Form This form is then filled in and submitted, with the form's ACTION resulting in the URL http://localhost/struts-test/actions/register1.do. This address is mapped by struts-config.xml to the RegisterAction1 class, whose execute method is invoked. This method returns a mapping.findForward with a value of "success", and that value is mapped by struts-config.xml to /WEB-INF/results/result1.jsp, which is the final result displayed to the user. However, since the JSP page is invoked with RequestDispatcher.forward, not response.sendRedirect, the URL displayed to the user is register1.do, not result1.jsp. See the following screen shot.