+ All Categories
Home > Documents > Hospitality Northwest Struts Training Material

Hospitality Northwest Struts Training Material

Date post: 07-Dec-2015
Category:
Upload: ro
View: 222 times
Download: 1 times
Share this document with a friend
Description:
n
Popular Tags:
60
STRUTS STRUTS Intermediate Intermediate
Transcript
Page 1: Hospitality Northwest Struts Training Material

STRUTSSTRUTSSTRUTSSTRUTS

IntermediateIntermediate

Page 2: Hospitality Northwest Struts Training Material

©Copyright 2004, Cognizant Academy, All Rights Reserved 2

About the Author

Created By: Aman Sindhwani (108624) & Shilpi Das (102831)

Credential Information:

<enter the trainer’s credentials>

Version and Date:

1.0

14-05-2004

Page 3: Hospitality Northwest Struts Training Material

©Copyright 2004, Cognizant Academy, All Rights Reserved 3

Icons used

Questions References

Key Concepts

A Welcome Break

Demo

Brain Teasers

Page 4: Hospitality Northwest Struts Training Material

©Copyright 2004, Cognizant Academy, All Rights Reserved 4

Courseware Information

Course Description

•Struts is a light weight, open source framework for building web applications.

•It is based on MVC (Model-View-Controller) design pattern and on standard technologies like Java Servlets, JavaBeans, ResourceBundles, and XML, as well as various packages provided by Jakarta.

•Struts helps you create an extensible development environment for your application, based on published standards and proven design patterns.

•Struts also provides us various other frameworks like Struts Validator & Tiles Framework.

Level Intermediate.

Prerequisites Participant must have the basic knowledge of Java & MVC architecture.

Page 5: Hospitality Northwest Struts Training Material

©Copyright 2004, Cognizant Academy, All Rights Reserved 5

Course Objective & Outline

Course Objective:After completing this course, you will able to successfully implement Struts along with

Validator & Tiles Framework in a web-based application.

Course Flow:

2.Request Flow

in a typical Struts

Architecture

3.Configuring

recipe

1.MVC Overview

4.Struts

Validator Framework

5.Tiles

Framework

6. Some Struts

Features

Page 6: Hospitality Northwest Struts Training Material

©Copyright 2004, Cognizant Academy, All Rights Reserved 6

1.0 MVC Overview

Introduction: Struts is an implementation of a popular design pattern called “Model-View-Controller” or MVC. To understand

what struts is, we need a brief understanding of MVC first.

Objective: After completing this module, you will be able to have the basic knowledge of design pattern on which struts is

based upon.

1 . Overview Of Model-View-Controller (MVC)

Page 7: Hospitality Northwest Struts Training Material

©Copyright 2004, Cognizant Academy, All Rights Reserved 7

Overview Of Model-View-Controller (MVC)

The MVC design pattern divides applications into three components:· the model maintains the state and data that the application represents· the view allows the display of information about the model to the user· the controller allows the user to manipulate the application

Model · Contains the core of the application’s functionality· Encapsulates the state of the application· Knows nothing about the view or the controller

View· Provides presentation of the model· Knows nothing about the controller

Controller· Reacts to the user input, that is, controls the flow and state of the user input

Page 8: Hospitality Northwest Struts Training Material

©Copyright 2004, Cognizant Academy, All Rights Reserved 8

Overview Of Model-View-Controller (MVC) ….. Cont.

Basic MVC architecture – Application flow - mediated by a central Controller. – Controller delegates requests to appropriate handler. – Handler acts as an adapter between the request and the Model. – Model represents, or encapsulates, an application's business logic or state. – Control is usually then forwarded back through the Controller to the appropriate View. – Request forwarding is determined by a set of mappings, usually loaded from configuration file.

Advantage:

Loose coupling between the View and Model (which makes applications significantly easier to create and maintain).

Page 9: Hospitality Northwest Struts Training Material

©Copyright 2004, Cognizant Academy, All Rights Reserved 9

MVC Overview : Summary

MVC design pattern basically modularizes the application .It results in loose coupling between 2 tiers. Any change in the model layer doesn’t effect the presentation layer. This leads to significantly easier creation and maintenance of applications.

Page 10: Hospitality Northwest Struts Training Material

©Copyright 2004, Cognizant Academy, All Rights Reserved 10

Struts and MVC

