actitime

120
ActiTime 2006 1. INTRODUCTION ABOUT THE PRODUCT actiTIME is time collection software that is streamlined for billing and invoicing purposes. actiTIME allows time tracking for customer and project related tasks. After being collected the data can then be exported for invoice generation. Task, Project, and Customer Management includes the following activities: Customer Management o Registering customers in the system o Editing information of registered customers Project Management o Registering projects in the system o Editing information of registered projects Task management o Creation of new tasks o Editing task information o Completing and re-opening tasks o Browsing open and completed tasks To access the interfaces for Tasks, Projects, and Customers Management use top-level menu option 'Projects & Tasks'. There are three (3) access rights defined for Task, Project, and Customer Management: Manage Customers Manage Projects Manage Tasks Each of the access rights regulates user access to the corresponding subset of system interfaces. System users may have any combination of these access rights. For example: A user who has only 'Manage Tasks' access right will be able to create new tasks to track time expenses for, but will not be allowed to create new projects and customers. 1

Upload: api-3725193

Post on 13-Nov-2014

184 views

Category:

Documents


8 download

TRANSCRIPT

Page 1: actiTime

ActiTime 2006

1. INTRODUCTION

ABOUT THE PRODUCT

actiTIME is time collection software that is streamlined for billing and invoicing purposes. actiTIME allows time tracking for customer and project related tasks. After being collected the data can then be exported for invoice generation.

Task, Project, and Customer Management includes the following activities: Customer Management o Registering customers in the system o Editing information of registered customers Project Management o Registering projects in the system o Editing information of registered projects Task management o Creation of new tasks o Editing task information o Completing and re-opening tasks o Browsing open and completed tasks

To access the interfaces for Tasks, Projects, and Customers Management use top-level menu option 'Projects & Tasks'. There are three (3) access rights defined for Task, Project, and Customer Management: Manage Customers Manage Projects Manage Tasks

Each of the access rights regulates user access to the corresponding subset of system interfaces. System users may have any combination of these access rights. For example:

A user who has only 'Manage Tasks' access right will be able to create new tasks to track time expenses for, but will not be allowed to create new projects and customers. A user who has only 'Manage Customers' access right will be able to create and modify customers but will not be able to create projects and tasks.

Grant these access rights to users according their responsibilities in everyday work. If you do not need to introduce subordination between users and responsibilities, just grant all three-access rights to those users who are responsible for project/task management in your organization. For example, you can grant them to project managers.

Note that users who do not have some access right will not see the interfaces associated with this right at all.

1

Page 2: actiTime

ActiTime 2006See section User management about information on how to grant access rights to system users.

PROJECT OVERVIEW

This is an intranet-based project, which provides Time Tracking, billing and

invoice generation for the customer projects. Projects related to customers can be

created, task related to a software can be created, tracked and completed by

employees of different departments. Time Tracking for each and every task

completed by each and every employee is maintained and generate based on

several criteria. This generates an effective billing based on the no of hours the

employee has worked and it can calculate the overtime bills also.

PROJECT SCOPE

This intranet application has been developed to be implemented in place of

existing manual system. This project would automate the operations of the

administrator and would retain the present functionality available in the current

system. The specific purpose of this system is to track the tasks in each and every

project for each and every every customer and generate the billing the

information. The superior can assign tasks to his sub-ordinates and he can monitor

the status of the task at any point of time. The administrator is responsible for the

maintenance of this system. Administrator can manage users and billing types

according to the needs of the application.

SCREEN DESIGN/GRAPHICAL USER INTERFACE

Graphical User Interface (GUI) that is straightforward and easy to navigate has

been designed. This GUI provide various screens with appropriate incorporate

icons, hyperlinks etc. to facilitate screen navigation and data entry. The user can

to return to home page from any location within the application.

2

Page 3: actiTime

ActiTime 2006GENERAL DESCRIPTION

This application is for fulfilling the different requirements of the administrator

and employees of an organization.

In this application an employee can:

1. He can add tasks to his list.

2. He can enter how much time he has worked on a particular task

3. He can close the task

4. He can submit the time track

5. He can submit the time track with overtime

6. He can view his Time Track

7. He can view the tasks page by page and he can set how many tasks has

to be

decided per page

8.Sometimes he can also generate the reports

9.Sometimes he can add the tasks also.

10.He can see the schedule of a particular date.

In addition to the above functions the administrator can perform the following

functionalities:

1. Adding, Deleting and editing the Customer Information

2. Adding, deleting and editing projects information

3. Setting up the Working days and Non-Working days for the

Organization.

4. Setting the calendar preferences

5. Creating, deleting and changing Billing Types

6. Create deleting, editing and assigning the tasks to different people

7. Enable, disable the users

8. Enable the over time option for a particular user

9. He can change his profile

10. Generating Billing, Staff Out, OverTime, Prepare Invoice Reports

11. Changing the status of the tasks

12. Copying the tasks from one project to another 3

Page 4: actiTime

ActiTime 200613. setting the deadlines to the tasks

14. setting different permissions for the users

2. SYSTEM ANALYSIS

2.1 NEED FOR THE SYSTEM

Every organization maintains the details of the customers, projects and Tasks that

are associated with it. The administrator of the organization is sole responsible for

the maintenance of the entire system. The administrator has to maintain the

information about the tasks and their status from toplevel to bottom level. He

should be able to store Time sheet of each and every employee and he has to

calculate the bills.

If the organization of medium scale (around 100 employees) then the

administrator can manually handle the system but, if the size increases then

managing the work will be cumbersome, tedious and error prone.

In order to make it more formal and efficient an intranet-based system is needed

that involves the GUI, so any authorized employee can access the system to view

the Time Track and make the administrator to easily generate the invoices.

An information system is needed to incorporate all factors, which help the

manager to take timely decisions and provide a better and more reliable service.

A user friendly system is one that is easy to manage always and information in all

fields are laid in a proper consistent and effective manner.

Drawbacks in present manual system:

Time consuming

Maintaining the details of Customers, projects, employees, and tasks

manually is a tedious job.

Security

Security in the database cannot be provided, as information is stored in the

logbook or in an excel sheet

4

Page 5: actiTime

ActiTime 2006 Difficult in coordination

In the manual system it is difficult to have coordination between the

employees of different departments.

Difficulty in maintenance

It would be difficult for an organization to maintain the time track of each and

every task for each and every task..

2.2 PROPOSED SYSTEM

The actiTime system is an intranet system, which gives information about the

Time Tracks and their bills. It helps the administrator for the administration and

maintenance of the organization. It fulfills the different requirements of the

employees and administrator of the organization. The specific purpose of this

system is to gather the information of the Time Tracks and generate the invoice

very effectively with user-friendly screens.

In this system about the customers, projects, tasks, users, etc. are maintained. The

administrator has the privilege to add customer, project, task and setting the

previliges to the users.

This system helps the administrator in the maintenance of the organization in an

efficient manner. The various tasks of the administrator are automated at different

levels that makes generation of bills effectively

The various users of the system include the employees and administrator of the

organization. The authorized user is given permission to view the tasks and can

submit the time track. Any user can view the completed tasks, his time track The

user can also search for tasks. He can see the report also

2.3 FEASIBILITY STUDY

2.3.1 Feasibility considerations

The feasibility study is carried out to find whether the proposed system can be developed and implemented without any problem. The following feasibility is considered for the project in

5

Page 6: actiTime

ActiTime 2006order to ensure that the project is viable and it does not have any major obstructions. In this regard technical, behavioral, and economic feasibility are analyzed.

2.3.2 Technical feasibility

Technical feasibility such as whether the necessary technology exist to do what is

suggested and if the equipment have the capacity to hold data required by the use

of new system. Also any technical guarantees of accuracy, reliability, ease of

access, data security could be provided etc.

2.3.3 Behavioral Feasibility

People are inherently resistant to change and computers have known to facilitate

changes. Every department welcomes the idea of computerization. But the

resistance will be from the operators who are involved in the existing system or

manual system.

Behavioral Feasibility is also studied like whether the changes made to the system

facilitates the user and if he is able to adapt to the change made by introducing

computers. An agreement is made between management and staff so that

computerizing system will be installed step by step by giving training to existing

staff members only.

2.4 Economic Feasibility

Economic feasibility like if the existing resources are sufficient introducing. Any

extra h/w required should be affordable in terms of cost. Also can the system be

built within the specified time interval? Establish cost and schedule constraints.

6

Page 7: actiTime

ActiTime 2006Defining functions for h/w, s/w people. Create system definition that forms a

foundation for all subsequent engineering work.

2.5 SOFTWARE REQUIREMENT SPECIFICATION

2.5.1 Introduction

2.5.1.1 Purpose

The actiTime systems provide an efficient way to manage the customers and their

projects in the Organization. It also the maintains schedule information of each

and every task, deadlines and the time track of the each and every user on that

task. Information related to different people and different tasks will be maintained

at a central location with co-ordination. We can schedule the work and at the

same time we can also monitor the the work and can take decisions at any point of

time. we can generate the bills for doing the project for a specific task Completed

tasks will automatically go to completed task list. Main purpose of this product is

to improve the productivity of the organization by monitoring at each and every

interval of time.

2.5.1.2 Document Conventions

The Conventions followed in this Document are:

Proper numbering format is used to demarcate different

sections of this document.7

Page 8: actiTime

ActiTime 2006 Capitalization is used to identify important entities.

Bullets are used to list important points.

Bold font is used for headings

Main headings are underlined

2.5.1.3 Intended Audience and Reading Suggestions

This Document is to be viewed by Developers, Project Leaders, Project

Managers, Customers and Users, so that they can get an elucidated view of what

the Product is all about.

The Reading Suggestions for the Intended audience are:

Developer

Product Perspective

Product Functions

User Classes and Characteristics

Operating Environment

Design and Implementation Constraints

Assumptions and Dependencies

User Interfaces

Hardware Interfaces

Software Interfaces

Communication Interfaces

System Features

Project Leader

Product Perspective

Product Functions

User Classes and Characteristics

Operating Environment

Design and Implementation Constraints

Assumptions and Dependencies

User Interfaces

Hardware Interfaces8

Page 9: actiTime

ActiTime 2006 Software Interfaces

Communication Interfaces

System Features

Project Manager

Product Perspective

Product Functions

System Features

Customers

Product Perspective

Product Functions

User Classes and Characteristics

Operating Environment

Design and Implementation Constraints

User Interfaces

Hardware Interfaces

Software Interfaces

Communication Interfaces

System Features

Performance Requirements

Safety Requirements

Security Requirements

Users

Product Perspective

Product Functions

User Classes and Characteristics

Operating Environment

User Documentation

2.5.1.4 Product Scope9

Page 10: actiTime

ActiTime 2006The Scope of this Product is mainly to meet the requirements of the superiors,

normal users and administrator who are the users of the system. It helps the

employees to submit the time track related to their particular task in a project and

which is assigned to him and see his billing. With these functionalities

administrator or the user an easily find efficient people depending on their bills.

This automated process just makes the task easy.

Standardized Technology is used to develop this Project to meet the objectives of

the Corporate Environment. The Project Specification is suitable and is easily

adaptable to the Business Strategies followed by the Clients (Employers) of the

System.

The Benefits of this Product are:

Provides updated information about the tasks with different status

from high level to bottom level.

Helps employees to complete the tasks with co-ordination and submit

the time track

Provides easy interaction between the employees and the

administrators to know that the given schedule is going smooth or not..

The Objectives of this Product are:

The Objective of this product is to take the decision at any point by

just seeing the statistics

To provide updated information about time tracks and invoces.

The Goals of this Product are:

To automate the managing process of an customers and their projects

in an organization and dynamically provide the status of the tasks, projects

currently present in the environment and also the time track of the employees in

the organization. This system also provides with the knowledge to estimate the

cost estimations of the billings on per project or per customer basis..

10

Page 11: actiTime

ActiTime 20062.5.1.5 References

This SRS is available to the Product Managers, Project Leaders, and

users through User manuals, which are provided in addition to this Software.

2.6 Overall Description

2.6.1 Product Perspective

This Product is an automated form of the Time Tracking and invoice generation

system, which replaces the manual task of the employees who assign the task to

another employee and regularly monitor the time track of each and every

employee. administrator who monitors the system with some privileged tasks

assigned to him. This is the product about the Time Tracking system, which

mainly provides tracking the time with over time calculations alsoand generate

the bills according to the users of the system on different projects and from

different customers

The major components of the overall system are:

1. Administration Module

2. Task Module

3. Time Track Module

4. Reports

The administrator mainly deals with the process of adding, deleting and changing

the user information into the system. Along user info he is responsible for adding

new customers, projects, Working and non-working days in the organization. He

11

Page 12: actiTime

ActiTime 2006can also create different types of billings. He can set the Calender preferences

also.

Task Module mainly deals adding tasks to a project and setting the deadlines. List

the tasks, search for a task and add a task to the list and finally close the task.

Convert the tasks from open state the closed state. set the no of tasks to be

displayed per page.

Time Track Module deals with submitting the time track depending on the

deadlines. The user can submit the overtime track also. User can see his Time

track at any point of time between some dates also.

Reports module deals with generating different type of reports like Billing

summary report, staff out report, overtime report and prepare invoice data report

Reports can be generated in different forms : HTML and CSV

Giving the permissions to the user for providing them specialized

services.

Generating the reports very easily based on different criteria.

Providing user the right to allow him to modify the profile.

2.6.2 User Classes and Characteristics

Developers

This is the major User class from whom the product is designed exactly.

The system designed is user friendly and is developed using GUI technology,

which provides better navigation facility to these users. And allows them to track

their tasks easily and much better than the manual system.

Users working as superiors but seeking for a better system to solve

tracking problems

Organizations willing to provide a best Time and Invoice Management

System. This is the second major user class, which already posses the basic

infrastructure, i.e. is the projects which are the major inputs to the system.

Administrator

The administrator is responsible for the maintenance of the whole site. He

is the person who maintains all the Login information of the users and allows

12

Page 13: actiTime

ActiTime 2006modifications or deletion users, projects, status types, customers and the time

tracks in the system.

2.6.3 Operating Environment

The Required Operating Environment support for this product is:

Operating System: Windows 2000 professional and above.

Database Support: Mysql 4.1and above.

Language: J2EE technology (Servlets, JSP and Struts)

GUI Design: Microsoft FrontPage, HTML, and JavaScript.

Browser Support: Internet Explorer5.0, NetScape4.0 or FireFox

Hardware: Processor with 1 GHz speed and with 256 MB Ram.

2.6.4 Design and Implementation Constraints

All Access rights:

-------Administrator

Add Task to his List, Complete Task and Submit Time Track:

--------Administrator

2.6.5 Assumptions and Dependencies

actiTime System mainly depends upon the following

Issue information provided by the user.

Administrator functionalities.

Bills stored in the database

2.7 EXTERNAL INTERFACE REQUIREMENTS

2.7.1 User Interfaces:

The basic User Interfaces are:

Login Form for the Employee/Administrator.

Administration Form

List User form 13

Page 14: actiTime

ActiTime 2006 Add/Modify User form

List Customers form

Add/Modify Customer or Form

List Tasks form displaying all the tasks shoeing their status.

List projects form

Add and Modify Project form.

