Struts Framework

Objectives
Understand the need for Struts Identify the components of Struts framework

© Copyright 2006 Sapient Corporation

2

Agenda
Web Technologies Overview Case Study Introduction Building Blocks Validation

© Copyright 2006 Sapient Corporation

3

Web Technologies – An Overview
Static content – HTML Dynamic content – CGI, ASP, PHP Java servlets brought platform independence to web It suffered from:
Coding is complex Presentation and biz logic are tightly coupled Difficult to maintain

JSP
Embeds Java into HTML Simplifies coding Custom tags for asset reuse Separation of concerns (site developers/coders)

© Copyright 2006 Sapient Corporation

4

Web Application – Architectures
Model 1 Architecture

Client Tier

Web Tier

Data Tier

Web Container JSP
Providing Presentation, Flow Control And Business Logic

Database

© Copyright 2006 Sapient Corporation

5

Web Application – Architecture (continued)
Model 2 – MVC Architecture Key Features
• • • • •

Application flow is mediated by a central Controller Controller acts as a single entry point Controller interacts with Model Controller delegates requests and forwards to target views Reusability, extensibility, modularity and easy maintainability

© Copyright 2006 Sapient Corporation

6

Web Application Framework
A Framework
Is an extensible/generic/flexible architecture Focuses on a specific domain (web / j2ee applications etc.) Provides extension points Can be customized and used on projects

© Copyright 2006 Sapient Corporation

7

What is the Struts Framework?
Used to create web applications Uses
JavaBeans Java servlets Java Server pages (JSP)

Based on the MVC design pattern Rich set of tag libraries provided for presentation tier Extensible

© Copyright 2006 Sapient Corporation

8

Why Struts?
Broad community acceptance Easy to learn One of the earliest open source frameworks Relatively stable with respect to other frameworks Constantly evolving Wide range of books / training material available Blessing of infrastructure providers (BEA / IBM / Sun)

© Copyright 2006 Sapient Corporation

9

Struts Framework – Case Study

Background – Requirements
XYZ organization needs a web based ‘User Management’ application with the following functionalities
Provide a user registration functionality Display all the register users

Proposed Solution: Design a simple application based on our existing knowledge on JSP and servlets using Struts Framework.

© Copyright 2006 Sapient Corporation

11

Struts Framework – Building Blocks

Introduction
Controller: ActionServlet Model: Action, Business Layer View: JSPs

© Copyright 2006 Sapient Corporation

13

(one time) digest

struts-config.xml [configuration file]

1.1 get mapping

Action Mapping

1 event HTTP Request

Action Servlet [Controller]

2 dispatch

Action [Model]

1.2 create Action Form Client Browser 3 forward 2.4 use

2.1 (can) use

Action Forward

2.3 create

2.2 interact

JSP [View] 4 update HTTP Response

3.1 (can) interact

Business Layer [Model]

© Copyright 2006 Sapient Corporation

14

Building Blocks
Basic Struts Components:
Action Servlet struts-config.xml Action Mapping Action Form Action Class Action Forward JSPs

Additional Components:
Action Messages Resource Bundle web.xml

© Copyright 2006 Sapient Corporation

15

Putting The Blocks Together – Action Servlet
(one time) digest struts-config.xml [configuration file]

1.1 get mapping

Action Mapping

Action 1 event HTTP Request 1.2 create Action Form Client Browser 3 forward 2.4 use Action Forward 2.3 create 2.2 interact 2.1 (can) use Action Servlet [Controller] 2 dispatch

JSP [View] 4 update HTTP Response

3.1 (can) interact

Business Layer [Model]

© Copyright 2006 Sapient Corporation

16

Action Servlet – Controller
Controller in the struts architecture Maps the incoming requests to the actions Mappings configurable in XML based file ActionServlet creates an ActionForm and uses an Action ActionServlet is a part of Struts framework

© Copyright 2006 Sapient Corporation

17

Putting the Blocks Together – Struts Configuration
(one time) digest struts-config.xml [configuration file]

1.1 get mapping

Action Mapping

1 event HTTP Request

Action Servlet [Controller]

2 dispatch

Action [Model]

1.2 create Action Form Client Browser 3 forward 2.4 use

2.1 (can) use

Action Forward

2.3 create

2.2 interact

