Struts An Open-source Architecture for Web Applications Facilitator: Tripti Shukla.

202
Struts An Open-source Architecture for Web Applications Facilitator: Tripti Shukla

Transcript of Struts An Open-source Architecture for Web Applications Facilitator: Tripti Shukla.

Page 1: Struts An Open-source Architecture for Web Applications Facilitator: Tripti Shukla.

Struts

An Open-source Architecture forWeb Applications

Facilitator: Tripti Shukla

Page 2: Struts An Open-source Architecture for Web Applications Facilitator: Tripti Shukla.

Agenda Why should you use Struts Installing Struts Struts Concepts What is MVC Configuring Struts Tag libraries Build a practical example What do you do when things go wrong? Advanced Topics

Page 3: Struts An Open-source Architecture for Web Applications Facilitator: Tripti Shukla.

Struts Overview

Page 4: Struts An Open-source Architecture for Web Applications Facilitator: Tripti Shukla.

Frameworks in general

Provide a reusable structure: may serve as a foundation for new

products re-usable semi-complete application specialize to produce custom

application

Page 5: Struts An Open-source Architecture for Web Applications Facilitator: Tripti Shukla.

Model 1 Framework JSP combines the roles of the

view and controller components JSP page alone is responsible for

processing the incoming request and replying back to the client

There is still separation of presentation from content, because all data access is performed using beans

Model 1 architecture is perfectly suitable for simple applications but it may not be desirable for complex implementations

Indiscriminate usage of this architecture usually leads to a significant amount of scriptlets or Java code embedded within the JSP page

Page 6: Struts An Open-source Architecture for Web Applications Facilitator: Tripti Shukla.

Drawbacks of JSP

Page 7: Struts An Open-source Architecture for Web Applications Facilitator: Tripti Shukla.

• Interweaving scriptlets and HTML results in hard to read and hard to maintain applications. • Writing code in JSPs diminishes the opportunity to reuse the code. Of course, you can put all Java methods in a JSP and include this page from other JSPs that need to use the methods. However, by doing so you're moving away from the object-oriented paradigm. For one thing, you will lose the power of inheritance. • It is harder to write Java code in a JSP than to do it in a Java class. Let's face it, your IDE is designed to analyze Java code in Java classes, not in JSPs. • It is easier to debug code if it is in a Java class. • It is easier to test business logic that is encapsulated in a Java class. • Java code in Java classes is easier to refactor.

Page 8: Struts An Open-source Architecture for Web Applications Facilitator: Tripti Shukla.

Model 2 Framework JSP & Servlets work together

in web applications Servlets handle data

access & control flow JSP focus on tasks of

writing HTML Model

contains the core of the application's functionality i.e. business domain

encapsulates the state of the application

Page 9: Struts An Open-source Architecture for Web Applications Facilitator: Tripti Shukla.

Model 2 Framework View

handles the presentation of the business domain

can access the model getters, but it has no knowledge of the setters

knows nothing about the controller

Controller processes the user input

to direct the flow and manage user state

reacts to the user input creates and sets the

model.

Page 10: Struts An Open-source Architecture for Web Applications Facilitator: Tripti Shukla.

Classic MVC Pattern

1. Controller mediates application flow2. Model encapsulates business logic & data3. View contains presentation logic

Page 11: Struts An Open-source Architecture for Web Applications Facilitator: Tripti Shukla.

Struts Framework Characteristics Open source hosted by Apache Based on

standard Java/J2EE technologies. Core of struts is flexible controller layer Struts encourages Model 2 application

architecture Model View Controller separates

responsibilities Struts is a Servlet that supports your applications JSP Pages are also Servlets Struts provides a pluggable framework Tools exist to simplify Struts development

Page 12: Struts An Open-source Architecture for Web Applications Facilitator: Tripti Shukla.

Struts – on Model 2, MVC

Struts framework based on Model 2 architecture Controller servlet manages flow between JSP

pages Special classes help with data access Substantial tag library for JSP pages makes

framework easy to use MVC pattern implementation

ActionForwards & ActionMappings keep control flow decisions out of the presentation layer

Page 13: Struts An Open-source Architecture for Web Applications Facilitator: Tripti Shukla.

Struts Client browser

An HTTP request from the client browser creates an event. The Web container will respond with an HTTP response.

Controller The Controller receives the

request from the browser, and makes the decision where to send the request.

With Struts, the Controller is a command design pattern implemented as a servlet.

The struts-config.xml file configures the Controller.

Page 14: Struts An Open-source Architecture for Web Applications Facilitator: Tripti Shukla.

Struts Business logic

The business logic updates the state of the model and helps control the flow of the application.

With Struts this is done with an Action class as a thin wrapper to the actual business logic.

Model state The model represents the state of

the application. The business objects update the

application state. The ActionForm bean represents

the Model state at a session or request level, and not at a persistent level.

The JSP file reads information from the ActionForm bean using JSP tags.

Page 15: Struts An Open-source Architecture for Web Applications Facilitator: Tripti Shukla.

Struts View

The view is simply a JSP file.

There is no flow logic, no business logic, and no model information -- just tags.

Tags are one of the things that make Struts unique compared to other frameworks.

Page 16: Struts An Open-source Architecture for Web Applications Facilitator: Tripti Shukla.

Benefits Configuration via XML files

Many changes can be made without modifying or recompiling Java code

Pages are loosely coupled; URLs not hardcoded Form beans

Greatly simplifies processing of request parameters HTML tags

Lets you get initial values from Java objects Lets you redisplay forms with previous values intact

Form field validation Client-side and server-side

Page 17: Struts An Open-source Architecture for Web Applications Facilitator: Tripti Shukla.

Benefits Consistent implementation

Encourages consistent use of MVC throughout applications which employ JSP

Internationalization and Localization Eg. en-us, en-ca, fr-ca Supported through “resources”

• Usually just a “properties” file i.e. resources.properties

Page 18: Struts An Open-source Architecture for Web Applications Facilitator: Tripti Shukla.

When to use Struts

In case of a very simple application, with a handful of pages, then you might consider a "Model 1" solution that uses only server pages.

With complicated application, with dozens of pages, that need to be maintained over time, then Struts can help

Page 19: Struts An Open-source Architecture for Web Applications Facilitator: Tripti Shukla.

Struts – Schematic Overview

Page 20: Struts An Open-source Architecture for Web Applications Facilitator: Tripti Shukla.

RELY-ON SOLUTIONS

Core Struts Classes

Anjali
Note: This is not always wise to do. There might be ways of using UserActionForm in other pages or business objects, where the validation might be different. Validation of the state might be better in the UserAction class.
Page 21: Struts An Open-source Architecture for Web Applications Facilitator: Tripti Shukla.

Core Struts Classes

ActionMappingMaps a path attribute to that of an incoming URI

ActionForwardEncapsulates the destination of where to send control upon completion of the Action

The destination is detailed in the configuration file:

HTML,JSP, servlets

Anjali
Note: This is not always wise to do. There might be ways of using UserActionForm in other pages or business objects, where the validation might be different. Validation of the state might be better in the UserAction class.
Page 22: Struts An Open-source Architecture for Web Applications Facilitator: Tripti Shukla.

Core Struts Classes ActionForm

Hold state and behavior for user input using corresponding fields from the HttpServletRequest

No more request.getParameter() calls. For instance,the Struts framework will take fname from request stream and call UserActionForm.setFname()

Can be used to validate presentation data Should be used to encapsulate data that is for

delivery to the data model

Anjali
Note: This is not always wise to do. There might be ways of using UserActionForm in other pages or business objects, where the validation might be different. Validation of the state might be better in the UserAction class.
Page 23: Struts An Open-source Architecture for Web Applications Facilitator: Tripti Shukla.

Core Struts Classes

ActionForm

is an abstract class that is sub-classed for each input form model

represents a general concept of data that is set or updated by a HTML form. E.g., you may have a UserActionForm that is set by an HTML Form

Also conducts form state validation can be maintained at a session level

Anjali
Note: This is not always wise to do. There might be ways of using UserActionForm in other pages or business objects, where the validation might be different. Validation of the state might be better in the UserAction class.
Page 24: Struts An Open-source Architecture for Web Applications Facilitator: Tripti Shukla.

Core Struts Classes ActionServlet

responsible for packaging and routing HTTP traffic to the appropriate handler

takes on administering the behavior of the “Controller”

configured via the deployment descriptor of the web application and is typically is configured in the deployment descriptor to accept a pattern of URLs such as *.do

uses a configuration file so values are not hard-coded Java developer does not need to recompile code

when making flow changes

Page 25: Struts An Open-source Architecture for Web Applications Facilitator: Tripti Shukla.

Core Struts Classes

Action ClassesThe RequestProcessor delegate the work to be done to an Action.Provides loose coupling between the user request and the business

RequestProcessor Takes on the behavior of the “Controller” by

handling the core processing logic Determine the ActionMapping associated with the