• Struts is a light weight, open source framework for building web applications with Servlet and JSP technology, based on the MVC design pattern and resides in the Web-tier of a typical web application

• Craig R. McClanahan created struts framework in 2000.

• Struts adds on more to MVC design pattern which makes it a very powerful framework for complex web applications.

• Struts framework adds modules, which help us to do away from repetitive tasks like request processing, mapping events to actions, user input validation etc. With help of struts provided components like the action servlet, xml configuration files, xml validation files, form beans, action classes, taglibs; we can reduce coding effort for the above repetitive tasks. This in turn reduces development and testing time.

Page 11: Hospitality Northwest Struts Training Material

©Copyright 2004, Cognizant Academy, All Rights Reserved 11

Struts and Model

• The model includes the business entities and the rules that govern access to and modification of

data.• The components within the Model should not be aware of what type of client or framework is using

it.• Struts framework is independent of the Model used.• Ideally, packages or classes from the Struts framework should not be used in the model part of any

application built on the Struts framework.

Page 12: Hospitality Northwest Struts Training Material

©Copyright 2004, Cognizant Academy, All Rights Reserved 12

  Struts View

• Generally constructed using JSP• Additional components that can be used by or in conjunction with jsp are as follows:• § HTML, JavaScript, StyleSheet etc• § JSP custom tag libraries (Struts includes an extensive custom tag library)• § Message Resource bundles • § ActionForm classes• § Tiles (Tiles is a powerful templating library that can be used in conjunction with JSP. Tiles

build on the "include" feature provided by the JSP specification. For more information, refer to : http://jakarta.apache.org/struts/userGuide/dev_tiles.html)

Page 13: Hospitality Northwest Struts Training Material

©Copyright 2004, Cognizant Academy, All Rights Reserved 13

Struts Controller

• Controller acts as a mediator/translator between client input and the model, providing common functionality such as security, logging etc on behalf of each client request.

• All requests are filtered through the controller. Hence view is decoupled from the business logic and other view components.

• Chief responsibilities of Struts controller are:• § Intercepting client requests• § Mapping each request to a specified business operation• § Collecting results from the business operation and making them available to the client• § Determining the view to display to the client based on the current state and result of the

business operation.

Page 14: Hospitality Northwest Struts Training Material

©Copyright 2004, Cognizant Academy, All Rights Reserved 14

MVC Overview : Quiz

• Struts Plays a pivotal role in Model layer of MVC Framework.– True– False

• False

Page 15: Hospitality Northwest Struts Training Material

©Copyright 2004, Cognizant Academy, All Rights Reserved 15

2.0 Request Flow in a typical Struts Architecture : Overview

Introduction:

Whenever any request is made from the client , how that request is processed and what is the overall flow of that request is the 1st question that comes to our mind. So We’ll try to see the complete request flow in a typical Struts architecture and how actually Struts fits in a MVC architecture.

Objective: After completing this module, you will know about the following :

1. Primary Components in Struts

2. Overall picture of Request Flow.

3. Struts Components – Details

4. Diagrammatic Representation of Struts

5. Work Flow of Struts

Page 16: Hospitality Northwest Struts Training Material

©Copyright 2004, Cognizant Academy, All Rights Reserved 16

Primary Components in Struts

• Struts View Primary Component – ActionForm – ActionForm is the class representation of a JSP page. It contains all the attributes that the corresponding

JSP page has as elements. It is used to capture input data from an HTML form and transfer it to the controller (Action class).

– The framework automatically collects the input from the request.– Action Form class acts as a buffer to hold the state of the data that the user has entered, while it is being

validated and this data can also be re-displayed to the user when an error occurs.– Instances of ActionForm class referred to a “form beans”.

• Struts Controller –Primary Components– ActionServlet – Acts as the interceptor for a Struts application (Struts provided)– RequestProcessor – This is where the majority of the core processing occurs for each request. (Struts

1.1 onwards) (Struts provided)– Action classes – Bridge between client request and business operation. (Developer needs to build this)– ActionMapping – Used for mapping request URI to an appropriate Action class (Struts provided)

Page 17: Hospitality Northwest Struts Training Material

©Copyright 2004, Cognizant Academy, All Rights Reserved 17

Primary Components in Struts …. Cont.

• Struts framework uses two separate XML-based configuration files

• 1. Web.xml -> This is the web application deployment descriptor, whose configuration is required fro all web applications. There is Struts-specific deployment information that must be configured here

• 2. struts-config.xml -> This is the Struts configuration file, commonly referred by this name but different name can be used for this file but the name needs to be specified in web.xml

• 3. Other configuration files might be necessary for Validator and tiles

Page 18: Hospitality Northwest Struts Training Material

©Copyright 2004, Cognizant Academy, All Rights Reserved 18

Overall picture of Request Flow

Flow Of Request

Client( Web Browser)

ActionServlet and RequestProcessor

(Controller)

View

Action (Controller)

Model

DB

Req

Res

•Every Http request comes to the ActionServlet (Processes the request using RequestProcessor).

•ActionServlet internally calls RequestProcessor to process each and every request.

•Request Processor maps every request to desired Action Class and transfer the control to that handler.

•Action Classes then calls the business methods to fetch the requested data & returns a reference to a destination url in the form of an ActionForward (may be a jsp or another action classmapping).

•Control again goes to ActionServlet which finally forwards the request to the referred ActionForward.

•If the referred ActionForward is a jsp, it is invoked and client is shown with the page.

Page 19: Hospitality Northwest Struts Training Material

©Copyright 2004, Cognizant Academy, All Rights Reserved 19

Struts Components - Details

• The following slides discusses in details the following Struts components– ActionForm– ActionServlet– RequestProcessor– Action class– ActionError– Dynamic ActionForm

Page 20: Hospitality Northwest Struts Training Material

©Copyright 2004, Cognizant Academy, All Rights Reserved 20

ActionForm

• Java class that extends the org.apache.struts.action.ActionForm• Captures user data from the Http request• Stores the data temporarily• Acts as a “firewall” between the presentation tier and the application• Provides the ability to validate the user input• ActionForm can have both request and session scope. Default is session. Needs to be specified in struts-

config.xml• reset() method in ActionForm-> controller calls it right before it populates ActionForm instance with values

form the request. Used for resetting ActionForm properties as form bean instance may be shared across different request or accessed by different threads. For ActionForm with request scope, the framework will create a new instance for each new request; hence no need to reset to default.

• validate() method in ActionForm -> called by the controller after the values from the request have been inserted into the ActionForm. Performs any input validation and return the errors to the controller. No business validation should be here, only presentation layer validation allowed.

Page 21: Hospitality Northwest Struts Training Material

©Copyright 2004, Cognizant Academy, All Rights Reserved 21

ActionForm Life cycle

Page 22: Hospitality Northwest Struts Training Material

©Copyright 2004, Cognizant Academy, All Rights Reserved 22

ActionServlet

• Extends javax.servlet.http.HttpServlet• Receives all framework requests• Selects proper application module• Delegates request handling to the RequestProcessor instance• One ActionServlet instance per web application• Default implementation provided by framework (can extend if necessary)

Page 23: Hospitality Northwest Struts Training Material

©Copyright 2004, Cognizant Academy, All Rights Reserved 23

RequestProcessor

• One instance per application module• Processes all requests for module• Invokes proper Action instance• Default implementation provided by framework (can extend if necessary)

Page 24: Hospitality Northwest Struts Training Material

©Copyright 2004, Cognizant Academy, All Rights Reserved 24

Action class

• Heart of the Struts framework • Extends org.apache.struts.action.Action• Developer Overrides the execute()method• Acts as a bridge between user-invoked URI and a business method • Returns information about which view should be rendered next, encapsulated in an object of type

ActionForward.• Each Action is typically designed to perform a single business operation on behalf of a client.

• Method Signature

public ActionForward execute(ActionMapping mapping,ActionForm form, HttpServletRequest request, HttpServletResponse response )

Page 25: Hospitality Northwest Struts Training Material

©Copyright 2004, Cognizant Academy, All Rights Reserved 25

ActionError

• Used to signify general purpose informational and error messages• Rely on the Resource Bundles (Constructor for ActionErrors(String key corresponding to a resource

bundle ))• JSP Tags can access them • There is a custom tag called Errors Tag which makes retrieving and displaying error messages very

easy)• <html:errors />