List Projects form

List Completed Tasks form

Submit Time Track Form

Time Track with over time form.

Holidays and Non-Holidays form

Calender preferences form

Reports form

2.7.2 Hardware Interfaces

The Hardware Interfaces for this system are:

Processor with at least 1GHz speed.

More than 256 MB Ram.

Type-3 driver support.

2.7.3 Software Interfaces

The various Software Interfaces for this system are:

JDK1.4.1_01

JNDI

JSP

Struts

Tomcat Server

Internet Explorer 6.0 or Netscape 4.0 browser with JVM support

MySQL4.1

Windows 2000 proffessional

14

Page 15: actiTime

ActiTime 20062.7.4 Communication Interfaces

The various communication interfaces for this system are:

HTTP Protocol for communication

RMI-IIOP

MVC architecture

JNDI: Java Naming and Directory Service to provide database

connectivity.

I.E 6.0 or Netscape 5.0 or FireFOxWeb Browsers.

2.8 SYSTEM FEATURES

2.8.1 Administration functionalities

2.8.1.1 Description:

The Administration functionalities include adding Customers, projects, users and

their time tracks. This process aims in system monitoring solely by one person

from top level so that nothing is moved unauthorized. Everything goes from the

administration hand.

2.8.1.2 Stimulus/Response Sequences

Providing the Customer Information.

Providing Project Information.

Providing User Information.

Providing TimeTrack information.

Providing Billing Details Details.

2.8.1.3 Functional Requirements

REQ-1: Customers Personal and Contact Details

REQ-2: Project Details.

REQ-3: Time Track details along with billing reports

15

Page 16: actiTime

ActiTime 2006

2.8.2 Display task Information details

2.8.2.1 Description:

The Issue information displays the details about the task assigned in the project.

This feature allows the user to add that task to his task list and he can submit the

time track and close that close task then that task automatically goes completed

tasks list. The users can sumbit the over time track also if he has the permission

only. he can see his time track any point of time and an administrator can generate

the bills by mixing all the users time tracks who has participated in that project.

2.8.2.2 Stimulus/Response Sequences

Displaying List of Tasks

Allowing to add the Task to the list

Allows to submit the time track.

Close the task.

2.8.2.3 Functional Requirements

REQ-1: Authorized (Registered) Employee.

REQ-2: Task details with Overtime Track

2.8.3 Provide List of Tasks

2.8.3.1 Description

The system provides the user with an option called list the tasks and

their details. This user can open the see the description of the task also. he can set

the number for displaying the task list per page. We can set that dynamically at

any point of time. We can generate the task list based on project or based on

customer or both or all the above

2.8.3.2 Stimulus/Response Sequences16

Page 17: actiTime

ActiTime 2006

Provides page wise listing of Tasks.

Allows accessing Tasks for a project or for a customer or both..

2.8.3.3 Functional Requirements

REQ-1: Task Details to a particular Task to be displayed.

REQ-2: Give project name and customer name to access a Task.

3. SYSTEM DEVELOPMENT ENVIRONMENT

Java coding standardsWhy Coding Standards are Important

Coding standards for Java are important because they lead to greater consistency

within your code and the code of your teammates. Greater consistency leads to

code that is easier to understand, which in turn means it is easier to develop and to

maintain. This reduces the overall cost of the applications that you create. You

have to remember that your Java code will exist for a long time, long after you

have moved on to other projects. An important goal during development is to

ensure that you can transition your work to another developer, or to another team

of developers, so that they can continue to maintain and enhance your work

without having to invest an unreasonable effort to understand your code. Code

that is difficult to understand runs the risk of being scrapped and rewritten – I

wouldn’t be proud of the fact that my code needed to be rewritten, would you? If

everyone is doing their own thing then it makes it very difficult to share code

between developers, raising the cost of development and maintenance.

Inexperienced developers, and cowboys who do not know any better, will often 17

Page 18: actiTime

ActiTime 2006fight having to follow standards. They claim they can code faster if they do it their

own way. Pure hogwash. They might be able to get code out the door faster, but I

doubt it. Cowboy programmers get hung up during testing when several difficult-

to-find bugs crop up, and when their code needs to be enhanced it often leads to a

major rewrite by them because they’re the only ones who understand their code.

Is this the way that you want to operate? I certainly do not.

The Prime Directive

No standard is perfect and no standard is applicable to all situations: sometimes

you find yourself in a situation where one or more standards do not apply. This

leads me to introduce what I consider to be the prime directive of standards:

When you go against a standard, document it. All standards, except for

this one, can be broken. If you do so, you must document why you broke the

standard, the potential implications of breaking the standard, and any conditions

that may/must occur before the standard can be applied to this situation. The

bottom line is that you need to understand each standard, understand when to

apply them, and just as importantly when not to apply them.

Important Instructions to maintain standards

Use full English descriptors that accurately describe the variable/field/class/…

For example, use names like first Name, grandTotal, or CorporateCustomer.

Although names like x1, y1, or fn are easy to type because they’re short, they do

not provide any indication of what they represent and result in code that is

difficult to understand, maintain, and enhance (Nagler, 1995; Ambler, 1998a).

Use terminology applicable to the domain. If your users refer to their clients as

customers, then use the term Customer for the class, not Client. Many developers

will make the mistake of creating generic terms for concepts when perfectly good

terms already exist in the industry/domain.

Use mixed case to make names readable. You should use lower case letters in

general, but capitalize the first letter of class names and interface names, as well

as the first letter of any non-initial word (Kanerva, 1997).

18

Page 19: actiTime

ActiTime 2006Use abbreviations sparingly, but if you do so then use them intelligently. This

means you should maintain a list of standard short forms (abbreviations), you

should choose them wisely, and you should use them consistently. For example, if

you want to use a short form for the word “number,” then choose one of nbr, no,

or num, document which one you chose (it doesn’t really matter which one), and

use only that one.

Avoid long names (< 15 characters is a good idea). Although the class name

PhysicalOrVirtualProductOrService might seem to be a good class name at the

time this name is simply too long and you should consider renaming it to

something shorter, perhaps something like Offering (NPS, 1996).

Avoid names that are similar or differ only in case. For example, the variable

names persistentObject and persistentObjects should not be used together, nor

should anSqlDatabase and anSQLDatabase (NPS, 1996).

Avoid leading or trailing underscores. Names with leading or trailing underscores

are usually reserved for system purposes, and may not be used for any user-

created names except for pre-processor defines (NPS, 1996). More importantly,

underscores are annoying and difficult to type so I try to avoid their use whenever

possible.

GOOD DOCUMENTATION

We will also be discussing documentation conventions, so let’s discuss some of

the basics first:

Comments should add to the clarity of your code. The reason why you document

your code is to make it more understandable to you, your coworkers, and to any

other developer who comes after you (Nagler, 1995).

If your program isn’t worth documenting, it probably isn’t worth running (Nagler,

1995). What can I say, Nagler hit the nail on the head with this one.

19

Page 20: actiTime

ActiTime 2006Avoid decoration, i.e. do not use banner-like comments. In the 1960s and 1970s

COBOL programmers got into the habit of drawing boxes, typically with

asterisks, around their internal comments (NPS, 1996). Sure, it gave them an

outlet for their artistic urges, but frankly it was a major waste of time that added

little value to the end product. You want to write clean code, not pretty code.

Furthermore, because many of the fonts used to display and print your code are

proportional, and many aren’t, you can’t line up your boxes properly anyway.

Keep comments simple. Some of the best comments I have ever seen are simple,

point-form notes. You do not have to write a book, you just have to provide

enough information so that others can understand your code.

Write the documentation before you write the code. The best way to document

code is to write the comments before you write the code. This gives you an

opportunity to think about how the code will work before you write it and will

ensure that the documentation gets written. Alternatively, you should at least

document your code as you write it. Because documentation makes your code

easier to understand you are able to take advantage of this fact while you are

developing it. The way I look at it, if you are going to invest the time writing

documentation you should at least get something out of it (Ambler, 1998a).

Document why something is being done, not just what. Fundamentally, I can

always look at a piece of code and figure out what it does. For example, I can

look at the code in Example 1 below and figure out that a 5% discount is being

given on orders of $1,000 dollars or more. Why is this being done? Is there a

business rule that says that large orders get a discount? Is there a limited-time

special on large orders or is it a permanent program? Was the original

programmer just being generous? I do not know unless it is documented

somewhere, either in the source code itself or in an external document (Ambler,

1998a).

An Overview of J2EE

The following topics describe the J2EE Platform requirements for each kind of

J2EE platform element.

J2EE Application Components

20

Page 21: actiTime

ActiTime 2006

The J2EE runtime environment defines four application component types that a

J2EE product must support:

Application clients are Java programming language programs that are typically

GUI programs that execute on a desktop computer. Application clients offer a

user experience similar to that of native applications, and have access to all of the

facilities of the J2EE middle tier.

Applets are GUI components that typically execute in a web browser, but can

execute in a variety of other applications or devices that support the applet-

programming model. Applets can be used to provide a powerful user interface for

J2EE applications. Servlets, JSP pages, filters, and web event listeners typically

execute in a web container and may respond to HTTP requests from web clients.

Servlets, JSP pages, and filters may be used to generate HTML pages that are an

application’s user interface. They may also be used to generate XML or other

format data that is consumed by other application components. A special kind of

servlet provides support for web services using the SOAP/HTTP protocol.

Servlets, pages created with the Java Server Pages™ technology, web filters, and

web event listeners are referred to collectively in this specification as “web

components.” Web applications are composed of web components and other data

such as HTML pages. Web components execute in a web container. A web server

includes a web container and other protocol support, security support, and so on,

as required by J2EE specifications. Enterprise Java Beans™ (EJB) components

execute in a managed environment that supports transactions. Enterprise beans

typically contain the business logic for a J2EE application. Enterprise beans may

directly provide web services using the SOAP/HTTP protocol.

J2EE Server Support for Application Components

The J2EE servers provide deployment, management, and execution support for

conforming application components. Application components can be divided into

three categories according to their dependence on a J2EE server:

Components that are deployed, managed, and executed on a J2EE server. These

components include web components and Enterprise JavaBeans components. See

the separate specifications for these components.21

Page 22: actiTime

ActiTime 2006

Components that are deployed and managed on a J2EE server, but are loaded to

and executed on a client machine. These components include web resources such

as HTML pages and applets embedded in HTML pages.

Components deployment and management is not completely defined by this

specification. Application Clients fall into this category. Future versions of this

specification may more fully define deployment and management of Application

Clients.

J2EE Containers

Containers provide the runtime support for J2EE application components.

Containers provide a federated view of the underlying J2EE APIs to the

application components. J2EE application components never interact directly with

other J2EE application components.

J2EE Servers

Underlying a J2EE container is the server of which it is a part. A J2EE Product

Provider typically implements the J2EE server-side functionality using an existing

transaction processing infrastructure in combination with Java 2 Platform,

Standard Edition (J2SE) technology. The J2EE client functionality is typically

built on J2SE technology.

Resource Adapters

A resource adapter is a system-level software component that implements

network connectivity to an external resource manager. A resource adapter can

extend the functionality of the J2EE platform either by implementing one of the

J2EE standard service APIs (such as a JDBC™ driver), or by defining and

implementing a resource adapter for a connector to an external application

system.

Java™ Transaction API (JTA)

The Java Transaction API consists of two parts:

22

Page 23: actiTime

ActiTime 2006An application-level demarcation interface is used by the container and

application components to demarcate transaction boundaries. An interface

between the transaction manager and a resource manager used at the J2EE SPI

level (in a future release).

RMI-IIOP

The RMI-IIOP subsystem is composed of APIs that allow for the use of RMI-

style programming that is independent of the underlying protocol, as well as an

implementation of those APIs that supports both the J2SE native RMI protocol

(JRMP) and the CORBA IIOP protocol. J2EE applications can use RMI-IIOP,

with IIOP protocol support, to access CORBA services that are compatible with

the RMI programming restrictions (see the RMI-IIOP spec for details).

JDBC™ API

The JDBC API is the API for connectivity with relational database systems. The

JDBC API has two parts: an application-level interface used by the application

components to access a database, and a service provider interface to attach a

JDBC driver to the J2EE platform. Support for the service provider interface is

not required in J2EE products.

Java™ Message Service (JMS)

The Java Message Service is a standard API for messaging that supports reliable

point-to-point messaging as well as the publish-subscribe model. This

specification requires a JMS provider that implements both point-to-point

messaging as well as publish-subscribe messaging.

Java Naming and Directory Interface™ (JNDI)

The JNDI API is the standard API for naming and directory access. The JNDI

API has two parts: an application-level interface used by the application

components to access naming and directory services and a service provider

interface to attach a provider of a naming and directory service.

Java Connector Architecture

The Connector architecture is a J2EE SPI that allows resource adapters that

support access to Enterprise Information Systems to be plugged in to any J2EE 23

Page 24: actiTime

ActiTime 2006product. The Connector architecture defines a standard set of system-level

contracts between a J2EE server and a resource adapter.

Security Services

The Java™ Authentication and Authorization Service (JAAS) enables services to

authenticate and enforce access controls upon users. It implements a Java

technology version of the standard Pluggable Authentication Module (PAM)

framework, and extends the access control architecture of the Java 2 Platform in a

compatible fashion to support user-based authorization. The Java™ Authorization

Service Provider Contract for Containers (JACC) defines a contract between a

J2EE application server and an authorization service provider, allowing custom

authorization service providers to be plugged into any J2EE product.

Web Services

J2EE provides full support for both clients of web services as well as web service

endpoints. Several Java technologies work together to provide support for web

services. The Java API for XML-based RPC (JAX-RPC) provides support for

web service calls using the SOAP/HTTP protocol. JAX-RPC defines the mapping

between Java classes and XML as used in SOAP RPC calls. The SOAP with

Attachments API for Java (SAAJ) provides support for manipulating low-level

SOAP messages. The Web Services for J2EE specification fully defines the

deployment of web service clients and web service endpoints in J2EE, as well as

the implementation of web service endpoints using enterprise beans. The Java

API for XML Registries (JAXR) provides client access to XML registry servers.

Deployment

The Java 2 Platform, Enterprise Edition Deployment Specification defines a

contract between deployment tools and J2EE products. The J2EE products

provide plug-in components that run in the deployment tool and allow the

deployment tool to deploy applications into the J2EE product. The deployment

tool provides services used by these plug-in components.

J2EE Architecture

24

Page 25: actiTime

ActiTime 2006Web Applications and Exploded Directory Format (EDF)

Overview of Web Applications

A Web application contains an application’s resources, such as servlets, Java

Server Pages (JSPs), JSP tag libraries, static resources such as HTML pages and

image files. A Web Application can also define links to outside resources such as

Enterprise Java Beans (EJBs). Web applications deployed on Web Logic Server

use a standard J2EE deployment descriptor file and Web Logic-specific

deployment descriptor file to define their resources and operating attributes.

JSP and HTTP servlets can access all services and APIs available in Web Logic

Server. These services include EJB, database connections via Java Database

Connectivity (JDBC), Java Messaging Service (JMS), XML, and more. A Web

archive (WAR file) contains the files that make up a Web application (WAR file).

A WAR file is deployed as a unit on one or more Web Logic Server instances. A