request and instantiates the Action Instantiates ActionForm if needed Processes the ActionForward

Page 26: Struts An Open-source Architecture for Web Applications Facilitator: Tripti Shukla.

Components

Page 27: Struts An Open-source Architecture for Web Applications Facilitator: Tripti Shukla.

Struts Controller

Controller responsibilities include receiving input from a client, invoking a business operation, and coordinating the view to return back to the client. Of course, there are many other functions that the controller may perform, but these are a few of the primary ones.

JSP Model 2 architecture, on which Struts was fashioned the controller was implemented by a Java Servlet.

Page 28: Struts An Open-source Architecture for Web Applications Facilitator: Tripti Shukla.

Struts Controller

This servlet becomes the centralized point of control for the web application.

The controller servlet maps user actions into business operations and then helps to select the view to return to the client based on the request and other state information .

Page 29: Struts An Open-source Architecture for Web Applications Facilitator: Tripti Shukla.

Struts Controller

Page 30: Struts An Open-source Architecture for Web Applications Facilitator: Tripti Shukla.

Struts Controller

In the Struts framework, the controller responsibilities are implemented by several different components, one of which is an instance of the

org.apache.struts.action.ActionServlet

Page 31: Struts An Open-source Architecture for Web Applications Facilitator: Tripti Shukla.

Action Servlet The ActionServlet extends the

javax.servlet.http.HttpServlet class and is responsible for packaging and routing HTTP traffic to the appropriate handler in the framework.

The ActionServlet class is not abstract and therefore can be used as a concrete controller by your applications.

Prior to version 1.3 of the Struts framework, the ActionServlet was solely responsible for receiving the request and processing it by calling the appropriate handler.

Page 32: Struts An Open-source Architecture for Web Applications Facilitator: Tripti Shukla.

Action Servlet In version 1.3, a new class called

org.apache.struts.action.RequestProcessor has been introduced to process the request for the controller.

Like any other Java servlet, the Struts ActionServlet must be configured in the deployment descriptor for the web application i.e. web.xml.

Once the controller receives a client request, it delegates the handling of the request to a helper class. This helper knows how to execute the business operation that is associated with the requested action.

Page 33: Struts An Open-source Architecture for Web Applications Facilitator: Tripti Shukla.

Action Class An org.apache.struts.action.Action class in the

Struts framework is an extension of the controller component.

The Action class decouples the client request from the business model. This decoupling allows for more than a one-to-one mapping between the user request and an Action class.

The Action class can perform other functions, such as authorization, logging, and session validation, before invoking the business operation .

Page 34: Struts An Open-source Architecture for Web Applications Facilitator: Tripti Shukla.

Action Class The Struts Action class contains several

methods, but the most important is the execute() method.

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

)throws IOException, ServletException;

Page 35: Struts An Open-source Architecture for Web Applications Facilitator: Tripti Shukla.

Action Class The execute() method is called on an instance of

an Action class by the controller when a request is received from a client.

The controller will create an instance of the Action class if one doesn’t already exist.

The Struts framework will only create a single instance of each Action class in your application.

Since there is only one instance for all users, you must ensure that all of your Action classes operate properly in a multi-threaded environment.

Page 36: Struts An Open-source Architecture for Web Applications Facilitator: Tripti Shukla.

Action Class

Page 37: Struts An Open-source Architecture for Web Applications Facilitator: Tripti Shukla.

execute Each one of the action classes that we’ll

create for the application will extend the Struts Action class and override the execute method to carry out the specific operation.

it’s best to create an abstract base Action class for your application that all of your other action classes extend.

Always extend org.apache.struts.action.Action Class and implement execute() method.

Page 38: Struts An Open-source Architecture for Web Applications Facilitator: Tripti Shukla.

Mapping Action At this point, you might be asking yourself,

“How does the controller know which Action instance to invoke when it receives a request?” The answer is by inspecting the request information and utilizing a set of action mappings.

Action mappings are part of the Struts configuration information that is configured in a special XML file.

Page 39: Struts An Open-source Architecture for Web Applications Facilitator: Tripti Shukla.

Mapping Action This configuration information is loaded into

memory at startup and made available to the framework at runtime.

Each <action> element is represented in memory by an instance of the org.apache.struts.action.ActionMapping class. The ActionMapping object contains a path attribute that is matched against a portion of the URI of the incoming request.

Page 40: Struts An Open-source Architecture for Web Applications Facilitator: Tripti Shukla.

Mapping Action<action path="/login"

type="com.test.struts.banking.action.LoginAction" scope="request" name="loginForm" validate="true" input="/login.jsp"> <forward name="Success"

path="/action/getaccountinformation" redirect="true"/>

<forward name="Failure" path="/login.jsp" redirect="true"/>

</action>

Page 41: Struts An Open-source Architecture for Web Applications Facilitator: Tripti Shukla.

Mapping Action The login action mapping shown here maps

the path “/login” to the Action class com.test.struts.banking.LoginAction.

Whenever the controller receives a request where the path in the URI contains the string “/login”, the execute() method of the LoginAction instance will be invoked.

The Struts framework also uses the mappings to identify the resource to forward the user to once the action has completed .

Page 42: Struts An Open-source Architecture for Web Applications Facilitator: Tripti Shukla.

Determine Next View

How or what determines the view to return back to the client ?

If you looked closely at the execute() method signature in the Action class from the previous section, you might have noticed that the return type for the method is an org.apache.struts.action.ActionForward class.

Page 43: Struts An Open-source Architecture for Web Applications Facilitator: Tripti Shukla.

Determine Next View

The ActionForward class represents a destination to which the controller may send control once an Action has completed.

Instead of specifying an actual JSP page in the code, you can declaratively associate an action forward mapping with the JSP and then use that ActionForward throughout your application.

Page 44: Struts An Open-source Architecture for Web Applications Facilitator: Tripti Shukla.

forward The action forwards are specified in the

configuration file, similar to action mappings. They can be defined for a specific action as this forward is for the logout action mapping.

<action path="/logout"

type="com.test.struts.banking.action.LogoutAction"

scope="request"> <forward name="Success" path="/login.jsp"

redirect="true"/></action>

Page 45: Struts An Open-source Architecture for Web Applications Facilitator: Tripti Shukla.

forward The logout action declares a <forward> element

that is named “Success”, which forwards to a resource of “/login.jsp”. Notice in this case, a redirect attribute is set to “true”. Instead of performing a forward using a RequestDispatcher, the request that invokes the logout action mapping will be redirected instead.

The action forward mappings can also be specified in a global section independent of any specific action mapping.

Page 46: Struts An Open-source Architecture for Web Applications Facilitator: Tripti Shukla.

Global-forward The forwards defined in the global section are

more general and don’t apply to a specific action. Notice that every forward must have a name and path, but the redirect flag is optional. If you don’t specify a redirect attribute, its default value is false and thus performs a forward.

<global-forwards> <forward name="SystemFail"

path="/systemerror.jsp" /> <forward name="SessionTimeOut"

path="/sessiontimeout.jsp" /> </global-forwards>

Page 47: Struts An Open-source Architecture for Web Applications Facilitator: Tripti Shukla.

Struts Model Components

Page 48: Struts An Open-source Architecture for Web Applications Facilitator: Tripti Shukla.

Model Components Using Model components to hide the implementation

details for interacting with remote systems is one of the keys to using Struts effectively

ActionForm Beans Represent actions that can change that state

Java Bean / EJBs Represent internal state & business logic of the

system Relational Database Access

Struts can define the datasources for an application from within its standard configuration file

Page 49: Struts An Open-source Architecture for Web Applications Facilitator: Tripti Shukla.

ActionForm Beans Create one for each input form in the application

Extends ActionForm class May be defined in ActionMapping configuration file Typically only has property getters & setters

Define property for each field present in the form With associated getXXX() & setXXX() methods Field name & property name must match

Place bean instance on form and use nested property references If there’s a customer bean on the Action Form, then

refer to the property “customer.name” in JSP This would correspond to methods customer.getName()

& customer.setName(String name) on customer bean

Page 50: Struts An Open-source Architecture for Web Applications Facilitator: Tripti Shukla.

ActionForm Beans The struts-config.xml file controls which HTML

form request maps to which ActionForm Multiple requests can be mapped to an

ActionForm ActionForm can be mapped over multiple

pages for things such as wizards

Page 51: Struts An Open-source Architecture for Web Applications Facilitator: Tripti Shukla.

Role of ActionForm Controller servlet performs following:

Check session for instance of bean of appropriate class

If no session bean exists, one is created automatically

For every request parameter whose name corresponds to name of a property in the bean, corresponding setter method is called

Updated ActionForm bean is passed to the Action class perform(), making these values immediately available

Page 52: Struts An Open-source Architecture for Web Applications Facilitator: Tripti Shukla.

JavaBeans of EJBs

Functional logic of the application: Represented by a set of business logic

beans Might be JavaBeans for small

applications that access a database using JDBC calls

For larger applications these beans will often be stateless or stateful EJBs