Page 26: Hospitality Northwest Struts Training Material

©Copyright 2004, Cognizant Academy, All Rights Reserved 26

Dynamic ActionForm

• Define ActionForm declaratively• Behave like regular ActionForm throughout the application• No need to define ActionForm classes • Example

<form-bean name="checkoutForm“ type="org.apache.struts.validator.DynaValidatorForm"><form-property name="shippingAddress" type="java.lang.String"/><form-property name="shippingCity" type="java.lang.String"/><form-property name="shippingState" type="java.lang.String"/><form-property name="shippingPostal" type="java.lang.String"/>

</form-bean><table><tr><b>Shipping Address</b></tr><tr> <td>Address:</td><td><html:text name="checkoutForm" property="shippingAddress"/></td></tr><tr><td>City:</td><td><html:text name="checkoutForm" property="shippingCity"/></td></tr><tr><td>State:</td><td><html:text name="checkoutForm" property="shippingState"/></td></tr><tr><td>Postal:</td><td><html:text name="checkoutForm" property="shippingPostal"/></td></tr></table>

Page 27: Hospitality Northwest Struts Training Material

©Copyright 2004, Cognizant Academy, All Rights Reserved 27

Diagrammatic Representation Of Struts Framework

Page 28: Hospitality Northwest Struts Training Material