Web archive on Web Logic Server always includes the following files: One

servlet or Java Server Page (JSP), along with any helper classes.

A web.xml deployment descriptor, which is a J2EE standard XML document that

describes the contents of a WAR file. A weblogic.xml deployment descriptor,

which is an XML document containing Web Logic Server-specific elements for

Web applications. A Web archive may also include HTML or XML pages and

supporting files such as image and multimedia files. The WAR file can be

deployed alone or packaged in an enterprise application archive (EAR file) with

other application components. If deployed alone, the archive must end with a .war

extension. If deployed in an EAR file, the archive must end with an .ear

extension. BEA recommends that you package and deploy your stand-alone Web

applications as part of an enterprise application. This is a BEA best practice,

which allows for easier application migration, additions, and changes. Also,

packaging your applications as part of an enterprise application allows you to take

advantage of the split development directory structure, which provides a number

of benefits over the traditional single directory structure.

Note: If you are deploying a directory in exploded format (not archived), do not

name the directory .ear, .jar, and so on.

25

Page 26: actiTime

ActiTime 2006

Web Application Directory Structure

Web applications use a standard directory structure defined in the J2EE

specification. You can deploy a Web application as a collection of files that use

this directory structure, known as exploded directory format, or as an archived file

called a WAR file. BEA recommends that you package and deploy your WAR

file as part of an enterprise application. This is a BEA best practice, which allows

for easier application migration, additions, and changes.

Also, packaging your Web application as part of an enterprise application allows

you to take advantage of the split development directory structure, which provides

a number of benefits over the traditional single directory structure. Web

application components are assembled in a directory in order to stage the WAR

file for the jar command.

HTML pages, JSP pages, and the non-Java class files they reference are accessed

beginning in the top level of the staging directory. The WEB-INF directory

contains the deployment descriptors for the Web application (web.xml) and

weblogic.xml) and two subdirectories for storing compiled Java classes and

library JAR files. These subdirectories are respectively named classes and lib. JSP

taglibs are stored in the Web Applications Basics WEB-INF directory at the top

level of the staging directory.

The Java classes include servlets, helper classes and, if desired, precompiled JSP.

The entire directory, once staged, is bundled into a WAR file using the jar

command. The WAR file can be deployed alone or as part of an enterprise

application (recommended) with other application components, including other

Web applications, EJB components, and Web Logic Server components. JSP

pages and HTTP servlets can access all services and APIs available in Web Logic

Server. These services include EJBs, database connections through Java Database

Connectivity (JDBC), Java Message Service (JMS), XML, and more.

Main Steps to Create a Web Application

26

Page 27: actiTime

ActiTime 2006The following is an example of a Web application directory structure, in which

myWebApp/ is the staging directory:

Web Application Directory Structure

Graphical User Interface

Graphical User Interfaces offer a standard look and feel to application thus

reducing development and learning time. A GUI is an application environment

that can work with graphical objects. For example, Microsoft Windows has the

following components:

Menus (including placement and names of options, and style

such as pull down and popup).

Icons (for identifying applications and resources).

Tiled windows (for views of multiple programs or data or for

multiple views of single program or data block).

Dialog boxes for selecting files, options and setting on when an

option is selected, the one previously selected is turned off.

Checklists from which the user can make multiple selections,

as specifying print or file attributes.

Support for a printing device, typically a mouse (especially to

select and drag screen elements).

Scroll bars along the edges of windows to show the relative

position of the contents (such as the end or beginning of the text) or to move to a

different position (such as another part of a spread sheet)

A GUI enforces consistency by restricting developers –they must support features

for the program to run under the GUI’s creators (such as the arrangement of menu

options) often become defects standards for applications.

27

Page 28: actiTime

ActiTime 2006 We have described how consistency simplifies the learning of anew application.

One benefit of a GUI is that the user can learn a second application faster because

he or she is familiar with the environment. Note that the benefit comes with

succeeding applications.

GUI CONCEPTS

Graphical User Interfaces are designed to present information to Users in

graphical form, so that they can work with friendly and easy environment. In

general GUI’s present information in rectangular areas on screen called windows.

GUI displays multiple applications in different windows at the same time. This

way user can see what is happening in one application while working with

another. Users are allowed to perform several manipulations on windows, such as

changing their size and position.

Windows can contain objects that can be selected by clicking a mouse pointer

and small object that can be minimized to become an icon, and users can restore

an icon to its normal size. Windows can also contain other graphical entities (such

as scroll bars, sliders, and buttons) that allow users to control the contents of the

window, and provide additional input to the application.

Instead of requiring a user to know application commands, a GUI uses an

intuitive, easy-to-use shell with a pointing device as well as application windows,

menus, dialog boxes, buttons and so on.

An Overview of JSP

28

Page 29: actiTime

ActiTime 2006Java Server Pages™ technology is the Java™ technology in the J2EE platform for

building applications containing dynamic Web content such as HTML, DHTML,

XHTML and XML. The Java Server Pages technology enables the authoring of

Web pages that create dynamic content easily but with maximum power and

flexibility.

The Java Server Pages technology provides a textual description for the creation

of a response from a request. The technology builds on the following concepts:

Template Data

Substantial portions of dynamic content are actually fixed. The JSP technology

allow for the natural manipulation of this data.

Addition of Dynamic Data

The JSP technology allows the addition of dynamic data to the template data in a

way that is simple yet powerful.

Encapsulation of Functionality

The JSP technology provides two related mechanisms for the encapsulation of

functionality: the standard Java Beans component architecture and the tag library

mechanism.

Good Tool Support

The JSP technology has features that enable the creation of good authoring tools.

The result is a flexible and powerful server-side technology.

29

Page 30: actiTime

ActiTime 2006Benefits of the Java Server Pages Technology

The Java Server Pages technology offers a number of benefits:

Write Once, Run Anywhere™ properties

The Java Server Pages technology is platform independent, both in its dynamic

Web pages, Web servers, and its underlying server components. You can author

JSP pages on any platform, run them on any Web server or Web enabled

application server, and access them from any Web browser.

High quality tool support

The Write Once, Run Anywhere properties of JSP allows the user to choose best-

of-breed tools. Additionally, an explicit goal of the Java Server Pages design is to

enable the creation of high quality portable tools.

Separation of Roles

JSP supports the separation of roles: developers write components that interact

with server-side objects.

Reuse of components and tag libraries

The Java Server Pages technology emphasizes the use of reusable components

such as Java Beans™ components, Enterprise Java Beans™ components and tag

libraries.

Separation of dynamic and static content

The Java Server Pages technology enables the separation of static content from

dynamic content that is inserted into the static template.

Support for scripting and actions

The Java Server Pages technology supports scripting elements as well as actions.

Actions permit the encapsulation of useful functionality in a convenient form that

can also be manipulated by tools; scripts provide a mechanism to glue together

this functionality in a per-page manner.30

Page 31: actiTime

ActiTime 2006

Web access layer for N-tier enterprise application architecture(s)

The Java Server Pages technology is an integral part of the Java 2 Platform

Enterprise Edition (J2EE), which brings Java technology to enterprise computing.

An Overview of Servlets

What is a Servlet

A servlet is a web component, managed by a container that generates dynamic

content. Servlets are small, platform independent Java classes compiled to an

architecture neutral byte code that can be loaded dynamically into and run by a

web server. Servlets interact with web clients via a request response paradigm

implemented by the servlet container. This request-response model is based on the

behavior of the Hypertext Transfer Protocol (HTTP).

What is a Servlet Container

The servlet container, in conjunction with a web server or application server,

provides the network services over which requests and responses are set, decodes

MIME based requests, and formats MIME based responses. A servlet container

also contains and manages servlets through their lifecycle. A servlet container can

either be built into a host web server or installed as an add-on component to a

Web Server via that server’s native extension API.

Servlet Containers can also be built into or possibly installed into web-enabled

Application Servers. All servlet containers must support HTTP as a protocol for

requests and responses, but may also support other request / response based

protocols such as HTTPS (HTTP over SSL). The minimum required version of

the HTTP specification that a container must implement is HTTP/1.0. It is

strongly suggested that containers implement the HTTP/1.1 specification as well.

A Servlet Container may place security restrictions on the environment that a

servlet can executed In a Java 2 Platform Standard Edition 1.2 (J2SE) or Java 2

Platform Enterprise Edition 1.3 (J2EE) environment, these restrictions should be

31

Page 32: actiTime

ActiTime 2006placed using the permission architecture defined by Java 2 Platform. For example,

high-end application servers may limit certain action, such as the creation of a

Thread object, to insure that other components of the container are not negatively

impacted.

An Overview of JDBC

JDBC drivers implement the interfaces and classes of the JDBC API. The

following sections describe the JDBC driver options that you can use with Web

Logic Server.

Types of JDBC Drivers

Web Logic Server uses the following types of JDBC drivers that work in

conjunction with each other to provide database access: Standard JDBC drivers

that provide database access directly between a Web Logic Server connection

pool and the database. Web Logic Server uses a DBMS vendor-specific JDBC

driver, such as the Web Logic drivers for Oracle and Microsoft SQL Server, to

connect to a back-end database.

Wrapper drivers that provide vendor-neutral database access. A Java client

application can use a wrapper driver to access any database configured in Web

Logic server (via a connection pool). BEA offers three wrapper drivers—RMI,

Pool, and JTS. The Web Logic Server system uses these drivers behind the scenes

when you use a JNDI look-up to get a connection from a connection pool through

a data source. A client application can also use these drivers directly to get a

connection from a connection pool (You can use RMI from external clients and

the pool and JTS from server-side clients only).

However, BEA recommends that you use a data source to get a connection from a

connection pool, rather than using these drivers directly. The middle tier

architecture of Web Logic Server, including data sources and connection pools,

allows you to manage database resources centrally in Web Logic Server. The

vendor-neutral wrapper drivers make it easier to adapt the purchased components

to your DBMS environment and to write more portable code.

32

Page 33: actiTime

ActiTime 2006

Using JDBC Drivers with Web Logic Server

Web Logic Server JDBC Drivers

WebLogic jDriver for Oracle

BEA’s WebLogic jDriver for Oracle is included with the WebLogic Server

distribution. This driver requires an Oracle client installation. The WebLogic

jDriver for Oracle XA driver extends the WebLogic jDriver for Oracle for

distributed transactions.

Type 2 (requires native libraries)

• WebLogic jDriver for Oracle

• WebLogic jDriver for OracleXA

• Third-party drivers, such as the Oracle OCI driver and the IBM DB2 driver

Between WebLogic Server and DBMS in local and distributed transactions.

Type 3

• WebLogic RMI Driver

Between an external client and WebLogic Server (connection pool).

Type 4 (pure Java)

• WebLogic jdrivers for Microsoft SQL Server

• Third-party drivers, including: Oracle Thin and Oracle Thin XA drivers

Between WebLogic Server and DBMS in local and distributed transactions.

33

Page 34: actiTime

ActiTime 2006

An Overview of WebLogic Server 8.1

WebLogic Server provides essential features for developing and deploying

mission-critical e-commerce applications across distributed, heterogeneous

computing environments. These features include the following:

Standards leadership—Comprehensive enterprise Java support to ease

the implementation and deployment of application components. WebLogic

Server is the first independently developed Java application server to achieve

J2EE certification. In addition, BEA actively participates in the development of

J2EE and Web Services standards that drive innovation and advancement in

Java and XML technology.

Rich client options—WebLogic Server supports Web browsers and

other clients that use HTTP; Java clients that use RMI (Remote Method

Invocation) or IIOP (Internet Inter-ORB Protocol); SOAP clients on any

SOAP-enabled platform; and mobile devices that use (WAP) Wireless Access

Protocol. Connectors from BEA and other companies enable virtually any client

or legacy application to work with a WebLogic Server application.

Flexible Web services—WebLogic Server provides a solid platform for

deploying Web services as components of a heterogeneous distributed

application. Web services use a cross-platform, cross-language data model

(XML) to provide interoperability among application components on diverse

hardware and software platforms. Web services support user-defined data types

and one-way asynchronous operations. A Web service can intercept SOAP

messages for further processing. New Ant tasks automatically generate

important components and package the service into a deployable EAR file.

WebLogic Server uses Web Services Description Language (WSDL) 1.1, an

XML-based specification, to describe Web services. WebLogic Web services

support Simple Object Access Protocol (SOAP) 1.1 and 1.2 as the message

format and HTTP as a connection protocol.

Note: WebLogic Web services accept both SOAP 1.1 and 1.2 incoming

requests, but produce only SOAP 1.1 outgoing responses.

Enterprise e-business scalability—Efficient use and high availability of

critical resources are achieved through Enterprise Java Bean business

34

Page 35: actiTime

ActiTime 2006components and mechanisms such as WebLogic Server clustering for dynamic

Web pages, backend resource pooling, and connection sharing.

Robust administration—WebLogic Server offers a Web-based

Administration Console for configuring and monitoring WebLogic Server

services. A command-line interface for configuration makes it convenient to

administer WebLogic Servers with scripts.

E-commerce-ready security—WebLogic Server provides Secure

Sockets Layer (SSL) support for encrypting data transmitted across WebLogic

Server, clients, and other servers. User authentication and authorization for all

WebLogic Server services are provided through roles and security providers.

External security stores, such as Lightweight Directory Access Protocol

(LDAP) servers, can still be adapted to WebLogic realms, enabling single sign-

on for the enterprise. The Security Service Provider Interface makes it possible

to extend WebLogic Security services and to implement WebLogic Security

features in applications.

Maximum development and deployment flexibility— WebLogic Server

provides tight integration with and support for leading databases, development

tools, and other environments.

Bi-directional functional interoperability between Java/J2EE objects and

Microsoft ActiveX components—BEA WebLogic jCOM provides a run-time

component that implements both Component Object Model (COM)/Distributed

Component Object Model (DCOM) and Remote Method Invocation (RMI)

distributed components infrastructures. This makes the objects look like native

objects for each environment.

Java Message Service (JMS)—An enterprise messaging system, also

referred to as message-oriented middleware (MOM), enables applications to

communicate with one another through the exchange of messages. A message is

a request, report, and/or event that contains information needed to coordinate

communication between different applications. A message provides a level of

abstraction, allowing you to separate the details about the destination system

from the application code.

The Java Message Service (JMS) is a standard API for accessing enterprise-

messaging systems. Specifically, JMS enables Java applications sharing a

35

Page 36: actiTime

ActiTime 2006messaging system to exchange messages, and it simplifies application

development by providing a standard interface for creating, sending, and

receiving messages.

Overview of Struts:In this chapter, you will cover:

• The struts configuration• Writing Actions• Working with Struts Custom tags• Setting up datasource• Handling exceptions• Displaying objects in a JSPJakarta Struts Live2In this chapter you will perform the following steps:1. Download Struts2. Setup a J2EE web application project that uses Struts3. Write your first Action4. Write your first “forward”5. Configure the Action and forward in the Struts configuration file6. Run and Test your first Struts application.7. Debugging Struts-Config.xml with the Struts Console8. Add Logging support with Log4J and commons logging.9. Write your first ActionForm10. Write your first input view (JSP page)11. Update the Action to handle the form, and cancel button12. Setup the database pooling with Struts13. Declaratively Handle Exception in the Struts Config file14. Display an Object with Struts Custom TagsJakarta Struts LiveDownload Struts 3