4 update HTTP Response

JSP [View]

3.1 (can) interact

Business Layer [Model]

Struts configuration digested by Controller Servlet
© Copyright 2006 Sapient Corporation

18

Struts Configuration
Main control file in the Struts framework Digested at startup by the ActionServlet Typically, the file is called ‘struts_config.xml’ Typically, it is placed in the WEB-INF directory of the web application

© Copyright 2006 Sapient Corporation

19

Sample

© Copyright 2006 Sapient Corporation

20

Putting the Blocks Together – Action Mapping
(one time) digest struts-config.xml [configuration file]

1.1 get mapping

Action Mapping

1 event HTTP Request

Action Servlet [Controller]

2 dispatch

Action [Model]

1.2 create Action Form Client Browser 3 forward 2.4 use

2.1 (can) use

Action Forward

2.3 create

2.2 interact

4 update HTTP Response

JSP [View]

3.1 (can) interact

Business Layer [Model]

© Copyright 2006 Sapient Corporation

21

Action Mapping
In the struts configuration file
All action mappings are contained under <action-mappings> node in the configuration Each action is represented by <action> node

ActionMapping associates requests with actions ActionMappings contain one or more ActionForwards Action Mapping objects are created and used by Action Servlet

© Copyright 2006 Sapient Corporation

22

Putting the Blocks Together – ActionForm
(one time) digest struts-config.xml [configuration file]

1.1 get mapping

Action Mapping

1 event HTTP Request

Action Servlet [Controller]

2 dispatch

Action [Model]

1.2 create Action Form Client Browser 3 forward 2.4 use

2.1 (can) use

Action Forward

2.3 create

2.2 interact

4 update HTTP Response

JSP [View]

3.1 (can) interact

Business Layer [Model]

© Copyright 2006 Sapient Corporation

23

ActionForm
Java bean class with setters and getters Represent the data entered in the web application Extend ActionForm to create custom classes Requires no specific methods to be implemented Beans can either be coarse or fine grained Same form can be reused in different actions Offers a standard validation mechanism

© Copyright 2006 Sapient Corporation

24

ActionForm Considerations
ActionForms are stored in various scopes
Page Request Session Application

The scope is specified in the Struts configuration file Always limit the scope to the bare minimum Request scope should be used for majority of forms

© Copyright 2006 Sapient Corporation

25

UserForm.java

© Copyright 2006 Sapient Corporation

26

Putting the Blocks Together – Action Class
(one time) digest struts-config.xml [configuration file]

1.1 get mapping

Action Mapping

1 event HTTP Request

Action Servlet [Controller]

2 dispatch 1.2 create 2.1 (can) use

Action [Model]

Action Form Client Browser 3 forward 2.4 use Action Forward 2.3 create 2.2 interact

4 update HTTP Response

JSP [View]

3.1 (can) interact

Business Layer [Model]

© Copyright 2006 Sapient Corporation

27

Action Class
The goal of an Action class is
Process the incoming request by interacting with the business layer Return an ActionForward object that identifies the resource to which control should be forwarded