©Copyright 2004, Cognizant Academy, All Rights Reserved 28

Work Flow of Struts

a) Client makes a Http Request.b) Every request has to go to the ActionServlet which actually is the Front Controller of Struts.c) ActionServlet calls the Request Processor for execution of the request.d) Request Processor reads the xml file (Struts-config.xml) where the mappings have been provided for each and

every request and finds out the corresponding Action Class mapping to that request.a)a) How the mappings are provided in Struts-Config.xml file will be discussed under Configuring Recipe How the mappings are provided in Struts-Config.xml file will be discussed under Configuring Recipe

Module.Module.

e) Before passing the control to the execute() method of the Action Class, it instantiates the Form Bean associated with that Action Class.

f) Once the Action Form/ Form Bean is instantiated, control goes to execute() method of Action Class.g) Action Class then call the Business Layers to fetch the data requested by the client.h) Once the data is fetched, it is populated in the Form Bean and control goes back to Action Class.i) And finally, Action Class throws the control to JSP page where the data is rendered.j) To render the data on JSP page, data is taken out of Form Bean with the help of Struts Tags.k) Struts provides us with various Tag Libraries which makes the JSP page easy to create and maintain.l) JSP Tags will be discussed later.

Page 29: Hospitality Northwest Struts Training Material

©Copyright 2004, Cognizant Academy, All Rights Reserved 29

Request Flow in a typical Struts Architecture : Quiz

• When does the Form Bean gets instantiated ? – A) When Request Reaches the corresponding Action class execute() method.– B) When request is handled by requestProcessor.– C) Inside Action Class constructor().

• Ans : option B

Page 30: Hospitality Northwest Struts Training Material

©Copyright 2004, Cognizant Academy, All Rights Reserved 30

3.0 Configuring recipe : Overview

Introduction:

This Module explains how to configure different xml files for implementing Struts in a web application.There are two main configuration files to be configured in a struts application: web.xml, struts-config.xml .

Objective: After completing this module, you will be able to configure and thus use Struts in your application.

1 . Configuring Web.xml.

2 . Configuring Struts-Config.xml.

Page 31: Hospitality Northwest Struts Training Material

©Copyright 2004, Cognizant Academy, All Rights Reserved 31

Configuring Web.xml

• This file is used for servlet mapping, providing init parameters, providing configuration file and also to give tag libraries.

• A sample file is provided:<web-app> <servlet>

<servlet-name>action</servlet-name> <servlet-class>org.apache.struts.action.ActionServlet</servlet-class>

<init-param> <param-name>config</param-name> <param-value>/WEB-INF/strus-config.xml</param-value>

</init-param> <init-param>

<param-name>validate</param-name> <param-value>true</param-value>

</init-param> </servlet>

<servlet-mapping> <servlet-name>action</servlet-name> <url-pattern>*.do</url-pattern>

</servlet-mapping>

Page 32: Hospitality Northwest Struts Training Material

©Copyright 2004, Cognizant Academy, All Rights Reserved 32

Configuring Web.xml ………cont.

<taglib> <taglib-uri>/WEB-INF/struts-html.tld</taglib-uri>

<taglib-location>/WEB-INF/struts-html.tld</taglib-location><taglib><taglib>