Download StrutsThe first step in getting started with Struts is to download the Struts framework. The Struts home page is locatedat http://jakarta.apache.org/struts/index.html. You can find online documentation at the Struts home page. However,to download Struts you need to go to the Jakarta Download page at http://jakarta.apache.org/site/binindex.cgi. Since all of the Jakarta download links are on the same page, search for “Struts” on this page. Look forthe link that looks like this:Struts KEYS• 1.1 zip PGP MD5

36

Page 37: actiTime

ActiTime 2006• 1.1 tar.gz PGP MD5Download either compressed file.One of the best forms of documentation on Struts is the source. Download the source from http://jakarta.apache.org/site/sourceindex.cgi. Once you have both the source and binaries downloaded, extract them.(WinZip works well for Windows users.) This tutorial will assume that you have extracted the files to c:\tools\jakarta-struts-1.1-src and c:\tools\ jakarta-struts-1.1. If you are using another drive, directory, or *n?x (UNIX orLinux), adjust accordingly.Jakarta Struts LiveSet up a J2EE Web Application Project That Uses Struts 4

Set up a J2EE Web Application Project That Uses StrutsStruts ships with a started web application archive file (WAR file) called struts-blank.war. The struts-blank.warfile has all of the configuration files, tag library descriptor files (tld files) and JAR files that you need to startusing Struts. The struts-blank.war file includes support for Tiles and the Validator framework. You can find thestruts-blank.war file under C:\tools\jakarta-struts-1.1\webapps.1. A war file is the same format as a ZIP file. Extract the struts-blank.war file to a directory calledc:\strutsTutorial (adjust if *n?x). When you are done, you should have a directory structure as follows:C:.|---META-INF|---pages|---WEB-INF|---classes| |--resources|---lib|---src|---java|---resourcesThe blank war file ships with an Ant build script under WEB-INF/src. The structure of the extracteddirectory mimics the structure of a deployed web application.2. In order for the build.xml file to work, you need to modify it to point to the jar file that contains theServlet API and the jar file that points to the JDBC API from your application server.For example, if you had Tomcat 5 installed under c:\tomcat5, then you would need to modify the

37

Page 38: actiTime

ActiTime 2006servlet.jar property as follows:<property name="servlet.jar"value="C:/tomcat5/common/lib/servlet-api.jar"/>Tip: Tomcat is a Servlet container that supports JSP. If you are new to web development in Java, there areseveral very good books on Java web development. You will need to know about JSP, Servlets andweb applications to get the most out of this chapter and this book. If you are new to Java web development,try this tutorial: http://java.sun.com/j2ee/1.4/docs/tutorial/doc/WebApp.html#wp76431.3. If you are using an IDE (Eclipse, NetBeans, JBuilder, WSAD, etc.), set up a new IDE project pointingto C:\strutsTutorial\WEB-INF\src\java as the source directory, add your application server’s servlet.jar file (servlet-api.jar for tomcat) and all the jar files from C:\strutsTutorial\WEB-INF\lib.Jakarta Struts LiveWrite Your First Action 5

Write Your First ActionActions respond to requests. When you write an Action, you subclass org.apache.struts.action.Actionand override the execute method.The execute method returns an ActionForward. You can think of an ActionForward as an output view.The execute method takes four arguments: an ActionMapping, ActionForm, HttpServletRequest and an HttpServletResponse(respectively).The ActionMapping is the object manifestation of the XML element used to configure an Action in the Strutsconfiguration file. The ActionMapping contains a group of ActionForwards associated with the current action.For now, ignore the ActionForm; we will cover it later. (It is assumed that you are familiar with HttpServletRequestand HttpServletResponse already.)Go to strutsTutorial\WEB-INF\src\java and add the package directory strutsTutorial. In the strutsTutorial directory,add the class UserRegistration as follows:package strutsTutorial;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import org.apache.struts.action.Action;import org.apache.struts.action.ActionForm;import org.apache.struts.action.ActionForward;import org.apache.struts.action.ActionMapping;public class UserRegistrationAction extends Action {public ActionForward execute(ActionMapping mapping,

38

Page 39: actiTime

ActiTime 2006ActionForm form,HttpServletRequest request,HttpServletResponse response)throws Exception {return mapping.findForward("success");}}Notice that this Action forwards to the output view called success. That output view, ActionForward, will be aplain old JSP. Let’s add that JSP.Jakarta Struts LiveWrite Your First “Forward” 6

Write Your First “Forward”Your first forward will be a JSP page that notifies the user that their registration was successful. Add a JSP pageto c:\strutsTutorial called regSuccess.jsp with the following content:<html><head><title>User Registration Was Successful!</title></head><body><h1>User Registration Was Successful!</h1></body></html>The forward is the output view. The Action will forward to this JSP by looking up a forward called success.Thus, we need to associate this output view JSP to a forward called success.Jakarta Struts LiveConfigure the Action and Forward in the Struts Configuration File 7

Configure the Action and Forward in the StrutsConfiguration FileNow that we have written our first Action and our first Forward, we need to wire them together. To wire themtogether we need to modify the Struts configuration file. The Struts configuration file location is specified by theconfig init parameter for the Struts ActionServlet located in the web.xml file. This was done for us already by theauthors of the blank.war starter application. Here is what that entry looks like:<servlet><servlet-name>action</servlet-name><servlet-class>org.apache.struts.action.ActionServlet</servlet-class>

39

Page 40: actiTime

ActiTime 2006<init-param><param-name>config</param-name><param-value>/WEB-INF/struts-config.xml</param-value></init-param>...<load-on-startup>2</load-on-startup></servlet>Thus, you can see that the blank.war’s web.xml uses WEB-INF/struts-config.xml file as the Struts configurationfile.Follow these steps to add the success forward:1. Open the c:\strutsTutorial\WEB-INF\struts-config.xml file.2. Look for an element called action-mappings.3. Add an action element under action-mappings as shown below.<action path="/userRegistration"type="strutsTutorial.UserRegistrationAction"><forward name="success" path="/regSuccess.jsp"/></action>The above associates the incoming path /userRegistration with the Action handler you wrote earlier, strutsTutorial.UserRegistrationAction.Jakarta Struts LiveConfigure the Action and Forward in the Struts Configuration File 8Whenever this web application gets a request with /userRegistration.do, the execute method of the strutsTutorial.UserRegistrationAction class will be invoked. The web.xml file maps request that end in *.do to the StrutsActionServlet. Since the web.xml file was provided for us, you will not need to edit it. Here is the mapping for inthe web.xml file for reference:<servlet-mapping><servlet-name>action</servlet-name><url-pattern>*.do</url-pattern></servlet-mapping>The Struts ActionServlet will invoke our action based on the path attribute of the above action mapping. TheActionServlet will handle all requests that end in *.do. You may recall that our Action looks up and returns a forwardcalled success. The forward element maps the success forward to the regSuccess.jsp file that you just createdin the last section.The ActionMapping that gets passed to the execute method of the Action handler is the object representation ofthe action mapping you just added in the Struts config file.Jakarta Struts LiveRun and Test Your First Struts Application 9

Run and Test Your First Struts Application40

Page 41: actiTime

ActiTime 2006The blank.war file ships with a started Ant script that will build and deploy the web application.If you are new to Ant, then today is a good day to get up to speed with it. Ant is a build system from Jakarta.Struts uses a lot of Jakarta projects. Most Jakarta projects use Ant. Ant is also a Jakarta project. (Technically, itused to be a Jakarta project, and it was promoted to a top level project at the 1.5 release.) You can learn moreabout Ant and read documentation at http://ant.apache.org/. You can download Ant at http://www.apache.org/dist/ant/. Also, you can find an install guide for Ant at http://ant.apache.org/manual/installlist.html.Technically, you do not have to use Ant to continue on with this tutorial, but it will make things easier for you.It’s up to you. If you are not using Ant, now is a good time to start. Read http://ant.apache.org/manual/usinglist.html to start using Ant after you install it.If you are using the Ant build.xml file that ships with the blank.war (look under WEB-INF/src), you will need toadd the ${servlet.jar} file to the compile.classpath as follows:<path id="compile.classpath"><pathelement path ="lib/commons-beanutils.jar"/><pathelement path ="lib/commons-digester.jar"/><pathelement path ="lib/struts.jar"/><pathelement path ="classes"/><pathelement path ="${classpath}"/><pathelement path ="${servlet.jar}"/></path>Notice the addition of the <pathelement path ="${servlet.jar}"/>. The compile classpath is used by the compiletarget.After you add the pathelement, change the project.distname property to strutsTutorial as follows:<property name="project.distname" value="strutsTutorial"/>Go ahead and run the Ant build script as follows:C:\strutsTutorial\WEB-INF\src> antIf things go well, you should see the message BUILD SUCCESSFUL. Once you run the Ant build script with thedefault target, you should get a war file in your c:\projects\lib directory called strutsTutorial.war. Deploy this warfile to your application server under the web context strutsTutorial. You will need to refer to your applicationserver manual for more details on how to do this. For Tomcat and Resin, this is a simple matter of copying thewar file to Tomcat’s or Resin’s home-dir/webapps directory. The webapps directory is under the server directory.

41

Page 42: actiTime

ActiTime 2006Jakarta Struts LiveRun and Test Your First Struts Application 10If you are not Ant savvy, you can simulate what this ant script does by setting your IDE to output the binary filesto C:\strutsTutorial\WEB-INF\classes, and then zipping up the c:\strutsTutorial directory into a file called strutsTutorial.war.Now that you have built and deployed your web application, test your new Action/forward combination by goingto http://localhost:8080/strutsTutorial/userRegistration.do. You should see the following:Figure 1.1 Running The Action for the first time

Congratulations! You have just written your first Struts Action. Now, admittedly this Action does not do much.At this point, you may be having troubles. The most obvious problem is probably a misconfigured struts-config.xml file. There are two ways to solve this.Jakarta Struts LiveRun and Test Your First Struts Application 11

Debug Struts-Config.xml with the Struts ConsoleIf you are new to XML, it may be a little hard to edit the struts-config.xml file. If you are having troubles withthe struts-config.xml file, you should download the Struts Console. The Struts Console is a Swing based strutsconfig.xml editor; it provides a GUI for editing struts-config files. The Struts Console works as a plugin forJBuilder, NetBeans, Eclipse, IntelliJ and more. The Struts Console can be found at http://www.jamesholmes.com/struts/console/; follow the install instructions at the site. If you have a problem, you can edit thestruts-config file with Struts Console. If there is a problem with the struts-config.xml file, the Struts Console willtake you to the line / column of text that is having the problem. For example, here is an example of editing astruts-config file with a malformed XML attribute:Figure 1.2 Running Struts Console against a malformed struts-config.xml file

Notice the Goto Error button. Clicking the button takes you to the exact line in the struts-config.xml file that ishaving the problem.Jakarta Struts LiveRun and Test Your First Struts Application 12Once everything is fixed, you can view and edit the struts-config.xml file with the Struts Console as follows:Figure 1.3 Running Struts Console in a happy world

The figure above shows editing struts-config.xml and inspecting the userRegistration action that you just configured.

42

Page 43: actiTime

ActiTime 2006Personally, I only use the Struts Console if there is a problem or I want to validate my struts-config.xml file withoutlaunching the application server. I prefer editing the struts-config.xml with a text editor, but find that theStruts Console comes in handy when there is a problem. In addition to mentoring new Struts developers anddoing development myself, I teach a Struts course. I have found that Struts Console is extremely valuable to newStruts developers. Students (and new Struts developers) can easily make a small mistake that will cause the configfile to fail. I can stare for a long time at a struts-config.xml file, and not find a “one off” error. Most of theseerrors, you will not make once you are a seasoned Struts developer, but they can be very hard to diagnose withoutthe Struts Console when you are first getting started.Another debugging technique is to use common logging to debug the application at runtime.Jakarta Struts LiveRun and Test Your First Struts Application 13

Add Logging Support with Log4J and Commons LoggingYou may wonder why we dedicate a whole section to logging. Well to put it simply, when you are new to Struts,you will need to do more debugging, and logging can facilitate your debugging sessions dramatically.The Struts framework uses Commons Logging throughout. Logging is a good way to learn what Struts does atruntime, and it helps you to debug problems. The Commons Logging framework works with many logging systems;mainly Java Logging that ships with JDK 1.4 and Log4J.Using Struts without logging can be like driving in the fog with your bright lights, especially when somethinggoes wrong. You will get a much better understanding how Struts works by examining the logs. Logging can beexpensive. Log4J allows you to easily turn off logging at runtime.Log4J is a full-featured logging system. It is easy to set up and use with Struts. You need to do several things:1. Download Log4J2. Unzip the Log4J distribution3. Copy the log4j.jar file to c:\strutsTutorial\WEB-INF\lib4. Create a log4j.properties file5. Start using logging in our own classesLike Struts, Log4J is an Apache Jakarta project. The Log4J home page is at http://jakarta.apache.org/log4j/docs/

43

Page 44: actiTime

ActiTime 2006index.html. You can download Log4J from http://jakarta.apache.org/site/binindex.cgi. Search for Log4J on thispage. Look for the link that looks like:Log4j KEYS• 1.2.8 zip PGP MD5• 1.2.8 tar.gz PGP MD5Click on the 1.2.8 ZIP file link. Download this file to c:\tools, and adjust accordingly for different drives, directoriesand operating systems (like *n?x). Copy the log4j-1.2.8.jar file located in C:\tools\jakarta-log4j-1.2.8\dist\libto c:\strutsTutorial\WEB-INF\lib.Jakarta Struts LiveRun and Test Your First Struts Application 14Now that you have the jar file in the right location you need to add log4j.properties files so that the web applicationclassloader can find it. The Ant script copies all properties (*.properties) files from \WEB-INF\src\java to\WEB-INF\classes. The Ant script also deletes the \WEB-INF\classes directory. Thus, create a log4j.propertiesfile in the \WEB-INF\src\java directory with the following contents:log4j.rootLogger=WARN, stdoutlog4j.appender.stdout=org.apache.log4j.ConsoleAppenderlog4j.appender.stdout.layout=org.apache.log4j.PatternLayoutlog4j.appender.stdout.layout.ConversionPattern=[%5p] %d{mm:ss}(%F:%M:%L)%n%m%n%nThe code above sends output to the stdout of the application with the priority, date time stamp, file name, methodname, line number and the log message. Logging is turned on for classes under the Struts package and the strutsTutorialcode.To learn more about Log4J, read the online documentation at http://jakarta.apache.org/log4j/docs/manual.html,and then read the JavaDoc at http://jakarta.apache.org/log4j/docs/api/index.html. Look up the classorg.apache.log4j.PatternLayout in the JavaDocs at the top of the file is a list of conversion characters for the outputlog pattern. You can use the conversion characters to customize what gets output to the log.Putting log4j on the classpath (copying the jar file to WEB-INF\lib), causes the Commons Logging to use it. Thelog4J framework finds the log4j.properties file and uses it to create the output logger.If you start having problems with Struts, then set up the logging level of Struts to debug by adding the followingline to log4j.properties file:log4j.logger.org.apache.struts=DEBUG

