Rhodes University Memorabilia Web Store
Submitted in partial fulfillment of the requirements of the degree Bachelor of Science (Honours) of Rhodes University
(Joint Project) By Farisai Mabvudza Computer Science Department November 2002
Acknowledgements
I have found this year to be enjoyable and rewarding, but this has only been possible due to a number of people. I would like to offer my heartfelt thanks to the following people:
My supervisors, Dr George Wells and Dr Greg Foster for their guidance, help and support during the year – they always kept their doors open for assistance. My team member and dear friend, Uma Rudraraju for her support during the year – the project could not have been done without her input. The Honours class of 2002 for adding excitement to the labs during the sleepless nights spent there! My family for the support they have given me throughout my University years Most importantly of all, God for always being there for me, no matter what.
Abstract
E-Commerce is rapidly finding its way into many businesses worldwide, and such is the nature of the Web that any organization can participate in this new business paradigm. This project aims to investigate the viability and implementation concerns associated with developing an e-commerce application at an institutional level, using Java-based technologies.
The system being investigated consisted of a web-based application modelled on the three-tier client-server architecture using free and low-cost software. The implementation of this project has resulted in a small to medium scaled practical system, which proves that such a system is feasible and affordable to Rhodes University.
Table of Contents
CHAPTER 1 : AN INTRODUCTION TO ELECTRONIC COMMERCE ............................ 1 1.1 What is E-Commerce? ............................................................................................................ 1 1.2 Why Rhodes University Memorabilia? ................................................................................. 2 1.3 Objectives ................................................................................................................................. 2 1.4 Scope ......................................................................................................................................... 3 1.5 Division of Work ...................................................................................................................... 3 1.6 Deliverables .............................................................................................................................. 4 1.7 Report Overview ...................................................................................................................... 4 CHAPTER 2 : THE R.U.M ARCHITECTURE .................................................................. 5 2.1 Description of the Tiers ........................................................................................................... 5 2.2 Reasons for this approach ....................................................................................................... 6 2.3 Other Architectural Options .................................................................................................. 7 2.3.1 Two Tier Architecture ........................................................................................................ 7 2.3.2 N-Tier Architecture ............................................................................................................ 7 2.4 Technologies used in each Tier ............................................................................................... 8 2.4.1 Development and Deployment Options ............................................................................. 8 2.4.2 Java for R.U.M. ................................................................................................................ 10 2.4.3 Hypertext Markup Language (HTML) / Cascading Style Sheets (CSS) ......................... 11 2.4.4 JavaScript ......................................................................................................................... 12 2.4.5 JavaMail ........................................................................................................................... 12 2.4.6 Java Database Connectivity (JDBC) ................................................................................ 12 2.4.7 Java Server Pages (JSP) and Java Beans .......................................................................... 12 CHAPTER 3 : THE CLIENT TIER (FRONT-END) ......................................................... 13 3.1 Responsibilities of the Front-End......................................................................................... 13 3.2 Thin Client Architecture ....................................................................................................... 13 3.3 Page Centric Approach with JavaBeans ............................................................................. 13 3.4 Form Elements ....................................................................................................................... 14 3.5 Front-End Technologies ........................................................................................................ 14 3.5.1 Web Browser .................................................................................................................... 14
3.5.2 Scripting Languages ......................................................................................................... 14 CHAPTER 4 : THE APPLICATION SERVER (MIDDLE-TIER) ..................................... 15 4.1 The Responsibilities of The Middle-Tier ............................................................................. 15 4.1.1 Enforcing the Business Rules ........................................................................................... 15 4.1.2 Fetching and Posting data for the user interface .............................................................. 15 4.2 The Server .............................................................................................................................. 16 4.2.1 The Web Server ................................................................................................................ 16 4.2.2 The Application Server ..................................................................................................... 16 4.2.3 Choosing a server for R.U.M............................................................................................ 17 4.3 Middle-Tier Technologies in Detail ..................................................................................... 17 4.3.2 Apache Tomcat ................................................................................................................. 17 4.3.3 Tomcat and Other Application Servers ............................................................................ 18 4.4 Session Tracking ................................................................................................................. 19 4.4.1 Cookies ............................................................................................................................. 20 4.4.2 URL (Uniform Resource Locator) rewriting .................................................................... 21 4.4.3 Hidden Form Fields .......................................................................................................... 22 4.4.4 The Session Tracking API ................................................................................................ 22 4.5 Java Server Pages (JSP) ........................................................................................................ 22 4.5.1 Overview .......................................................................................................................... 22 4.5.2 JSP Scripting Elements..................................................................................................... 23 4.5.2.1 JSP Expressions ......................................................................................................... 23 4.5.2.2 JSP Scriptlets ............................................................................................................. 24 4.5.2.3 JSP Declarations ........................................................................................................ 25 4.5.3 JSP Directives ................................................................................................................... 25 4.5.3.1 Page Directive............................................................................................................ 25 4.5.3.2 Include Directive ....................................................................................................... 26 4.5.4 JSP Actions ....................................................................................................................... 26 4.5.4.1 Forward...................................................................................................................... 27 4.5.4.2 JSP Bean Tags ........................................................................................................... 27 4.6 The Fundamentals of JavaBeans ......................................................................................... 27 4.6.1 JavaBean Conventions...................................................................................................... 28 4.6.1.1 The JavaBeans API.................................................................................................... 28 4.6.1.2 Beans Are Objects ..................................................................................................... 28 4.6.1.3 Class Naming Conventions ....................................................................................... 29 4.6.1.4 Introspection .............................................................................................................. 29 4.6.2 Using the JavaBeans with JSP .......................................................................................... 29 4.6.2.1 The
tag ............................................................................................. 30 4.6.2.2 The tag ........................................................................................ 31 4.6.2.3 The tag ........................................................................................ 31 4.6.3 An Example From R.U.M. ............................................................................................... 32 4.7 Java Mail ................................................................................................................................ 33
4.8 Security in R.U.M. ................................................................................................................. 35 CHAPTER 5 : THE DATA TIER (BACK-END) .............................................................. 37 5.1 Responsibilities of the Back-End .......................................................................................... 37 5.2 The Database .......................................................................................................................... 37 5.3 Talking to the Database using JDBC ................................................................................... 38 5.3.1 Benefits of JDBC .............................................................................................................. 38 5.3.2 The JDBC API Core Classes ............................................................................................ 38 5.3.3 Using JDBC to Access The R.U.M. Database ................................................................. 40 5.3.4 Types of JDBC Drivers .................................................................................................... 42 5.3.4.1 JDBC-ODBC Bridge ................................................................................................. 42 5.3.4.2 Part Java, Part Native Driver ..................................................................................... 43 5.3.4.3 Intermediate Database Access Server........................................................................ 43 5.3.4.4 Pure Java Drivers ....................................................................................................... 43 5.3.5 Alternatives to JDBC ........................................................................................................ 43 CHAPTER 6 : R.U.M. IMPLEMENTATION.................................................................... 45 6.1 The Middle-Tier – An Overview of the JavaBeans used in RUM..................................... 46 6.1.1 ConnectionBean ............................................................................................................... 46 6.1.2 CountryBean ..................................................................................................................... 46 6.1.3 CustomerBean .................................................................................................................. 46 6.1.4 EmailBean ........................................................................................................................ 47 6.1.5 OrderBean ......................................................................................................................... 47 6.1.6 ShoppingCart .................................................................................................................... 47 6.1.7 ProductBean ..................................................................................................................... 47 6.1.8 ProductDisplay ................................................................................................................. 47 6.1.9 SearchBean ....................................................................................................................... 48 6.1.10 Result .............................................................................................................................. 48 6.1.11 ValidationBean ............................................................................................................... 48 6.1.12 The Property Sheet ......................................................................................................... 48 6.2 Implementing the JavaBeans................................................................................................ 49 6.2.1 The Welcome page ........................................................................................................... 49 6.2.2 Logging Into R.U.M. ........................................................................................................ 50 6.2.3 Registering as a new User ................................................................................................ 50 6.2.3.1 Connecting to the Database ....................................................................................... 50 6.2.3.2 Validating the Form ................................................................................................... 51 6.2.3.3 Sending the E-mails ................................................................................................... 53 6.2.4 Existing user logging into R.U.M..................................................................................... 54 6.2.5 Forgotten Password .......................................................................................................... 55 6.2 The Products Pages ............................................................................................................... 56 6.2.6 The Product Category Pages ............................................................................................ 56 6.2.7 Checkout Process – Shipping Details ............................................................................... 61 6.2.8 Checkout Process - Delivery Costs .................................................................................. 61
6.2.9 Checkout Process - Payment Details ................................................................................ 63 6.2.10 Checkout Process - Confirmation ................................................................................... 63 6.3 Database Implementation ..................................................................................................... 64 6.4 Implementation Problems ..................................................................................................... 65 CHAPTER 7 : CONCLUSION ........................................................................................ 67 7.1 Overview ................................................................................................................................. 67 7.2 The Future .............................................................................................................................. 67 7.2.1 Automatic Stock Control .................................................................................................. 67 7.2.2 Connection Pooling .......................................................................................................... 68 7.2.3 Improved Credit Card Validation ..................................................................................... 68 7.2.4 Dynamic recommendations .............................................................................................. 68 REFERENCES ............................................................................................................... 69 APPENDIX A: R.U.M.’S FILE HIERARCHY .................................................................. 73 APPENDIX B: INSTALLING AND CONFIGURING R.U.M. UNDER WINDOWS .......... 74 1. Copying the Files ................................................................................................................... 74 2. Setting up the Environment Variables ................................................................................ 75 3. Configuring RUM .................................................................................................................. 75 APPENDIX C: GLOSSARY ........................................................................................... 77 APPENDIX D : PROJECT POSTER .............................................................................. 83
Chapter 1 : An Introduction to Electronic Commerce
1.1 What is E-Commerce? E-Commerce (electronic commerce) may be defined, by Joseph (2000), as the practice of buying and selling products and services over the Internet, utilizing technologies such as the Web, electronic data interchange, e-mail, electronic fund transfers, and smart cards. In recent years, ecommerce has exploded, and future trends indicate that more and more businesses will connect themselves to the Internet. It is now becoming imperative for some organizations to engage in ecommerce in order to remain competitive.
There are various reasons why e-commerce is making an impact on the computing world. Businesses have realised that there are lower start-up and overhead expenses. Running costs are also quite low since the order processing is automated and there is no need to employ people to take care of this. Before the advent of e-commerce, businesses were often restricted and
expansion was difficult. Since the Internet is accessible from almost anywhere on the planet, businesses can have global exposure. Businesses can also advertise thousands of products
without incurring huge costs. It is clear that the low cost factor plays a major role in inspiring organizations to travel the e-commerce route.
The consumer also reaps numerous benefits from e-commerce. Customers can shop whenever they want, from the comfort of their homes and there is no need for them to even leave their houses. All the hassles of driving to the store, finding parking and hunting for products, are eliminated. After placing their orders, the customer can then sit back and wait until their goods are delivered to their doorstep.
Despite the many advantages of e-commerce, many e-businesses found themselves failing. Many of them over-rated the Internet revolution and made misjudgements about the purchasing habits over the Internet, in its current state. This does not mean that there is no future for e-commerce, for only its growth was slowed down momentarily. According to Nayzak Communications (2002), there is still a bright future ahead for e-commerce. Once the details of online commerce are worked out, it and the Internet in general could reshape the structure of the business world.
1
1.2 Why Rhodes University Memorabilia? The sale of Rhodes University Memorabilia is currently paper-based – old Rhodians are sent brochures describing the products available and their respective prices. The alumni can then order the memorabilia by completing the supplied forms and then mailing it to the Alumni Department, which then processes the order and sends the goods. This system has been in place for a good number of years, but as with any manual based system, there are problems. The time period, between the order being mailed and the order being received by the department, can be large. For instance, an order from the United States could take as much as four weeks to reach the department. These time delays are likely to put off potential customers, and of course, there is always the chance that the order may get lost on the way and never reach Rhodes. Security is also a major issue, as it is possible for the customer‟s order to be intercepted, and their credit card details to be stolen. In addition, a significant number of leavers change their addresses and do not inform the Alumni department of this. This means that there is little chance of them receiving the brochures in the first place.
These problems can be solved by harnessing the power of the Internet and e-commerce. Most graduates from the University are likely to have Internet access regardless of their location. An online shop to sell the memorabilia would be an ideal addition to the existing system. The alumni can then view and order products wherever they are, using their web browsers. They will have peace of mind, knowing that their details have been transmitted securely, and that their order will definitely have reached the University.
1.3 Objectives The primary objective of this project is to deliver this online store. This will involve an
investigation into Java Server Page (JSP) technology and how it can aid web designers to rapidly develop and easily maintain, information-rich, dynamic web pages. Throughout this document the system, known as Rhodes University Memorabilia, will be referred to with the acronym R.U.M.
2
1.4 Scope Since this project can be classified as a small to medium-scale e-commerce endeavour, the developers have investigated and implemented the vital features for the successful operation of an e-commerce website. The developers have not delved into issues such as using purchasing habits in order to target certain products at customers and stock control. It is felt that such large features would not be applicable to a small institution such as Rhodes and would add inconveniences for the maintainers of the system. However, these features have been considered as possible
extensions to the project. Please refer to Section 7.2 for more details.
1.5 Division of Work Since this project is a small to medium-scale endeavour, it has been undertaken by two people, one of them being the author. The task has been considered too big for a single individual to handle in the time allotted. The tasks were fairly divisible and this meant that two major parts of the project had been worked on concurrently. The task was quite complex and for this reason it was thought that different team members would contribute different knowledge and skills. Furthermore, the real world also requires projects of this nature to be undertaken by teams. The division of the work for the project is highlighted below. The reader should be aware that some of the sections of work have overlapped and so a clear division of work could not be shown.
The Author (Farisai Mabvudza) – Back End Database setup and validation. Linking the RUM interface to database using Java Database Connectivity (JDBC) and the Tomcat web server. Implementation of security features into RUM. Product search engine. Development of the supporting JavaBeans for the above tasks. Documentation for the above mentioned tasks of the project.
3
Team Member (Uma Rudraraju) - Front End Development of RUM user interface using Hyper-Text Markup Language (HTML), Cascading Style Sheets (CSS), JavaScript and Java Server Pages (JSP). Form Validation and Error Handling. Context sensitive help system. Development of the supporting JavaBeans for the above tasks. Documentation for the above mentioned tasks of the project.
1.6 Deliverables The investigation has resulted in this report as well as a practical system, which the University can implement for the use of old Rhodians, as well as existing students. R.U.M. allows its users to browse the range of memorabilia that Rhodes has to offer, interacting with the system using their web browser software. Before they can actually buy anything, they need to create an account by registering with the web shop. At any point, the customer can modify his account details. Once they are registered, they can run through the checkout process to complete their orders. The order information is then e-mailed to the Alumni department for processing.
1.7 Report Overview
The report is structured as follows: Chapter 2 “The R.U.M. Architecture” discusses the architecture used in the R.U.M. system as well as the technologies which have been used. Chapter 3 “The Client Tier (Front-End)” gives an overview of the first tier of the system, being the Client Tier. Similarly Chapter 4 “The Application Server (Middle Tier)” explores the middletier, and Chapter 5 The Data Tier (Back-End)” explores the back end of the system. Chapter 6 “R.U.M. Implementation” describes how the author implemented the R.U.M. system. It is designed to help future developers to build a website similar to R.U.M. Finally Chapter 7 “Conclusion” concludes the thesis and highlights how the project can be extended in the future. 4
Chapter 2 : The R.U.M Architecture
(3) Web Tier
(1) Client Tier
(4) Data Tier (2) Business Tier
Figure 2-1: Three-tiered Client-Server Architecture [Adapted from Sun Microsystems, 2002]
It has been decided by the developers to use a three-tiered Client-Server architecture for R.U.M. as illustrated in Figure 2-1 above. The main components of the tiers are described briefly below, with reference to Figure 2-1:
2.1 Description of the Tiers The Client Tier (1) of the system, sometimes known as the Front-end is responsible for the rendering of web pages to the client, which in this case would be a web browser such as Internet Explorer or Netscape Communicator.
The Application Server Tier (Middle Tier) of the system is usually sub-divided into the Business Tier (2) and the Web Tier (3), although they may appear to be separate tiers. The Business Tier retrieves data from the database and processes it if necessarily before delivering it to the Web Tier. The Business Tier then sends the data to the Web Tier, which dynamically generates the
5
HTML page for display by the Front-end. The data for the Business Tier, which could either be Customer data or Product data, is supplied by the Data Tier (4). The Data tier stores the data in a Microsoft Access Database. The data is read and/or modified using SQL queries. Each of the three tiers is discussed in great detail in Chapters 2, 3 and 4.
2.2 Reasons for this approach By breaking down R.U.M. into three distinct and separate tiers, advantages were gained in several areas. Marston (2002) suggests several advantages: Scalability and deployment flexibility - component roles are specialized, improving maintainability, networking, and Input/Output (I/O) overheads. An application constructed using the three-tier software architecture is an ideal candidate for being deployed on three layers of hardware. For R.U.M. this meant that the Back-end could be stored on one machine, the Middle Tier stored on another machine, and the customers would access the system using the Front-end on their own machines Component roles are also clearly defined within a three-tier framework. This provides a good basis for component-based development and reusability. Components in the business layer can be shared by any number of components in the presentation layer. Chapters 3 and 6 contain detailed descriptions of the components which ended up being shared and reused in R.U.M. Infrastructure independence is enhanced by the use of a 3-tier architecture. This is because presentation and data access - areas that are often infrastructure-dependent are separated from the application's business logic. A specific set of skills is required for the development of each tier This meant that the tiers could be developed independently of each other. The author could then concentrate on developing the Back-end and Middle Tier of the system without being affected by developments in the Front-end.
6
2.3 Other Architectural Options 2.3.1 Two Tier Architecture Request
CLIENT
Response
SERVER
Figure 2-2 : The Two-Tier Architecture
The two-tier architecture consists of two computers as shown in Figure 2-2 - a client and a server, with areas of logic combined on the client. The components comprise of presentation, processing, and data which are divided among two software entities or tiers, client application code and database server. Presentation is handled exclusively by the client while processing is split between client and server. The data for the system is stored on and accessed through the server. Communication between the components is fairly simple – the client sends a request to the server. The server simply processes the request and sends the results back to the client over the network. Such an architecture was clearly not suitable for R.U.M as it has limitations which would have made the implementation of R.U.M. difficult, if not impossible. Users of R.U.M. would have to install a program on their computers. If there were any upgrade to the system as a whole, then each user would have to download the upgrade for their client program. Small changes to the application would require a complete rollout of the “R.U.M. Client”. 2.3.2 N-Tier Architecture N-Tier architectures are similar to three-tier architectures. According to Poulton (2002) N-tier architectures, however, solve some problems inherent in the three-tier architecture. Many
applications are likely to share application objects, and so the middle tier from the three-tier system would be extended to support these shared objects. These objects will have a common interface, which allows them to communicate and work together. 7
At first glance, this approach would appear to be ideal for a system such as R.U.M. However, there are a number of reasons why the N-tier architecture was not adopted. With N-tier
architectures, there is quite a steep learning curve. It also takes time to learn how to use a new Application Program Interface (API) [www.javaworld.com]. Secondly, a quality web server which supports the N-tier model, such as BEA's Weblogic or IBM's WebSphere, can easily cost tens of thousands of Rands and would not be worth it in the long run, especially for a system like R.U.M. In addition, there are also some architectural issues, which need to be considered. It is fairly difficult to make objects reusable – the design and implementation effort put into making the objects reusable could be used on other aspects of the system. The complexity of the system would increase and would be more prone to bugs. Distributed web applications are also
notoriously slow due to the slowness of the protocols themselves. Finally, in an n-tier system, load balancing is difficult. In a three-tier architecture, if the number of users accessing the system increases, then additional servers can be introduced. This is known as load balancing. However with an n-tier system, the objects would reside on many different machines, and it would be difficult to pinpoint the machine, which needs load balancing. 2.4 Technologies used in each Tier 2.4.1 Development and Deployment Options The developers of R.U.M. had two major choices of deployment environments being Java and Microsoft .NET. Java 2 Enterprise Edition (J2EE), as described by Poulton (2002), is essentially a collection of specifications for web services, business objects, data access, and messaging. This collection of APIs is provided to define the way in which web applications communicate with the servers, which host them. J2EE primarily focuses on making web applications portable. This means that the web applications can run on any server regardless of its hardware or operating system. Oberg (2002) defines Microsoft‟s .NET initiative as a set of tools, which “address issues of application development and delivery in both the PC and web domains”. It draws on some of the best ideas in the industry, including Java, XML and Microsoft‟s own Component Object Model
8
(COM). The key differences between these two technologies are outlined in Table 2-1 below taken and adapted from Farley (2000): Microsoft.NET J2EE Key Differences
C# and Java both derive from C and C++. Most significant features (e.g., garbage collection, hierarchical namespaces) are present in both. C# borrows some of the component concepts from JavaBeans (properties/attributes, events, etc.), adds some of its own (like metadata tags), but incorporates these features into the syntax differently. C# programming language Java programming language Java runs on any platform with a Java Virtual Machine. C# only runs in Windows for the foreseeable future. C# is implicitly tied into the IL common language runtime (see below), and is run as just-in-time (JIT) compiled bytecodes or compiled entirely into native code. Java code runs as Java Virtual Machine (VT) bytecodes that are either interpreted in the VM or JIT compiled, or can be compiled entirely into native code. High-level .NET components will include support for distributed access using XML and SOAP (see ADO.NET below). ASP.NET uses Visual Basic, C#, and other languages for code snippets. All get compiled into native code through the common language runtime (as opposed to being interpreted each time, like ASPs). JSPs use Java code (snippets, or JavaBean references), compiled into Java bytecodes (either on-demand or batchcompiled, depending on the JSP implementation). NET common language runtime allows code in multiple languages to use a shared set of components, on Windows. Underlies nearly all of .NET framework (common components, ASP.NET, etc.). Java's Virtual Machine spec allows Java bytecodes to run on any platform with a compliant JVM. CORBA allows code in multiple languages to use a shared set of objects, on any platform with an ORB available. Not nearly as tightly integrated into J2EE framework. Similar web components (e.g., based on JSP) not available in Java standard platform, some proprietary components available through Java IDEs, etc. Win Forms Forms and Web Java Swing Win Forms and Web Forms RAD development supported through the MS Visual Studio IDE - no other IDE support announced at this writing. Swing support available in many Java IDEs and tools. ADO+ is built on the premise of XML data interchange (between remote data objects and layers of multi-tier apps) on top of HTTP (AKA, SOAP). .NET's web services in general assume SOAP messaging models. EJB, JDBC, etc. leave the data interchange protocol at the developer's discretion, and operate on top of either HTTP, RMI/JRMP or IIOP.
NET common components (also known as the ".NET Framework SDK")
Java core API
Active Server (ASP.NET)
Pages+
Java ServerPages (JSP)
IL Common Runtime
Language
Java Virtual Machine and CORBA IDL and ORB
ADO.NET and SOAPbased Web Services
JDBC, EJB, JMS and Java XML Libraries (XML4J, JAXP)
9
Table 2-1: J2EE vs. Microsoft .NET
2.4.2 Java for R.U.M. In light of the features of Java mentioned in Table 2-1, the developers have decided to use the Java environment for the development and deployment of R.U.M. In addition, Java has
numerous features which can be taken advantage of, when developing an e-commerce application such as R.U.M. The benefits that are applicable to R.U.M. are summarized briefly below: [Naughton and Schildt, 1999] Simple Java was designed to be easy for professional programmers to learn and use effectively. This meant that the creation of R.U.M. was done fairly quickly and efficiently. Object Oriented Java has borrowed liberally from many seminal object-software environments of the last few decades. The object model in Java is simple and easy to extend, while primitive types such as integers are retained as non-objects with a high performance. This allowed the developers to visualize the components of the system in a simple way and helped the coding to be done quickly and easily. Robust The multi-platformed environment of the Internet places significant demands on a program. For this reason, the ability to create robust programs was given high priority in the design of Java. An e-commerce application such as R.U.M. needs to execute reliably on a variety of systems – there is no room for system crashes due to unreliable software. Distributed
10
Java has been designed for the distributed environment of the Internet, because it can handle the common network protocols. This simplified the development of R.U.M. since it inevitably involved the use of network protocols to communicate. Multithreaded An e-commerce application has to be able to handle simultaneous requests as well as respond to several users simultaneously. This is known as multithreading. Because Java supports multithreaded programming, it was the ideal language for use in R.U.M. Architecture-Neutral Before the arrival of Java, there was no guarantee that programs written to run on today‟s computers would run on tomorrow‟s computers. Operating system upgrades and
processor upgrades could all combine to make a program malfunction. Using Java for R.U.M. ensures that even if Rhodes should upgrade their existing hardware and/or software, R.U.M. will still operate on that new system. Portability Many types of computers and operating systems are in use throughout the world. It is likely that the Alumni department may wish to run the system on a different machine such as Linux. Java programs are compiled into byte code and this byte code will run under any system, which has a Java Virtual Machine (JVM) installed and running. Since most computers nowadays have this JVM installed, R.U.M. can be ported to any machine regardless of the operating system. 2.4.3 Hypertext Markup Language (HTML) / Cascading Style Sheets (CSS) To publish information for global distribution, a universally understood language is needed. The publishing language used by the World Wide Web is HTML (Hypertext Mark-up Language). This was used for the development of the Front-end of R.U.M. and is discussed in the other team member‟s report.
11
Cascading Style Sheets (CSS) is a mechanism for adding style (for example, fonts, colours and spacing) to Web documents. It is merely an extension to HTML and was used to add
enhancement to the online help system of R.U.M.
2.4.4 JavaScript JavaScript is a scripting language, which is similar to Java. Developed by Netscape, it carries with it a smaller command set and a much simpler structure, though it remains an Object Oriented Programming Language (OOP). It was used to add dynamic content to R.U.M. in the Front-end and is also detailed in the other team member‟s report. 2.4.5 JavaMail JavaMail provides a set of APIs and provider implementations, which allow for the development of fully functional e-mail applications. These applications can read, compose and send e-mails. This technology is discussed further in Chapter 5 2.4.6 Java Database Connectivity (JDBC) JDBC technology is an API that allows developers to create Java programs, which can access virtually any tabular data source. JDBC was used extensively in the back-end of R.U.M. and allowed the middle-tier to access a Microsoft Access Database. 2.4.7 Java Server Pages (JSP) and Java Beans Java Server Pages (JSP) is a Sun Microsystems specification for combining Java with HTML to provide dynamic content for Web pages. When a web designer creates dynamic content, JSPs are more convenient to write than HTTP servlets because they allow him to embed Java code directly into his HTML pages, in contrast with HTTP servlets, in which HTML is embedded inside Java code. JSP is part of the J2EE, and is also supported by Apache Tomcat. JSP was used for the dynamic content in many of the R.U.M. web pages.
12
Chapter 3 : The Client Tier (Front-End)
3.1 Responsibilities of the Front-End The Front-end is responsible for providing services that an application needs to allow the user to view and manipulate it. Fields & Kolb (2000) state that the Front-end can be thought of as the user interface because it is used to get input from the end user and display the application‟s results. The Front-end is not concerned with the details of how the information was obtained or where it came from. It is only responsible for displaying information and passing any activity up the chain to the other tiers. In R.U.M. the development of the Front-end was undertaken by the author‟s team member, so it will not be discussed in detail. The author will only briefly describe the features of the Front-end of R.U.M.
3.2 Thin Client Architecture A thin client option is described by Poulton (2002) as one where the application and data exist server, while the client simply uses a generic presentation application in the form of a web browser. In contrast, in a thick client model, most, if not all the processing is done on the client machine and the client must download software (e.g. Java applets), in order to access the system. Maintenance is a problem because any changes in the server side software will usually require the client side software to be changed as well. Therefore R.U.M. has made use of the thin client model to avoid the issues associated with the thick client option.
3.3 Page Centric Approach with JavaBeans R.U.M. has been designed so that there was a series of interrelated JSP pages where the user could proceed from one page to another. The JSP pages accessed resources, such as the database, with the assistance of JavaBeans. The Page Centric Approach was chosen over the Servlet Centric approach, which would have involved the use of servlets of to send the required page to the user; the servlet acting is a controller for the whole application.
13
3.4 Form Elements HTML Form elements have been used in R.U.M. These form elements include text boxes, text areas, selection lists, combination boxes and buttons. They are created using static HTML tags. This was considered to be the ideal method of displaying forms, as opposed to applets, because again, no software needs to be downloaded onto the client machine; the user‟s web browser is more than adequate.
3.5 Front-End Technologies 3.5.1 Web Browser R.U.M. has been designed and tested to run well under Microsoft Internet Explorer 6.0. It was also tested under Netscape Communicator 4.7x, and although there are slight visual discrepancies, the web shop is still completely useable. 3.5.2 Scripting Languages The Front-end of R.U.M. was constructed using mainly HTML code for the static content and the visual output, which was generated by the HTML, was enhanced by using CSS. The dynamic content was generated by JavaBeans and Java Server Pages. These two technologies are
discussed in depth in Chapter 3. Finally JavaScript was used for limited client side validation in R.U.M, as well as for some special effects, such as the fading product display on the front page.
14
Chapter 4 : The Application Server (Middle-Tier)
4.1 The Responsibilities of The Middle-Tier As mentioned earlier, the middle-tier consists of server-side business application logic components. Booth brings to light the fact that the responsibilities of these objects vary widely. Functions such as the enforcement of business rules, separation of the user interface and the database source, and providing a single data access layer for multiple divergent database servers are amongst the possible responsibilities. The design of the system will have a strong influence on the actual functions, which are provided by the middle-tier object. Two of the functions will now be outlined below briefly. 4.1.1 Enforcing the Business Rules Booth highlights the fact that in many database systems there are sets of rules, which determine whether data is valid, or not. Such rules can be divided into two types, mainly domain
constraints and business rules. A domain describes all of the possible values that an entity or an attribute can have. For instance, in R.U.M. the domain for the country field includes all of the countries in the world. Business rules are a subset of a domain. Business rules place further restrictions on the possible values for a domain. For example if R.U.M. was only serving people residing in South Africa, then the domain for the city field would encompass all the cities of the world, but the business rules would restrict the field to only the cities within South Africa. The Middle-Tier business tier objects of R.U.M. have been considered to be the most ideal candidates to enforce the business rules. This is because a database like Microsoft Access is likely to be over-restrictive if the validation rules were enforced there. 4.1.2 Fetching and Posting data for the user interface As mentioned in Chapter 2, in the three-tier design, the user interface is separated from the data source by the middle-tier. There is thus a need for some sort of mechanism to retrieve the data from the database so that the Front-end can use it. There is a middle-tier object, which performs the role of translating the data from the format found in Microsoft Access to a format that can be used by the user interface. It also works the other way round, and translates data from the user 15
interface into a form, which can be stored in the database. Using this design approach ensured that any changes to the database would only require minor enhancements to the middle-tier, and any changes to the user interface would require the middle-tier to be enhanced. 4.2 The Server There are two main types of servers, which can reside in the middle-tier – an application server and a web server. There is often confusion regarding the functions of each type of server. Sintes (2002) reckons that “a Web Server exclusively handles HTTP (Hyper-text Transfer Protocol) requests, whereas an application server serves business logic to application program through any number of protocols”. Each will now be examined in more detail: 4.2.1 The Web Server When a web server receives a request for a web page (via HTTP), it responds with an HTTP response in the form of an HTML page. The response may also be an image or a page redirect. The Web server may even delegate dynamic response generation to some other program - in the case of R.U.M. dynamic responses are handled by JSP. A web server‟s delegation model is fairly simple. When the web server receives, a request, it simply passes this request to a program, which can handle it. The web server does not provide any functionality besides providing an environment in which the server-side program (JSP) can execute and pass back the relevant response. While a web server may not itself, support
transaction management or connection pooling, it can employ certain strategies for fault tolerance and scalability such as load balancing, caching, and clustering. erroneously associated with application servers only. 4.2.2 The Application Server An application server exposes business logic to client applications through various protocols, including HTTP. The application program can then use this logic just as if it were calling a method on an object. Examples of application clients can include GUIs (graphical user These features are often
interfaces) running on a workstation, a Web server, or even other application clients. The data travelling between the application server and the client is not just display information as is the case with a Web server. Instead, the data contains the program logic.
16
In many cases, the business logic is exposed through a component API such as the EJB (Enterprise Java Bean) component model found on J2EE application servers. In addition, the application server is capable of managing its resources. Such functions would include security, transaction processing, resource pooling and messaging. The application server is also able to it employ strategies for fault tolerance and scalability, similar to a web server. 4.2.3 Choosing a server for R.U.M. The developers of R.U.M. had to choose whether to use a web server, application server, or both. It was decided that both a web server and an application server would be the best choice for R.U.M. This is because the R.U.M. middle-tier serves web pages in addition to handling
business logic. The middle-tier takes care of transaction processing, e-mailing users and security among other things. Apache Tomcat was chosen as the server because it adequately meets the needs of a system as complex as R.U.M. Apache Tomcat will be discussed in detail below. 4.3 Middle-Tier Technologies in Detail 4.3.2 Apache Tomcat According to Bollinger & Natarajan (1999), the Apache Software Foundation supports Java Server Pages with the mission “to provide commercial-quality server solutions based on the Java Platform.” Apache Tomcat is the official JavaSoft-endorsed reference implementation for the Servlet 2.2 and JSP 1.1 specifications. To support JSP, a special component present in Tomcat was needed – the JSP container. Bollinger & Natarajan define containers as special Java classes to which the Web server directs HTTP requests when the resource requested is a servlet or a JSP page. Such containers manage one or more Java Virtual Machines (JVMs) to execute the servlets and Java Server Pages. The Tomcat containers support both stand-alone and hybrid configurations. A stand-alone
configuration is one where the container can also perform the functions of a web server such as Apache or Microsoft‟s Internet Information Services (IIS), while a hybrid configuration is one where the container runs alongside the web server. Bollinger & Natarajan emphasise that Web servers are best suited to handling static resources such as HTML, while servlet and JSP containers handle servlets and Java Server Pages best. This implies that the hybrid configuration is able to improve response times and scalability.
17
R.U.M. has been deployed on Tomcat as a stand-alone system. The developers have felt that while a hybrid configuration would perform better than a stand-alone configuration, such additional features would not benefit a system, which attracts low volumes of traffic, such as R.U.M. If the need to improve response time arises, then industrial-strength servers can be installed and configured, but that is beyond the scope of this investigation. 4.3.3 Tomcat and Other Application Servers The developers had numerous options with regards to choosing a web/application server. Tomcat was chosen because it is free, supports JSP, and has detailed documentation available from third parties. It was also found that the most commonly used Java application server execution environment today is Tomcat, according to BZ Research‟s latest Java Awareness Study [Zeichick, 2002], conducted in August 2002. In the study, 52.2 percent of all respondents said Tomcat was currently in use at their companies. Table 4-1 shows the percentages pertaining to the other Java application servers. Java Application Server
Apache Tomcat IBM WebSphere BEA WebLogic Oracle‟s Oracle9iAS Macromedia JRun JBoss Sun ONE app server (iPlanet), Borland AppServer/Enterprise Server
Percentage
52.2% 29% 24.4% 20.8% 14.7% 13.9% 11.8% 9.4%
Table 4-1: Popular Java application server execution environments
The survey also found that ease of use and standards compliance were the most important features, which a Java application server execution environment needs to exhibit. In addition Schultz (2001) provided Table 4-2, showing how Apache Tomcat compared with JRun and JServ:
18
Product
Pros
Free Active open-source development effort Very current in terms of servlet API compliance Free for development purposes Relatively speedy Supported by Allaire (Macromedia)
Cons
Not the fastest implementation on the planet Poor support from Apache themselves
Apache Tomcat
JRun
Costs money for production use Versions before 3.0 had numerous configuration headaches Slightly behind the times with updates (compared to open source projects) No longer in active development (Tomcat inherited this effort) Has some thread-leaking issues Only supports servlet API 2.0 (not later) Poor support
Free
Apache JServ
Table 4-2: Apache Tomcat compared with other web servers
The author considered the above pros and cons of Tomcat as well as the fact that numerous companies, which are pursuing the Java route, use Apache Tomcat, and concluded that Tomcat is well suited to real-world applications such as R.U.M. 4.4 Session Tracking Poulton (2002) classifies communication between a client and a web server as being either stateless or stateful. The key difference between the two is the nature of the connection. HTTP is inherently a stateless protocol. This means that the web server knows nothing about what the client is doing. In the case of R.U.M. this would mean that the server would not be able to keep track of shopping carts, for example. This can be extremely problematic – when a customer adds products to their shopping cart, the server would not know about what was already in the cart. Worse still, browsing through another page, such as one of the products pages, would cause the contents of the shopping cart to be lost. Hall (1999) highlights four typical solutions to this problem:
19
4.4.1 Cookies HTTP cookies can be used to store information about a shopping session. Cookies are small text files, which are stored on the client machine and maintained by the web browser software. The text files can contain information about the customer‟s session. According to Mayer-Schönberger (2002), cookies are based on a two-stage process. First the cookie is stored on the client machine without their consent or knowledge. For example, with customisable Web search engines like My Yahoo!, a user selects categories of interest from the web page. The Web server then creates a specific cookie, and then transmits this cookie to the client machine. The user's web browser receives the cookie and then stores it in a special file called a cookie list. With each subsequent connection the server can request for the information stored on the client, and the client‟s browser will transmit it to the server. Servlets and JSP have a high-level and easy-to-use interface for cookies, but there are a number of relatively tedious details that need to be handled: Extracting the cookie that stores the session identifier from the other cookies, Setting an appropriate expiration time for the cookie (sessions interrupted by 24 hours probably should be reset), and Associating information on the server with the session identifier (there may be far too much information to actually store it in the cookie, plus sensitive data like credit card numbers should never be stored in cookies). Cookies were not used in R.U.M. for the following reasons: Cookies can be controlled by programming a low-level API, which is more difficult to implement than some other approaches. This would have made the development of R.U.M. difficult and cumbersome, All data relating to a session is stored on the client machine. Corruption, expiration or purging of cookie files can all result in incomplete, inconsistent, or missing information, Cookies may not be available for many reasons: the user may have disabled them (due to privacy issues), the browser version may not support them, or the browser may be behind a firewall that filters cookies. Servlets and JSP pages that rely exclusively on cookies for client-side session state will not operate properly for all clients. Automatically detecting 20
whether cookies are enabled would have created unnecessary programming headaches for the developers, Historically, cookie implementations in both browsers and servers have tended to be buggy, and/or vary in their conformance to standards. While the developer may have direct control of the web servers, buggy or non-conformant browser versions are still in use by many people, and Browser instances share cookies, so users cannot have multiple simultaneous sessions. [Sun Microsystems, 2001] 4.4.2 URL (Uniform Resource Locator) rewriting It is possible to append extra data, to the end of each URL, which identifies the session. An example of URL rewriting is shown below:
http://www.somehost.com/somefile.html?s=34324324324324
The example shows a unique session identifier being appended to a URL request. The server can then read this data and can associate that session identifier with data it has stored about that session. This solution avoids the problems associated with cookies – it works with browsers that do not support cookies, or browsers which have cookies disabled. URL rewriting also allows multiple simultaneous sessions for a user. This is because session information is local to each browser instance. Each web page in the system will need to have dynamically generated links (i.e. the session state will need to be appended to each link). URL rewriting was not used for R.U.M. because every page would need code to extract the session ID from the URL. Furthermore, this session ID would have to be appended to every link and that would have been extremely cumbersome.
21
4.4.3 Hidden Form Fields Poulton (2002) highlights the fact that HTML defines a HIDDEN form element, which is not rendered by the browser. Such elements are submitted along with the other visible form elements, when the user clicks the „SUBMIT‟ button on the form. The JSP page or Servlet which processes the form can then read the value of the hidden form field and process it accordingly. Similar to URL rewriting, each hidden form element needs to be dynamically generated. Thus to maintain the session, the session ID is included as one of the hidden form fields. The use of hidden form fields for session tracking would require that every page in the system be dynamically generated. Since not all of R.U.M.‟s pages are dynamic, the developers have opted not to use this method of session tracking. 4.4.4 The Session Tracking API Java provides an HttpSession API which allows for session tracking with Servlets and JSP. This means that Servlets and JSP pages have built-in session tracking capabilities. The Session Tracking API, as we call the portion of the Servlet API devoted to session tracking, should be supported in any web server that supports Servlets, such as Apache Tomcat. When a user accesses R.U.M. a session object is created for them. This session object can be examined and manipulated by all the JSP pages in the system. There is no need to manipulate cookies or information appended to the URL. In R.U.M. session tracking is done using Session Beans. For example, customer information is stored in a Session Bean known as CustomerBean. Session Beans are placed into the user‟s session object and are hence accessible from any page in the system. Session Beans effectively eliminate the problems inherent in URL rewriting, Hidden Form Fields and Cookies. 4.5 Java Server Pages (JSP) 4.5.1 Overview As mentioned in Chapter 2, Java Server Pages allows web designers to separate the dynamic contents of their pages from the static HTML. According to Hall (1999), the designer simply has to write the regular HTML in the normal manner, either by hand or using a web design tool. The code for the dynamic content is enclosed using special tags usually starting with “<%” and ending
22
with “%>”. For example, a code snippet from R.U.M. is shown in Listing 4-1, which welcomes the customer who is currently logged in. The JSP code is in bold.
Welcome <%=customer.getfstname()%>! Please click on the above tabs to begin your shopping experience. If you are not <%=customer.getfstname()%> then please click here.
Listing 4-1 : Welcome page logic The files containing the code are usually given a .jsp extension. Although what is written often appears like regular HTML, behind the scenes, the JSP page is converted to a servlet by the JSP container in Apache Tomcat. This conversion process is quite time consuming and, thus, is only done the first time the page is requested, or if any changes are made to the code. Aside from regular HTML, there are three main types of JSP constructs that can be embedded in a page – scripting elements, directives and actions. 1. Scripting elements allow the designer to specify Java code which will become part of the resultant servlet, 2. Directives allow the designer to control the overall structure of the servlet, and 3. Actions allow the designer to specify existing components that should be used, and otherwise control the behaviour of the JSP engine. 4.5.2 JSP Scripting Elements Hall emphasises that scripting elements allow Java code to be inserted into the servlet that will be generated from the current JSP page. There are three types of elements, being expressions, scriptlets and declarations and are detailed below: 4.5.2.1 JSP Expressions A JSP expression is used to insert Java values directly into the output. It has the following format:
<%= Java Expression %>
23
The Java expression is evaluated, converted to a string, and subsequently inserted into the web page. The evaluation is performed at run-time (i.e. when the page is requested), and thus has full access to information about the request. The following code snippet shows the date and time that the page was requested:
Current time: <%= new java.util.Date() %>
4.5.2.2 JSP Scriptlets JSP scriptlets allow the designer to do more complex tasks than simple expressions. JSP
scriptlets let the designer insert arbitrary code into the servlet method that will be built to generate the page. Scriptlets have the following form:
<% Java Code %>
Hall emphasizes that scriptlets have access to the same automatically defined variables as expressions. He also notes that code inside a scriptlet gets inserted exactly as written and any HTML text before or after a scriptlet gets converted to the appropriate servlet code. The code fragment in Listing 4-2, taken from R.U.M., illustrates a mixture of static HTML and scriptlets:
<% if (!customer.getloggedin()) { %> A warm welcome to all our Rhodents! Rhodes University would like to thank
you for visiting RUM. We hope this website will provide you with a pleasant shopping experience. We are continually adding new items to our stock; please bookmark this page and visit us regularly for the latest product information. We always strive to update and improve the RUM webpage. Any suggestions and comments are welcomed!
<% } else { %> Welcome <%=customer.getfstname()%>! Please click on the above tabs to begin your shopping experience. If you are not <%=customer.getfstname()%> then please click here.
Listing 4-2 : Mixing HTML with Scriptlets <% } %>
24
4.5.2.3 JSP Declarations JSP declarations allow developers to define methods or fields that get inserted into the main body of the servlet class. It has the following form:
<%! Java Code %>
Such declarations are not meant to generate any output for end users. They are normally used in conjunction with JSP expressions or scriptlets. Variables declared in this manner, will become “global” and hence, any servlet instances can access them. The following code fragment prints out the number of times that the current page has been accessed:
<%! private int accessCount = 0; %> Accesses to page since server reboot: <%= ++accessCount %>
Listing 4-3 : An Example of JSP Declarations JSP declarations were not used in R.U.M. because there was no need to use global variables in the system. 4.5.3 JSP Directives Fields & Kolb (2000) state that directives are used to convey special processing information about the page to the JSP container. The directives can be used for the following:
To specify the scripting language for the page, To include the contents of another page and To indicate that a page uses a custom tag library.
Like declarations, directives do not directly display any output, but they affect the way in which the JSP container processes the page. 4.5.3.1 Page Directive Fields & Kolb rate the page directive to be the most complicated JSP directive, primarily because it allows a wide range of attributes and associated functionality. The syntax of the page directive is as follows: 25
<%@ page attribute1 = “value1” attribute2 = “value2” attribute3 = … %>
The page directive supports a total of eleven attributes. Only one of those attributes was used in R.U.M. The import attribute was used in all the JSP pages to extend the set of Java classes that the pages could reference. This meant that the developers did not have to explicitly specify class package names. It is analogous to Java‟s import statement, which is used when writing Java class files. 4.5.3.2 Include Directive The include directive enables designers to include the contents of one file in another. The file to be included is specified as a local URL. The directive effectively replaces itself with the contents of the specified file. The file may be a static HTML file or it may consist of additional JSP elements that will be processed as if they were in the original page. It was used in R.U.M. to add a text menu at the bottom of every JSP page as follows:
<%@ include file = “bottom.jsp” %>
4.5.4 JSP Actions According to Fields & Kolb, JSP actions enable JSP pages to interact with JavaBean component objects residing on the web server. Actions serve three major roles in a system such as R.U.M. JSP actions allow for:
The Transfer of control between pages, The Specification of Java applets in a browser-independent manner, and The Interaction of JavaBeans component objects residing on the server.
The developers did not use all of the above actions in R.U.M. Since R.U.M. does not make use of Java applets, there was no need for the developers to use Java applet specifications. The two actions which were used are described in the next section.
26
4.5.4.1 Forward Fields & Kolb emphasise that the action can be used by developers to transfer control from one JSP page to another page on the local server. Any content which is currently being generated by the current page is discarded and processing of the request begins at the alternate location. The following example shows one of the tags which have been used in R.U.M.:
The page attribute of the action is used to specify the web page which control needs to be passed to. This page may be a static document, a servlet, or another JSP page. In R.U.M. forwarding was used in all the JSP pages which did server-side processing. 4.5.4.2 JSP Bean Tags JSP provides three different actions for interacting with server-side JavaBeans. These actions are
, ,
and . The interaction between JSP
and JavaBeans will be discussed in detail in the next section.
4.6 The Fundamentals of JavaBeans JavaBeans are described by Infobus Technology (2002) as the Java component architecture, which allows the creation and distribution of reusable components. Fields & Kolb describe a Bean as simply a Java class that adheres to a set of simple naming and design conventions outlined by the JavaBeans specification. The specification was created by Sun Microsystems with the co-operation of the industry and “dictates the rules that software developers must follow in order to create stand-alone, reusable software components”. Beans encapsulate both state and behaviour. Fields & Kolb emphasise that developers can use JSP‟s collection of Bean-related tags to leverage the power of Java to add dynamic elements to their web pages.
27
4.6.1 JavaBean Conventions If a Java class file adheres to the JavaBean conventions, then the Bean container can analyse the class file and interpret its methods as properties, designating the class as a JavaBean. Fields & Kolb add that the conventions dictate rules for defining a Bean‟s constructor and the methods that will define its properties.
According to Hall (1999), in order for a class to be a bean it must meet the following requirements:
1. Have a constructor which takes no arguments. 2. Have no publicly declared instance variables. All instance variables in a JavaBean class must be declared with a private access modifier. 3. Accessor and setter operations must have methods that take the following format: - getXxx (or isXxx): to get the values stored in instance variables (known as Bean attributes). - setXxx: to set the values stored in instance variables. (where Xxx is replaced with the method or instance variable name). 4.6.1.1 The JavaBeans API By adhering to the conventions which are stated in the JavaBeans API, the JSP container can interact with Beans at a programmatic level, despite the fact that the container has no knowledge about the functions of the Bean. For JSP, the developers need only concern themselves with the aspects of the API which dictate how the Bean‟s constructors and property access methods are written. 4.6.1.2 Beans Are Objects Fields & Kolb reiterate that like any other Java class, instances of Bean classes are simply Java objects. This allows developers to reference the Beans and their methods directly through Java code in other classes or through JSP scripting elements. Bean containers, such as the JSP container bundled with Apache Tomcat, can provide easy access to Beans and their properties. 28
The developers of R.U.M. had to create methods, which controlled access to each property within the Bean, in order to adhere to the coding conventions. For example, in the ShoppingCart bean, there was a getsize() function to return the size of the cart. Beans can also have regular methods just like any other Java object. In order for the JSP pages to manipulate the Beans, the developers had to use scriptlets and expressions within the JSP code. 4.6.1.3 Class Naming Conventions Most of the Bean classes which have been used in R.U.M. have included the word “Bean” in their name. Fields and Kolb consider this to be a common approach, which allows other
developers to immediately understand the intended role of the class. However, it is not a requirement for a Bean to be used inside a JSP page, or any other Bean container. JavaBeans follow the same class naming rules as normal Java classes – the initial character must be alphabetic and the rest of the characters can contain only alphanumeric and underscore characters. compulsory. 4.6.1.4 Introspection Fields et al highlights the fact that the JSP container cannot interact with a Bean object without the benefit of a common interface. Java manages this via a process known as introspection. Introspection, which happens at run time, allows a class to expose its methods and capabilities on request. In addition, the Bean class usually starts with a capital letter, but this is not
Introspection occurs through a mechanism known as reflection, which allows the Bean container to examine any class to determine its method signatures. The Apache Tomcat Bean container effectively searches the Bean for public methods, which meet the criteria defined by the JavaBeans API. For a property to exist, its Bean class must have methods, which can change the property and/or change the value of the property. 4.6.2 Using the JavaBeans with JSP To interact with a Bean, the JSP page needs to know where to find the Java class file that defines the Bean and assign it a name [Fields & Kolb, 2000]. This name can then be used to access the 29
values stored in the Bean‟s properties. The three JSP actions which provide the link are now discussed in-depth. 4.6.2.1 The tag The tag effectively makes a JavaBean available to a JSP page. If a Bean object does not exist on the server, then a new one is created, otherwise the existing one is retrieved. The tag is supplied attributes which specify the type of Bean that the developer wishes to use as well as the name that can be used to refer to it. The comes in two forms. The simplest form of the tag requires only two attributes to be specified – id and class. The basic syntax for the tag‟s two forms is:
initialisation code
Listing 4-4 : The useBean tag
The id attribute specifies a name for the Bean which will be a unique value that will refer to this particular Bean throughout its lifetime, The class attribute specifies the class name of the JavaBean itself, The scope attribute controls a Bean‟s accessibility and lifespan. Table 4-3, taken from Fields & Kolb, briefly explains all the possible Bean scopes.
Scope
Page
Accessibility
Current page only Current page and any included or forwarded pages The current request and any subsequent request from the same browser window The current and any future request that is part of the same web application
Life Span
Until page is displayed or control is forwarded to a new page Until the request has been completely processed and the response has been sent back to the user Life of the User‟s session.
Request
Session
Application
Life of the application
Table 4-3 : Possible Bean scopes 30
For R.U.M., the developers chose to use most of the Beans with a session scope, in order to maintain the state of the objects throughout the users‟ sessions. The Validation and Country Beans were the only Beans whose lifespans were not valid for the users‟ sessions. The
developers chose to make the Validation Bean valid for the request only, since it was only needed for processing and validating forms, while the Country Bean was valid for the page, since it was only needed for that page. Keeping both of these Beans active for the entire session would waste valuable memory. 4.6.2.2 The tag The primary way to access a Bean‟s properties is through the tag. [Fields & Kolb, 2000]. Unlike the tag, this one actually produces content which can be seen in the HTML which is generated by the page. The getproperty tag has no body element and requires two attributes, being name and property. Its syntax is
The name attribute specifies the Bean that is being evaluated and it should correspond to the name that was selected in the tag‟s id attribute,
The property attribute is the name of the Bean attribute which needs to be accessed. The property name must correspond with the name of the Bean attribute and there must be a corresponding accessor method within the Bean.
In the resulting HTML that is displayed at run-time, the tag is replaced with the value of the property of the requested Bean. The developers made use of the tag to get the forms to “remember” the data that had been typed in, when the forms are redisplayed in the event of validation errors. 4.6.2.3 The tag The tag modifies the attributes of Beans. Fields & Kolb add that the tag can be used to modify the properties, provided that the property has been made writable by the Bean developer. Property values are usually modified to control the specifics of the Bean‟s 31
operation or to access its services. The tag may be used anywhere in the JSP page after the Bean has been defined with the useBean tag.
The tag requires three attributes, being name, property and value. The format is of the tag is:
The name and property attributes function exactly like those of the tag. The optional value attribute is used to specify the text that the property needs to be set to. Again, there must be a corresponding property and a corresponding setter function in the Bean. If the value attribute is omitted, then the value is extracted from the page request. This allows developers to dynamically configure the Beans based on the data entered in forms. If multiple form field names map directly to Bean properties, then a special wild card character “*” can be used in place of the property name. This means that the value of any Bean property, whose name corresponds to the name of a request parameter, will be set. During the coding phase of R.U.M. the author noted that if a form element is left blank, then the property is not set. Why this is the case, is not known, but it could possibly be a bug inherent in Apache Tomcat. 4.6.3 An Example From R.U.M. To illustrate the use of Beans in R.U.M., a code extract is provided, which covers the aforementioned JSP tags. The JSP code is highlighted in bold.
32
<%@ page import="java.sql.*, java.util.*, ValidationBean, CustomerBean, CountryBean" %> <%@ include file = "https" %> . . . <% if (customer.getloggedin()) { %>
<% } else { %>
<% } %> . . . " size="20" maxlength = "50"> . . . <%@ include file = "bottom.jsp" %> Listing 4-5 : An example from R.U.M.