The Action class defines an execute method that you override public ActionForward execute( ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception;

© Copyright 2006 Sapient Corporation

28

Execute Method
A typical Action class can implement the following logic in its execute method
Validate the current state of the user's session Perform any business level validations Process the incoming request Update the server-side objects to create the next page Return an appropriate ActionForward object that identifies the JSP page to be used to generate this response, based on the newly updated beans

© Copyright 2006 Sapient Corporation

29

SaveUserAction.java

© Copyright 2006 Sapient Corporation

30

Considerations
Only one instance of your Action class is created and used for all requests Therefore they need to be thread safe Exceptions thrown from execute() method should be appropriately logged Consider using custom actions to simplify coding
DispatchAction ForwardAction

© Copyright 2006 Sapient Corporation

31

Putting the Blocks Together – Action Forwards
(one time) digest struts-config.xml [configuration file]

1.1 get mapping

Action Mapping

1 event HTTP Request

Action Servlet [Controller]

2 dispatch

Action [Model]

1.2 create Action Form Client Browser 3 forward 2.4 use

2.1 (can) use

Action Forward

2.3 create

2.2 interact

4 update HTTP Response

JSP [View]

3.1 (can) interact

Business Layer [Model]

© Copyright 2006 Sapient Corporation

32

Action Forwards
ActionForward associates a logical name with a system path
Action returns an ActionForward to the controller

Two kinds of ActionForwards provided by the Struts
Global forward
Visible to any Action object throughout the application Application can have any number of global action forwards

Local forward
Available to the Action object associated with ActionMapping An action mapping can have any number of local forwards Local action forwards always take precedence

© Copyright 2006 Sapient Corporation

33

Consideration
Actions are flexible and can return any number of different forwards depending on the circumstances Action needs to know the logical name of the forward
e.g. "success" or "failure“

© Copyright 2006 Sapient Corporation

34

Putting the Blocks Together – JSP
(one time) digest struts-config.xml [configuration file]

1.1 get mapping

Action Mapping

1 event HTTP Request

Action Servlet [Controller]

2 dispatch

Action [Model]

1.2 create Action Form Client Browser 3 forward 2.4 use

2.1 (can) use

Action Forward

2.2 interact 2.3 create

JSP [View] 4 update HTTP Response

3.1 (can) interact

Business Layer [Model]

© Copyright 2006 Sapient Corporation

35

JSPs As View
Struts uses JSPs as View component. Several special-purpose JSP tag libraries are also defined by Struts Tag library simplifies the HTML specification of input components

© Copyright 2006 Sapient Corporation

36

RegisterForm.jsp

© Copyright 2006 Sapient Corporation

37

Additional Components
web.xml Is the deployment descriptor for web applications For a pure struts application little configuration is required
Configure ActionServlet as a startup servlet Configure action servlet mappings Configure tag libraries Configure any additional J2EE resource

© Copyright 2006 Sapient Corporation

38

Sample

© Copyright 2006 Sapient Corporation

39

Struts Application – Simple 5 Step Process
1. 2. 3. 4. 5.

Create and edit the web app deployment descriptor (web.xml) Create and edit the struts-config.xml file with appropriate action and form mapping. Write a Java class extending Struts Action class.
1.

Provide the business functionality in the ‘execute()’ method.

Write a JavaBean class extending Struts ActionForm class Write the HTML based view elements in a JSP.

© Copyright 2006 Sapient Corporation

40

Struts Framework – Validation Strategy

Objectives
To know the validation strategies in struts framework To understand the manual validation and its disadvantages

© Copyright 2006 Sapient Corporation

42

Form Validation Strategy
Manual Validation
Do validation in the Action
Must write validation rules yourself

Do validation in the form bean
Using the validate method

Automatic validation
Using Validation framework Handles many common cases

© Copyright 2006 Sapient Corporation

43

Using Manual Validation
Put validation code in bean
Insert <html:errors/> in input form Override validate method in ActionForm class

Drawbacks associated with Manual Validation
Repeats same logic many times Embedded in Java code Violates Struts strategy of configuring and reuse editable XML files

© Copyright 2006 Sapient Corporation

44

Manual Validation – Validate method

--------17public class UserForm extends ValidatorActionForm { 18 private String firstName; 19 private String lastName; --------- @return Returns the age. 29 * 30 */ 31 public String getAge() { 32 return age; 33 } 34 --------------------------133 public ActionErrors validate(ActionMapping mapping, 134 HttpServletRequest request) 135 { 136 ActionErrors lErrors = new ActionErrors(); 137 if(getLoginId() == null || getLoginId().length() <= 0) { 138 lErrors.add(getLoginId(),new ActionError("errors.required","Login Id")); 139 } 140 141 return lErrors; 142} ------------------© Copyright 2006 Sapient Corporation

45

Struts HTML tag ‘<html:errors/>’ should be embedded in the JSP page.

© Copyright 2006 Sapient Corporation

46

Sample Output Screen

Validation messages

With empty fields click of Registration button

© Copyright 2006 Sapient Corporation

47

Where to go from here?
Struts User Guide http://jakarta.apache.org/struts/userGuide/index.html Struts Controller UML diagrams http://rollerjm.free.fr/pro/Struts.html The Apache Struts Application Framework http://jakarta.apache.org/struts/ About Tiles http://www.lifl.fr/~dumoulin/tiles/doc/tutorial.html http://www.theserverside.com/resources/strutsreview.jsp

© Copyright 2006 Sapient Corporation

48

Questions