Page 53: Struts An Open-source Architecture for Web Applications Facilitator: Tripti Shukla.

Struts View Components

Page 54: Struts An Open-source Architecture for Web Applications Facilitator: Tripti Shukla.

Struts View Components

JSP or HTML pages Use Struts tag library, JSTL tag

library DO NOT HARD CODE labels

Utilize ResourceBundle Uses beans stored in request or

session or application scope

Page 55: Struts An Open-source Architecture for Web Applications Facilitator: Tripti Shukla.

Tag Libraries

Page 56: Struts An Open-source Architecture for Web Applications Facilitator: Tripti Shukla.

Struts Tag Libraries

taglib directive:

Tells JSP compiler, where to find the tag library

descriptor for the struts tag library

Page 57: Struts An Open-source Architecture for Web Applications Facilitator: Tripti Shukla.

Struts Tag Libraries

Tag Library Descriptor

Purpose

struts-html.tld JSP tag extension for HTML forms

struts-bean.tld JSP tag extension for handling JavaBeans

struts-logic.tldJSP tag extension for testing the values of properties

Page 58: Struts An Open-source Architecture for Web Applications Facilitator: Tripti Shukla.

Overview Number of taglibs included as part of Struts Usage is not required, but helpful Bean tags Tags for accessing Beans and their properties Html tags Form bridge between JSP view and other

components Logic tags Provides presentation logic tags that eliminate

need for scriptlet Template tags (Tiles in v1.1) Tags to form JSP templates that include

parameterized content

Page 59: Struts An Open-source Architecture for Web Applications Facilitator: Tripti Shukla.

Overview All tag libs are defined in web.xml using <tablib> element

<!-- Struts Tag Library Descriptors --><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 -html.tld</taglib-uri><taglib -location>/WEB-INF/struts-html.tld</taglib-location>

</taglib >

Page 60: Struts An Open-source Architecture for Web Applications Facilitator: Tripti Shukla.

Bean Tags Tags for accessing beans and their properties

Enhancements to <jsp:useBean>

Convenient mechanisms to create newbeans based on the value of:

Cookies Request Headers Parameters

Page 61: Struts An Open-source Architecture for Web Applications Facilitator: Tripti Shukla.

HTML Tags Form bridge between JSP view and other components Input forms are important for gathering data Most of the actions of the HTML taglib involve HTML

forms Error messages, hyperlinking, internationalization

In ActionForm Class

ActionErrors errors = new ActionErrors();if ((username == null) || (username.length() < 1))

errors.add("username", newActionError("error.username.required"));

Page 62: Struts An Open-source Architecture for Web Applications Facilitator: Tripti Shukla.

HTML Tags

In JSP write

<td align="left"><html:text property="username"

size="16" maxlength="16"/><html:errors property="username"/>

</td>

Page 63: Struts An Open-source Architecture for Web Applications Facilitator: Tripti Shukla.

<html:link> tag

The <html:link> tag provides convenience and a great deal of flexibility if it makes sense for your application to URL encode request parameters. It also automatically handles URL encoding of Session IDs to ensure that you can maintain session state with users who have cookies turned off in their browser.

<html:link forward=”index”>Go Home</html:link> The HTML generated is <a href=”/myapp/index.jsp”>Go Home</a> Create Link by Specifying a Full URL <html:link

href=”http://jakarta.apache.org/struts/index.html”>Generate an “href” directly

</html:link>

Page 64: Struts An Open-source Architecture for Web Applications Facilitator: Tripti Shukla.

The Basics of Form Processing This section provides information on

the following tags: <html:form> - Render an HTML <form> element

<html:text> - Text box INPUT element

<html:hidden>— INPUT type=hidden element

Page 65: Struts An Open-source Architecture for Web Applications Facilitator: Tripti Shukla.

<html:submit>—Place a Submit INPUT element

<html:cancel>—Place a Submit INPUT element which can be used to “cancel” workflow

Page 66: Struts An Open-source Architecture for Web Applications Facilitator: Tripti Shukla.

Form tags

<html:form action="simpleAction" method="POST">

<html:text property="firstName"/> Generates HTML: <input type="text"

name="firstName" value="">

Page 67: Struts An Open-source Architecture for Web Applications Facilitator: Tripti Shukla.

<html:submit value="Submit"/>

Generates: <input type="submit"

value="Submit">

Page 68: Struts An Open-source Architecture for Web Applications Facilitator: Tripti Shukla.

<html:select> <html:select property="address">

<html:option value="Please, make selection"/>

<html:options property="addresses"/> </html:select> Where address is a form bean property which

will be set with a selected value addresses – Collection type property for

inputs

Page 69: Struts An Open-source Architecture for Web Applications Facilitator: Tripti Shukla.

Logic Tags Provides presentation logic tags that

eliminateneed for scriptlets

Value comparisonsInclude: = != <= >= < >

Substring matchingmatch, notmatch

Presentation logicforward, redirect

Collectionsiterate

Page 70: Struts An Open-source Architecture for Web Applications Facilitator: Tripti Shukla.

Template Tags Templates are JSP pages that include parameterized content Useful for creating dynamic JSP templates for pages that

share a common format Three template tags work in an interrelated function:

Get Insert Put

Layout various tiles of a web page Header, Navigation, Body, Footer

Specified in tiles-definition.xml Specifies the layout Logical names for various tiles Associate filenames to the tiles

Page 71: Struts An Open-source Architecture for Web Applications Facilitator: Tripti Shukla.

Resource Bundles Extends basic approach of java.util.ResourceBundle

org.apache.struts.util.MessageResources Allows specification of dynamic locale key on a per user

basis Limited to presentation, not input Configure resource bundles in web.xml file Configures message resource bundles

<message-resources parameter=“myApplication”/> All static strings should be specified in

myApplication.properties file Format: key=value

Name.label=Enter first name

Page 72: Struts An Open-source Architecture for Web Applications Facilitator: Tripti Shukla.

Automatic Form Validation

Validation with ActionForm Struts automatically validates inputs

from the form Override a stub method Provides error messages in the

standard application resource To utilize this feature

Override the validate() method in ActionForm class

Page 73: Struts An Open-source Architecture for Web Applications Facilitator: Tripti Shukla.

Automatic Form Validation

public ActionErrors validate(ActionMapping map, HttpServletRequest req)

{ActionErrors errors = new ActionErrors();if (name==null || name.length() < 1)

errors.add(“nameMissing”, new ActionError(“msg.key”));return errors;

}

Page 74: Struts An Open-source Architecture for Web Applications Facilitator: Tripti Shukla.

Automatic Form Validation

validate() is called by controller servlet After bean properties have been

populated Before corresponding Action class’s

validate() method is invoked Add the following to Input page

<html:errors property=“nameMissing”/>

Page 75: Struts An Open-source Architecture for Web Applications Facilitator: Tripti Shukla.

Validator Package

Automatically generate client side JavaScript code

Specify WEB-INF/validation.xml Define regular expressions for validating

data, phone#, social security#, etc. For each form specify required fields

Augment rules in WEB-INF/validator-rules.xml

Page 76: Struts An Open-source Architecture for Web Applications Facilitator: Tripti Shukla.

No need to write ActionForm

Dynamically generate ActionForm class for your forms

Specify form fields in struts-config.xml

Basic idea is properties of a bean are a HashMap

Again check Jakarta Commons Project

Page 77: Struts An Open-source Architecture for Web Applications Facilitator: Tripti Shukla.

Struts Controller Components

Page 78: Struts An Open-source Architecture for Web Applications Facilitator: Tripti Shukla.

Controller Components ActionServlet

Controller servlet which implements primary function of mapping a request URI to an Action class

Action class Extension of the Action class For each logical request that may be received

In struts-config.xml Action mapping used to configure the controller

servlet In web.xml

Include the necessary Struts components

Page 79: Struts An Open-source Architecture for Web Applications Facilitator: Tripti Shukla.

Action Class The primary method that must be written

in an Action class is the execute() method Defines the execute() method that is

overridden The framework calls execute() method after the

form bean is populated and validated correctly Goal of an Action class is to:

Process this request and then to return an ActionForward object, that identifies the JSP page (if any) to which control should be forwarded to generate corresponding response

Page 80: Struts An Open-source Architecture for Web Applications Facilitator: Tripti Shukla.

Typical logic in execute() method

If validation has not yet occurred, validate the form bean properties as necessary

Update server side objects that will be used to create the next page of the user interface

Return an appropriate ActionForward object that identified JSP page to be used to generate this response, based on the newly updated beans

Page 81: Struts An Open-source Architecture for Web Applications Facilitator: Tripti Shukla.

Typical logic in execute() method

The signature of the execute() method in any Action class:

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

Page 82: Struts An Open-source Architecture for Web Applications Facilitator: Tripti Shukla.

Typical logic in execute() method ActionMapping mapping

The ActionMapping provides access to the information stored in the configuration file (struts-config.xml) entry that configures this Action class