<taglib-uri>/WEB-INF/struts-bean.tld</taglib-uri> <taglib-location>/WEB-INF/struts-bean.tld</taglib-location><taglib><taglib> <taglib-uri>/WEB-INF/struts-logic.tld</taglib-uri> <taglib-location>/WEB-INF/struts-logic.tld</taglib-location><taglib>

</web-app>

Page 33: Hospitality Northwest Struts Training Material

©Copyright 2004, Cognizant Academy, All Rights Reserved 33

Configuring Struts-Config.xml

• The struts-config.xml file is used to provide: form-bean declaration, global exception declaration, global forward declaration, action mappings, adding different plugins.

• The outermost XML element must be <struts-config>. Inside of the <struts-config> element, there are three

important elements that are used to describe the actions:

<form-beans>This section contains form bean definitions. Form beans are descriptors that are used to create ActionForm instances at runtime. You use a <form-bean> element for each form bean, which has the following important attributes: name: A unique identifier for this bean, which will be used to reference it in corresponding action mappings. Usually, this is also the name of the request or session attribute under which this form bean will be stored. type: The fully-qualified Java classname of the ActionForm subclass to use with this form bean.

<global-forwards>This section contains global forward definitions. Forwards are instances of the ActionForward class returned from an ActionForm's execute method. These map logical names to specific resources (typically JSPs). Use a <forward> element for each forward definition, which has the following important attributes: name: The logical name for this forward. This is used in your ActionForm's execute method to forward to the next appropriate resource. Example: homepage path: The context relative path to the resource. Example: /index.jsp or /index.do redirect: True or false (default). Should the ActionServlet redirect to the resource instead of forward?

Page 34: Hospitality Northwest Struts Training Material

©Copyright 2004, Cognizant Academy, All Rights Reserved 34

Configuring Struts-Config.xml ………cont.

• <action-mappings>This section contains action definitions. Use an <action> element for each of the mappings you would like to define. Most action elements will define at least the following attributes:

path: The application context-relative path to the action. type: The fully qualified java classname of your Action class. name: The name of your <form-bean> element to use with this action

Other often-used attributes include:parameter: A general-purpose attribute often used by "standard" Actions to pass a required property. roles: A comma-delimited list of the user security roles that can access this mapping.

Page 35: Hospitality Northwest Struts Training Material

©Copyright 2004, Cognizant Academy, All Rights Reserved 35

Sample Struts-Config.xml

<struts-config> <form-beans >

<form-bean name=“<Registry Name>" type=“<absolute path of FormBean>"> </form-bean> </form-beans> <global-exceptions>

<forward name=“error" path="/login.do" /> </global-exceptions>

<global-forwards> <forward name="frontDoor" path="/MRQueue.do" />

<forward name="mrqueue" path="/MRQueue.do" /></global-forwards>

<action-mappings> <action path="/MRQueue" type=“<ActionClass Path>" name=“<FormBeans Registry Name>" scope="session" validate="true“

input=“<path if error is encountered>"> <forward name=“<success>" path=“<path of JSP page>"> </forward> </action> </action-mappings>

Page 36: Hospitality Northwest Struts Training Material

©Copyright 2004, Cognizant Academy, All Rights Reserved 36

Sample Struts-Config.xml ………cont.

<message-resources parameter=“<path of Application Resource File>" /><plug-in className="org.apache.struts.validator.ValidatorPlugIn">

<set-property property="pathnames" value="/WEB-INF/validator-rules.xml, / WEB-INF/validation.xml , / WEB-INF/custom-validator-rules.xml "/></plug-in><plug-in className="org.apache.struts.tiles.TilesPlugin" >

<set-property property="moduleAware" value="true" /> <set-property property="definitions-config" value="/ WEB-INF/tiles-defs.xml"/> </plug-in></struts-config>

Page 37: Hospitality Northwest Struts Training Material

©Copyright 2004, Cognizant Academy, All Rights Reserved 37

Configuring recipe :Summary

• Two main configuration files to be configured in a struts application: web.xml, struts-config.xml.

• Web.xml : This file is used for servlet mapping, providing init parameters, providing configuration file and also to give tag libraries. The 2nd xml file is also declared in this file.

• Struts-Config.xml : struts-config.xml file is used to provide: form-bean declaration, global exception declaration, global forward declaration, action mappings, adding different plugins.