44

Page 45: actiTime

ActiTime 2006Underneath the covers, we are using Log4J. However, if we want to use logging in our own code, we should useCommons Logging, which allows us to switch to other logging systems if necessary. Thus, we will use the CommonsLogging API in our own code. To learn more about Commons Logging, read the “short online manual” athttp://jakarta.apache.org/commons/logging/userguide.html.Jakarta Struts LiveRun and Test Your First Struts Application 15Edit the UserRegistrationAction by importing the two Commons Logging classes and putting a trace call in theexecute method as follows:import org.apache.commons.logging.Log;import org.apache.commons.logging.LogFactory;…private static Log log = LogFactory.getLog(UserRegistrationAction.class);public ActionForward execute(...) throws Exception {log.trace("In execute method of UserRegistrationAction");return mapping.findForward("success");}You will need to add the Commons Logging Jar file to the compile.classpath in \WEB-INF\src\java\build.xmlfile as follows:<path id="compile.classpath"><pathelement path ="lib/commons-beanutils.jar"/><pathelement path ="lib/commons-digester.jar"/><pathelement path ="lib/struts.jar"/><pathelement path ="classes"/><pathelement path ="${classpath}"/><pathelement path ="${servlet.jar}"/><pathelement path ="lib/commons-logging.jar"/></path>Then to get the above trace statement to print out to the log you need to add this line to the log4j.properties file:log4j.logger.strutsTutorial=DEBUGRebuild and deploy the war file, re-enter the url to exercise the action class and look for the log line in the appserver’s console output.Jakarta Struts LiveRun and Test Your First Struts Application 16There are six levels of logging as follows listed in order of importance: fatal, error, warn, info, debug andtrace. The log object has the following methods that you can use to log messages.log.fatal(Object message);log.fatal(Object message, Throwable t);

45

Page 46: actiTime

ActiTime 2006log.error(Object message);log.error(Object message, Throwable t);log.warn(Object message);log.warn(Object message, Throwable t);log.info(Object message);log.info(Object message, Throwable t);log.debug(Object message);log.debug(Object message, Throwable t);log.trace(Object message);log.trace(Object message, Throwable t);Logging is nearly essential for debugging Struts applications. You must use logging; otherwise, your debuggingsessions may be like flying blind.Jakarta Struts LiveWrite Your First ActionForm 17