ActionForm formThis is the form bean. By this time, the form bean has been prepopulated and the validate() method has been called and returned with no errors (assuming that validation is turned on). All the data entered by the user is available through the form bean.

Page 83: Struts An Open-source Architecture for Web Applications Facilitator: Tripti Shukla.

Typical logic in execute() method

HttpServletRequest requestThis is the standard JSP or Servlet request object.

HttpServletResponse responseThis is the standard JSP or Servlet response object.

Page 84: Struts An Open-source Architecture for Web Applications Facilitator: Tripti Shukla.

Design Issues

One instance of Action class used for all requests Action class should operate correctly in

multi-threaded environment Important principle that aids thread-safe

coding Use only local variables, not instance

variables

Page 85: Struts An Open-source Architecture for Web Applications Facilitator: Tripti Shukla.

Design Issues Model Beans may throw exceptions

Trap all such exceptions in the logic of execute() method, and log them to application log file

As a general rule Allocating scarce resources and keeping

them across requests from same user (in user’s session) can cause scalability problems

Page 86: Struts An Open-source Architecture for Web Applications Facilitator: Tripti Shukla.

Struts Configuration

Page 87: Struts An Open-source Architecture for Web Applications Facilitator: Tripti Shukla.

Struts Configuration

ApplicationResources.propertiesStores localized messages & labels

struts-config.xmlStores the default configuration of the

controller

web.xmlIncludes all the required struts components

Page 88: Struts An Open-source Architecture for Web Applications Facilitator: Tripti Shukla.

Resource Bundle Struts manage multilanguage needs is to

use the standard Tag libraries <bean:message key=“”/>

Used to store application constants Example: text.customer.name=Name Predefined values for errors like:

errors.header, errors.footer, errors.prefix, and errors.suffix

Used for error messages Example: errors.required={0} is required.

Located in <docroot>/web-inf/classes

Page 89: Struts An Open-source Architecture for Web Applications Facilitator: Tripti Shukla.

Resource Bundle To define the keys and the proper

messages, you need an ApplicationResourceBundle For every language you want to support, a

single ApplicationResources_xx_XX.properties file is required (where "xx_XX" stands for the specific locale; for example, en_US).

In view, pass the attribute locale; otherwise, Struts does not look for the locale that the user's browser passes to the server via its request <html:html locale="true">

Page 90: Struts An Open-source Architecture for Web Applications Facilitator: Tripti Shukla.

Resource Bundle

struts-config.xml<message-resources parameter="resources.ApplicationResources"/>

web.xml<servlet>

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

<param-name>application</param-name> <param-value>ApplicationResources</param-value></init-param></servlet>

Page 91: Struts An Open-source Architecture for Web Applications Facilitator: Tripti Shukla.

struts-config.xml The primary Struts framework configuration

and implementation configuration are contained in the stuts-config.xml file

The power and flexibility of Struts is due to the extracting of configuration information from across the frame work.

struts-config.xml may be given a different name

Modular, easy to maintain, change application configuration without redeploying app

Page 92: Struts An Open-source Architecture for Web Applications Facilitator: Tripti Shukla.

struts-config.xml Located in web-inf directory Outermost element is <struts-config> Two elements which describe actions:

<form-beans>• Contains form bean definitions• Use <form-bean> element for each form

bean <action-mappings>

• Contains action definitions• Use <action> for each of action to be defined

Page 93: Struts An Open-source Architecture for Web Applications Facilitator: Tripti Shukla.

<form-beans> Section Contains form bean definitions Use <form-bean> element for each form

bean Attributes of <form-bean> element

name:• The name of the request or session level attribute that

this form bean will be stored as• A unique identifier for this bean, which will be used to

reference it in corresponding action mappings type:

• The fully classified Java class name of form bean

Page 94: Struts An Open-source Architecture for Web Applications Facilitator: Tripti Shukla.

<action-mappings> Section Contains action definitions Action mapping determine navigation Use <action> element for each of the actions Attributes of <action> element

path:• Application context-relative path to the action

type:• Fully qualified Java class name of Action class

name:• Name of the <form-bean> element to use with the action

Page 95: Struts An Open-source Architecture for Web Applications Facilitator: Tripti Shukla.

<action-mappings> Section Other <action-mapping> attributes:

unknown:• Set to true if this action should be configured as the

default for this application, to handle all requests not handled by another action.

• Only one action can be defined as a default within a single application

validate:• Set to true, if the validate() method of the action

associated with this mapping should be called• Trigger automatic validation of form beans

<exception>• What to do if uncaught exception is thrown

Page 96: Struts An Open-source Architecture for Web Applications Facilitator: Tripti Shukla.

<data-sources> Section

Specifies data sources that application can use:

Page 97: Struts An Open-source Architecture for Web Applications Facilitator: Tripti Shukla.

Global Forwards

Remember RequestDispatcher.forward() method – hence the name forward!!!

Logical name for all global filenames Addresses associated with common

situations, so each action need not specify a specific address

NO FILENAMES in execute()<forward name=“displayResults”

path=“/pages/default.jsp”/>

Page 98: Struts An Open-source Architecture for Web Applications Facilitator: Tripti Shukla.

Message Resources

<messageResources> Designate the location of a properties

file Properties in that file can then be

output via <bean:message>

Page 99: Struts An Open-source Architecture for Web Applications Facilitator: Tripti Shukla.

web.xml

Includes all the required struts components

Route request to the ActionServlet Is stored WEB-INF/web.xml

Page 100: Struts An Open-source Architecture for Web Applications Facilitator: Tripti Shukla.

web.xml<web-app>

<display-name>myApp</display-name><servlet>

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

class><init-param>

<param-name>application</param-name><param-value>ApplicationResources</param-value>

</init-param><init-param>

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

</init-param>...

<load-on-startup>1</load-on-startup></servlet>

Page 101: Struts An Open-source Architecture for Web Applications Facilitator: Tripti Shukla.

web.xml

……………………..<servlet-mapping>

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

</servlet-mapping></web-app>

Page 102: Struts An Open-source Architecture for Web Applications Facilitator: Tripti Shukla.

The Error Classes The Struts framework provides two classes to

assist

ActionError —This class is used to represent a single validation error

ActionErrors —This class provides a place to store all the individual ActionError objects. As ActionError objects are created, simply stuff them into the ActionErrors holder and continue processing

Page 103: Struts An Open-source Architecture for Web Applications Facilitator: Tripti Shukla.

The Error Classes The Hello World! application has been defined to

have two different types of errors: basic data/form validation errors and business logic errors. The requirements for the two types are: Form validation Business Validation

If the validate() method returns the ActionErrors object empty, Struts assumes there are no errors and processing moves to the Action class. If ActionErrors contains any ActionError elements, the user is redirected to the appropriate page to correct the errors

Page 104: Struts An Open-source Architecture for Web Applications Facilitator: Tripti Shukla.

The Error Classes If processing is redirected for the user to correct

the data entry, the ActionErrors object carries the individual ActionError elements back to the View for display. The View component can access the ActionErrors either directly or through the <html:errors> tag.

Validation can be enabled or disabled on a page-by-page basis through settings in the Struts configuration file (struts-config.xml).

Page 105: Struts An Open-source Architecture for Web Applications Facilitator: Tripti Shukla.

The ActionMapping Class The struts-config.xml determines what Action

class the Controller calls The struts-config.xml configuration

information is translated into a set of ActionMapping, which are put into container of ActionMappings

Classes that end with s are containers The ActionMapping contains the knowledge

of how a specific event maps to specific Actions

Page 106: Struts An Open-source Architecture for Web Applications Facilitator: Tripti Shukla.

The ActionMapping Class

The ActionServlet (Command) passes the ActionMapping to the Action class via the execute() method.

This allows Action to access the information to control flow.

Page 107: Struts An Open-source Architecture for Web Applications Facilitator: Tripti Shukla.

Fitting the Pieces

The following basic ideas provide a quick view of the strengths of Struts:

The Struts framework enables user to break the application functions into components quickly and easily

A configuration file (struts-config.xml) enables user to assemble the application from components

Page 108: Struts An Open-source Architecture for Web Applications Facilitator: Tripti Shukla.

Struts – Before & After

A lot of complexity and layers have been added

No more direct calls from the JSP file to the Service layer

Page 109: Struts An Open-source Architecture for Web Applications Facilitator: Tripti Shukla.

What struts-blank.war provides

Properties file with standard validator error messages However, properties file name

does not match the message-resources name in struts-config.xml

Page 110: Struts An Open-source Architecture for Web Applications Facilitator: Tripti Shukla.

Using Struts

1. Use WEB-INF/struts-config.xml to:1. Designate Action classes to handle

requests for blah.do2. Specify URLs that apply in various

situations3. Declare any form beans that are being

used

2. Create form bean to be populated by the form submission

3. Create other results beans

Page 111: Struts An Open-source Architecture for Web Applications Facilitator: Tripti Shukla.