• Request Processor reads all the mappings from struts-config.xml file and controls the flow of application.• These 2 files play a very important role as far as configuration is concerned and they make the application more

loosely coupled.

Page 38: Hospitality Northwest Struts Training Material

©Copyright 2004, Cognizant Academy, All Rights Reserved 38

Multi-Module Support

• Separate, independent application modules (sub-applications)• Supports parallel development• Separate Struts configuration files• Use the SwitchAction to move between application modules

Page 39: Hospitality Northwest Struts Training Material

©Copyright 2004, Cognizant Academy, All Rights Reserved 39

Page 40: Hospitality Northwest Struts Training Material

©Copyright 2004, Cognizant Academy, All Rights Reserved 40

Configuring recipe : Quiz

• Is it mandatory to declare every FormBean we are using in our application ? – Yes– No– Cant Say

• Yes

Page 41: Hospitality Northwest Struts Training Material

©Copyright 2004, Cognizant Academy, All Rights Reserved 41

4.0 Struts Validator Framework : Overview

Introduction: The Validator framework is an open source project that supports centralized data validation throughout the

application and allows declarative configuration of validation rules through external XML files.The Validator framework offers several benefits over the more conventional method of defining validation rules within the source code of an application.

Objective: After completing this module, you will be able to do your validations implementing struts validator framework.

1 . Setting up the Struts Validator Framework Environment.

2 . Pre-requisite for Struts Validator Framework .

3 . How to perform validations.

Page 42: Hospitality Northwest Struts Training Material

©Copyright 2004, Cognizant Academy, All Rights Reserved 42

Setting up the Struts Validator Framework Environment

• Put “struts.jar” in the lib folder and set the “CLASSPATH” variable to point to this jar file.

• Add the required plug-in the Struts-Config.xml file as follows:<plug-in className="org.apache.struts.validator.ValidatorPlugIn">

<set-property property="pathnames" value="/WEB-INF/validator-rules.xml, / WEB-INF/validation.xml , / WEB-INF/custom-validator-rules.xml "/>

</plug-in>

• “validation.xml” •contains all the necessary validations to be put in. •Any new validation rule to be defined for any field needs an entry in “validation.xml”

• “validator-rules.xml” •contains the default Struts Validator pluggable validator definitions. •This file acts as a template, defining all of the possible Validators that are available to an application.

• “custom-validation-rules.xml” •contains the definition of the custom validators created by the developer. •Any new custom validator requires an entry here.

Page 43: Hospitality Northwest Struts Training Material

©Copyright 2004, Cognizant Academy, All Rights Reserved 43

Pre-requisite for Struts Validator Framework

Before working with the Struts Validator framework, we need to define “ValidatorForm” or “ValidatorActionForm” as the base class for all the formbeans.

ValidatorActionForm

passes the 'path' attribute from the action element in the struts-config.xml, which should match the form element's ‘name’ attribute in the validation.xml and the Validator uses the ‘path’ attribute to decide whether validation needs to be invoked for a particular action.

ValidatorForm

instead uses the ‘name’ of the ActionForm to look up the set of validation rules to be used.

•Use of ValidatorForm always invokes the validation for a particular form.

•Use of ValidatorActionForm allows the developer to switch on/off the validations in the same JSP page.

Page 44: Hospitality Northwest Struts Training Material

©Copyright 2004, Cognizant Academy, All Rights Reserved 44

How to perform validations

Validator-rules.xmlValidator-rules.xml

<validator name="required" classname="org.apache.struts.validator.FieldChecks" method="validateRequired" methodParams="java.lang.Object,

org.apache.commons.validator.ValidatorAction, org.apache.commons.validator.Field, org.apache.struts.action.ActionErrors, javax.servlet.http.HttpServletRequest"

msg="errors.required">

</validator>

Validation.xmlValidation.xml

<form name="/abc">

<field property="stockNbr“ depends="required">

<arg0 key="StockNumberRequired"/> </field>

</form>

Page 45: Hospitality Northwest Struts Training Material

©Copyright 2004, Cognizant Academy, All Rights Reserved 45

How to perform validations……cont.

Custom-validator-rules.xmlCustom-validator-rules.xml

<form-validation>

<global>

<validator name=“<name which is referred in validation.xml in depends attribute>" classname=“<absolute path of java class where validation method is written>“ method=“<method name written in java class>" methodParams="java.lang.Object,

