Struts 2 Tutorial
Struts 2 Tutorial
RoseIndia Struts 2 Tutorial and Online free training h
RoseIndia Struts 2 Tutorial and Online free training helps you learn new elegant Struts 2elps you learn new elegant Struts 2 Framework with examples. Struts 2 is very elegant and flexible front controller
Framework with examples. Struts 2 is very elegant and flexible front controller framework based on many standard technologies
framework based on many standard technologies like Java Filters, Java Beans,like Java Filters, Java Beans, ResourceBundles, XML etc.
ResourceBundles, XML etc. 1.
1. Struts 2 FeaturesStruts 2 Features
It is very extensible as each class of the
It is very extensible as each class of the framework is based on an Interface andframework is based on an Interface and all the base classes are given an extra application and even you can add your all the base classes are given an extra application and even you can add your own.
own. 2.
2. Struts 2 HistoryStruts 2 History
Apache Struts is an open-source framework that is
Apache Struts is an open-source framework that is used for developing Java webused for developing Java web application. Originally developed by the programmer and author Craig R.
application. Originally developed by the programmer and author Craig R. McClanahan this was later taken over by the Apache Software Foundation in McClanahan this was later taken over by the Apache Software Foundation in 2002.
2002. 3.
3. Struts 2 ArchitectureStruts 2 Architecture
Struts and webwork has joined together to
Struts and webwork has joined together to develop the Struts 2 Framework. Strutsdevelop the Struts 2 Framework. Struts 2 Framework is very extensible and elegant
2 Framework is very extensible and elegant for the development of enterprise webfor the development of enterprise web application of any size. In this section we
application of any size. In this section we are going to explain you are going to explain you the architecturethe architecture of Struts 2 Framework.
of Struts 2 Framework. 4.
4. Why Struts 2Why Struts 2
The new version Struts 2.0 is a
The new version Struts 2.0 is a combination of the Sturts action framework andcombination of the Sturts action framework and Webwork. According to the Struts 2.0.1
Webwork. According to the Struts 2.0.1 release announcement, some key featuresrelease announcement, some key features are:
are: 5.
5. Struts 1.x Vs Struts 2.xStruts 1.x Vs Struts 2.x
In the following section, we are going
In the following section, we are going to compare the various features betweento compare the various features between the two frameworks. Strut
the two frameworks. Struts 2.x s 2.x is very simple is very simple in comparison to the strin comparison to the struts 1.x ,uts 1.x , few of its excelling features are:
few of its excelling features are: 6.
6. Downloading and Installing Struts 2Downloading and Installing Struts 2 In this section we will download and
In this section we will download and install the Struts 2.0 on the latest version of install the Struts 2.0 on the latest version of Tomcat container. We will first download tomcat and
Tomcat container. We will first download tomcat and configure it as our configure it as our development server.
development server.
Struts 2 Hello World Application
Struts 2 Hello World Application
7.
7. Creating the development directory StructureCreating the development directory Structure
In this section we will create directory structure of our Struts 2 Hello World In this section we will create directory structure of our Struts 2 Hello World application based on Struts 2 framework. Our Struts 2 Hello World application is application based on Struts 2 framework. Our Struts 2 Hello World application is your first step towards developing applications based on Struts 2
your first step towards developing applications based on Struts 2 framework.framework. 8.
8. Writing Jsp, Java and Configuration filesWriting Jsp, Java and Configuration files In this section we will write JSP, Java and
Struts 2 Hello World application. Now in struts 2
Struts 2 Hello World application. Now in struts 2 struts.xmlstruts.xml is used to configureis used to configure the applications. We will also deploy and test the application.
the applications. We will also deploy and test the application. 9.
9. Struts 2 xml configuration fileStruts 2 xml configuration file
In this section we will introduce you with the struts.xml file. This section explains In this section we will introduce you with the struts.xml file. This section explains you how best you can
you how best you can use the struts.xml file for you big projects.use the struts.xml file for you big projects.
Struts 2 Actions
Struts 2 Actions
10.
10.Struts 2 Actions ExampleStruts 2 Actions Example
When a client request matches the
When a client request matches the action's name, the framework uses the mappingaction's name, the framework uses the mapping from
fromstruts.xmlstruts.xml file to process the request.file to process the request.
11.
11.Struts 2 Actions IntroductionStruts 2 Actions Introduction When a client request matches the
When a client request matches the action's name, the framework uses the mappingaction's name, the framework uses the mapping from
fromstruts.xmlstruts.xml file to process the request. The mapping file to process the request. The mapping to an action is usuallyto an action is usually generated by a Struts Tag.
generated by a Struts Tag. Struts 2 Login Application
Struts 2 Login Application
12.
12.Developing Login Application in Struts 2Developing Login Application in Struts 2 In this section we are going to
In this section we are going to develop login application based on develop login application based on Struts 2Struts 2 Framework. Our current login application does not validate the user against the Framework. Our current login application does not validate the user against the database
database 13.
13.Adding Validation to Struts 2 Login ApplicationAdding Validation to Struts 2 Login Application In this section we will write the code to
In this section we will write the code to validate the login application. After validate the login application. After completing this section you will be able to write validations for your Struts 2 completing this section you will be able to write validations for your Struts 2 projects.
projects. 14.
14.Running and testing applicationRunning and testing application
In this section we will run the example on Tomcat 6.0 server and check how it In this section we will run the example on Tomcat 6.0 server and check how it works.
works. 15.
15.Client Side Validation in Struts 2 Login ApplicationClient Side Validation in Struts 2 Login Application In this section we will see how to write c
In this section we will see how to write code that will generate Java Script codeode that will generate Java Script code for client side validation. In the last section we
for client side validation. In the last section we developed Login-validator.xmldeveloped Login-validator.xml configuration file for defining the server side validation.
configuration file for defining the server side validation. 16.
16.Validations using Struts 2 AnnotationsValidations using Struts 2 Annotations In this section we are going to
In this section we are going to validate our login application using Annotations invalidate our login application using Annotations in Action class. Our current login application does not
Action class. Our current login application does not validate the user against thevalidate the user against the database.
database. Struts 2 Tags
Struts 2 Tags
17.
17.Struts TagsStruts Tags
In this section we will introduce you with the tags
In this section we will introduce you with the tags provided along withprovided along withStruts 2Struts 2
framework. It is necessary to understand all the tags provided
framework. framework. 18.
18. Struts Generic Tags ExamplesStruts Generic Tags Examples
Struts 2 Examples
Struts 2 Examples
19.
19.Struts 2 DateStruts 2 Date
In this section we will discuss the date processing functionalities available in In this section we will discuss the date processing functionalities available in thethe Struts 2 Framework.
Struts 2 Framework. 20.
20.Date Format ExamplesDate Format Examples
In this tutorials you will learn about Date Format function in S
In this tutorials you will learn about Date Format function in Struts 2. We havetruts 2. We have provided fully tested example code to
provided fully tested example code to illustrate the concepts.illustrate the concepts.
21.
21.Struts 2 datepicker ExampleStruts 2 datepicker Example
In this section we will show you how to
In this section we will show you how to develop datetimepicker in struts 2. Strutsdevelop datetimepicker in struts 2. Struts 2 uses the dojo toolkit for creating
2 uses the dojo toolkit for creating date picker.date picker.
22.
22.Struts 2 Format ExamplesStruts 2 Format Examples
In this section you will learn how to format Date an
In this section you will learn how to format Date and numbers in Struts 2d numbers in Struts 2 Framework. Our Struts 2 Format Examples are very easy to
Framework. Our Struts 2 Format Examples are very easy to grasp and you willgrasp and you will learn these concepts in very small time.
learn these concepts in very small time. 23.
23.Struts 2 File UploadStruts 2 File Upload
In this section you will learn how to write program in
In this section you will learn how to write program in Struts 2 to upload the fileStruts 2 to upload the file on the server. In this example we
on the server. In this example we will also provide you the code to will also provide you the code to save the savesave the save on the server in the upload directory.
on the server in the upload directory. Struts 2 Resources Examples
Struts 2 Resources Examples
24.
24.Struts 2 Resources ExamplesStruts 2 Resources Examples The struts 2 resources examples The struts 2 resources examples 25.
25.Static ParameterStatic Parameter
In this section, we will develop a simple application to access the static parameter. We In this section, we will develop a simple application to access the static parameter. We will use a JavaBean to set and get the
will use a JavaBean to set and get the static parameters. Each static parameter has astatic parameters. Each static parameter has a value.
value. 26.
26.Accessing Session ObjectAccessing Session Object
In this section, we will develop a
In this section, we will develop a simple application to access the framework simple application to access the framework resources like the session object, session context and
resources like the session object, session context and the last accessed sessionthe last accessed session time.
time. 27.
27.Access Request and ResponseAccess Request and Response
In this section, you will learn to develop a
In this section, you will learn to develop an application that accesses the requestn application that accesses the request and response object in struts 2 application.
and response object in struts 2 application. Struts 2 Tools
28.
28.Struts 2 Eclipse PluginStruts 2 Eclipse Plugin
This page contains the examples
This page contains the examples and the list of plugins that are available and the list of plugins that are available for Strutsfor Struts 2 Development using Eclipse IDE.
2 Development using Eclipse IDE. 29.
29.Struts 2 IDEStruts 2 IDE
This page contains the list of IDE available
This page contains the list of IDE available to ease the development of to ease the development of Struts 2Struts 2 Framework based applications. The IDE for Struts 2
Framework based applications. The IDE for Struts 2 will actually make thewill actually make the development cycle of the much easier.
development cycle of the much easier. 30.
30.Struts 2 ApplicationStruts 2 Application
Developing user registration application based on S
Developing user registration application based on Struts 2 Framework. This Strutstruts 2 Framework. This Struts 2 Application is a simple user registration application that will help
2 Application is a simple user registration application that will help you learn howyou learn how to develop real world application using S
to develop real world application using Struts 2 Framework.truts 2 Framework.
31.
31.Struts 2 AjaxStruts 2 Ajax
In this section explains you Ajax based d
In this section explains you Ajax based development in Struts 2. Struts 2 providesevelopment in Struts 2. Struts 2 provides built-in support for Ajax using Dojo toolkit.
built-in support for Ajax using Dojo toolkit.
Struts 2 Features
Struts 2 Features
The strut-2 framework is designed for the compilation of
The strut-2 framework is designed for the compilation of the entire development cyclethe entire development cycle including of building, developing and maintaining the whole application. It is very including of building, developing and maintaining the whole application. It is very extensible as each class of the
extensible as each class of the framework is based on an Interface and framework is based on an Interface and all the base classesall the base classes are given an extra application and even you can add your own. The basic platform
are given an extra application and even you can add your own. The basic platform requirements are Servlet API 2.4, JSP API 2.0 and Java 5.
requirements are Servlet API 2.4, JSP API 2.0 and Java 5.
Some of the general features of the current Apache Strut 2 framework are given below. Some of the general features of the current Apache Strut 2 framework are given below. Architecture
Architecture – First the web browser request a resource for which the Filter Dispatcher – First the web browser request a resource for which the Filter Dispatcher decides the suitable action. Then
decides the suitable action. Then the Interceptors use the required functions and after thatthe Interceptors use the required functions and after that the Action method executes all
the Action method executes all the function like storing and retrieving data the function like storing and retrieving data from afrom a database. Then the result can be seen on the output of the browser in HTML, PDF, database. Then the result can be seen on the output of the browser in HTML, PDF, images or any other.
images or any other. Tags
Tags - Tags in Strut 2 allow creating dynamic w- Tags in Strut 2 allow creating dynamic web application with less number of eb application with less number of coding. Not only these tags contain output data but also provide style sheet driven coding. Not only these tags contain output data but also provide style sheet driven markup that in turn helps in creating pages with less code. Here the tags also support markup that in turn helps in creating pages with less code. Here the tags also support validation and localization of coding
validation and localization of coding that in turn offer more utilization. The less number that in turn offer more utilization. The less number of codes also makes it easy to read and maintain.
of codes also makes it easy to read and maintain. MVC
MVC – The – TheModel View ControllerModel View Controller in Strut 2 framework acts as a cin Strut 2 framework acts as a co-coordinator o-coordinator between application’s model and web view. Its Controller and View components can between application’s model and web view. Its Controller and View components can
come together with other technology to
come together with other technology to develop the model. The develop the model. The framework has its libraryframework has its library and markup tags to p
Configuration
Configuration – Provides a deployment descriptor to initialize resources and – Provides a deployment descriptor to initialize resources and is in XMLis in XML format. The initialization is taken place by scanning
format. The initialization is taken place by scanning all the classes using Java packages or all the classes using Java packages or you can use an
you can use an application configuration file to control the entire configuration. Itsapplication configuration file to control the entire configuration. Its general-purpose defaults allow using struts directly Out of the box.
general-purpose defaults allow using struts directly Out of the box. Configuration files are reloadable that allows changes
Configuration files are reloadable that allows changes without restarting a web container.without restarting a web container.
Other Features:
Other Features:
•
• All framework classes are based on interfaces and coAll framework classes are based on interfaces and core interfaces are independentre interfaces are independent from HTTP.
from HTTP. •
• Check boxes do noCheck boxes do not require any kind of special application t require any kind of special application for false values.for false values. •
• Any class can be used as an action class and one can input properties by using anyAny class can be used as an action class and one can input properties by using any JavaBean directly to the action class.
JavaBean directly to the action class. •
• Strut 2 actions are Spring friendly and so Strut 2 actions are Spring friendly and so easy to Spring integration.easy to Spring integration. •
• AZAX theme enables to make AZAX theme enables to make the application more dynamic.the application more dynamic. •
• Portal and servlet deployment are easy due to automatic portlet support withoutPortal and servlet deployment are easy due to automatic portlet support without altering code.
altering code. •
• The request handling in every action The request handling in every action makes it easy to customize, when required.makes it easy to customize, when required.
Struts 2 History
Struts 2 History
Apache Struts is an open-source framework that
Apache Struts is an open-source framework that is used for developing Java webis used for developing Java web
application. Originally developed by the programmer and author Craig R. McClanahan application. Originally developed by the programmer and author Craig R. McClanahan this was later taken over by the Apache Software Foundation in 2002. Struts have this was later taken over by the Apache Software Foundation in 2002. Struts have
provided an excellent framework for developing application easily by organizing JSP and provided an excellent framework for developing application easily by organizing JSP and
Servlet basically based on HTML formats and
Servlet basically based on HTML formats and Java code. Strut1 with all standard JavaJava code. Strut1 with all standard Java technologies and packages of Jakarta assists to create an extensible development
technologies and packages of Jakarta assists to create an extensible development environment. However, with the growing demand of web application,
environment. However, with the growing demand of web application,Strut 1Strut 1 does notdoes not stand firm and needs to be changed with demand. This led to the creation of Strut2, which stand firm and needs to be changed with demand. This led to the creation of Strut2, which is more developer friendly with features like Ajax, rapid
is more developer friendly with features like Ajax, rapid development and extensibility.development and extensibility. Strut is a well-organized framework based on
Strut is a well-organized framework based on MVCMVCarchitecture. Inarchitecture. InModel-View-
Model-View-Architecture
Architecture, Model stands for the business or database , Model stands for the business or database code, the View represents thecode, the View represents the page design code and the Controller for navigational code. All these together makes page design code and the Controller for navigational code. All these together makes
Struts an essential framework for building Java application. But
Struts an essential framework for building Java application. But with the development of with the development of new and lightweight MVC based
new and lightweight MVC based frame works like Spring, Stripes and Tapestry, itframe works like Spring, Stripes and Tapestry, it becomes necessary to modify the Struts framework. So, the team of Apache Struts and becomes necessary to modify the Struts framework. So, the team of Apache Struts and
another J2EE framework,
another J2EE framework, WebWork WebWork of of OpenSymphonyOpenSymphony joined hand together to developjoined hand together to develop an advanced
an advanced frame works with all possible developing features that will make itframe works with all possible developing features that will make it developer and user friendly.
developer and user friendly. Strut2
Strut2 is a combined features of Struts Ti and WebWork is a combined features of Struts Ti and WebWork 2 projects that advocates higher 2 projects that advocates higher level application by using the architecture of
level application by using the architecture of WebWork2 with features including a pluginWebWork2 with features including a plugin framework, a new API, Ajax tags etc. So the Struts communities and the WebWork team framework, a new API, Ajax tags etc. So the Struts communities and the WebWork team brought together several special features in WebWork2 to
Open Source world. Later the name of WebWork2 has changed to Struts2. Hence, Open Source world. Later the name of WebWork2 has changed to Struts2. Hence, Apache Strut 2 is a dynamic, extensible framework for a complete application Apache Strut 2 is a dynamic, extensible framework for a complete application development from building, deploying and
development from building, deploying and maintaining.maintaining.
WebWork is a framework for web-application development
WebWork is a framework for web-application development that has been included inthat has been included in Struts framework 2.0 release. It has some unique
Struts framework 2.0 release. It has some unique concepts and constructs like itsconcepts and constructs like its
compatibility of working within existing Web APIs in Java rather than trying to replace compatibility of working within existing Web APIs in Java rather than trying to replace them completely. It has been built specifically taking into
them completely. It has been built specifically taking into account the developer’saccount the developer’s productivity and code simplicity. Furthermore it is completely context dependent that productivity and code simplicity. Furthermore it is completely context dependent that provides a wrapper around XWork. When working on web applications the web work provides a wrapper around XWork. When working on web applications the web work provides a context that helps
provides a context that helps web developer in specific implementations.web developer in specific implementations.
While, XWork provides a mechanism that is used for configuration and factory While, XWork provides a mechanism that is used for configuration and factory implementation management. This mechanism is dependencies inject mechanism. implementation management. This mechanism is dependencies inject mechanism.
Struts
Struts 2 Ar
2 Architecture
chitecture
Struts and webwork has joined together to develop the Struts 2 Framework. Struts 2 Struts and webwork has joined together to develop the Struts 2 Framework. Struts 2 Framework is very extensible and elegant
Framework is very extensible and elegant for the development of enterprise webfor the development of enterprise web application of any size. In this section we are going to explain you the architecture of application of any size. In this section we are going to explain you the architecture of Struts 2 Framework.
Struts 2 Framework.
Request Lifecycle in Struts 2 applications
Request Lifecycle in Struts 2 applications
1.
1. User Sends request:User Sends request: User sends a request to the server for some User sends a request to the server for some resource.resource.
2.
2. FilterDispatcher determines the appropriate action:FilterDispatcher determines the appropriate action: The FilterDispatcher The FilterDispatcher looks at the request and then
looks at the request and then determines the appropriate Action.determines the appropriate Action. 3.
3. Interceptors are applied:Interceptors are applied: Interceptors configured for applying the commonInterceptors configured for applying the common functionalities such as workflow, validation, file upload etc. are
functionalities such as workflow, validation, file upload etc. are automaticallyautomatically applied to the request.
applied to the request. 4.
4. Execution of Action:Execution of Action: Then the action method is executed to perform the databaseThen the action method is executed to perform the database related operations like storing or retrieving the data from database.
related operations like storing or retrieving the data from database. 5.
5. Output rendering:Output rendering: Then the Result render the output.Then the Result render the output.
6.
6. Return of Request:Return of Request: Then the request returns through the Then the request returns through the interceptors in theinterceptors in the reverse order. The returning request allows us to perform the
reverse order. The returning request allows us to perform the clean-up or clean-up or additional processing.
additional processing. 7.
7. Display the result to user:Display the result to user: Finally the control is returned to the servlet container,Finally the control is returned to the servlet container, which sends the output to the
which sends the output to the user browser.user browser.
Image: Struts 2 high level overview of request processing:
Struts 2 Architecture
Struts 2 Architecture
Struts 2 is very elegant and flexible front con
Struts 2 is very elegant and flexible front controller framework based on many standardtroller framework based on many standard technologies like Java Filters, Java Beans,
technologies like Java Filters, Java Beans, ResourceBundles, XML etc.ResourceBundles, XML etc.
For the
For the ModelModel, the framework can use any data access technologies like JDBC, EJB,, the framework can use any data access technologies like JDBC, EJB, Hibernate etc. and for the
Hibernate etc. and for theViewView, the framework can be integrated with JSP, JTL, JSF,, the framework can be integrated with JSP, JTL, JSF, Jakarta Velocity Engine, Templates, PDF, XSLT
Jakarta Velocity Engine, Templates, PDF, XSLT etc.etc.
Exception Handling:
Exception Handling:
The Struts 2 Framework allows us to define
The Struts 2 Framework allows us to define exception handlers and inceptors.exception handlers and inceptors.
•
• Exception Handlers:Exception Handlers:
Exception handlers allows us to define the exception handling procedure on Exception handlers allows us to define the exception handling procedure on global and local basis. Framework catches the exception and then displays the global and local basis. Framework catches the exception and then displays the page of our choice with appropriate message and exception details.
page of our choice with appropriate message and exception details. •
• Interceptors:Interceptors:
The Interceptors are used to specify the "request-processing lifecycle" for an The Interceptors are used to specify the "request-processing lifecycle" for an action. Interceptors are configured to apply the co
action. Interceptors are configured to apply the common functionalities likemmon functionalities like workflow, validation, etc.. to the request.
workflow, validation, etc.. to the request. Struts 2 Architecture
Struts 2 Architecture
The following diagram depicts the architecture of
The following diagram depicts the architecture of Struts 2 Framework. FollowingStruts 2 Framework. Following diagram shows the the initial request goes to
diagram shows the the initial request goes to the servlet container such as tomcat, whichthe servlet container such as tomcat, which is then passed through standard filer chain.
Image: Struts 2 Architecture
Image: Struts 2 Architecture
The filter chain includes: The filter chain includes:
•
• Action ContextCleanUp filterAction ContextCleanUp filter::
The ActionContextCleanUp filter is optional and it is useful when
The ActionContextCleanUp filter is optional and it is useful when integration hasintegration has to be done with other technologies like SiteMash Plugin.
to be done with other technologies like SiteMash Plugin. •
• FilterDispatcher:FilterDispatcher:
Next the FilterDispatch is called, which in turn u
Next the FilterDispatch is called, which in turn uses the ActionMapper toses the ActionMapper to
determine weather to invoke an Action. If the action is required to be invoked, the determine weather to invoke an Action. If the action is required to be invoked, the FilterDispatcher delegates the control to the
FilterDispatcher delegates the control to theActionProxyActionProxy..
•
• ActionProxy:ActionProxy:
The ActionProxy takes the help from Configuration Files manager, which is The ActionProxy takes the help from Configuration Files manager, which is initialized from the struts.xml. Then the ActionProxy creates an
initialized from the struts.xml. Then the ActionProxy creates an ActionInvocation,
ActionInvocation, which implements the command pattern. Thewhich implements the command pattern. The
ActionInvocation process invokes the Interceptors (if configured) and then ActionInvocation process invokes the Interceptors (if configured) and then invokes the action. The the
invokes the action. The the ActionInvocation looks for proper result. Then theActionInvocation looks for proper result. Then the result is executed, which involves the
Then the Interceptors are executed
Then the Interceptors are executed again in reverse order. Finally the responseagain in reverse order. Finally the response returns through the filters configured in web.xml file. If the
returns through the filters configured in web.xml file. If the
ActionContextCleanUp filter is configured, the FilterDispatcher does not clean ActionContextCleanUp filter is configured, the FilterDispatcher does not clean the ThreadLocal ActionContext. If the ActionContextCleanUp filter is not present the ThreadLocal ActionContext. If the ActionContextCleanUp filter is not present then the FilterDispatcher will cleanup all the ThreadLocals present.
then the FilterDispatcher will cleanup all the ThreadLocals present. In this section we have learned
In this section we have learned about the Architecture of Struts 2 Framework.about the Architecture of Struts 2 Framework.
Why Struts 2
Why Struts 2
The new version Struts 2.0 is a combination of the Sturts action framework and
The new version Struts 2.0 is a combination of the Sturts action framework and
Webwork. According to the Struts 2.0.1 release announcement, some key features
Webwork. According to the Struts 2.0.1 release announcement, some key features
are:
are:
•
• Simplified DesignSimplified Design - Programming the abstract classes instead of interfaces is one- Programming the abstract classes instead of interfaces is one of design problem of struts1 framework that has been
of design problem of struts1 framework that has been resolved in the struts 2resolved in the struts 2 framework. Most of the Struts 2 classes are based on interfaces and most of its framework. Most of the Struts 2 classes are based on interfaces and most of its core interfaces are HTTP independent.
core interfaces are HTTP independent. Struts 2 Action classes are framework Struts 2 Action classes are framework independent and are simplified to look
independent and are simplified to look as simple POJOs. Framework componentsas simple POJOs. Framework components are tried to keep loosely coupled.
are tried to keep loosely coupled. •
• Simplified ActionsSimplified Actions - Actions are simple POJOs.- Actions are simple POJOs.Any java class with execute()Any java class with execute() method can be used as an Action class. Even we don't need to implement
method can be used as an Action class. Even we don't need to implement
interfaces always. Inversion of Control is introduced while developing the action interfaces always. Inversion of Control is introduced while developing the action classes. This make the actions to be
classes. This make the actions to be neutral to the underlying framework .neutral to the underlying framework . •
• No more ActionFormsNo more ActionForms - ActionForms feature is no more known to - ActionForms feature is no more known to the struts2the struts2 framework. Simple JavaBean flavored actions are used to put properties directly . framework. Simple JavaBean flavored actions are used to put properties directly . No need to use all String properties.
No need to use all String properties. •
• Simplified testabilitySimplified testability - Struts 2 Actions are HTTP independent - Struts 2 Actions are HTTP independent and framework and framework neutral. This enables to test struts applications very easily without resorting to neutral. This enables to test struts applications very easily without resorting to mock objects.
mock objects. •
• Intelligent DefaultsIntelligent Defaults - Most configuration elements have a default value - Most configuration elements have a default value whichwhich can be set according to the need. Even there are xml-based default configuration can be set according to the need. Even there are xml-based default configuration files that can be overridden according to the need.
files that can be overridden according to the need. •
• Improved resultsImproved results - Unlike ActionForwards, Struts 2 - Unlike ActionForwards, Struts 2 Results provides flexibilityResults provides flexibility to create multiple type of outputs and in
to create multiple type of outputs and in actual it helps to prepare the response.actual it helps to prepare the response. •
• Better Tag featuresBetter Tag features - Struts 2 tags enables to add style sheet-driven markup- Struts 2 tags enables to add style sheet-driven markup capabilities, so that we can create
capabilities, so that we can create consistent pages with less code. Struts 2 tags areconsistent pages with less code. Struts 2 tags are more capable and result oriented. Struts 2 tag markup can be altered by changing more capable and result oriented. Struts 2 tag markup can be altered by changing an underlying stylesheet. Individual tag markup can be changed by editing a an underlying stylesheet. Individual tag markup can be changed by editing a FreeMarker template. Both JSP and FreeMarker
FreeMarker template. Both JSP and FreeMarker tags are fully supported.tags are fully supported. •
• Annotations introducedAnnotations introduced : Applications in struts 2 can use use Java 5 annotations: Applications in struts 2 can use use Java 5 annotations as an alternative to XML and Java properties configuration. Annotations
as an alternative to XML and Java properties configuration. Annotations minimizes the use of xml.
•
• Stateful CheckboxesStateful Checkboxes - Struts 2 checkboxes do not require special handling for - Struts 2 checkboxes do not require special handling for false values.
false values. •
• QuickStartQuickStart - Many changes can be - Many changes can be made on the fly without restarting a webmade on the fly without restarting a web container.
container. •
• customizing controllercustomizing controller - Struts 1 lets to customize the request processor pe- Struts 1 lets to customize the request processor per r module, Struts 2 lets to customize the request handling per action, if desired. module, Struts 2 lets to customize the request handling per action, if desired. •
• Easy Spring integrationEasy Spring integration - Struts 2 Actions are Spring-aware. Just needs to - Struts 2 Actions are Spring-aware. Just needs to addadd Spring beans!
Spring beans! •
• Easy pluginsEasy plugins - Struts 2 extensions can be added by dropping in a JAR. No- Struts 2 extensions can be added by dropping in a JAR. No manual configuration required!
manual configuration required! •
• AJAX supportAJAX support - The AJAX theme gives interactive applications a significant- The AJAX theme gives interactive applications a significant boost.
boost.
The framework provides a set of tags to
The framework provides a set of tags to help you ajaxify your applications, evenhelp you ajaxify your applications, even on Dojo. The AJAX features include:
on Dojo. The AJAX features include: 1.
1. AJAJAX ClAX Clieient Sint Side Vade Valilidatdatioionn 2.
2. RemotRemote form se form submisubmission ssion support (upport (works works with twith the submihe submit tag as t tag as wellwell)) 3.
3. An advanAn advanced div tced div templatemplate that pre that provides dovides dynamiynamic reloac reloading of pding of partiartialal HTML
HTML 4.
4. An advanAn advanced a temced a template tplate that prohat provides vides the abilthe ability to ity to load and load and evaluaevaluatete JavaScript remotely
JavaScript remotely 5.
5. An AJAAn AJAX-oX-only tnly tabbabbed Paneed Panel impl implemlemententatiationon 6.
6. A riA rich pch pub-ub-susub evb evenent mot modedell 7.
7. IntInteraeractictive ve autauto co compompletlete te tagag
Struts 1.x Vs Struts 2.x
Struts 1.x Vs Struts 2.x
In the following section, we are
In the following section, we are going to compare the various features between going to compare the various features between the twothe two frameworks. Struts
frameworks. Struts 2.x 2.x is very is very simple in comsimple in comparison to the sparison to the struts 1.x , truts 1.x , few of itfew of itss excelling features are:
excelling features are: 1.
1. Servlet Servlet Dependency:Dependency:
Actions in Struts
Actions in Struts 1 1 have dependencies on the shave dependencies on the servlet API siervlet API since thence theHttpServletRequestHttpServletRequest
and
and HttpServletResponseHttpServletResponse objects are passed to theobjects are passed to the executeexecute method when an Action ismethod when an Action is invoked but in case of Struts 2 , Actions are not container dependent because they are invoked but in case of Struts 2 , Actions are not container dependent because they are made simple POJOs. In struts 2, the servlet contexts are
made simple POJOs. In struts 2, the servlet contexts are represented as simple Mapsrepresented as simple Maps which allows actions to be tested in isolation. Struts 2 Actions can access the original which allows actions to be tested in isolation. Struts 2 Actions can access the original request and response, if required. However,
request and response, if required. However, other architectural elements reduce or other architectural elements reduce or eliminate the need to access
eliminate the need to access the HttpServetRequest or HttpServletResponse directly.the HttpServetRequest or HttpServletResponse directly.
2.
2. Action Action classesclasses
Programming the abstract classes instead of interfaces is one of
Programming the abstract classes instead of interfaces is one of design issues of struts1design issues of struts1 framework that has been resolved in
framework that has been resolved in the struts 2 framework.the struts 2 framework.
Struts 1 Action classes needs to extend framework dependent abstract base class. But in Struts 1 Action classes needs to extend framework dependent abstract base class. But in case of Struts 2 Action class
custom services. In case of Struts 2 , Actions are not container dependent because they custom services. In case of Struts 2 , Actions are not container dependent because they are made simple POJOs. Struts 2 provides a
are made simple POJOs. Struts 2 provides a base ActionSupport class to implementbase ActionSupport class to implement commonly used interfaces. Albeit, the Action interface is
commonly used interfaces. Albeit, the Action interface isnotnotrequired. Any POJO objectrequired. Any POJO object with a
with aexecuteexecute signature can be used as signature can be used as an Struts 2 Action object.an Struts 2 Action object.
3. Validation
3. Validation
Struts 1 and Struts 2
Struts 1 and Struts 2 both supports the both supports the manual validation via amanual validation via avalidatevalidate method.method. Struts 1 uses validate method on
Struts 1 uses validate method on the ActionForm, or validates through an ethe ActionForm, or validates through an extension to thextension to the Commons Validator. However, Struts 2 supports manual validation via the
Commons Validator. However, Struts 2 supports manual validation via the validatevalidate method and the XWork Va
method and the XWork Validation framework. The Xwork Validation Framework lidation framework. The Xwork Validation Framework supports chaining validation into sub-properties using the validations defined
supports chaining validation into sub-properties using the validations defined for thefor the properties class type and the validation context.
properties class type and the validation context. 4.
4. Threading Threading ModelModel
In Struts 1, Action resources must be thread-safe or synchronized. So Actions are In Struts 1, Action resources must be thread-safe or synchronized. So Actions are singletons and thread-safe, there should only be
singletons and thread-safe, there should only be one instance of a class to one instance of a class to handle allhandle all requests for that Action. The singleton strategy places restrictions on what can
requests for that Action. The singleton strategy places restrictions on what can be donebe done with Struts 1 Actions and requires extra care to develop. However in case of Struts 2, with Struts 1 Actions and requires extra care to develop. However in case of Struts 2, Action objects are instantiated for each request,
Action objects are instantiated for each request, so there are no thread-safety issues. (Inso there are no thread-safety issues. (In practice, servlet containers generate many throw-away objects per request,
practice, servlet containers generate many throw-away objects per request, and one moreand one more object does not impose a performance penalty or impact garbage collection.)
object does not impose a performance penalty or impact garbage collection.) 5. Testability
5. Testability
Testing Struts1 applications are a bit complex.
Testing Struts1 applications are a bit complex. A major hurdle to test Struts 1 Actions isA major hurdle to test Struts 1 Actions is that the
that the executeexecutemethod because it exposes the Servlet API. A third-party extension,method because it exposes the Servlet API. A third-party extension, Struts TestCase, offers a set of mock object for S
Struts TestCase, offers a set of mock object for Struts 1. But the Struts 2 Actions can betruts 1. But the Struts 2 Actions can be tested by instantiating the Action, setting properties, and invoking
tested by instantiating the Action, setting properties, and invoking methods. Dependencymethods. Dependency Injection support also makes testing simpler. Actions in struts2 are simple POJOs and are Injection support also makes testing simpler. Actions in struts2 are simple POJOs and are framework independent,
framework independent, hence testability hence testability is quite easy is quite easy in struts2.in struts2.
6.
6. Harvesting Harvesting InputInput
Struts 1 uses an ActionForm object to capture input. And all ActionForms needs to Struts 1 uses an ActionForm object to capture input. And all ActionForms needs to
extend a framework dependent base class. JavaBeans cannot be used as ActionForms, so extend a framework dependent base class. JavaBeans cannot be used as ActionForms, so the developers have to create redundant classes to capture input.
the developers have to create redundant classes to capture input. However the Struts 2 uses Action properties (as input
However the Struts 2 uses Action properties (as input properties independent of properties independent of
underlying framework) that eliminates the need for a second input object, hence reduces underlying framework) that eliminates the need for a second input object, hence reduces redundancy. Additionally in struts2, Action properties can be ac
redundancy. Additionally in struts2, Action properties can be accessed from the web pagecessed from the web page via the taglibs. Struts 2 also supports the ActionForm
via the taglibs. Struts 2 also supports the ActionForm pattern, as well as POJO formpattern, as well as POJO form objects and POJO Actions. Even
objects and POJO Actions. Even rich object types, including business or domain objects,rich object types, including business or domain objects, can be used as input/output objects.
can be used as input/output objects. 7.
Struts 1 integrates with JSTL, so it uses the JSTL-EL. The
Struts 1 integrates with JSTL, so it uses the JSTL-EL. The struts1 EL has basic objectstruts1 EL has basic object graph traversal, but relatively weak collection and
graph traversal, but relatively weak collection and indexed property support. Struts 2 canindexed property support. Struts 2 can also use JSTL, however it supports a
also use JSTL, however it supports a more powerful and flexible expression languagemore powerful and flexible expression language called "Object Graph Notation Language" (OGNL).
called "Object Graph Notation Language" (OGNL). 8.
8. Binding values Binding values into into viewsviews
In the view section, Struts 1 uses
In the view section, Struts 1 uses the standard JSP mechanism to bind obthe standard JSP mechanism to bind objects(processedjects(processed from the model section) into the page
from the model section) into the page context to access . However Scontext to access . However Struts 2 uses atruts 2 uses a
"ValueStack" technology so that the taglibs can access values without coupling your view "ValueStack" technology so that the taglibs can access values without coupling your view to the object type it is rendering. The
to the object type it is rendering. The ValueStack strategy allows the reuse of viewsValueStack strategy allows the reuse of views across a range of types which may
across a range of types which may have the same property name buhave the same property name but different propertyt different property types.
types. 9.
9. Type Type ConversionConversion
usually , Struts 1 ActionForm properties are all Strings. Struts 1 uses Commons-Beanutils usually , Struts 1 ActionForm properties are all Strings. Struts 1 uses Commons-Beanutils for type conversion. These type converters are per-class, and not configurable per
for type conversion. These type converters are per-class, and not configurable per instance. However Struts 2 uses OGNL for type
instance. However Struts 2 uses OGNL for type conversion. The framework includesconversion. The framework includes converters for basic and common object types and primitives.
converters for basic and common object types and primitives. 10.
10. Control Of Control Of Action ExecutionAction Execution
Struts 1 supports separate Request Processors (lifecycles) for each module, but all Struts 1 supports separate Request Processors (lifecycles) for each module, but all thethe Actions in a module must share
Actions in a module must share the same lifecycle. However Struts 2 supports creatingthe same lifecycle. However Struts 2 supports creating different lifecycles on a per Action basis via Interceptor Stacks.
different lifecycles on a per Action basis via Interceptor Stacks. Custom stacks can beCustom stacks can be created and used with different Actions, as needed.
created and used with different Actions, as needed.
Download Struts 2.0
Download Struts 2.0
In this section we will download and
In this section we will download and install the Struts 2.0 on the latest version of Tomcatinstall the Struts 2.0 on the latest version of Tomcat container. We will first download tomcat and con
container. We will first download tomcat and configure it as our development server.figure it as our development server. Then we will download S
Then we will download Struts 2.0 and install the struts-blank application on the tomcattruts 2.0 and install the struts-blank application on the tomcat server server to check the ex
server server to check the examples that comes with the struts-blank application.amples that comes with the struts-blank application.
Downloading Struts 2.0
Downloading Struts 2.0
Visit the Struts download site
Visit the Struts download site http://struts.apache.org/download.cgihttp://struts.apache.org/download.cgiand download theand download the Struts 2.0 for this
We have download
We have download the Struts 2.0.6 (struts-2.0.6-all.zip) for this tutorial.the Struts 2.0.6 (struts-2.0.6-all.zip) for this tutorial.
Download the Tomcat
Download the Tomcat
Download the latest version of tomcat from
Download the latest version of tomcat from http://tomcat.apache.org/download-55.cgihttp://tomcat.apache.org/download-55.cgi.. We have downloaded
I am assuming that latest version of Java
I am assuming that latest version of Java is installed on your system. Extract downloadedis installed on your system. Extract downloaded file and run the C:\apache-tomcat-5.5.20\bin\startup.bat to start the tomcat.
file and run the C:\apache-tomcat-5.5.20\bin\startup.bat to start the tomcat. TypeType http://localhost:8080/
http://localhost:8080/ in your browser, it should show the welcome page in the browser in your browser, it should show the welcome page in the browser window as shown below.
Congratulations you have now successfully installed latest version of tomcat for learning Congratulations you have now successfully installed latest version of tomcat for learning Struts 2.0. Now we will install the struts-blank application on
Struts 2.0. Now we will install the struts-blank application on the tomcat container andthe tomcat container and test the application.
test the application.
Extracting Struts 2.0 distribution and installing on tomcat
Extracting Struts 2.0 distribution and installing on tomcat
Extract the downloaded
Extract the downloaded struts distribution struts-2.0.6-all.zip into your favoritestruts distribution struts-2.0.6-all.zip into your favorite directory. To install the struts blank application copy "struts2-blank-2.0.6" from directory. To install the struts blank application copy "struts2-blank-2.0.6" from "
"<extracted directory>\struts-2.0.6-all\struts-2.0.6\apps<extracted directory>\struts-2.0.6-all\struts-2.0.6\apps" into the webapps directory of " into the webapps directory of tomcat. Tomcat will automatically deploy the application.
tomcat. Tomcat will automatically deploy the application.
Feb 25, 2007 11:42:23 PM org.apache.coyote.http11.Http11BaseProtocol start Feb 25, 2007 11:42:23 PM org.apache.coyote.http11.Http11BaseProtocol start INFO: Starting Coyote HTTP/1.1 on http-8080
INFO: Starting Coyote HTTP/1.1 on http-8080
Feb 25, 2007 11:42:24 PM org.apache.jk.common.ChannelSocket init Feb 25, 2007 11:42:24 PM org.apache.jk.common.ChannelSocket init
INFO: JK: ajp13 listening on /0.0.0.0:8009 INFO: JK: ajp13 listening on /0.0.0.0:8009
Feb 25, 2007 11:42:24 PM org.apache.jk.server.JkMain start Feb 25, 2007 11:42:24 PM org.apache.jk.server.JkMain start INFO: Jk running ID=0 time=0/141 config=null
INFO: Jk running ID=0 time=0/141 config=null
Feb 25, 2007 11:42:24 PM org.apache.catalina.storeconfig.StoreLoader load Feb 25, 2007 11:42:24 PM org.apache.catalina.storeconfig.StoreLoader load INFO: Find registry server-registry.xml at classpath resource
INFO: Find registry server-registry.xml at classpath resource
Feb 25, 2007 11:42:24 PM org.apache.catalina.startup.Catalina start Feb 25, 2007 11:42:24 PM org.apache.catalina.startup.Catalina start INFO: Server startup in 6672 ms
INFO: Server startup in 6672 ms
Feb 25, 2007 11:52:55 PM org.apache.catalina.startup.HostConfig Feb 25, 2007 11:52:55 PM org.apache.catalina.startup.HostConfig deployWAR
deployWAR
INFO: Deploying web application archive struts2-blank-2.0.6.war INFO: Deploying web application archive struts2-blank-2.0.6.war
To test the struts-blank application type
To test the struts-blank application type http://localhost:8080/struts2-blank-2.0.6http://localhost:8080/struts2-blank-2.0.6in thein the browser and the struts-blank application get displayed in your b
browser and the struts-blank application get displayed in your browser window.rowser window.
Click the English link and familiarize yourself with Struts Blank sample application. Click the English link and familiarize yourself with Struts Blank sample application. Struts 2.0 distribution also contains the following samples applications that you can Struts 2.0 distribution also contains the following samples applications that you can try:try:
• • struts2-mailreader-2.0.6.war struts2-mailreader-2.0.6.war • • struts2-portlet-2.0.6.war struts2-portlet-2.0.6.war • • struts2-showcase-2.0.6.war struts2-showcase-2.0.6.war You can simply copy these files to the
You can simply copy these files to the webapps directory of your tomcat server. Tomcatwebapps directory of your tomcat server. Tomcat will automatically deploy these application and then
Struts
Struts 2 Hello World - Developing
2 Hello World - Developing Hello W
Hello World
orld
Application
Application
In this section we will develop
In this section we will develop Hello WorldHello World based onbased onStruts 2 Framework Struts 2 Framework . Our . Our StrutsStruts
2 Hello World
2 Hello World application is your first step towards developing applications based onapplication is your first step towards developing applications based on Struts 2 Framework
Struts 2 Framework . We are here providing step by step guide for developing. We are here providing step by step guide for developing HelloHello
World
Worldapplication in Struts 2 framework.application in Struts 2 framework.
Tutorial covers basic steps like creating directory structure, developing bu
Tutorial covers basic steps like creating directory structure, developing build.xml file toild.xml file to build the application using ant build tool. Then we have explained Java, JSP and
build the application using ant build tool. Then we have explained Java, JSP and configuration files that is required in this application.
configuration files that is required in this application. Creating directory structure for the project
Creating directory structure for the project
Step1:
Step1: Extract struts 2 download and copyExtract struts 2 download and copy struts2-blank-2.0.6.warstruts2-blank-2.0.6.war(If you are using(If you are using latest version of struts 2 then version may be different for
latest version of struts 2 then version may be different for you) to your tomcatsyou) to your tomcatswebappswebapps
directory. Rename
directory. Rename struts2-blank-2.0.6.warstruts2-blank-2.0.6.war totostruts2tutorialstruts2tutorial and unzip it in the and unzip it in the tomcatstomcats webapps directory. Now start the tomcat and type
webapps directory. Now start the tomcat and type http://localhost:8080/struts2tutorial/http://localhost:8080/struts2tutorial/ into your browser. You browser should show look
into your browser. You browser should show look like:like:
Congratulations you have successfully installed struts 2 blank application to start with. Congratulations you have successfully installed struts 2 blank application to start with.
Step 2:
Step 2: Now delete the content of Now delete the content of struts2tutorial\WEB-INF\srcstruts2tutorial\WEB-INF\src andand struts2tutorial\WEB-INF\classes
struts2tutorial\WEB-INF\classes directories, as we don't need these directories, as we don't need these files that comesfiles that comes with struts 2 blank application.
with struts 2 blank application. Step 3:
Step 3: CreateCreatebuild.xmlbuild.xml file in thefile in the struts2tutorial\WEB-INF\srcstruts2tutorial\WEB-INF\src and paste theand paste the following content in the
following content in the build.xmlbuild.xml file.file.
<project name="Struts 2 Tutorial" basedir="../" default="all"> <project name="Struts 2 Tutorial" basedir="../" default="all">
<!-- Project settings --> <!-- Project settings -->
<property name="project.title" value="RoseIndia Struts 2 Tutorials"/> <property name="project.title" value="RoseIndia Struts 2 Tutorials"/>
<property name="project.jar.file" value="struts2tutorial.jar"/> <property name="project.jar.file" value="struts2tutorial.jar"/>
<path id="class.path"> <path id="class.path"> <fileset dir="lib"> <fileset dir="lib"> <include name="**/*.jar"/> <include name="**/*.jar"/> </fileset> </fileset> <fileset dir="libext"> <fileset dir="libext"> <include name="**/*.jar"/> <include name="**/*.jar"/> </fileset> </fileset> </path> </path>
<!-- Classpath for Project --> <!-- Classpath for Project --> <path id="compile.classpath"> <path id="compile.classpath">
<pathelement path ="lib/commons-beanutils.jar"/> <pathelement path ="lib/commons-beanutils.jar"/> <pathelement path ="lib/commons-digester.jar"/> <pathelement path ="lib/commons-digester.jar"/> <pathelement path ="lib/struts.jar"/>
<pathelement path ="lib/struts.jar"/>
<pathelement path ="libext/servlet-api.jar"/> <pathelement path ="libext/servlet-api.jar"/> <pathelement path ="libext/catalina-ant.jar"/> <pathelement path ="libext/catalina-ant.jar"/> <pathelement path ="classes"/>
<pathelement path ="classes"/>
<pathelement path ="${classpath}"/> <pathelement path ="${classpath}"/> </path>
</path>
<!-- Check timestamp on files --> <!-- Check timestamp on files --> <target name="prepare"> <target name="prepare"> <tstamp/> <tstamp/> <copy <copy file="src/struts.xml" file="src/struts.xml"
todir="src/classes"/> todir="src/classes"/>
</target> </target>
<!-- Copy any resource or configuration files --> <!-- Copy any resource or configuration files --> <target name="resources">
<target name="resources">
<copy todir="src/classes" includeEmptyDirs="no"> <copy todir="src/classes" includeEmptyDirs="no">
<fileset dir="src/java"> <fileset dir="src/java"> <patternset> <patternset> <include name="**/*.conf"/> <include name="**/*.conf"/> <include name="**/*.properties"/> <include name="**/*.properties"/> <include name="**/*.xml"/> <include name="**/*.xml"/> </patternset> </patternset> </fileset> </fileset> </copy> </copy> </target> </target>
<!-- Normal build of application --> <!-- Normal build of application -->
<target name="compile" depends="prepare,resources"> <target name="compile" depends="prepare,resources">
<javac srcdir="src" destdir="src/classes" <javac srcdir="src" destdir="src/classes"
debug="true" debuglevel="lines,vars,source"> debug="true" debuglevel="lines,vars,source"> <classpath refid="class.path"/> <classpath refid="class.path"/> </javac> </javac> <jar <jar jarfile="lib/${project.jar.file}" jarfile="lib/${project.jar.file}" basedir="src/classes"/> basedir="src/classes"/> </target> </target>
<!-- Remove classes directory for clean build --> <!-- Remove classes directory for clean build --> <target name="clean"
<target name="clean"
description="Prepare for clean build"> description="Prepare for clean build"> <delete dir="classes"/>
<delete dir="classes"/> <mkdir dir="classes"/> <mkdir dir="classes"/>
</target> </target>
<!-- Build Javadoc documentation --> <!-- Build Javadoc documentation --> <target name="javadoc"
<target name="javadoc"
description="Generate JavaDoc API docs"> description="Generate JavaDoc API docs">
<delete dir="./doc/api"/> <delete dir="./doc/api"/> <mkdir dir="./doc/api"/> <mkdir dir="./doc/api"/> <javadoc sourcepath="./src/java" <javadoc sourcepath="./src/java" destdir="./doc/api" destdir="./doc/api" classpath="${servlet.jar}:${jdbc20ext.jar}" classpath="${servlet.jar}:${jdbc20ext.jar}" packagenames="*" packagenames="*" author="true" author="true" private="true" private="true" version="true" version="true" windowtitle="${project.title} API windowtitle="${project.title} API Documentation" Documentation" doctitle="<h1>${project.title} doctitle="<h1>${project.title} Documentation (Version $ Documentation (Version $ {project.version})</h1>" {project.version})</h1>" bottom="Copyright © 2002"> bottom="Copyright © 2002"> <classpath refid="compile.classpath"/> <classpath refid="compile.classpath"/> </javadoc> </javadoc> </target> </target>
<!-- Build entire project --> <!-- Build entire project -->
<target name="project" depends="clean,prepare,compile"/> <target name="project" depends="clean,prepare,compile"/> <!-- Create binary distribution -->
<!-- Create binary distribution --> <target name="dist"
<target name="dist"
description="Create binary distribution"> description="Create binary distribution"> <mkdir <mkdir dir="${distpath.project}"/> dir="${distpath.project}"/> <jar <jar
jarfile="${distpath.project}/$ jarfile="${distpath.project}/$ {project.distname}.jar" {project.distname}.jar" basedir="./classes"/> basedir="./classes"/> <copy <copy file="${distpath.project}/${project.distname}.jar" file="${distpath.project}/${project.distname}.jar" todir="${distpath.project}"/> todir="${distpath.project}"/> <war <war basedir="../" basedir="../" warfile="${distpath.project}/$ warfile="${distpath.project}/$ {project.distname}.war" {project.distname}.war" webxml="web.xml"> webxml="web.xml"> <exclude name="${distpath.project}/$ <exclude name="${distpath.project}/$ {project.distname}.war"/> {project.distname}.war"/> </war> </war> </target> </target>
<!-- Build project and create distribution--> <!-- Build project and create distribution-->
<target name="all" depends="project"/> <target name="all" depends="project"/>
</project> </project> Step 4:
Step 4: Create directoryCreate directorylibextlibext under theunder thestruts2tutorial\WEB-INF\struts2tutorial\WEB-INF\ then you copy latestthen you copy latest Servlets api jar (in our case
Servlets api jar (in our case servlet-api.jar servlet-api.jar ) file over there. This library file will be used to) file over there. This library file will be used to compile Servlets in our application.
compile Servlets in our application. Step 5:
Step 5: Now create directoriesNow create directories java java andandclassesclasses under under struts2tutorial\WEB-INF\src.struts2tutorial\WEB-INF\src.
The directory
The directory struts2tutorial\WEB-INF\src\javastruts2tutorial\WEB-INF\src\java will be used to put all the will be used to put all the java sourcesjava sources file and directory
file and directory struts2tutorial\WEB-INF\src\classesstruts2tutorial\WEB-INF\src\classes will be used by ant build utilitywill be used by ant build utility to stored compile java files.
to stored compile java files.
Now we have successfully created the directory structure and ant build file for out Struts Now we have successfully created the directory structure and ant build file for out Struts
2 Hello World Application. In the
2 Hello World Application. In the next section we will create JSP, Java file annext section we will create JSP, Java file and thed the configuration file and then test our Struts 2
Writing JSP, Java and Configuration for Hello
Writing JSP, Java and Configuration for Hello
World Application
World Application
In this section we will write JSP, Java and
In this section we will write JSP, Java and required configuration files for our Struts 2required configuration files for our Struts 2 Hello World application. Now in struts 2
Hello World application. Now in struts 2 struts.xmlstruts.xml is used to configure the applications.is used to configure the applications.
Understanding the application
Understanding the application
Our application is very simple application that displays Hello World message along Our application is very simple application that displays Hello World message along withwith current date and time of the server. When user clicks on the "
current date and time of the server. When user clicks on the "Run Struts 2 Hello WorldRun Struts 2 Hello World
Application
Application" link on the tutorial home " link on the tutorial home page, a request is sent to the page, a request is sent to the struts framework.struts framework. Then struts framework sends the input to the
Then struts framework sends the input to the action class (in our caseaction class (in our case
Struts2HelloWorld.java). After action is fired the Result selects the resource Struts2HelloWorld.java). After action is fired the Result selects the resource "/pages/HelloWorld.jsp" to render the response.
"/pages/HelloWorld.jsp" to render the response.
In this example we have to develop three parts view, Action class and mapping In this example we have to develop three parts view, Action class and mapping (struts.xml) to couple action and page.
(struts.xml) to couple action and page. By creating these three components we By creating these three components we areare separating the application in three parts View,
separating the application in three parts View, Model and Controller.Model and Controller.
Developing View:
Developing View:
This page is used to display the
This page is used to display the result on the browser. The HelloWorld.jsp is view part of result on the browser. The HelloWorld.jsp is view part of our application. Create "HelloWorld.jsp" in the struts2tutorial\pages directory and add the our application. Create "HelloWorld.jsp" in the struts2tutorial\pages directory and add the following content:
following content:
<%@ taglib prefix="s" uri="/struts-tags" %>
<%@ taglib prefix="s" uri="/struts-tags" %>
<html> <html> <head> <head>
<title>Struts 2 Hello World Application!</title> <title>Struts 2 Hello World Application!</title> </head>
</head> <body> <body> <h2>
<h2><s:property value="message" /><s:property value="message" /></h2></h2> <p>Current date and time is: <b>
<p>Current date and time is: <b><s:property value="currentTime" /><s:property value="currentTime" /></b></b> </body>
</body> </html> </html> The line
The line <%@ taglib prefix="s" uri="/struts-tags" %><%@ taglib prefix="s" uri="/struts-tags" %> declares data tag library of thedeclares data tag library of the struts. The struts data tag is used to display the
struts. The struts data tag is used to display the dynamic data. The tagdynamic data. The tag<s:property<s:property
value="message" />
value="message" /> andand<s:property value="currentTime" /><s:property value="currentTime" /> calls the methodscalls the methods getMessage() and getCurrentTime() respectively of the Struts2HelloWorld action class getMessage() and getCurrentTime() respectively of the Struts2HelloWorld action class and merges the values with response.
and merges the values with response.
Developing Action (to interact with Model):