Using Struts

4. Create Action subclasses to handle requests

5. Create form that invokes blah.do1. FORM ACTION="…/blah.do"

…>…</FORM>

6. Display results in JSP1. Usually uses Struts bean or HTML tags2. Sometimes uses JSTL or Struts

looping/logic tags

Page 112: Struts An Open-source Architecture for Web Applications Facilitator: Tripti Shukla.

Struts Flow

Page 113: Struts An Open-source Architecture for Web Applications Facilitator: Tripti Shukla.

Struts Flow1. User select URL ending in .do ie: /myApp.do2. Struts Action servlet receives control3. URL is associated with an Action class The Action

class is associated with a Form bean4. The Form's reset method is called5. Request parameters are mapped to the Form6. The execute method on the Action class is called7. An ActionForward is returned ie: /myApp.jsp

Page 114: Struts An Open-source Architecture for Web Applications Facilitator: Tripti Shukla.

Creating Struts Application

Step 1: Create entity beansStep 2: Create logic beans to manipulate entity

beansStep 3: Create form bean with necessary

propertiesYou skip this step with DynaActionForm

Step 4: Create Action classExtend Action or DispatchAction

Step 5: Update struts-config.xmlDefine global forward, form, and action mappings

Step 6: Create JSP page to support application

Page 115: Struts An Open-source Architecture for Web Applications Facilitator: Tripti Shukla.

Hands On – Case Study 1

Components One simple result mapping No beans

Illustrates Editing struts-config.xml Creating an Action Forms that invoke Actions Application organization

Page 116: Struts An Open-source Architecture for Web Applications Facilitator: Tripti Shukla.

Hands On – Case Study 1

Step 1: Editing struts-config.xml1. Make an action entry within action-mappings

1. path: URL pattern that should invoke the Action ".do" implied! You say /…/register1 but real pattern is /…/regsiter1.do

2. type: fully qualified class name of Action3. scope: as in normal MVC (request, session,

application)4. name: bean name (use arbitrary name if no

beans)5. input: form that will trigger the Action

Page 117: Struts An Open-source Architecture for Web Applications Facilitator: Tripti Shukla.

Hands On – Case Study 1

2. Create one or more forward entries within action1. name: String that will be returned from the

Action2. path: address of associated JSP page3. redirect: forward if false (default); redirect if

true

3. Restart serverstruts-config.xml read only when application

starts

Page 118: Struts An Open-source Architecture for Web Applications Facilitator: Tripti Shukla.

Hands On – Case Study 1struts-config.xml

<?xml version="1.0" encoding="ISO-8859-1" ?>

<!DOCTYPE struts-config PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 1.1//EN" "http://jakarta.apache.org/struts/dtds/struts-config_1_1.dtd"><struts-config>

<action-mappings><action path="/register1"type="training.RegisterAction1"name="noBean"scope="request"input="register1.jsp"><forward name="success" path="/result1.jsp"/></action>

…</action-mappings>

</struts-config>

Page 119: Struts An Open-source Architecture for Web Applications Facilitator: Tripti Shukla.

Hands On – Case Study 1Step 2 & 3

1. Bean to be populated by form submission1. Values automatically filled in based on correspondence

between request parameter names and bean property names

2. Like <jsp:setProperty property="*" …/> or my BeanUtils.populateBean method

2. Results beans1. Objects to hold results of business logic, data access

logic, etc.2. Just like the beans in normal MVC

Page 120: Struts An Open-source Architecture for Web Applications Facilitator: Tripti Shukla.

Hands On – Case Study 1Step 4: Create Action subclass

1. Add Struts-specific import statementsimport javax.servlet.http.*;import org.apache.struts.action.*;

2. Extend the Action classpublic class SomeAction extends Action { … }