org.apache.commons.validator.ValidatorAction, org.apache.commons.validator.Field,

org.apache.struts.action.ActionErrors, javax.servlet.http.HttpServletRequest"

msg="errors.stockNumberFormat">

</validator>

</global>

</form-validation>

In Validation.xml, this would be the only chg

depends="required , <Rule name which should be defined in custom-validator-rules.xml>"

Page 46: Hospitality Northwest Struts Training Material

©Copyright 2004, Cognizant Academy, All Rights Reserved 46

Struts Validator Framework :Summary

• For implementing Struts Validator Framework,– put the relevant jars in the lib folder.– add a plug-in in Struts-Config.xml file.– extend all the formbeans either from ValidatorForm or ValidatorActionForm.– Put Validator-rules.xml in WEB-INF folder for using struts inbuilt validation methods.– Configure validation.xml for invoking the inbuilt methods or customized methods.– define custom-validator-rules.xml for customized validations.

Page 47: Hospitality Northwest Struts Training Material

©Copyright 2004, Cognizant Academy, All Rights Reserved 47

Struts Validator Framework : Quiz

• Validations using Struts Framework are totally– A) Client Side Validations– B) Server Side Validations.– C) Partially server side.

• Ans : Option C

Page 48: Hospitality Northwest Struts Training Material

©Copyright 2004, Cognizant Academy, All Rights Reserved 48

5.0 Tiles Framework : Overview

Introduction: TILES is a framework that help to manage the layout in a webpage. Tiles enable a page to be fragmented in to

independent pieces. These pieces can be reused in some other pages.

This improves code reusability, reduces debugging time and hence reduces development time.

Objective: After completing this module, you will be able to implement Tiles Framework .

1 . How to use Tiles Framework.

Page 49: Hospitality Northwest Struts Training Material

©Copyright 2004, Cognizant Academy, All Rights Reserved 49

How to use Tiles Framework

Tiles can be implemented by an xml file, which defines the individual tiles of a layout.

Layout is a jsp file, which declares the position of each tile in a page. The xml file defines the actual jsp names that should be placed in each placeholder in a layout.

A sample Layout File can be: (say layout.jsp)

<tiles:insert attribute="screenHeader"/>

<tiles:insert attribute="errorHeader"/>

<tiles:insert attribute="body"/>

<tiles:insert attribute="footer"/>

Now to define this layout, the xml file can have nodes like:

<definition name=“<forward name defined in struts-config.xml>" path="/layout/ layout.jsp ">

<put name="screenHeader" value="/pages/screenHeader.jsp"/>

<put name="errorHeader" value="/pages/errorHeader.jsp"/>

<put name="body" value="/pages/myPage.jsp"/>

<put name=“footer" value="/pages/analystFooter.jsp"/>

</definition>

Page 50: Hospitality Northwest Struts Training Material

©Copyright 2004, Cognizant Academy, All Rights Reserved 50

Tiles Framework :Summary

• For implementing Tiles Framework,– Divide the JSP page into different components.– Write a layout.jsp file having placeholders for all the components in the JSP page.– Define a tiles-definition.xml file.– put the actual paths of JSPs for all the placeholders in the layout.jsp file.

Page 51: Hospitality Northwest Struts Training Material

©Copyright 2004, Cognizant Academy, All Rights Reserved 51

Tiles Framework : Quiz

• When we are using Tiles Framework, content is inserted into template page during Runtime or Compile Time ? – Runtime– Compile Time

• Ans : Runtime

Page 52: Hospitality Northwest Struts Training Material

©Copyright 2004, Cognizant Academy, All Rights Reserved 52

6.0 Some Struts Features : Overview

Introduction: This module explains certain Best Practices Of Struts.

Apart from this, Brief description of tag libraries provided by Struts have also been dealt here..

Objective: After completing this module, you will be able to implement Tiles Framework .

1 . Best Practices Of Struts.

2. Tag Libraries.

Page 53: Hospitality Northwest Struts Training Material

©Copyright 2004, Cognizant Academy, All Rights Reserved 53

Best Practices Of Struts

Extend When You Must

•Struts framework can be stretched and customized to allow for customized behavior.

•Configuration classes in the Struts framework (say, Struts configuration file , ActionServlet RequestProcessor) can be substituted for a customized version.