Write Your First ActionFormActionForms represent request data coming from the browser. ActionForms are used to populate HTML forms todisplay to end users and to collect data from HTML forms. In order to create an ActionForm, you need to followthese steps:1. Create a new class in the strutsTutorial package called UserRegistrationForm that subclassesorg.apache.struts.action.ActionForm as follows:import org.apache.struts.action.ActionForm;import org.apache.struts.action.ActionMapping;import org.apache.struts.action.ActionErrors;import org.apache.struts.action.ActionError;import javax.servlet.http.HttpServletRequest;public class UserRegistrationForm extends ActionForm {2. Now you need to create JavaBean properties for all the fields that you want to collect from the HTMLform. Let’s create firstName, lastName, userName, password, passwordCheck (make sure theyentered the right password), e-mail, phone, fax and registered (whether or not they are already registered)properties. Add the following fields:private String firstName;private String lastName;private String userName;private String password;private String passwordCheck;private String email;private String phone;private String fax;private boolean registered;Add getter and setter methods for each field as follows:

46

Page 47: actiTime

ActiTime 2006public String getEmail() {return email;}public void setEmail(String string) {email = string;}Jakarta Struts LiveWrite Your First ActionForm 183. Now you have defined all of the properties for the form. (Reminder: each getter and setter pair definesa property.) Next, you need to override the reset method. The reset method gets called each time arequest is made. The reset method allows you to reset the fields to their default value. Here is anexample of overwriting the reset method of the ActionForm:public void reset(ActionMapping mapping,HttpServletRequest request) {firstName=null;lastName=null;userName=null;password=null;passwordCheck=null;email=null;phone=null;fax=null;registered=false;}If you like, please print out a trace method to this method using the logging API, e.g.,log.trace("reset").4. Next you need validate the user entered valid values. In order to do this, you need to override thevalidate method as follows:public ActionErrors validate(ActionMapping mapping,HttpServletRequest request) {ActionErrors errors = new ActionErrors();if (firstName==null|| firstName.trim().equals("")){errors.add("firstName",new ActionError("userRegistration.firstName.problem"));}...return errors;}The validate method returns a list of errors (ActionErrors). The ActionErrors display on the input

47

Page 48: actiTime

ActiTime 2006HTML form. You use your Java programming skills to validate if their typing skills are up to task.The above code checks to see that firstName is present; if it is not present (i.e., it is null or blank),then you add an ActionError to the ActionErrors collection. Notice that when you construct anActionError object, you must pass it a key into the resource bundle (“userRegistration.firstName”).Thus, we need to add a value to this key in the Resource bundle.Jakarta Struts LiveWrite Your First ActionForm 19Please open the file C:\strutsTutorial\WEB-INF\src\java\resources\application.properties. Add a keyvalue pair as follows:userRegistration.firstName.problem=The first name was blankIf the firstName is blank, the control gets redirected back to the input form, and the above messagedisplays. Using a similar technique, validate all the fields.Jakarta Struts LiveWrite Your First Input View (JSP Page) 20

Write Your First Input View (JSP Page)Next, we want to create an HTML form in JSP that will act as the input to our Action. The input is like the inputview, while the forwards are like output views. In order to create the input view, you will do the following:1. Create a JSP page called userRegistration.jsp in the c:\strutsTutorial directory.2. Import both the Struts HTML and Struts Bean tag libraries. The tag libraries have already beenimported into the web.xml file as follows:<taglib><taglib-uri>/tags/struts-bean</taglib-uri><taglib-location>/WEB-INF/struts-bean.tld</taglib-location></taglib><taglib><taglib-uri>/tags/struts-html</taglib-uri><taglib-location>/WEB-INF/struts-html.tld</taglib-location></taglib>One of the advantages of using the blank.war file is that all the things you need are already configured.You just add the parts that are needed for your application. To import the two tag libraries, youwould use the taglib directive as follows:<%@ taglib uri="/tags/struts-html" prefix="html"%><%@ taglib uri="/tags/struts-bean" prefix="bean"%>

48

Page 49: actiTime

ActiTime 20063. Use the html:form tag to associate the form with the Action. The html:form tag associates theform to an action mapping. You use the action attribute to specify the path of the action mapping asfollows:<html:form action="userRegistration">4. Output the errors associated with this form with the html:errors tag. ActionForms have a validatemethod that can return ActionErrors. Add this to the JSP:<html:errors/>Note there are better ways to do this. Struts 1.1 added html:messages, which is nicer as it allowsyou to get the markup language out of the resource bundle. This is covered in more detail later.Jakarta Struts LiveWrite Your First Input View (JSP Page) 215. Update the Action to associate the Action with the ActionForm and input JSP. In order to do this, youneed to edit the struts-config.xml file. If you do not feel comfortable editing an XML file, then use theStruts Console. Add the following form-bean element under the form-beans element as follows:<form-bean name="userRegistrationForm"type="strutsTutorial.UserRegistrationForm" />The code above binds the name userRegistration to the form you created earlier: strutsTutorial.UserRegistrationForm.Now that you have added the form-bean element, you need to associate the userRegistrationaction mapping with this form as follows:<action path="/userRegistration"type="strutsTutorial.UserRegistrationAction"name="userRegistrationForm"input="/userRegistration.jsp"><forward name="success" path="/regSuccess.jsp" /></action>Notice the addition of the name and input attributes. The name attribute associates this action mappingwith the userRegistrationForm ActionForm that you defined earlier. The input attribute associatesthis action mapping with the input JSP. If there are any validation errors, the execute method ofthe action will not get called; instead the control will go back to the userRegistration.jsp file until theform has no ActionErrors associated with it.

49

Page 50: actiTime

ActiTime 20066. Create the labels for the Form fields in the resource bundle. Each field needs to have a label associatedwith it. Add the following to the resource bundle (c:/strutsTutorial/WEB-INF/src/java/resources/application.properties):userRegistration.firstName=First NameuserRegistration.lastName=Last NameuserRegistration.userName=User NameuserRegistration.password=PassworduserRegistration.email=EmailuserRegistration.phone=PhoneuserRegistration.fax=FaxYou could instead hard code the values in the JSP page. Putting the value in the resource bundleallows you to internationalize your application.Jakarta Struts LiveWrite Your First Input View (JSP Page) 227. Use the bean:message to output the labels. When you want to output labels in the JSP from theresource bundle, you can use the bean:message tag. The bean:message tag looks up the value inthe resource bundle and outputs it from the JSP. The following outputs the label for the firstNamefrom the resource bundle:<bean:message key="userRegistration.firstName" />8. Use the html:text tag to associate the ActionForm’s properties to the HTML form’s fields. Thehtml:text associates an HTML text field with an ActionForm property as follows:<html:text property="firstName" />The above associates the HTML text field with the firstName property from your ActionForm. Thehtml:form tag is associated with the ActionForm via the action mapping. The individual text fieldsare associated with the ActionForm’s properties using the html:text tag.9. Create an html:submit tag and an html:cancel tag to render a submit button and a cancel buttonin html as follows:<html:submit />...<html:cancel />At this point you should be able to deploy and test your Struts application. The Action has not beenwired to do much of anything yet. But the form will submit to the Action. And, if a form field is

50

Page 51: actiTime

ActiTime 2006invalid the control will be forwarded back to the input form. Try this out by leaving the firstNamefield blank.Jakarta Struts LiveWrite Your First Input View (JSP Page) 23If you are having problems, you may want to compare what you have written to the solution. Here is what theuserRegistration.jsp looks like after you finish (your HTML may look different):<%@ taglib uri="/tags/struts-html" prefix="html"%><%@ taglib uri="/tags/struts-bean" prefix="bean"%><html><head><title>User Registration</title></head><body><h1>User Registration</h1><html:errors/><table><html:form action="userRegistration"><tr><td><bean:message key="userRegistration.firstName" />*</td><td><html:text property="firstName" /></td></tr><td><bean:message key="userRegistration.lastName" />*</td><td><html:text property="lastName" /></td><tr><td><bean:message key="userRegistration.userName" />*</td><td><html:text property="userName" /></td></tr><tr><td><bean:message key="userRegistration.email" />*</td><td><html:text property="email" /></td>

51

Page 52: actiTime

ActiTime 2006</tr><tr>Jakarta Struts LiveWrite Your First Input View (JSP Page) 24<td><bean:message key="userRegistration.phone" /></td><td><html:text property="phone" /></td></tr><tr><td><bean:message key="userRegistration.fax" /></td><td><html:text property="fax" /></td></tr><tr><td><bean:message key="userRegistration.password" />*</td><td><html:password property="password" /></td></tr><tr><td><bean:message key="userRegistration.password" />*</td><td><html:password property="passwordCheck" /></td></tr><tr><td><html:submit /></td><td><html:cancel /></td></tr></html:form></table></body></html>Jakarta Struts LiveWrite Your First Input View (JSP Page) 25

52

Page 53: actiTime

ActiTime 2006The form should look like this when it first gets loaded. (You load the form by going to http://localhost:8080/strutsTutorial/userRegistration.jsp.)Figure 1.4 User Registration JSPJakarta Struts LiveWrite Your First Input View (JSP Page) 26If you leave the firstName blank, then you should get a form that looks like this.Figure 1.5 User Registration JSP with validation errors

Notice that the error message associated with the firstName displays, since the firstName was left blank. It isinstructive to view the logs as you run the example to see the underlying interactions of the Struts framework.Once you complete the form and hit the Submit button, the execute method of gets UserRegistrationActioninvoked. Currently the execute method just forwards to regSuccess.jsp, which is mapped into the successforward, whether or not the Cancel button is pressed.Jakarta Struts LiveUpdate the Action to Handle the Form and Cancel Buttons 27

Update the Action to Handle the Form and Cancel ButtonsLet’s do something with the ActionForm that gets passed to the Action. Once you fill in the form correctly (novalidation errors) and hit the submit button, the execute method of the UserRegistrationAction is invoked.Actually, the execute method gets invoked whether or not you hit the submit button or the cancel button.You need check to see if the cancel button was clicked; it was clicked forward to welcome. The welcome forwardwas setup by the authors of blank.war, and it forwards to “/Welcome.do”, which forwards to /pages/Welcome.jsp. Check out the struts-config.xml file to figure out how they did this. To check and see if the cancelbutton was clicked, you need to use the isCanceled method of the Action class in the execute method as follows:public ActionForward execute(...)...{...if (isCancelled(request)){log.debug("Cancel Button was pushed!");return mapping.findForward("welcome");}...}The isCancelled method takes an HttpServletRequest as an argument. The execute method was passed anHttpServerletRequest.

53

Page 54: actiTime

ActiTime 2006Next, you need to cast the ActionForm to an UserRegistrationForm . In order to use the form that was submittedto the action, you need to cast the ActionForm to the proper type. Thus, you will need to cast the Action-Form that was passed to the execute method to a UserRegistrationForm as follows:UserRegistrationForm userForm =(UserRegistrationForm) form;Now you can start using the UserRegistrationForm like this:log.debug("userForm firstName" + userForm.getFirstName());For now, just print out the firstName with the logging utility. In the next section, you’ll do something more usefulwith this form—you will write it to a database.

Exception Handling with StrutsBad things happen to good programs. It is our job as fearless Struts programmers to prevent these bad thingsfrom showing up to the end user. You probably do not want the end user of your system to see a Stack Trace. Anend user seeing a Stack Trace is like any computer user seeing the “Blue Screen of Death” (generally not a verypleasant experience for anyone).It just so happens that when you enter an e-mail address into two User Registrations, you get a nasty error messageas the e-mail address is the primary key of the database table. Now, one could argue that this is not a true“exceptional” condition, as it can happen during the normal use of the application, but this is not a tutorial ondesign issues. This is a tutorial on Struts, and this situation gives us an excellent opportunity to explain Strutsdeclarative exception handling.If you enter in the same e-mail address twice into two User Registrations, the system will throw ajava.sql.SQLException. In Struts, you can set up an exception handler to handle an exception.An exception handler allows you to declaratively handle an exception in the struts-config.xml file by associatingan exception to a user friendly message and a user friendly JSP page that will display if the exception occurs.Let’s set up an exception handler for this situation. Follow these steps:1. Create a JSP file called userRegistrationException.jsp in the root directory of the project (c:\strutsTutorial).<%@ taglib uri="/tags/struts-html" prefix="html"%><html><head><title>

54

Page 55: actiTime

ActiTime 2006User Registration Had Some Problems</title></head><body><h1>User Registration Had Some Problems!</h1><html:errors/></body></html>Notice the use of html:errors to display the error message associated with the exception.Jakarta Struts LiveException Handling with Struts 332. Add an entry in the resource bundle under the key userRegistration.sql.exception thatexplains the nature of the problem in terms that the end user understands. This message will be usedby the exception handler. Specifically, you can display this message using the html:errors tag in theuserRegistrationException.jsp file. Edit the properties file associated with the resource bundle(located at C:\strutsTutorial\WEB-INF\src\java\resources\application.properties if you have been followingalong with the home game version of the Struts tutorial).userRegistration.sql.exception=There was a problem adding the User. \n Themost likely problem is the user already exists or the email\n address isbeing used by another user.(The code above is all one line.)3. Add an exception handler in the action mapping for /userRegistration that handlesjava.sql.SQLException as follows:<action path="/userRegistration"type="strutsTutorial.UserRegistrationAction"name="userRegistrationForm"input="/userRegistration.jsp"><exception type="java.sql.SQLException"key="userRegistration.sql.exception"path="/userRegistrationException.jsp" /><forward name="success" path="/regSuccess.jsp" /><forward name="failure" path="/regFailure.jsp" /></action>Notice that you add the exception handler by using the exception element (highlighted above). Theabove exception element has three attributes: type, key and path. The type attribute associates thisexception handler with the exception java.sql.SQLException. The key attribute associates the

55

Page 56: actiTime

ActiTime 2006exception handler with a user friendly message out of the resource bundle. The path attribute associatesthe exception handler with the page that will display if the exception occurs.Jakarta Struts LiveException Handling with Struts 34If you do everything right, you get the following when the exception occurs.Figure 1.6 Declaritive Exception HandlingJakarta Struts LiveDisplay an Object with Struts Tags 35

Display an Object with Struts TagsStruts supports a Model 2 architecture. The Actions interact with the model and perform control flow operations,like which view is the next view to display. Then, Actions delegate to JSP (or other technologies) to displayobjects from the model.To start using Struts with this tutorial, follow these steps:1. Add an attribute called attribute to the mapping that causes the ActionForm to be mapped intoscope as follows:<action path="/userRegistration"type="strutsTutorial.UserRegistrationAction"name="userRegistrationForm"attribute="user"input="/userRegistration.jsp">...Notice the above action mapping uses the attribute called attribute. The attribute maps the Action-Form into a scope (session scope by default) under “user”. Now that the ActionForm is in sessionscope, you can display properties from the ActionForm in the view.2. Edit the regSuccess.jsp that you created earlier. The regSuccess.jsp is an ActionForward for the User-RegistrationAction. The regSuccess.jsp is the output view for the Action. In order to display theActionForm, you could use the Struts bean tag library.3. Import the bean tag library into the JSP as follows:<%@ taglib uri="/tags/struts-bean" prefix="bean"%>4. Use the bean:write to output properties of the ActionForm<bean:write name="user" property="firstName" />The code above prints out the firstName property of the user object. Use the above technique toprint out all of the properties of the user object.When you are done with the JSP, it should look something like this:<%@ taglib uri="/tags/struts-bean" prefix="bean"%><html><head>

56

Page 57: actiTime

ActiTime 2006<title>User Registration Was Successful!Jakarta Struts LiveDisplay an Object with Struts Tags 36</title></head><body><h1>User Registration Was Successful!</h1></body><table><tr><td><bean:message key="userRegistration.firstName" /></td><td><bean:write name="user" property="firstName" /></td></tr><tr><td><bean:message key="userRegistration.lastName" /></td><td><bean:write name="user" property="lastName" /></td></tr><tr><td><bean:message key="userRegistration.email" /></td><td><bean:write name="user" property="email" /></td></tr></table></html>Jakarta Struts LiveUsing Logic Tags to Iterate over Users 37

Using Logic Tags to Iterate over UsersStruts provides logic tags that enable you to have display logic in your view without putting Java code in yourJSP with Java scriptlets. To start using the Logic tags, follow these steps.1. Create a JavaBean class called User to hold a user with email, firstName and lastName properties.Here is a possible implementation (partial listing):package strutsTutorial;import java.io.Serializable;public class User implements Serializable {

57

Page 58: actiTime

ActiTime 2006private String lastName;private String firstName;private String email;public String getEmail() {return email;}...public void setEmail(String string) {email = string;}...}2. Create a new Action called DisplayAllUsersAction.public class DisplayAllUsersAction extends Action {In the new Action’s execute method, complete the following steps:3. Get the userDB datasource.DataSource dataSource = getDataSource(request, "userDB");4. Create a DB connection using the datasource.Connection conn = dataSource.getConnection();Statement statement = conn.createStatement();Jakarta Struts LiveUsing Logic Tags to Iterate over Users 385. Query the DB, and copy the results into a collection of the User JavaBean:ResultSet rs =statement.executeQuery("select FIRST_NAME, LAST_NAME, EMAIL from USER");List list = new ArrayList(50);while (rs.next()){String firstName = rs.getString(1);String lastName = rs.getString(2);String email = rs.getString(3);User user = new User();user.setEmail(email);user.setFirstName(firstName);user.setLastName(lastName);list.add(user);}if (list.size() > 0){request.setAttribute("users", list);}Tip: Don’t forget to close the connection using a try/finally block.Warning! You do not typically put SQL statements and JDBC code directly in an Action. This type of codeshould be in a DataAccessObject. A DataAccessObject would encapsulate the CRUD access for aparticular domain object. The DataAccessObject is part of the Model of the application.6. Create a new JSP called userRegistrationList.jsp.In the new JSP, perform the following steps:7. Import the logic tag library into the userRegistrationList.jsp.

58

Page 59: actiTime

ActiTime 2006<%@ taglib uri="/tags/struts-logic" prefix="logic"%>8. Check to see if the users are in scope with the logic:present tag.<logic:present name="users">... (Step 9 goes here)</logic:present>9. If the users are in scope, iterate through them.<logic:iterate id="user" name="users">... (Step 10 goes here)</logic:iterate>Jakarta Struts LiveUsing Logic Tags to Iterate over Users 3910. For each iteration, print out the firstName, lastName and email using bean:write<bean:write name="user"property="firstName"/><bean:write name="user"property="lastName"/><bean:write name="user"property="email"/>One possible implementation for the JSP is as follows:<%@ taglib uri="/tags/struts-bean" prefix="bean"%><%@ taglib uri="/tags/struts-logic" prefix="logic"%><html><head><title>User Registration List</title></head><body><h1>User Registration List</h1><logic:present name="users"><table border="1"><tr><th><bean:messagekey="userRegistration.firstName"/></th><th><bean:messagekey="userRegistration.lastName" /></th><th><bean:messagekey="userRegistration.email" /></th></tr><logic:iterate id="user" name="users"><tr><td><bean:write name="user"Jakarta Struts Live

59

Page 60: actiTime

ActiTime 2006Using Logic Tags to Iterate over Users 40property="firstName"/></td><td><bean:write name="user"property="lastName"/></td><td><bean:write name="user"property="email"/></td></tr></logic:iterate></table></logic:present></body></html>Jakarta Struts LiveUsing Logic Tags to Iterate over Users 41Figure 1.7 User Listing

11. Create a new entry in the struts-config.xml file for this new Action.<action path="/displayAllUsers"type="strutsTutorial.DisplayAllUsersAction"><forward name="success"path="/userRegistrationList.jsp"/></action>Now you can deploy and test this new Action by going to: http://localhost:8080/strutstutorial/displayAllUsers.do

Working with ActionForms and DynaActionFormsActionForms function as data transfer objects to and from HTML forms.ActionForms populate HTML forms todisplay data to the user and also act like an object representation of request parameters, where the requestparameters attributes are mapped to the strongly typed properties of the ActionForm. ActionForms also performfield validation.This chapter is divided into two sections. The first section covers the theory and concepts behind ActionForms.The second part covers common tasks that you will need to perform with ActionForms like:• Creating a master detail ActionForm (e.g., Order has LineItems)• Creating an ActionForm with nested JavaBean properties• Creating an ActionForm with nested indexed JavaBean properties• Creating an ActionForm with mapped backed properties• Loading form data in an ActionForm to display

60

Page 61: actiTime

ActiTime 2006• Configuring DynaActionFormsJakarta Struts LiveDefining an ActionForm 75

Defining an ActionFormAn ActionForm is an object representation of an HTML form (or possibly several forms in a wizard-style interface).ActionForms are a bit of an anomaly in the MVC realm. An ActionForm is not part of the Model. AnActionForm sits between the View and Controller acting as a transfer object between the two layers. An Action-Form represents not the just the data, but the data entry form itself.ActionForms have JavaBean properties to hold fields from the form. An ActionForm’s JavaBean properties canbe primitive types, indexed properties, Maps (i.e., HashMap), or other JavaBeans (nested beans). Thus, Action-Forms do not have to be one-dimensional; they can consist of master detail relationships and/or can havedynamic properties. (Examples of indexed properties, dynamic properties, and master detail relationships can befound in the tutorial section of this chapter.)ActionForms are configured to be stored by Struts in either session or request scopes. Session scope is the defaultscope. Struts automatically populate the ActionForm's JavaBean properties from corresponding request parameters,performing type conversion into primitive types (or primitive wrapper types) if needed. You typically useSession scope for wizard-style interfaces and shopping carts.With ActionForms, you use JavaBean properties to represent the fields in the HTML form. You can also use JavaBeanproperties to represent buttons and controls; this helps when deciding which button or control the userselected.Understanding the Life Cycle of an ActionFormThe ActionServlet handles requests for Struts (i.e., requests ending in *.do are common). The ActionServletlooks up the RequestProcessor associated with the module prefix. The RequestProcessor implements the handlingof the life cycle and uses RequestUtils as a façade to Struts objects mapped into Servlet scopes (request,session, and application).When a form gets submitted, Struts looks up the action mapping for the current request path from the Module-Config. The ModuleConfig is the object manifestation of the struts-config.xml file, each module gets its own

61

Page 62: actiTime

ActiTime 2006ModuleConfig. (Recall that the action attribute in the html:form tag specifies the path of the action to invoke.)Struts locates the form-bean mapping from the action mapping associated with the request path. (This occurs inthe processActionForm method of the RequestProcessor by calling the createActionForm method ofRequestUtils.)If Struts does not find an ActionForm in the scope specified by the action mapping, it will create an instance ofthe ActionForm identified form-bean mapping.Struts populates the ActionForm by mapping the request parameters from the HTML form variables to the Java-Bean properties of the ActionForm instance. Before it populates the form, Struts calls the reset() method of theActionForm. (This occurs in the processPopulate method of the RequestProcessor by calling the populatemethod of RequestUtils.)Jakarta Struts LiveDefining an ActionForm 76If validation is required and is successful, an instance of the Action class will be invoked. Validation is requiredif the validate attribute of the action mapping is not false (the default is true). If validation fails, control will bereturned to the submitting form (the input JSP) where the JSP form fields will be populated by the ActionForm.The ActionForm is valid if the validate() method returns null or an empty ActionErrors collection. (This occursin the processValidate method of the RequestProcessor.)The life cycle of an ActionForm is demonstrated in the following diagram.Figure 3.1 Life Cycle of an ActionFormJakarta Struts LiveDefining an ActionForm 77Understanding ActionForm’s reset() MethodThe reset() method allows you to set properties to default values. The ActionForm is a transfer object; therefore,you should not deal with the Model from the reset() method, and don’t initialize properties for an update operationin the reset() method.The reset() method was mainly added so you could reset check boxes to false. Then, the selected check boxeswill be populated when Struts populates the form. The HTTP protocol sends only selected check boxes. It doesnot send unselected check boxes. (Examples of working with check boxes in the reset() method are in the tutorialsection of this chapter.)Understanding ActionForm’s validate() Method

62

Page 63: actiTime

ActiTime 2006The purpose of the validate() method is to check for field validation and relationships between fields. Do not performbusiness logic checks in the validate() method; it is the job of the action to work with the Model to performbusiness logic checks.A field validation would check to see if a field is in a certain range, if a field was present, a certain length, andmore. A relationship validation would check the relationship between the fields. Checking to see if the start dateis before the end date is a good example of a relationship validation. Another relationship validation is checkingto see if the password and the check password field are equal. (Examples of performing validation can be foundin the tutorial section of this chapter.)Jakarta Struts LiveDefining an ActionForm 78

The Do’s and Don’ts of Automatic Type ConversionActionForms can be strongly typed. Struts will convert Strings and String Arrays into primitive and primitivearrays.Struts converts the request parameters into a HashMap and then uses common BeanUtils to populate the Action-Form with the request parameters. (This occurs in the processPopulate method of the RequestProcessor bycalling the populate method of RequestUtils.) The interesting thing about this is that BeanUtils will performtype conversion from the strings coming from the request parameter to any primitive or primitive wrapperclass.At first, this seems like a boon. Problems arise when you implement validation. Let’s say a user mistypes an integerfield with the letters “abc”. BeanUtils will convert “abc” to 0 if it corresponds to an int property of theActionForm. This is bad news. Even if you did bounds checking in the validate() method of the ActionForm andthe 0 field was not allowed, when control forwarded back to the input JSP the user will not see the “abc” theytyped in; they will see 0. Even worse is if 0 is a valid value for your application, then there is no way to check tosee if the user entered in the right number for the field.Thus, you have to follow this rule when using the automatic type conversion: if the user types in the value, thenmake the ActionForm property representing the field a string. Usually this means if the field is rendered with

63

Page 64: actiTime

ActiTime 2006html:text, html:textarea, or html:password, then make the field a string. This does not apply to drop-down boxes(html:select), check boxes (html:checkbox), and the like.Tip: If the user types in the value, then make the property a string.Jakarta Struts LiveWhat an ActionForm Is 79

What an ActionForm IsData Supplier: Supplies Data to html:formAn ActionForm supplies data to be displayed by JSP pages. In the CRUD realm, the ActionForm would be usedto transfer data to the html:form tag of an update.jsp page. In fact, the html:form tag will not work unless theActionForm is present and in the correct scope. In this role, the ActionForm supplies data to the html:form.Data Collector: Processes Data from html:formAn ActionForm receives form data (request parameters) from browsers usually with forms that were renderedwith html:form. Struts converts that data into an ActionForm. Thus, instead of handling request parametersdirectly, you would work with the ActionForm (possibly strongly typed).Action Firewall: Validates Data before the Action Sees ItAn ActionForm acts like a traffic cop. If validation is turned on for an action, the action will never be executedunless the ActionForm’s validate() method says the ActionForm is valid. The action in turn deals with theModel; the Model is never passed bad data from the view. This is a boon from an architecture standpoint. YourModel just needs to worry about business rule violations not fumbling finger violations. This turns out to be agood separation of concern that makes the Model easier to test and validate.Jakarta Struts LiveWhat an ActionForm is Not 80

What an ActionForm is NotActionForms can be abused and used in manners that were not intended by the Struts framework. There are somethings to keep in mind when using ActionForms.Not Part of the Model or Data Transfer ObjectActionForms are not part of the Model and should not be used as data transfer objects between the controller(Actions) and the Model. The first reason is that the Model should be “Struts agnostic.” The second reason is thatActionForms are not strongly typed as they are used to perform field validations and reflect bad fields back to the

64

Page 65: actiTime

ActiTime 2006user to see and fix. Often times there are one-to-one relationships between ActionForms and the Model DTOs(data transfer objects). In that case, you could use BeanUtils.copyProperties to move and convert data from theActionForm to the Model DTOwhere appropriate.Not an Action, Nor Should It Interact with the ModelThe ActionForm should not deal with the Model in the reset() method or the validate() method. This is the job ofthe Action. ActionForms have a limited set of responsibilities: act as a transfer object, reset the fields to defaultvalues, and validate the fields. If you are doing more than that in your ActionForm, then you are breaking howStruts delimits the areas of concern. (I am okay with breaking the rules, as long as you know what the rules areand have a good reason for breaking them.)Jakarta Struts LiveReducing the Number of ActionForms 81

Reducing the Number of ActionFormsA common concern with Struts is the number of ActionForms that need to be created. Essentially, you have tocreate an ActionForm for each HTML form. There are many strategies to get around this.Super ActionFormsOne common strategy to get around the number of ActionForms is to use a super class ActionForm that hasmany of the fields that each of the other HTML forms need. This works out well if a lot of forms are similar,which can be the case with some web applications.AdvantageThe advantage to this approach is that you reduce the number of fields you need to add to each ActionForm byhaving a super class ActionForm that contains a lot of the common fields.DeltaOne of the disadvantages to this approach is you end up carrying around a lot of fields that some Actions don’tcare about. Essentially, you have opted to trade the cohesiveness of an ActionForm to reduce the number ofclasses in your system.DynaActionFormsIn teaching, consulting Struts, and developing with Struts, I have found that DynaActionForms are either readilyembraced or consistently avoided. The idea behind DynaActionForms is that instead of creating an ActionForm

65

Page 66: actiTime

ActiTime 2006for each HTML form, you instead configure an ActionForm for each HTML form.AdvantageSome folks feel creating an ActionForm class for each HTML form in your Struts application is time-consuming,maintenance-intensive, and plain frustrating. With DynaActionForm classes, you don’t have to create an Action-Form subclass for each form and a bean property for each field. Instead, you configure a DynaActionForm’sproperties, type, and defaults in the Struts configuration file.DeltaYou still have to create the DynaActionForm in the Struts configuration file. When you use the DynaAction-Form, you have to cast all the properties to their known type. Using a DynaActionForm is a lot like using a Hash-Map. In your Action, if you are accessing a DynaActionForm and misspell a property name, the compiler willnot pick it up; instead, you will get a runtime exception. If you cast an integer to a float by mistake, the compilerwill not pick it up; you will get a runtime exception. DynaActionForms are not type safe. If you use an IDE, codecompletion does not work with DynaActionForms. If you override the reset() method or validate() method, youdefeat the purpose of having a DynaActionForm. Finally, DynaActionForms are not really dynamic, as you stillhave to change the configuration file and then restart the web application to get Struts to recognize an additionalfield.Tip: As you can probably tell, I think using DynaActionForms is less than ideal. However, I will cover them. I feelDynaActionForms are not really dynamic at all since you have to restart the web application when you changethem. I prefer to code my forms in Java instead of XML. I find DynaActionForms no more dynamic than usingJava classes. I prefer to create my ActionForms by subclassing ActionForm and using bean properties. I findthat modern IDEs make short work of adding JavaBean properties. I see no real advantage to using DynaActionFormsover ActionForms. If I want to make an ActionForm dynamic, I add a mapped back property. I haveworked on projects that forced DynaActionForms. I much prefer regular ActionForms. With subclassing Action-Forms, you get strongly typed properties, IDE code completion, and XDoclet support. The XDoclet material iscovered when you cover the Validator framework.Jakarta Struts LiveSession vs. Request Scope ActionForms 84

Session vs. Request Scope ActionForms66

Page 67: actiTime

ActiTime 2006A reoccurring question about ActionForms is which scope should I put them in: session or request? The answeris: it depends. Putting ActionForms in session scope may work out really well for web applications with rich userinterfaces. ActionForms in the session scope will ease the development process.Whether you put ActionForms in session scope or request scope depends on what type of application you arebuilding. If you are building an application similar to eBay or Amazon.com, then a different set of rules willapply than if you are writing an intranet application for a company with 500 workers. Don’t exclude putting anythingin session scope as a knee jerk reaction. Putting objects like ActionForms into session scope can make iteasier to create a rich GUI environment.However, as a general rule, you should limit how much you put into session scope as it uses up memoryresources until either you remove the object from scope or the user’s session times out. Resources are usurpedfurther when you implement session sharing via a cluster of J2EE application servers because you are now eatingup both memory resources and network bandwidth. This is not a suggestion that you refrain from putting anythinginto session scope, but simply a warning that you are careful with what you put into session scope.To determine how much you can put into session scope, you should do some capacity planning and hardwarearchitecture planning for your web application. How many users will use the application? Is hardware failoverrequired? Is session failover required? Will you use load balancing? Will you focus on scaling up or scaling out?How much down time is allowed? How much money can be spent on hardware?If you decide to put ActionForms into session scope, you can help conserve resources in a few ways. If you arebuilding a wizard-style interface like a multi-step User Registration form, be sure to remove the ActionFormfrom session scope on the last step of the wizard or when the user presses the Cancel button. For a shopping cart,make sure you remove the shopping cart ActionForm from session scope after the user finishes checking out.Always implement a log out feature. Study how the web application is going to be used and only make the sessiontimeout as long as is needed; this process can be refined once the site goes live by studying how users areusing the system. (Ex. One company I consulted with set the session time out to six minutes, which was perfect

67

Page 68: actiTime

ActiTime 2006for their application.)Note: I helped create an ASP (application service provider systems) that almost always put ActionForms intorequest scope. We used hidden fields and cookies to help manage state. I’ve also helped create a B2B applicationwith a known number of users with a rich HTML GUI that almost always put ActionForms into sessionscope.

The Validator FrameworkThe Validator framework is used to validate fields. Validation is done in many forms—for example, a zip code inboth a user registration form and an order form. Instead of writing the zip code validation twice (in each of thevalidate methods of the form beans corresponding to these forms), you can create a general validation mechanismfor all zip code numbers in the system.Since Struts was built with i18N in mind, the validation mechanism that ships with Struts has support for internationalization.The Validator framework provides many common validation rules. In addition to the common validationrules, you can write your own rules using the Validator framework. By the end of this chapter, you will beable to use the common validation rules to validate form fields and create your own validation rules.This chapter covers the following topics:• Understanding how the Validator framework integrates with Struts• Using the Validator framework with static ActionForms and with DynaActionForms• Working with common validation rules• Building and using your own validation rules (zip code with plus 4)• Working with wizards (multistep user registration) by employing the page attribute• Using the Validator framework and your own custom validation at the same time• Employing JavaScript validation on the client sideJakarta Struts LiveGetting Started with the Validator Framework 123

Getting Started with the Validator FrameworkIt’s hard to get started with the Validator framework, so let’s go right into the tutorial.Let’s use the Validator framework to validate fields from the user registration form. As part of this user registration,you want the end user to enter a username. The username should start with a letter, consist of at least 5

68

Page 69: actiTime

ActiTime 2006alphanumeric characters or underscores, and be no longer than 11 characters.To use the Validator framework, follow these steps:1. Add the Validator plug-in to the Struts configuration file. The Validator framework integrates withStruts via this plug-in, which is responsible for reading the configuration files for the Validator rules.To use the Validator framework with Struts, you need to add this plug-in after any message resourceelements in the Struts configuration file as follows:<plug-inclassName="org.apache.struts.validator.ValidatorPlugIn"><set-propertyproperty="pathnames"value="/WEB-INF/validator-rules.xml,/WEB-INF/validation.xml"/></plug-in>2. Copy the validator-rules.xml and validation.xml files into WEB-INF (from the blank Struts webapplication). The validator-rules.xml file serves as the deployment descriptor for validation rule components.Since the user registration is based on the blank WAR file, you don’t have to perform thisstep for the tutorial.For now, you will use a common, preexisting validation rule component so that you do not have tomodify the validator-rules.xml file. The validator.xml file enables you to set up the mappings fromthe ActionForm's property to the rules and any error message for the rules. Examples of both the validator-rules.xml file and the validation.xml file are in the blank starter web application that ships withStruts.Jakarta Struts LiveGetting Started with the Validator Framework 1243. Change the ActionForm class (UserRegistrationForm.java) to the subclass ValidatorForm(org.apache.struts.validator.ValidatorForm). The ValidatorForm is the Struts hook into the Validatorframework. The ValidatorForm overrides the validate() method of the ActionForm and communicateswith the Validator framework to validate the fields of this form.Here are the changes you need to make to UserRegistrationForm.java:import org.apache.struts.validator.ValidatorForm;public class UserRegistrationForm extends ValidatorForm {…private String userName;public String getUserName() {

69

Page 70: actiTime

ActiTime 2006return userName;}public void setUserName(String string) {userName = string;}…4. Add a form to the form set in the validation.xml file. You may recall that the userRegistrationForm ismapped into the struts-config.xml file as follows:<form-beans><form-bean name="userRegistrationForm"type="strutsTutorial.UserRegistrationForm" />Then, the above form is used by the action mapping as follows:<action path="/userRegistration"type="strutsTutorial.UserRegistrationAction"name="userRegistrationForm"attribute="user"input="/userRegistration.jsp">...<forward name="success" path="/regSuccess.jsp" /><forward name="failure" path="/regFailure.jsp" /></action>You must add the mapping from the userRegistrationForm bean definition in the struts-config.xmlfile to the rules that should be invoked for the individual properties of the userRegistrationForm bean:<formset><form name="user">...</form></formset>Jakarta Struts LiveGetting Started with the Validator Framework 125This code states that you are going to write rules for the properties of the form bean that is associatedwith the attribute user as defined in the struts-config.xml file. The name has to match the attributevalue of the form bean for a mapping that you defined in the struts-config.xml file earlier.Warning! Do not match the name of the form, but the value of the attribute. This gets confusing because if you donot give an action mapping an attribute (attribute="user") , then the value of the attribute defaults to the nameof the ActionForm (name="userRegistrationForm"). Thus, if you did not specify the attribute, the attribute wouldhave been userRegistrationForm and you would use userRegistrationForm for the name of the form in theformset in the validation.xml file.

70

Page 71: actiTime

ActiTime 20065. Add a field to the form declaration in the validation.xml file corresponding to the userName field.Now that you specified which form you want to associate with rules, you can start associating fields(also known as bean properties) with the predefined rules: the field sub-element maps inputForm'suserName property to one or more rules.<form name="user"><field property="userName" ...>...</field></form>6. Specify that the userName field corresponds to the required, minlength, and maxlength rules:<form name="user"><field property="userName"depends="required,minlength,maxlength">...</field></form>The depends attribute of the field element takes a comma-delimited list of rules to associate with thisproperty. Therefore, this code associates the userName property with the required, minlength, andmaxlength rules. These rules are some of the many rules built into the Validator framework. Theserules are associated with rule handlers and an error message key. For example, if you looked up theminlength rule in the validator-rules.xml file, you would see the following:<validator name="minlength"classname="org.apache.struts.validator.FieldChecks"method="validateMinLength"...depends=""msg="errors.minlength">...</validator>Jakarta Struts LiveGetting Started with the Validator Framework 126Notice that the validator element defines the minlength rule. It also uses the classname attribute tospecify the rules handler, the class that implements the rule. In the example, the handler for this rule isimplemented in the class org.apache.struts.validator.FieldChecks by the validateMinLength()method. The msg attribute specifies the key for the message that the framework will look up in the

71

Page 72: actiTime

ActiTime 2006resource bundle to display an error message if the associated fields do not validate. You will need toadd this message to the resource bundle.7. Add the error message for the rules to the resource bundle. Because you are using the common rules,you must import its associated message into the resource bundle for this web application. The validator-rules.xml file has sample messages for all of the rules in a commented section. You may changethe wording, but the sample messages are a good guide. Find the sample messages (e.g., errors.minlength)in the comments of validator-rules.xml, and copy and paste the errors to the resource bundle.(If you are using the blank WAR file as the base, the error messages are already in the resource bundle.)The resource bundle for the tutorial is located in resources/application.properties in the src/javadirectory. Ensure the resource bundle contains the following messages:errors.invalid={0} is invalid.errors.maxlength={0} cannot be greater than {1} characters.errors.minlength={0} cannot be less than {1} characters.errors.range={0} is not in the range {1} through {2}.errors.required={0} is required.errors.byte={0} must be a byte.errors.date={0} is not a date.errors.double={0} must be a double.errors.float={0} must be a float.errors.integer={0} must be an integer.errors.long={0} must be a long.errors.short={0} must be a short.errors.creditcard={0} is not a valid credit card number.errors.email={0} is an invalid e-mail address.Notice the three error messages below correspond to the three rules that you are configuring:required, minlength, and maxlength.errors.maxlength={0} cannot be greater than {1} characters.errors.minlength={0} cannot be less than {1} characters.errors.required={0} is required.Notice that the maxlength rule message (errors.maxlength) takes two arguments ({0} and {1}) asdoes the minlength rule. The required rule message only takes one argument. You will need to configurevalues for these arguments. The first argument of all three rules corresponds to the label of thefield. The second argument for the length rules corresponds to cardinality of the characters. See

72

Page 73: actiTime

ActiTime 2006java.text.MessageFormat API docs for more information on working with messages and arguments tomessages.Jakarta Struts LiveGetting Started with the Validator Framework 1278. Specify that the username label is the first argument to the error message. Notice for example that theerrors.minlength message takes two arguments. The first argument is the name of the field as itappears to the end user (i.e., the label). The second argument is the value of the minlength variable(you will set up the second argument later). To set up the first argument, use the arg0 element as follows:<form name="user"><field property="userName"depends="required,minlength,maxlength"><arg0 key="userRegistration.userName"/>…</field></form>The arg0 element passes the key of the message resource, userRegistration.userName. Therefore,the error message in this example will display the userRegistration.userName message, which isthe label for the userName field.9. Configure the value of the minlength value to 5 and the maxlength to 11. Rules take parameters. Thisparticular rule takes a parameter that tells it what the numeric value of the minimum length is. To seta parameter, you use the var element as follows:<form name="user"><field property="userName"depends="required,minlength,maxlength,match"><arg0 key="userRegistration.userName"/><var><var-name>minlength</var-name><var-value>5</var-value></var></field></form>The minlength rule has a variable called minlength (rule names and variable names do not alwaysmatch). The var element has two sub-elements that specify the name of the parameter and the value ofthe parameter. In addition to setting up the minlength rule to 5, you need to set up the maxlength ruleto 11 as follows:

73

Page 74: actiTime

ActiTime 2006<var><var-name>maxlength</var-name><var-value>11</var-value></var>Jakarta Struts LiveGetting Started with the Validator Framework 12810. Specify that:• The value of the rules’ minlength variable is the second argument (arg1) to the error messageif the minlength rule gets actuated.• The maxlength variable is the second argument (arg1) if the maxlength rule is actuated.Therefore, instead of getting the argument from the resource bundle, you want to get it from the variablethat you just defined. To do this, you must specify another argument. This time, use the arg1 element:<field property="userName"depends="required,minlength,maxlength"><arg0 key="userRegistration.userName"/><arg1 key="${var:minlength}"name="minlength"resource="false"/><var><var-name>minlength</var-name><var-value>5</var-value></var><var><var-name>maxlength</var-name><var-value>11</var-value></var></field></form>Notice that the code sets the resource attribute equal to false (resource="false"), which means thatthe second argument will not be looked up in the resource bundle. Instead, the second argument willuse the minlength variable defined in the previous step. To do this, the key attribute is set to${var:minlength) (key="${var:minlength}), which states that the value of the second argument isequal to the value of the minlength variable (in kind of a bastardized JSTL expression).The name attribute of arg1 states that this second argument is appropriate only for the minlength rule(name="minlength"). Thus, the second argument will be the value of the minlength variable only if

74

Page 75: actiTime

ActiTime 2006there is a validation problem with the minlength rule. Remember that the property can be associatedwith many rules because the depends attribute of the field element takes a comma-delimited list ofrules to associate with the property. Therefore, the name attribute specifies which rule this argumentis used with.Now set the first argument for the maxlength rule as follows:<arg1 key="${var:maxlength}"name="maxlength"resource="false"/>Jakarta Struts LiveGetting Started with the Validator Framework 129If the above seems like a lot of work, don’t fret. Once you set up the framework, using additionalrules is easy. The following listing shows the rules for your user registration form so far:<formset><form name="user"><field property="userName"depends="required,minlength,maxlength"><arg0 key="userRegistration.userName"/><arg1 key="${var:maxlength}"name="maxlength"resource="false"/><arg1 key="${var:minlength}"name="minlength"resource="false"/><var><var-name>minlength</var-name><var-value>5</var-value></var><var><var-name>maxlength</var-name><var-value>11</var-value></var></field></form></formset>Now to get this to run, you will need to comment out your old validate() method so that the validate()method defined by ValidatorForm can execute. As part of this user registration, the code above makesthe username a required field, consist of at least 5 characters, and no longer than 11 characters. It doesnot ensure that the first character is a letter and the remaining characters are alphanumeric, you will

75

Page 76: actiTime

ActiTime 2006do that later after you cover the mask rule.The last step before you start testing what you have done is to turn on logging. Edit your log4j.propertiesfile (see chapter 1 if you don’t know what this is), and add these two entries:#For debugging validator configurationlog4j.logger.org.apache.commons.validator=DEBUGlog4j.logger.org.apache.struts.validator=DEBUGNow read through the log file as your web application gets loaded and the user registration gets submitted.Doing this will help you understand how the Validator framework works and will help youdebug it when things go wrong. When you are done with this chapter, you can set the above back toWARN.Jakarta Struts LiveCommon Validator Rules 130

Common Validator RulesBefore you start writing your own rules, you should become familiar with Table 4.1, which describes the standardrules included with the framework. As you can see, you get a lot of functionality with very little work.Let's cover using several combinations of the rules from the table and see the ramifications of doing so. Not all ofthe rules are covered—just the most useful ones.Table 4.1: Common Validator RulesRule Name(s) Description Variable(s)required The field is required. It must be present for theform to be valid.Noneminlength The field must have at least the number ofcharacters as the specified minimum length.The minlength variable specifiesthe minimum allowednumber of characters.maxlength The field must have no more characters thanthe specified maximum length.The maxlength variable specifiesthe maximum number ofcharacters allowed.intrange, floatrange,doublerangeThe field must equal a numeric value betweenthe min and max variables.min variable specifies start ofthe rangemax variable specifies end ofthe rangebyte, short, integer,long, float, doubleThe field must parse to one of these standard

76

Page 77: actiTime

ActiTime 2006Java types (rules names equate to theexpected Java type).Nonemask The field must match the specified regularexpression (Perl 5 style).The mask variable specifiesthe regular expression.date The field must parse to a date. The optionalvariable datePattern specifies the date pattern(see java.text.SimpleDateFormat in the Java-Docs to learn how to create the date patterns).You can also pass a strict variable equal tofalse to allow a lenient interpretation of dates(i.e., 05/05/99 = 5/5/99). If you do not specifya date pattern, the short date form for the currentlocale is used (i.e., DateFormat.SHORT).datePatterndatePatternStrict

creditCard The field must be a valid credit card number

4. SYSTEM DESIGN

DATA DICTIONARY

access_right

NAME CONSTRAINT DATA TYPEID PRIMARY

KEYAUTONUMBER

NAME TEXTDESCRIPTION TEXT

At_user

NAME CONSTRAINT DATA TYPE

77

Page 78: actiTime

ActiTime 2006ID PRIMARY

KEYAUTONUMBER

USERNAME TEXTUSERNAME_LOWER TEXTMD5_PASSWORD TEXTFIRST_NAME TEXTMIDDLE_NAME TEXTLAST_NAME TEXTEMAIL TEXTPHONE TEXTFAX TEXTMOBILE TEXTOTHER_CONTACT TEXTIS_ROOT YES/NOIS_ENABLED YES/NOWORKDAY_DURATION NUMBEROVERTIME_TRACKING YES/NO

billing_type

NAME CONSTRAINT DATA TYPE

ID PRIMARY KEY AUTONUMBERNAME TEXTNAME_LOWER TEXT

customer

NAME CONSTRAINT DATA TYPEID PRIMARY

KEYAUTONUMBER

CREATE_TIMESTAMP DATE/TIMENAME TEXTNAME_LOWER TEXTDESCRIPTION MEMOBILLING_STATUS YES/NO

Overtime

NAME CONSTRAINT DATA TYPE

78

Page 79: actiTime

ActiTime 2006ID PRIMARY

KEYNUMBER

OVERTIME_DATE PRIMARY KEY

DATE/TIME

OVERTIME NUMBER

Patch_history

NAME CONSTRAINT DATA TYPE

PATH PRIMARY KEY

NUMBER

PATCH_TIMESTAMP DATE/TIME

project

NAME CONSTRAINT DATA TYPE

ID PRIMARY KEY

AUTONUMBER

CUSTOMER_ID NUMBERCREATE_TIMESTAMP TEXTNAME TEXTNAME_LOWER TEXTDESCRIPTION MEMOBILLING_STATUS YES/NODEFAULT_BILLING_TYPE_ID NUMBER

SYSTEM_PREFS

NAME CONSTRAINT DATA TYPECAL_LAYOUT TEXTDEFAULT_WORKTIME NUMBER

TASK

NAME CONSTRAINT DATA TYPE

ID PRIMARY KEY AUTONUMBER PROJECT_ID NUMBER

79

Page 80: actiTime

ActiTime 2006CREATE_TIMESTAMP DATE/TIMECOMPLETION_DATE DATE/TIMELAST_TT_DATE DATE/TIMENAME TEXTNAME_LOWER TEXTDESCRIPTION MEMODEADLINE_DATE DATE/TIMEBILLING_STATUS YES/NOBILLING_TYPE_ID NUMBER

TT_RECORD

NAME CONSTRAINT DATA TYPE

USER_ID PRIMARY KEY NUMBER TASK_ID PRIMARY KEY NUMBERRECORD_DATE PRIMARY KEY DATE/TIMEACTUALS NUMBER

USER_ACCESS_RIGHT

NAME CONSTRAINT DATA TYPE

USER_ID PRIMARY KEY NUMBER ACCESS_RIGHT_ID PRIMARY KEY NUMBER

USER_TASK

NAME CONSTRAINT DATA TYPE

USER_ID PRIMARY KEY NUMBER TASK_ID PRIMARY KEY NUMBERUSER_TASK_COMMENT

NAME CONSTRAINT DATA TYPE

USER_ID PRIMARY KEY NUMBER TASK_ID PRIMARY KEY NUMBERCOMMENT_DATE PRIMARY KEY DATE/TIMECOMMENTS MEMO

W_DAYS

NAME CONSTRAINT DATA TYPE

W_DATE PRIMARY KEY DATE/TIME 80

Page 81: actiTime

ActiTime 2006

5. INPUT OUTPUT SCREENS

6.SYSTEM TESTING

Testing Fundamentals

Testing is a process, which reveals errors in the program. It is the major quality

measure employed during software development. The testing method varies from

project to project depending on the nature and complexity of the system, working

environment etc. During testing the program is executed with a set of test cases

81

Page 82: actiTime

ActiTime 2006and the output of the program for the test cases is evaluated to determine if the

program is performing as it is expected to.

In order to make sure that the system does not have errors, the different levels of

testing strategies that are applied at different phases of software development. In

the conventional methods White-box testing and Black-box testing are two well-

known methods.

Black-box tests are used to demonstrate that software functions are operational,

that input is properly accepted and output is correctly produced, and that the

integrity of the external information is maintained.

White-box testing of software is predicted on close examination of procedural

detail. Providing test cases that exercise specific sets of conditions and / or loops

tests logical paths through the software.

Testing Levels

There are several levels in testing phase. These are unit testing, integration

testing, system testing and acceptance testing. Initially the tests are focused on

each module individually to test whether it is functioning as a unit.

In conventional applications, unit-testing focuses on the smallest combinable

program unit the sub program (e.g. module, sub routine, procedure, component).

After testing them individually, it is integrated into a program structure and does

the remaining tests.

Unit Testing

The first level of testing is unit testing. When object-oriented software is

considered the concept of unit changes. Rather than testing an individual module,

the smallest testable unit is the encapsulated class or object. Class testing for

object-oriented software is the equivalent of unit testing for conventional

82

Page 83: actiTime

ActiTime 2006software. Unlike unit testing of conventional software, which tends to focus on

the algorithmic detail of a module and the data that flow across the module

interface, class testing for object oriented software is driven by the operations

encapsulated by the class and state behavior of the class.

Integration Testing

This testing is second level in testing process. After completion of unit testing,

which confirms the module's functionality, we integrated modules to form sub

systems. These subsystems are tested under this integration testing. It checks

whether data lost or preserved between interface calls. In this module whether

data flowed properly across the procedures is tested. Modules are integrated by

moving downward through the control hierarchy beginning from the main control

module.

System testing

System testing is responsible to ensure total software is worked as per

requirements specified in requirement documents. The main reference for this

level of testing is requirement document. This goal of this testing is to see,

whether system meets its requirements or not.

Acceptance testing

83

Page 84: actiTime

ActiTime 2006 Acceptance testing was top level testing which tests with some realistic data of

the client to demonstrate that the software is working satisfactory. Testing here

focuses on the external behavior of the system.

Test Case Report

Test case design methods for object-oriented software are still evolving. However

Bernard has defined an overall approach to object-oriented test case design.

1. Each test case should be uniquely identifies and explicitly associated

with the module to be tested.

2. The purpose of the test should be stated.

3. A list of testing steps should be developed for each test and should

contain

i. A list of specified states for the module that is to be tested.

ii. A list of errors that may occur as the module is tested.

Unlike conventional test case design, which is driven by an input-process-output

view of software or the algorithmic detail of individual modules, object-oriented

testing focuses on designing appropriate sequences of operations to exercise the

status of a class.

In this project I have done the class testing with some test data and a test driver

for each class. The system testing is also done. After that the test report is

prepared which gives the actual result obtained for each test case and action taken

for that result.

84

Page 85: actiTime

ActiTime 2006

System testing is performed against the requirements specification documents. In

this by using use case diagrams we can prepare test cases for system testing. For

this test no driver or stub required. Entire system is available for installation.

Before installation system can be performed various tests under system testing.

Under system testing we are selecting the following test cases.

For testing all test cases we have to select the test data. And also develop test

drive. For each test case we gave the input as test data and observe the result.

Actual result is compared with expected result. If both are the same no action is

taken other wise appropriate action is taken for correcting the error.

TesC.No.

Input Expected Behaviour

Observed behaviour

StatusP = PassedF = Failed

1

Enter the Wrong username and password in the Admin Screen

Error should be displayed in the same login screen and redisplay the login form

-do- P

2Enter the Correct username and password in the Admin Screen

Admin Home page should be displayed -do- P

3 Add new user with any name

A New User has to be created -do- P

Add new types of

85

Page 86: actiTime

ActiTime 2006

4billings workingdays and coustomers, projects and Tasks and Reports

Forums has to be created

-do- P

5

Change the Administrator of the actiTime

Administrator has to be changed -do-

P

6Create a normal user with the name sagar and sagar with necessary permistions

It has to validate parameters and create a new administrator

-do- P

7

Create a user bhaskar in the actiTime userand gave permitions

This user has to be created in the actiTime as a Administrator or User

-do- P

8 Login as sagar with correct username and password

Forum Admin Home Page should be displayed with billings workingdays and coustomers, projects and Tasks and Reports

-do- P

9Login as normal bhasker and select the tasks

New time sheet will be created displayed in the user account

-do- P

10

11

Login as another normal user and post the reply

Post a Thread in JSP Forum

Login as Forum

Reply has to be posted

It should not be displayed in the JSP Forum thread list

-do-

-do-

P

P

86

Page 87: actiTime

ActiTime 2006

12

Moderator and accept the thread Now it should be

displayed

-do-P

87

Page 88: actiTime

ActiTime 2006

7.Maintenance and Implementation

Corrective maintenance

This acts to correct errors that are uncovered after the software is in use.

Adaptive Maintenance

This is applied when changes is the external environment precipitate

modifications to software.

Preventive maintenance

This improves future maintainability and reliability and provides basis for

future enhancements

88

Page 89: actiTime

ActiTime 20068. Conclusion

The fundamental problem in managing and maintaining the work by the

administrator is hence overcome. Prior to this it was a bit cumbersome for

maintaining the library and also keeping track of the users who were using it. But

by developing this web-based application the administrator can enjoy the task,

doing it ease and also by saving the valuable time. The amount of time

consumption is reduced and also the manual calculations are omitted, the reports

and bills can be obtained regularly and also whenever on demand by the user. The

effective utilization of the work, by proper sharing it and by providing the

accurate results. The storage facility will ease the job of the operator. Thus the

system developed will be helpful to the administrator by easing his/her task.

Glossary

89

Page 90: actiTime

ActiTime 2006

API ---- Application Programming Interface.

CGI ---- Common Gateway Interface.

DHTML ---- Dynamic Hyper Text Markup Language.

EJB ---- Enterprise Java Beans.

GUI ---- Graphical User Interface .

HTML ---- HyperText Markup Language.

HTTP ---- HyperText Transfer Protocol.

J2EE ---- Java 2 Enterprise Edition.

JDBC ---- Java DataBase Connectivity.

JSP ---- Java Server Pages.

ODBC ---- Open DataBase Connectivity.

SQL ---- Structured Query Language.

URL ---- Uniform Resource Locator.

XHTML ---- Extensible HyperText Markup Language.

XML ---- Extensible Markup Language.

References90

Page 91: actiTime

ActiTime 2006

1. Java Server Programming , J2EE –Wrox Publications -

1. Subramanyam and Allam

Raju

2. Java.2 ,Complete Reference -

i. Herbert Schildt.

3. Java Programming -

Ivon Horton.

4. 4.Servlets - Java Servlet Programming -

a. Reilly , Jason Hunter.

5. Java2 - Sun Micro Systems.

6. Ian Somerville, Principles of Software Engineering, 4 Edition .

7. Roger S. Pressman ,Software Engineering – A Practitioner’s Approach .

8. IEEE, IEEE Software Standards , IEEE Press ,1989 .

9. Patrick Naughton and Herbert Schildt , Complete Reference –Java 2 ,

3 Edition ,Tata McGraw – Hill ,1999.

10. Er. V.K.Jain , Programming Java Server Pages & Servlets.

91