3. Override the execute methodpublic ActionForward execute(ActionMapping mapping,ActionForm form,HttpServletRequest request,HttpServletResponse response)throws Exception {

4. Return mapping.findForwardreturn(mapping.findForward("name-matching-entry-in-forward"));

Page 121: Struts An Open-source Architecture for Web Applications Facilitator: Tripti Shukla.

Hands On – Case Study 1package training;

import javax.servlet.http.*;import org.apache.struts.action.*;

public class RegisterAction1 extends Action {public ActionForward execute(ActionMapping mapping,

ActionForm form,HttpServletRequest request,HttpServletResponse response)

throws Exception {return(mapping.findForward("success"));}

}

Page 122: Struts An Open-source Architecture for Web Applications Facilitator: Tripti Shukla.

Hands On – Case Study 1Step 5: Create Form

1. ACTION should list …/register1.do1. include the .do part, even though it is omitted

in the struts-config.xml file2. Relative URLs should be used3. Struts-specific custom tags often used

1. Lets you associate a bean with the input elements1.Make initial values come from database2.Redisplay partially completed form

Page 123: Struts An Open-source Architecture for Web Applications Facilitator: Tripti Shukla.

Hands On – Case Study 1wipro_casestudy_1\register1.jsp

<!DOCTYPE …><HTML><HEAD><TITLE>New Account Registration</TITLE></HEAD><BODY BGCOLOR="#FDF5E6"><CENTER><H1>New Account Registration</H1><FORM ACTION="register1.do" METHOD="POST">Email address: <INPUT TYPE="TEXT" NAME="email"><BR>Password: <INPUT TYPE="PASSWORD" NAME="password"><BR><INPUT TYPE="SUBMIT" VALUE="Sign Me Up!"></FORM></CENTER></BODY></HTML>

Page 124: Struts An Open-source Architecture for Web Applications Facilitator: Tripti Shukla.

Hands On – Case Study 1

Step 6: Display Results in JSP

1. System automatically forwards to appropriate page1. By matching condition returned by the

action to the name listed in the forward entry in struts-config.xml

Page 125: Struts An Open-source Architecture for Web Applications Facilitator: Tripti Shukla.

Hands On – Case Study 1wipro_casestudy_1\result1.jsp

<!DOCTYPE …><HTML><HEAD><TITLE>Success</TITLE></HEAD><BODY BGCOLOR="#FDF5E6"><CENTER><H1>You have registered successfully.</H1>(Version 1)</CENTER></BODY></HTML>

Page 126: Struts An Open-source Architecture for Web Applications Facilitator: Tripti Shukla.

Hands On – Case Study 1

Step 7: Compile Action class

Page 127: Struts An Open-source Architecture for Web Applications Facilitator: Tripti Shukla.

Hands On – Case Study 1

Step 8: Access the page

http://<host_name>:8080/wipro_casestudy_1/register1.jsp

Page 128: Struts An Open-source Architecture for Web Applications Facilitator: Tripti Shukla.

Hands On – Case Study 2

Components Multiple result mappings No beans

Illustrates Editing struts-config.xml

• Multiple forward entries within the action element

Creating an Action• Multiple mapping.findForward calls

Page 129: Struts An Open-source Architecture for Web Applications Facilitator: Tripti Shukla.

Hands On – Case Study 2Step 1: Editing struts-config.xml

struts-config.xml

<?xml version="1.0" encoding="ISO-8859-1" ?><!DOCTYPE struts-config PUBLIC "-//Apache Software Foundation//DTD Struts

Configuration 1.1//EN" "http://jakarta.apache.org/struts/dtds/struts-

config_1_1.dtd"><struts-config>

Page 130: Struts An Open-source Architecture for Web Applications Facilitator: Tripti Shukla.

Hands On – Case Study 2<action-mappings>

<action path="/register2"type="training.RegisterAction2"name="noBean"scope="request"input="register2.jsp"><forward name="success" path="/result2.jsp"/><forward name="bad-address"

path="/bad_address2.jsp"/><forward name="bad-pass" path="/bad_pass.jsp"/></action> …

</action-mappings>

</struts-config>

Page 131: Struts An Open-source Architecture for Web Applications Facilitator: Tripti Shukla.

Hands On – Case Study 2Step 2 & 3

1. Bean to be populated by form submission1. Values automatically filled in based on

correspondence between request parameter names and bean property names

2. Like <jsp:setProperty property="*" …/> or my BeanUtils.populateBean method

2. Results beans1. Objects to hold results of business logic, data

access logic, etc.2. Just like the beans in normal MVC

Page 132: Struts An Open-source Architecture for Web Applications Facilitator: Tripti Shukla.

Hands On – Case Study 2Step 4: Create Action subclass

package training;import javax.servlet.http.*;import org.apache.struts.action.*;public class RegisterAction2 extends Action{

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

Page 133: Struts An Open-source Architecture for Web Applications Facilitator: Tripti Shukla.

Hands On – Case Study 2{

String email = request.getParameter("email");String password = request.getParameter("password");

if ((email == null) || (email.trim().length() < 3) || (email.indexOf("@") == -1))

{return(mapping.findForward("bad-address"));

}else if ((password == null) ||(password.trim().length() < 6)){

return(mapping.findForward("bad-password"));}else{

return(mapping.findForward("success"));}

}}

Page 134: Struts An Open-source Architecture for Web Applications Facilitator: Tripti Shukla.

Hands On – Case Study 2Step 5: Create Form wipro_casestudy_2\register2.jsp

<!DOCTYPE …><HTML>

<HEAD><TITLE>New Account Registration</TITLE></HEAD><BODY BGCOLOR="#FDF5E6">

<CENTER><H1>New Account Registration</H1><FORM ACTION="register2.do" METHOD="POST">

Email address: <INPUT TYPE="TEXT" NAME="email"><BR>Password: <INPUT TYPE="PASSWORD"

NAME="password"><BR><INPUT TYPE="SUBMIT" VALUE="Sign Me Up!">

</FORM></CENTER>

</BODY></HTML>

Page 135: Struts An Open-source Architecture for Web Applications Facilitator: Tripti Shukla.

Hands On – Case Study 2

Step 6: Display Results in JSP

1. System automatically forwards to appropriate page1. By matching condition returned by the

action to the name listed in the forward entry in struts-config.xml

Page 136: Struts An Open-source Architecture for Web Applications Facilitator: Tripti Shukla.

Hands On – Case Study 2

Step 7: Compile Action class

Page 137: Struts An Open-source Architecture for Web Applications Facilitator: Tripti Shukla.

Hands On – Case Study 2

Step 8: Access the page

http://<host_name>:8080/wipro_casestudy_2/register2.jsp

Page 138: Struts An Open-source Architecture for Web Applications Facilitator: Tripti Shukla.

Hands On – Case Study 3 Components

Multiple result mappings Form bean to hold request data Result bean to hold computed data

Illustrates Editing struts-config.xml

• form-bean declaration• action name matching form-bean name

Creating an Action• Typecast of incoming form bean• Creating and storing results beans

Page 139: Struts An Open-source Architecture for Web Applications Facilitator: Tripti Shukla.

Hands On – Case Study 3Step 1: Editing struts-config.xml

struts-config.xml

<?xml version="1.0" encoding="ISO-8859-1" ?><!DOCTYPE struts-config PUBLIC "-//Apache Software Foundation//DTD Struts

Configuration 1.1//EN" "http://jakarta.apache.org/struts/dtds/struts-

config_1_1.dtd"><struts-config>

Page 140: Struts An Open-source Architecture for Web Applications Facilitator: Tripti Shukla.

Hands On – Case Study 3<action-mappings>

<action path="/register2"type="training.RegisterAction2"name="noBean"scope="request"input="register2.jsp"><forward name="success" path="/result2.jsp"/><forward name="bad-address"

path="/bad_address2.jsp"/><forward name="bad-pass"

path="/bad_pass.jsp"/></action> …

</action-mappings></struts-config>

Page 141: Struts An Open-source Architecture for Web Applications Facilitator: Tripti Shukla.

Hands On – Case Study 3Step 2: Create Form Bean to be auto populated

1. Must extend ActionForm1. Argument to "execute" will be of type ActionForm2. Cast value to your real type3. ActionForm is in org.apache.struts.action package4. Alternatively, DynaActionForm, can be used, which

results in a Map of incoming names and values2. Must have a zero argument constructor

1. System will automatically call this default constructor

Page 142: Struts An Open-source Architecture for Web Applications Facilitator: Tripti Shukla.

Hands On – Case Study 3

3. Must have setXXX() methods1. One method corresponding to each incoming

request parameter that has to be inserted automatically

2. Request param names must match bean property names

4. Must have getXXX() methods1. One method corresponding to each bean

property which has to be displayed in JSP without Java syntax

Page 143: Struts An Open-source Architecture for Web Applications Facilitator: Tripti Shukla.

Hands On – Case Study 3UserFormBean.java

package training;import org.apache.struts.action.*;public class UserFormBean extends ActionForm {

private String email = "Missing address";private String password = "Missing password";public String getEmail() {

return(email); }public void setEmail(String email) {

this.email = email; }public String getPassword() {

return(password); }public void setPassword(String password) {

this.password = password; }}

Page 144: Struts An Open-source Architecture for Web Applications Facilitator: Tripti Shukla.

Hands On – Case Study 3Step 3: Create Result Beans

These are the normal value objects used in MVC Do not need to extend any particular class Do not need zero argument constructors if JSP

page will never create the objects Still need getter methods Setter methods are optional; you sometimes

supply all needed values to the constructor Often returned by business-logic or data-

access-logic code

Page 145: Struts An Open-source Architecture for Web Applications Facilitator: Tripti Shukla.

Hands On – Case Study 3SuggestionBean.java

package training;public class SuggestionBean {

private String email;private String password;public SuggestionBean(String email, String password) {this.email = email;this.password = password;}public String getEmail() {return(email);}public String getPassword() {return(password);}

}

Page 146: Struts An Open-source Architecture for Web Applications Facilitator: Tripti Shukla.

Hands On – Case Study 3Step 4: Create Action subclass

package training;import javax.servlet.http.*;import org.apache.struts.action.*;

public class RegisterAction3 extends Action {public ActionForward execute(ActionMapping mapping,ActionForm form,HttpServletRequest request,HttpServletResponse response)throws Exception

Page 147: Struts An Open-source Architecture for Web Applications Facilitator: Tripti Shukla.

Hands On – Case Study 3{

UserFormBean userBean = (UserFormBean)form;String email = userBean.getEmail();String password = userBean.getPassword();SuggestionBean suggestionBean =SuggestionUtils.getSuggestionBean();request.setAttribute("suggestionBean", suggestionBean);if ((email == null) ||(email.trim().length() < 3) ||(email.indexOf("@") == -1)) {return(mapping.findForward("bad-address"));} else if ((password == null) ||(password.trim().length() < 6)) {return(mapping.findForward("bad-password"));} else {return(mapping.findForward("success"));}

}}

Page 148: Struts An Open-source Architecture for Web Applications Facilitator: Tripti Shukla.

Hands On – Case Study 3Step 5: Create Form wipro_casestudy_3\register3.jsp

<!DOCTYPE …><HTML>

<HEAD><TITLE>New Account Registration</TITLE></HEAD><BODY BGCOLOR="#FDF5E6">

<CENTER><H1>New Account Registration</H1><FORM ACTION="register3.do" METHOD="POST">

Email address: <INPUT TYPE="TEXT" NAME="email"><BR>Password: <INPUT TYPE="PASSWORD"

NAME="password"><BR><INPUT TYPE="SUBMIT" VALUE="Sign Me Up!">

</FORM></CENTER>

</BODY></HTML>

Page 149: Struts An Open-source Architecture for Web Applications Facilitator: Tripti Shukla.

Hands On – Case Study 3

Step 6: Display Results in JSP

Use Struts bean:write tag Most common approach bean:write automatically filters special

HTML characters < replaced by &lt; > replaced by &gt;

Page 150: Struts An Open-source Architecture for Web Applications Facilitator: Tripti Shukla.

Hands On – Case Study 3bad_address3.jsp

<!DOCTYPE …>HTML><HEAD><TITLE>Illegal Email Address</TITLE></HEAD><CENTER><H1>Illegal Email Address</H1><%@ taglib uri="/WEB-INF/struts-bean.tld" prefix="bean" %>The address"<bean:write name="userFormBean" property="email"/>"is not of the form username@hostname (e.g.,<bean:write name="suggestionBean" property="email"/>).<P>Please <A HREF="register3.jsp">try again</A>.</CENTER></BODY></HTML>

Page 151: Struts An Open-source Architecture for Web Applications Facilitator: Tripti Shukla.

Hands On – Case Study 3bad_pass3.jsp

<!DOCTYPE HTML …><HTML><HEAD><TITLE>Illegal Password</TITLE></HEAD><CENTER><H1>Illegal Password</H1><%@ taglib uri="/WEB-INF/struts-bean.tld" prefix="bean" %>The password"<bean:write name="userFormBean" property="password"/>“ is too shortHere is a possible password:<bean:write name="suggestionBean" property="password"/>.<P>Please <A HREF="register3.jsp">try again</A>.</CENTER></BODY></HTML>

Page 152: Struts An Open-source Architecture for Web Applications Facilitator: Tripti Shukla.

Hands On – Case Study 3result3.jsp

<!DOCTYPE …><HTML><HEAD><TITLE>Success</TITLE></HEAD><CENTER><H1>You have registered successfully.</H1><%@ taglib uri="/WEB-INF/struts-bean.tld" prefix="bean" %><UL><LI>Email Address:<bean:write name="userFormBean" property="email"/><LI>Password:<bean:write name="userFormBean" property="password"/></UL></CENTER></BODY></HTML>

Page 153: Struts An Open-source Architecture for Web Applications Facilitator: Tripti Shukla.

Hands On – Case Study 3

Step 7: Compile java classes

Page 154: Struts An Open-source Architecture for Web Applications Facilitator: Tripti Shukla.

Hands On – Case Study 3

Step 8: Access the page

http://<host_name>:8080/wipro_casestudy_3/register3.jsp

Page 155: Struts An Open-source Architecture for Web Applications Facilitator: Tripti Shukla.

Hands On – Case Study 4 Components

Application requirements Using the Model-View-Controller pattern to design a

solution using Struts The View component: The HTML form and the form bean MessageResources and Application.properties files The Struts form bean: HelloForm.java Data validation and using ActionErrors The Controller component: HelloAction.java The Model component: HelloModel.java Passing data to the View using attributes: Constants.java Tying it all together: struts-config.xml

Page 156: Struts An Open-source Architecture for Web Applications Facilitator: Tripti Shukla.

Hands On – Case Study 4

Illustrates Enable the user to enter a name to say

Hello! to and output the string Hello <name>!.

Don't let the user submit the entry form without entering a name.

If user does, provide an error message to help him fill the form out correctly.

Page 157: Struts An Open-source Architecture for Web Applications Facilitator: Tripti Shukla.

Hands On – Case Study 4

Step 1: Create struts application structure

copy blank.war to <tomcat_home>/webapps

Rename to application start Tomcat Server

Page 158: Struts An Open-source Architecture for Web Applications Facilitator: Tripti Shukla.

Hands On – Case Study 4

Step 2: The view component, HTML Form

Use custom tags include tag libraries

Pick up static text from properties file i18n & localization

Page 159: Struts An Open-source Architecture for Web Applications Facilitator: Tripti Shukla.

Hands On – Case Study 4

Step 3: MessageResources & ApplicationResources.properties

Page 160: Struts An Open-source Architecture for Web Applications Facilitator: Tripti Shukla.

Hands On – Case Study 4

Step 4: Form Bean On form submission, the data from form is

populated into a java bean called form bean Has properties that match up with all the fields

in the form must have getters & setters

Form beans provide support for automatic data validation & resetting of bean property values

validate() & reset() methods can be overridden as per requirement

Page 161: Struts An Open-source Architecture for Web Applications Facilitator: Tripti Shukla.

Hands On – Case Study 4

Step 5: Data validation & ActionErrors The Hello World! application has been defined

to have two different types of errors: basic data/form validation errors and business logic errors. The requirements for the two types are: Form validation—In the data entry form, make sure

that the user doesn't submit the form with the person field empty

Business logic—Enforce a rule that the user can't say hello to a person he isn't allowed to talk to. (Because Atilla the Hun has such a bad reputation, let's make him the person we won't speak to.)

Page 162: Struts An Open-source Architecture for Web Applications Facilitator: Tripti Shukla.

Hands On – Case Study 4

Step 6: The Controller Component

Action class

Page 163: Struts An Open-source Architecture for Web Applications Facilitator: Tripti Shukla.

Hands On – Case Study 4

Step 7: The model component

Page 164: Struts An Open-source Architecture for Web Applications Facilitator: Tripti Shukla.

Hands On – Case Study 4

Step 8: Passing data to the view using Attributes

Page 165: Struts An Open-source Architecture for Web Applications Facilitator: Tripti Shukla.

Hands On – Case Study 4

Step 9: Tying it all togetherstruts-config.xml

Page 166: Struts An Open-source Architecture for Web Applications Facilitator: Tripti Shukla.

Hands On – Case Study 4

Step 10: Access the page

http://<host_name>:8080/wipro_casestudy_4/hello.jsp

Page 167: Struts An Open-source Architecture for Web Applications Facilitator: Tripti Shukla.

Struts Validator

Page 168: Struts An Open-source Architecture for Web Applications Facilitator: Tripti Shukla.

Nature of Validations

Client-side validations often implemented through

JavaScript JavaScript may not be enabled/ may

not be supported Front-end validations in business tier

may affect performance Business level validations

Page 169: Struts An Open-source Architecture for Web Applications Facilitator: Tripti Shukla.

Struts Validator – To Rescue Using the Jakarta Commons Validator [ASF, Validator] brings

several consequences: The Validator is a framework component that meets

client side validation & server-side validation requirements

configured from an XML file that generates validation rules for the fields in the form

Rules are defined by a Validator that is also configured through XML Validators for basic types, like dates and integers, are provided. If needed, it can be created

Regular expressions can be used for pattern-based validations such as postal codes and phone numbers

Localized validations are supported

Page 170: Struts An Open-source Architecture for Web Applications Facilitator: Tripti Shukla.

Validation Technique before Struts1.1

Two options for Form Validation: ActionForm class -- for simple/syntax

validation Action class – business validation

On validation errors: ActionErrors object is returned

Technique is still valid in 1.1

Page 171: Struts An Open-source Architecture for Web Applications Facilitator: Tripti Shukla.

Benefits Optimal use of resources: JavaScript

validations are provided when enabled, and server-side validations are guaranteed

A single point of maintenance: Both client-side and server-side validations are generated from the same configuration

Extendibility: Custom validations can be defined as regular expressions or in Java code

Maintainability: It is loosely coupled to the application and can be maintained without changing markup or code

Page 172: Struts An Open-source Architecture for Web Applications Facilitator: Tripti Shukla.

Benefits The Struts ActionForm can simply extend the

ValidatorForm or ValidatorActionForm class. The rest is automatic.

Easy deployment of client-side validation: To make use of the client-side validations, just add a single JSP tag to generate the validation script and use that script to submit the form

Easy configuration: The Validator uses an XML file for configuration, just like the web application deployment descriptor and the Struts configuration

Page 173: Struts An Open-source Architecture for Web Applications Facilitator: Tripti Shukla.

Benefits Localization: Localized validations can be

defined only when and where they are needed Integration with Struts: By default, validations

share the Struts message bundle Localized text can be centralized and reused Easy deployment of server-side validation: To

make use of the server-side validations,

Page 174: Struts An Open-source Architecture for Web Applications Facilitator: Tripti Shukla.

Shortcomings Nonmodal client-side validations

The generated JavaScript is nonmodal; it does not engage until the form is submitted

Dependencies The validations are detached from the

fields and from the ActionForm properties. The page markup, the ActionForm, and the Validator and Struts configuration files must all be synchronized

Page 175: Struts An Open-source Architecture for Web Applications Facilitator: Tripti Shukla.

Overview -- Pieces that make up Struts Validator

Component

Validators -- Validator-Rules.xml

Resource Bundle -- ApplicationResources.properties

XML Configuration File -- Validation.xml

JSP Tag

ValidatorForm

ValidatorActionForm

Page 176: Struts An Open-source Architecture for Web Applications Facilitator: Tripti Shukla.

Validator Configuration File Struts Validator can actually use two XML

files: one to set up the validators -- Validator-rules.xml another with the settings for the applications –

Validation.xml NOTE: Struts 1.0 uses a single configuration file

Strength: validations are declared outside the application

source code using an XML configuration file The configuration specifies which fields on a form

need validation, the validators a field uses, and any special settings to be used with a field.

Page 177: Struts An Open-source Architecture for Web Applications Facilitator: Tripti Shukla.

Validator Configuration File Strength

Alternate formsets can be configured for different locales and override any locale-sensitive validations

All of the validators used by the framework are configured through XML, including the basic validators that ship with the package

Option for custom Validators This makes for a very flexible package

Page 178: Struts An Open-source Architecture for Web Applications Facilitator: Tripti Shukla.

Validator Configuration File

In Struts 1.1, the paths to the Validator configuration files are declared in the struts-config.xml file:

<plug-in className="org.apache.struts.validator.ValidatorPlugIn">

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

</plug-in>

Page 179: Struts An Open-source Architecture for Web Applications Facilitator: Tripti Shukla.

Validator-rules.xml Includes validators for :

basic validators• native types and other common needs, like e-mail and

credit card validations Declare required validators

Validator elements are defined in two parts: A Java class and method for the server-side

validation JavaScript for the client-side validation

Location web-inf

Page 180: Struts An Open-source Architecture for Web Applications Facilitator: Tripti Shukla.

Validator-rules.xml

Validator Purpose

requiredSucceeds if the field contains any characters other than whitespace.

maskSucceeds if the value matches the regular expression given by the mask attribute.

rangeSucceeds if the value is within the values given by the min and max attributes ((value >= min) & (value <= max)).

maxLength

Succeeds if the field’s length is less than or equal to the max attribute.

minLengthSucceeds if the field’s length is greater than or equal to the min attribute.

Page 181: Struts An Open-source Architecture for Web Applications Facilitator: Tripti Shukla.

Validator-rules.xml

Validator Purpose

byte, short,integer, long,float, double

Succeeds if the value can be converted to the corresponding primitive.

dateSucceeds if the value represents a valid date. A date pattern may be provided.

creditCard Succeeds if the value could be a valid credit card number.

email Succeeds if the value could be a valid e-mail address.

Page 182: Struts An Open-source Architecture for Web Applications Facilitator: Tripti Shukla.

Validation.xml A formset is a wrapper for one or more forms

Contains validations for entire application Each form element is given its own name

correspond to either the form bean name or the action path from Struts configuration

Each form element is composed of a number of field elements. The field elements designate which validator(s) to use with the

depends attribute The optional msg element lets you specify a custom message key

for a validator and the message key to use for any replacement parameters

The arg0 element specifies the first replacement parameter to use with any messages that need them

The var element is used to pass variable properties to the validator

Can be localized

Page 183: Struts An Open-source Architecture for Web Applications Facilitator: Tripti Shukla.

ApplicationResources.properties On validation failure, it passes back a message

key and replacement parameters Entry for our required validator looks like:

errors.required={0} is required. When a field is configured to use the required

validator, the field’s label is also passed as a replaceable parameter The validator can then reuse the same

message for all the required fields Alternatively, customized messages can be

defined to selectively override the defaults

Page 184: Struts An Open-source Architecture for Web Applications Facilitator: Tripti Shukla.

JSP Tag Import the validator taglib

<%@ taglib uri="/tags/struts-validator" prefix="validator" %>

This section calls the validation script. Then, the form is submitted<html:form action="/logonSubmit" focus="username"onsubmit="validateLogonForm(this)">

Add the tag to output the JavaScript anywhere on the page<validator:javascript formName="logonForm"/></BODY></HTML>

Page 185: Struts An Open-source Architecture for Web Applications Facilitator: Tripti Shukla.

ValidatorForm & ValidatorActionForm

To enable the Struts Validator for Struts 1.1 extend FormBean from ValidatorForm OR

ValidatorActionForm• The ValidatorForm will match the formset name with the

form-bean name• The ValidatorActionForm will match the formset name

with the actionmapping path In most cases, the Struts Validator can completely replace the

need to write a custom validate method for an ActionForm First, call the ancestor validate method

• Validator framework is invokedpublic ActionErrors validate(ActionMapping

mapping,HttpServletRequest request) {// bActionErrors errors = super.validate(mapping, request);}

Page 186: Struts An Open-source Architecture for Web Applications Facilitator: Tripti Shukla.

ValidatorForm & ValidatorActionForm

To run our own validations• Implement validate() methodpublic ActionErrors validate(ActionMapping

mapping,HttpServletRequest request) {// bActionErrors errors =

super.validate(mapping, request);//continue validating}

Page 187: Struts An Open-source Architecture for Web Applications Facilitator: Tripti Shukla.

The validate() method Extend form bean from ValidatorForm instead of

ActionFormpublic final class LogonForm extends

org.apache.struts.validator.action.ValidatorForm {}

When the controller calls the validate method, the ValidatorForm method will kick in and follow the rules we defined in the validation.xml fileActionErrors errors = super.validate(mapping,

request); if (errors == null) errors = new ActionErrors();

Page 188: Struts An Open-source Architecture for Web Applications Facilitator: Tripti Shukla.

Hands On

Implement Struts Validator

http://wiki.apache.org/jakarta-commons/ValidatorSetup

Page 189: Struts An Open-source Architecture for Web Applications Facilitator: Tripti Shukla.

Adding struts to an existing web-app

Copy struts_install_dir/lib/*.tld Place in theWEB-INF directory of your Web application

Copy struts_install_dir/lib/*.jar Place in the WEB-INF/lib directory of your Web

application Also include struts.jar in your development

CLASSPATH Modify WEB-INF/web.xml Use servlet and servlet-mapping entries so that URLs

that end in *.do are mapped to org.apache.struts.action.ActionServlet

Create struts-config.xml Define mappings for specific URLs to specific actions

Page 190: Struts An Open-source Architecture for Web Applications Facilitator: Tripti Shukla.

Best Practices

The Action should not perform any business logic. (Action is part of the controller)

The ActionForm should not be used as the data model

The ActionForm should not be used to validate business objects

Page 191: Struts An Open-source Architecture for Web Applications Facilitator: Tripti Shukla.

Tips Always start at .do – never show .jsp Use some JavaScript to submit forms

onClick() or onChange() Don't bother with /do/myAction notation When back buttons and refresh won't work

Place forms in session scope with nocache="true"

Always redirect to a get before presenting page (use xxx.do?action="refresh")

This is an all or nothing solution that could impact performance due to memory utilization

Page 192: Struts An Open-source Architecture for Web Applications Facilitator: Tripti Shukla.

Common Errors

Check boxes are not set Use reset method in form to set check box

properties to false Session timeouts cause null pointer

exceptions Use lazy lists in forms with factory

Properties not set on form Verify type is correct Make sure form values start with lower case and

each separator (.) has a getter

Page 193: Struts An Open-source Architecture for Web Applications Facilitator: Tripti Shukla.

Common Errors Button does not call proper method

Use JavaScript if necessary to set action for buttons Action class is not being called on submit

Verify action path in struts-config matches the form action name

Remove validate="true" from struts-config and call form.validate directly from action

When chaining actions form properties are lost The reset() action is called between actions so add

properties to the request string

Page 194: Struts An Open-source Architecture for Web Applications Facilitator: Tripti Shukla.

Chaining Actions Used when more than one action will

process a single request Challenges:

Different actions will have different forms – input may not match up

Setting return point is difficult Solutions:

Avoid chaining actions Start with a clean slate each time – use redirect Store return point in session

Page 195: Struts An Open-source Architecture for Web Applications Facilitator: Tripti Shukla.

Features Built in exception handling at an action an global

scope are specified in the config file. I18 N, Internationalization, support with

resource bundles. JSP custom tags Validator framework from the jakarta.commons

project; this is set up as a plugin and configured via validation.xml and validation-rules.xml

Tiles – a templating mechanism incorporated into Struts for managing page layout.

Supports database access classes.

Page 196: Struts An Open-source Architecture for Web Applications Facilitator: Tripti Shukla.

ForwardAction ForwardAction is the one of the most frequently used built-

in Action classes. The primary reason behind this is that ForwardAction allows you to adhere to MVC paradigm when designing JSP navigation. Most of the times you will perform some processing when you navigate from one page to another. In Struts, this processing is encapsulated in the Action instances. There are times however when all you want to do is navigate from one page to another without performing any processing. You would be tempted to add a hyperlink on the first page for direct navigation to the second. Watch out! In Model 2 paradigm, a straight JSP invocation from another JSP is discouraged, although not

prohibited.

Page 197: Struts An Open-source Architecture for Web Applications Facilitator: Tripti Shukla.

To configure the use of this Action in your struts-config.xml file, create an entry like this:

<action path="/saveSubscription" type="org.apache.struts.actions.ForwardAction" name="subscriptionForm" scope="request" input="/subscription.jsp" parameter="/path/to/processing/servlet"/>

Page 198: Struts An Open-source Architecture for Web Applications Facilitator: Tripti Shukla.

DispatchAction DispatchAction is one of the Struts

built-in action that provides a mechanism that facilitates having a set of related functionality in a single action instead of creating separate independent actions for each function.

public abstract class DispatchActionextends BaseAction

Page 199: Struts An Open-source Architecture for Web Applications Facilitator: Tripti Shukla.

To configure the use of this action in your struts-config.xml file, create an entry like this:<action path="/saveSubscription" type="org.apache.struts.actions.DispatchAction" name="subscriptionForm" scope="request" input="/subscription.jsp" parameter="method"/>

which will use the value of the request parameter named "method" to pick the appropriate "execute" method, which must have the same signature (other than method name) of the standard Action.execute method. For example, you might have the following three methods in the same action:•public ActionForward delete(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception•public ActionForward insert(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception•public ActionForward update(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception

and call one of the methods with a URL like this:http://localhost:8080/myapp/saveSubscription.do?method=update

Page 200: Struts An Open-source Architecture for Web Applications Facilitator: Tripti Shukla.

public abstract class LookupDispatchAction extends DispatchAction

An abstract Action that dispatches to the subclass mapped execute method. This is useful in cases where an HTML form has multiple submit buttons with the same name. The button name is specified by the parameterproperty of the corresponding ActionMapping. To configure the use of this action in your struts-config.xml file, create an entry like this:

<action path="/test" type="org.example.MyAction" name="MyForm" scope="request" input="/test.jsp" parameter="method"/>

Page 201: Struts An Open-source Architecture for Web Applications Facilitator: Tripti Shukla.

Your subclass must implement both getKeyMethodMap and the methods defined in the map. An example of such implementations are:

protected Map getKeyMethodMap() { Map map = new HashMap(); map.put("button.add", "add"); map.put("button.delete", "delete"); return map; }

Page 202: Struts An Open-source Architecture for Web Applications Facilitator: Tripti Shukla.

LookupDispatchAction VS. DispatchAction

We will perform following changes to the application to make it work with LoopupDispatchAction:

Our action class  (InvitationAction.java) will extend LoopupDispatchAction instead of DispatchAction.

Add a application properties file that will contain the detail of the method to be executed when a particular value will come from the request parameter which is defined in attribute parameter in action tag.

Some basic changes to jsp for making the ui more perfect.