•Declarative Exception Handling mechanism also allows for custom exception handlers to be used to better respond to application failures.

•Extension should be done judiciously.

•Before extending a Framework, we should always make sure that the functionality doesn't already exist somewhere.

Use Application Modules

•Splitting of a single Struts application into multiple modules is allowed.

•This solves one of the biggest complaints that development groups of more than a few people have had for some time because we can create Separate Struts Configuration Files for Individual Applications.

•Each Struts application module should have its own configuration file. This allows us to configure separate Actions, ActionForms, exception handling, and much more, independent of other application modules.

Page 54: Hospitality Northwest Struts Training Material

©Copyright 2004, Cognizant Academy, All Rights Reserved 54

Best Practices Of Struts……cont.

Use Declarative Exception Handling

•Struts framework includes a class called ExceptionHandler.

•This class by default is responsible for processing any exceptions that occur during action execution.

•This class actually creates an ActionError object and stores it in the appropriate scope object.

•This allows the JSP pages to use the errors to inform the user of a problem.

•Customized ExceptionHandler classes can also be used.

Use a Base Action for your application

•Often, Actions in an application will need to perform some basic tasks.

•To ensure these tasks are implemented consistently, create a base Action that can be sub-classed by other actions in the application.

Check logins at the Controller Level

Use Validator Framework for validating user input

Use Custom tags instead of using scriplets and Java code in JSP pages

Page 55: Hospitality Northwest Struts Training Material

©Copyright 2004, Cognizant Academy, All Rights Reserved 55

Tag Libraries

•Contains the tag handler classes for the Struts tag libraries.

•Tags provided by struts are very powerful.

•Helps in prevention of scriplets in JSP page.

•Important Tag Libraries are:

•Bean Tag Lib : The "struts-bean" tag library contains JSP custom tags useful in defining new beans (in any desired scope) from a variety of possible sources, as well as a tag to render a particular bean (or bean property) to the output response.

•HTML Tag Lib : The HTML taglib contains tags used to create Struts input forms, as well as other tags generally useful in the creation of HTML-based user interfaces.

•Logic Tag Lib : The "struts-logic" tag library contains tags that are useful in managing conditional generation of output text, looping over object collections for repetitive generation of output text, and application flow management.

•There are other libraries as well but the above shown are used very often.

•Have a look at all libraries on : http://jakarta.apache.org/struts/userGuide/release-notes.html.

Page 56: Hospitality Northwest Struts Training Material

©Copyright 2004, Cognizant Academy, All Rights Reserved 56

Some Struts Features :Summary

• Struts framework has excellent features that address some of critical design problems and provides an extensible J2EE architecture. Struts allow a developer to focus on developing business logic instead of spending a huge amount of time on low-level infrastructure functionality like client data validation, flow control etc.

• Some of the key features are listed below : – Almost every component can be extended & customized according to the requirement .– Enforces Modularity and Application Partitioning.– Error handling mechanisms.– Support for jsp custom tags.– Support for Validator Framework for centralized and declarative validation .– Support for Tiles framework .– XML-based configuration file .

Page 57: Hospitality Northwest Struts Training Material

©Copyright 2004, Cognizant Academy, All Rights Reserved 57

Some Struts Features : Quiz

• Each Struts tag must have an ending tag .i.e. <html:text> must have an ending tag </html:text>.– True– False

• Ans : True

Page 58: Hospitality Northwest Struts Training Material

©Copyright 2004, Cognizant Academy, All Rights Reserved 58

STRUTS: Next Step

The following items will provide more information on the subjects covered in this course:

Resource Type Description Reference Topic or Module

Book Struts by O’Reilly Complete reference for Struts.

Book

PDF

PDF

URL http://jakarta.apache.org/struts/index.html Complete reference for Struts.

White Paper http://www.luhala.com/web2/files/strutsvajwhitepaper.pdf

Research article

e-learning course

Classroom training

Page 59: Hospitality Northwest Struts Training Material

©Copyright 2004, Cognizant Academy, All Rights Reserved 59

Course Name - Summary

• List most important points from whole course

Page 60: Hospitality Northwest Struts Training Material

Congratulations!Congratulations!You have successfully You have successfully

completedcompleted

Congratulations!Congratulations!You have successfully You have successfully

completedcompleted

STRUTSSTRUTS


Recommended