0% found this document useful (0 votes)
3 views246 pages

Advanced Java

This document is a course textbook for Advanced Java published by Assam Down Town University, containing comprehensive content on Java programming, object-oriented design, and related technologies. It includes chapters on various topics such as Swing, JDBC, Servlets, and JSP, along with objectives, learning outcomes, and self-assessment sections. The book is copyrighted and aims to provide accurate and current information while allowing for content updates as needed.

Uploaded by

Bhuvan Kharvi
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views246 pages

Advanced Java

This document is a course textbook for Advanced Java published by Assam Down Town University, containing comprehensive content on Java programming, object-oriented design, and related technologies. It includes chapters on various topics such as Swing, JDBC, Servlets, and JSP, along with objectives, learning outcomes, and self-assessment sections. The book is copyrighted and aims to provide accurate and current information while allowing for content updates as needed.

Uploaded by

Bhuvan Kharvi
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Advanced Java

This book is a part of the course by Assam Down Town University, Assam.
This book contains the course content for Advanced Java.

ADTU, Assam
First Edition 2011

The content in the book is copyright of ADTU. All rights reserved.


No part of the content may in any form or by any electronic, mechanical, photocopying, recording, or any other
means be reproduced, stored in a retrieval system or be broadcast or transmitted without the prior permission of
the publisher.

ADTU makes reasonable endeavours to ensure content is current and accurate. ADTU reserves the right to alter
the content whenever the need arises, and to vary it at any time without prior notice.
Index
Content................................................................................................................................................................... II
List of Figures.......................................................................................................................................................IX
List of Tables.........................................................................................................................................................XI
Abbreviations.......................................................................................................................................................XII
Application.......................................................................................................................................................... 212
Bibliography....................................................................................................................................................... 228
Self Assessment Answers.................................................................................................................................... 231
Book at a Glance

I/ADTU OLE
Contents
Chapter I........................................................................................................................................................ 1
Advanced Java.............................................................................................................................................. 1
Aim................................................................................................................................................................. 1
Objectives....................................................................................................................................................... 1
Learning outcome........................................................................................................................................... 1
1.1 Introduction to Basic Java......................................................................................................................... 2
1.2 Advanced Java ......................................................................................................................................... 2
1.3 Object-Oriented Design Using Java.......................................................................................................... 2
1.3.1 Classes vs. Interfaces................................................................................................................ 2
1.3.2 Data Members........................................................................................................................... 3
1.3.3 Methods.................................................................................................................................... 3
1.3.4 Constructors.............................................................................................................................. 4
1.3.5 Creating and Initialising an Object........................................................................................... 6
1.3.6 Inheritance................................................................................................................................ 7
1.3.7 Code Reuse............................................................................................................................... 8
1.4 OOP -Strong, Efficient, and Effective...................................................................................................... 9
1.5 Java I/O Routines...................................................................................................................................... 9
1.6 Streams...................................................................................................................................................... 9
1.7 The Java Core System............................................................................................................................. 10
1.8 The System Class.................................................................................................................................... 10
1.8.1 Input Using the System Class................................................................................................. 10
1.8.2 Output Using the System Class...............................................................................................11
1.9 Files..........................................................................................................................................................11
1.9.1 The Basics................................................................................................................................11
1.9.2 Taking Files One Step Further................................................................................................ 12
1.10 The Abstract Window Toolkit and Swing Classes................................................................................ 13
1.10.1 Input Alternatives.................................................................................................................. 14
1.10.2 Output Alternatives............................................................................................................... 14
1.10.3 I/O in Short........................................................................................................................... 14
1.11 Thread Basics........................................................................................................................................ 14
1.12 Why Use Threads?................................................................................................................................ 15
1.12.1 More responsive UI.............................................................................................................. 15
1.12.2 Take Advantage of Multiprocessor Systems......................................................................... 15
1.12.3 Simplicity of Modelling........................................................................................................ 15
1.12.4 Asynchronous or Background Processing............................................................................ 16
1.12.5 Simple But Sometimes Risky............................................................................................... 16
1.12.6 Don’t Overdo It..................................................................................................................... 16
1.13 Creating Threads................................................................................................................................... 17
1.13.1 Ending Threads..................................................................................................................... 18
1.13.2 Joining With Threads............................................................................................................ 18
1.13.3 Scheduling............................................................................................................................ 18
1.13.4 Sleeping................................................................................................................................ 19
1.13.5 Daemon Threads................................................................................................................... 19
1.13.6 Who Creates Threads?.......................................................................................................... 20
1.14 AWT and Swing.................................................................................................................................... 20
1.15 Using TimerTask................................................................................................................................... 20
1.16 Servlets and Java Server Pages Technology......................................................................................... 21
1.17 Implementing an RMI Object............................................................................................................... 21
1.18 All Threads Live in the Same Memory Space...................................................................................... 22
1.19 Synchronisation for Controlled Access................................................................................................. 22
1.20 Ensuring Visibility of Changes to Shared Data.................................................................................... 22
1.21 Atomic Code Blocks Protected by Locks............................................................................................. 22
1.22 Java Locking......................................................................................................................................... 23

II/ADTU OLE
1.22.1 Synchronised Methods.......................................................................................................... 24
1.22.2 Synchronised Blocks............................................................................................................. 24
1.22.3 Most Classes are Not Synchronised...................................................................................... 25
Summary...................................................................................................................................................... 26
References.................................................................................................................................................... 26
Recommended Reading.............................................................................................................................. 27
Self Assessment............................................................................................................................................ 28

Chapter II.................................................................................................................................................... 30
Introduction to Swing ................................................................................................................................ 30
Aim............................................................................................................................................................... 30
Objectives..................................................................................................................................................... 30
Learning outcome......................................................................................................................................... 30
2.1 Introduction to UIs.................................................................................................................................. 31
2.2 Swing’s Role........................................................................................................................................... 31
2.3 MVC....................................................................................................................................................... 31
2.4 JComponent............................................................................................................................................ 32
2.5 Simple Swing Widgets............................................................................................................................ 32
2.5.1 JLabel...................................................................................................................................... 32
2.5.2 JButton.................................................................................................................................... 32
2.5.3 JTextField................................................................................................................................ 33
2.5.4 JFrame..................................................................................................................................... 33
2.5.5 A Simple Application.............................................................................................................. 34
2.6 Additional Swing Widgets...................................................................................................................... 36
2.6.1 JComboBox............................................................................................................................ 36
2.6.2 JTabbedPane........................................................................................................................... 36
2.6.3 JPasswordField....................................................................................................................... 37
2.6.4 JCheckBox/JRadioButton....................................................................................................... 38
2.6.5 JMenu/JMenuItem/JMenuBar................................................................................................ 39
2.6.6 JSlider..................................................................................................................................... 40
2.6.7 JSpinner.................................................................................................................................. 40
2.6.8 JToolBar.................................................................................................................................. 41
2.6.9 JToolTip.................................................................................................................................. 41
2.6.10 JOptionPane.......................................................................................................................... 41
2.6.11 JTextArea.............................................................................................................................. 42
2.6.12 JScrollPane............................................................................................................................ 43
2.6.13 JList....................................................................................................................................... 43
2.6.14 JTable.................................................................................................................................... 44
2.6.15 JTree...................................................................................................................................... 45
2.7 Swing Concepts...................................................................................................................................... 46
2.7.1 Easy Layouts . ........................................................................................................................ 46
2.7.2 GridBagLayout....................................................................................................................... 48
2.7.3 Events...................................................................................................................................... 48
2.7.4 Models.................................................................................................................................... 49
2.7.5 Model Examples..................................................................................................................... 49
2.8 Application.............................................................................................................................................. 50
Summary...................................................................................................................................................... 54
References.................................................................................................................................................... 54
Recommended Reading.............................................................................................................................. 55
Self Assessment............................................................................................................................................ 56

III/ADTU OLE
Chapter III................................................................................................................................................... 58
Database and SQL Fundamentals............................................................................................................. 58
Aim............................................................................................................................................................... 58
Objectives..................................................................................................................................................... 58
Learning outcome......................................................................................................................................... 58
3.1 Introduction............................................................................................................................................. 59
3.2 What is a Database?................................................................................................................................ 59
3.3 Data vs Information................................................................................................................................ 59
3.4 Data Base Concepts................................................................................................................................ 59
3.5 Benefits of the Database Approach......................................................................................................... 59
3.6 Data Retrieval on the Basis of Selection Criteria................................................................................... 60
3.7 Why have Databases (and a DBMS)?..................................................................................................... 60
3.8 DBMS Standardisation........................................................................................................................... 61
3.9 Data Base Project Development............................................................................................................. 61
3.9.1 Analysis................................................................................................................................... 61
3.9.2 Design..................................................................................................................................... 61
3.9.3 Development........................................................................................................................... 62
3.9.4 Implementation....................................................................................................................... 62
3.9.5 Maintenance............................................................................................................................ 62
3.10 Conceptual Data Modelling.................................................................................................................. 62
3.11 Types of Relationship Between Data Item............................................................................................ 63
3.11.1 One to One Association........................................................................................................ 63
3.11.2 One to Many Association...................................................................................................... 64
3.11.3 Many to Many Association................................................................................................... 65
3.12 Codd’s Rules......................................................................................................................................... 65
3.13 Structured Query Language.................................................................................................................. 67
3.13.1 Using SQL as a Data Definition Language........................................................................... 67
3.14 The CREATE DATABASE DatabaseName......................................................................................... 67
3.15 Using SQL as a Dataquery Language................................................................................................... 69
3.16 The Where Clause................................................................................................................................. 70
3.17 Union.................................................................................................................................................... 71
3.18 Simple Joins.......................................................................................................................................... 71
3.19 Parent/Children Relationships.............................................................................................................. 72
3.20 Functions............................................................................................................................................... 74
3.21 Query Processing Rules with HAVING................................................................................................ 74
3.22 Introduction :Remote Database Access................................................................................................ 75
3.23 ODBC and JDBC drivers...................................................................................................................... 75
3.23.1 Microsoft’s ODBC................................................................................................................ 75
3.23.2 JDBC..................................................................................................................................... 76
Summary...................................................................................................................................................... 79
References.................................................................................................................................................... 79
Recommended Reading.............................................................................................................................. 80
Self Assessment............................................................................................................................................ 81

Chapter IV................................................................................................................................................... 83
JDBC Fundamentals................................................................................................................................... 83
Aim............................................................................................................................................................... 83
Objectives..................................................................................................................................................... 83
Learning outcome......................................................................................................................................... 83
4.1 Introduction............................................................................................................................................. 84
4.2 Model...................................................................................................................................................... 84
4.3 Drivers..................................................................................................................................................... 84
4.4 Connecting to an ODBC Data Source.................................................................................................... 84
4.5 JDBC Connection................................................................................................................................... 86
4.5.1 Working With the Driver Manager......................................................................................... 86

IV/ADTU OLE
4.5.2 Loading Drivers...................................................................................................................... 86
4.5.3 Preloading from Program........................................................................................................ 87
4.6 JDBC Implementation............................................................................................................................ 87
4.6.1 Using the Connection Class.................................................................................................... 87
4.6.2 DBC URL............................................................................................................................... 88
4.6.3 Managing SQL Transactions................................................................................................... 90
4.6.4 Using the Statement................................................................................................................ 90
4.6.5 Statement................................................................................................................................ 90
4.6.6 Complete Program.................................................................................................................. 91
4.6.7 DriverManager........................................................................................................................ 93
4.6.8 Getconnection......................................................................................................................... 93
4.6.9 CreateStatement...................................................................................................................... 93
4.6.10 ExecuteUpdate...................................................................................................................... 93
4.6.11 Selecting Rows...................................................................................................................... 94
4.7 Resultset Processing: Retrieving Results................................................................................................ 95
4.7.1 Deleting a Record................................................................................................................... 98
4.7.2 Inserting a Record................................................................................................................. 100
4.7.3 Updating Records................................................................................................................. 101
4.7.4 Deleting a Table.................................................................................................................... 102
4.8 Prepared Statement............................................................................................................................... 103
4.9 Callable Statement................................................................................................................................ 105
Summary.................................................................................................................................................... 109
References.................................................................................................................................................. 109
Recommended Reading............................................................................................................................ 109
Self Assessment...........................................................................................................................................110

Chapter V....................................................................................................................................................112
Servlets........................................................................................................................................................112
Aim..............................................................................................................................................................112
Objectives....................................................................................................................................................112
Learning outcome........................................................................................................................................112
5.1 Introduction of Java Servlets.................................................................................................................113
5.2 Servlet Process Flow..............................................................................................................................113
5.3 The Java Servlet API..............................................................................................................................114
5.4 The Servlet Life Cycle...........................................................................................................................114
5.4.1 Understanding the Life-Cycle................................................................................................115
5.4.2 Servlet Initialisation: Init Method..........................................................................................115
5.4.3 Servlet Request Handling......................................................................................................116
5.5 Basic Servlet Examples..........................................................................................................................117
5.5.1 Simple HTTP Servlet.............................................................................................................117
5.5.2 Basic Servlet Structure...........................................................................................................117
5.5.3 What the Service Method Does?...........................................................................................118
5.5.4 How the Servlet Gets Invoked...............................................................................................118
5.5.5 Running the Servlet...............................................................................................................119
5.6 HTML form Generator Servlet..............................................................................................................119
5.6.1 Response Object................................................................................................................... 120
5.6.2 Invoking the Servlet.............................................................................................................. 120
5.6.3 Servlet Output....................................................................................................................... 121
5.7 HTML Form Processing Servlet........................................................................................................... 121
5.7.1 Getting Form Values............................................................................................................. 123
5.7.2 General Request Properties................................................................................................... 123
5.8 Simple Counter Servlet......................................................................................................................... 125
5.8.1 Persistence............................................................................................................................ 125
5.8.2 Multi-Threaded..................................................................................................................... 125
5.9 Servlet Initialisation Parameters........................................................................................................... 126

V/ADTU OLE
5.9.1 ServletConfig object............................................................................................................. 126
5.9.2 What this Servlet does?......................................................................................................... 126
5.9.3 Servlet Configuration File.................................................................................................... 127
5.9.4 Understanding the Configuration File Format...................................................................... 127
5.10 HTTP Request Handling Utility Servlet............................................................................................. 128
5.11 Additional Servlet Examples............................................................................................................... 128
5.11.1 Cookie Servlet..................................................................................................................... 128
5.12 URL Rewriting Servlet....................................................................................................................... 130
5.13 A Real Persistent Servlet Between Servlet Life-Cycle....................................................................... 130
5.14 User Sessions...................................................................................................................................... 132
5.15 User Session Counter Servlet.............................................................................................................. 133
5.16 JDBC Servlet...................................................................................................................................... 134
5.17 Servlet Tag with SHTML.................................................................................................................... 136
5.18 Servlet Interaction Techniques............................................................................................................ 137
Summary.................................................................................................................................................... 138
References.................................................................................................................................................. 138
Recommended Reading............................................................................................................................ 138
Self Assessment.......................................................................................................................................... 139

Chapter VI................................................................................................................................................. 141


JSP.............................................................................................................................................................. 141
Aim............................................................................................................................................................. 141
Objectives................................................................................................................................................... 141
Learning outcome....................................................................................................................................... 141
6.1 Introduction........................................................................................................................................... 142
6.2 How Java Server Pages Work?............................................................................................................. 142
6.3 Components of Java Server Pages........................................................................................................ 143
6.3.1 JSP Directives....................................................................................................................... 143
6.3.2 Declarations.......................................................................................................................... 145
6.3.3 Scriptlets............................................................................................................................... 145
6.3.4 Comments............................................................................................................................. 146
6.3.5 Expressions........................................................................................................................... 146
6.4 WebSphere Extensions to JSP Scripting............................................................................................... 147
6.5 Accessing Implicit Objects................................................................................................................... 147
6.6 JSP Interactions..................................................................................................................................... 148
6.7 Invoking a JSP by URL......................................................................................................................... 148
6.8 Calling a servlet from a JSP.................................................................................................................. 148
6.9 Calling a JSP from a Servlet................................................................................................................. 150
6.10 Invoking a JSP from a JSP.................................................................................................................. 151
6.11 Creating Dynamic Content in JSPs..................................................................................................... 151
6.12 Standard JSP Tags............................................................................................................................... 151
6.13 WebSphere-specific tags..................................................................................................................... 155
6.14 Differences Between Java Server Page specification .91 and 1.0...................................................... 160
Summary.................................................................................................................................................... 161
References.................................................................................................................................................. 161
Recommended Reading............................................................................................................................ 161
Self Assessment.......................................................................................................................................... 162

Chapter VII............................................................................................................................................... 164


Java Beans................................................................................................................................................. 164
Aim............................................................................................................................................................. 164
Objectives................................................................................................................................................... 164
Learning outcome....................................................................................................................................... 164
7.1 Introduction to Software Components.................................................................................................. 165
7.1.1 Need for Software components............................................................................................. 165

VI/ADTU OLE
7.1.2 Classifications of Software Components.............................................................................. 165
7.2 Software Component Model................................................................................................................. 166
7.2.1 Features of Software Component......................................................................................... 166
7.3 Javabean................................................................................................................................................ 166
7.3.1 Importance of Java Component Model................................................................................. 166
7.3.2 JavaBeans Objectives........................................................................................................... 167
7.3.3 Basic Bean Concepts............................................................................................................ 167
7.4 Bean Development Kit.......................................................................................................................... 168
7.4.1 Starting the BeanBox............................................................................................................ 168
7.4.2 Using the BDK BeanBox and the Demo JavaBeans............................................................ 168
7.5 Building the First Bean......................................................................................................................... 171
7.5.1 How the Program Works?..................................................................................................... 172
7.6 Event Handling..................................................................................................................................... 174
7.6.1 Registering Event Listeners.................................................................................................. 174
7.6.2 Naming Event Listeners........................................................................................................ 175
7.6.3 Following the ActionEvent................................................................................................... 175
7.6.4 Dispatching Events to Event Listeners................................................................................. 175
7.7 Bean Persistence................................................................................................................................... 176
7.7.1 Serialisation and Deserialisation........................................................................................... 176
7.7.2 Serialisable Bean................................................................................................................... 178
7.7.3 Listing [Link]................................................................................................................ 178
7.7.4 Listing [Link].................................................................................................................. 182
Summary.................................................................................................................................................... 184
References.................................................................................................................................................. 184
Recommended Reading............................................................................................................................ 185
Self Assessment.......................................................................................................................................... 186

Chapter VIII.............................................................................................................................................. 188


Hibernate and Struts................................................................................................................................ 188
Aim............................................................................................................................................................. 188
Objectives................................................................................................................................................... 188
Learning outcome....................................................................................................................................... 188
8.1 Introduction to Hibernate...................................................................................................................... 189
8.2 Hibernate Architecture.......................................................................................................................... 189
8.3 Hibernate Communication with RDBMS............................................................................................. 190
8.4 What Does Hibernate Offer?................................................................................................................. 191
8.5 Using Hibernate.................................................................................................................................... 193
8.6 Pros and Cons of Hibernate.................................................................................................................. 193
8.7 JDBC Vs Hibernate............................................................................................................................... 194
8.7.1 Relational Persistence for JAVA........................................................................................... 194
8.7.2 Transparent Persistence......................................................................................................... 194
8.7.3 Support for Query Language................................................................................................ 194
8.7.4 Database Dependent Code.................................................................................................... 194
8.7.5 Maintenance Cost................................................................................................................. 194
8.7.6 Optimise Performance.......................................................................................................... 194
8.7.7 Automatic Versioning and Time Stamping........................................................................... 194
8.8 Disadvantages of Hibernate.................................................................................................................. 195
8.9 The Model-View-Controller Architecture............................................................................................. 195
8.10 What is Struts?.................................................................................................................................... 196
8.11 Struts Tags........................................................................................................................................... 196
8.11.1 Common Attributes............................................................................................................. 196
8.11.2 Referencing Properties . ..................................................................................................... 196
8.11.3 Creating Beans.................................................................................................................... 197
8.11.4 Other Bean Tags.................................................................................................................. 197
8.11.5 Creating HTML Forms....................................................................................................... 198

VII/ADTU OLE
8.12 Generics.............................................................................................................................................. 201
8.13 Generic Type-safety............................................................................................................................ 201
8.14 Naming Conventions.......................................................................................................................... 202
8.15 Writing Generic Classes...................................................................................................................... 202
8.16 Generics and Substitutability ............................................................................................................. 203
8.17 Generic Methods................................................................................................................................. 204
Summary.................................................................................................................................................... 209
References.................................................................................................................................................. 209
Recommended Reading............................................................................................................................ 209
Self Assessment.......................................................................................................................................... 210

VIII/ADTU OLE
List of Figures
Fig. 1.1 Just as customising our BMW makes it different from other BMWs............................................... 7
Fig. 1.2 Figure for given example................................................................................................................... 7
Fig. 1.3 Pipes enable interaction between two or more applications............................................................ 10
Fig. 1.4 Graphical representation of input and output streams..................................................................... 12
Fig. 2.1 The JLabel....................................................................................................................................... 32
Fig. 2.2 The JButton...................................................................................................................................... 32
Fig. 2.3 The JTextField................................................................................................................................. 33
Fig. 2.4 The JFrame...................................................................................................................................... 34
Fig. 2.5 HelloWorld example........................................................................................................................ 34
Fig. 2.6 The JComboBox.............................................................................................................................. 36
Fig. 2.7 The JPasswordField......................................................................................................................... 38
Fig. 2.8 JCheckBox and JRadioButton......................................................................................................... 38
Fig. 2.9 JMenu, and JMenuItem................................................................................................................... 39
Fig. 2.10 The JSlider..................................................................................................................................... 40
Fig. 2.11 The JSpinner.................................................................................................................................. 40
Fig. 2.12 Non-floating JToolBar................................................................................................................... 41
Fig. 2.13 A JToolTip..................................................................................................................................... 41
Fig. 2.14 A JOptionPane............................................................................................................................... 42
Fig. 2.15 A JTextArea................................................................................................................................... 42
Fig. 2.16 JScrollPane example...................................................................................................................... 43
Fig. 2.17 The JList........................................................................................................................................ 44
Fig. 2.18 A JTable......................................................................................................................................... 45
Fig. 2.19 A JTree........................................................................................................................................... 45
Fig. 2.20 The FlowLayout at work............................................................................................................... 46
Fig. 2.21 The GridLayout at work................................................................................................................ 47
Fig. 2.22 The BorderLayout at work............................................................................................................ 47
Fig. 3.1 One to one association..................................................................................................................... 64
Fig. 3.2 One to many association.................................................................................................................. 64
Fig. 3.3 Many to many association............................................................................................................... 65
Fig. 3.4 A Database client talks to a Database server on the user’s behalf................................................... 75
Fig. 3.5 A Database client can talk to many database servers via ODBC drivers........................................ 76
Fig. 3.6 A Database client can talk to many database servers via JDBC ODBC drivers.............................. 77
Fig. 3.7 A Database client can talk to many database Servers via JDBC type2 drivers............................... 77
Fig. 3.8 A Database client can talk to many database access servers via JDBC drivers............................... 78
Fig. 3.9 A Database client can talk to many database Servers via JDBC type4 drivers............................... 78
Fig. 4.1 Create new data source.................................................................................................................... 85
Fig. 4.2 Oracle8 ODBC driver setup............................................................................................................ 85
Fig. 4.3 ODBC data source administrator..................................................................................................... 86
Fig. 5.1 High-level client-to-servlet process flow.......................................................................................113
Fig. 5.2 Basic client-to-servlet interaction...................................................................................................115
Fig. 5.3 Servlet life-cycle.............................................................................................................................115
Fig. 5.4 HTML form generator servlet: response output............................................................................ 121
Fig. 5.5 HTML form handler servlet response output................................................................................ 124
Fig. 6.1 The JSP processing life-cycle on first-time invocation................................................................. 143
Fig. 7.1 Slider created in Java..................................................................................................................... 166
Fig. 7.2 Demonstration Juggler Bean......................................................................................................... 169
Fig. 7.3 Demonstration Beans bound with each other by Event Handling mechanism.............................. 170
Fig. 7.4 creating an instance of Spectrum in the BeanBox......................................................................... 173
Fig. 7.5 Event handling............................................................................................................................... 174
Fig. 7.6 Circle Bean.................................................................................................................................... 177
Fig. 7.7 Example of circle bean.................................................................................................................. 177
Fig. 8.1 Hibernate architecture.................................................................................................................... 189

IX/ADTU OLE
Fig. 8.2 Mapping mechanism used by Hibernate....................................................................................... 192
Fig. 8.3 Use of Struts for using forms......................................................................................................... 199
Fig. 8.4 Figure for given example............................................................................................................... 203

X/ADTU OLE
List of Tables
Table 4.1 JDBC Classes................................................................................................................................ 87
Table 4.2 Driver, Driver Manager and Related Methods.............................................................................. 89
Table 4.3 [Link] Methods and Constants................................................................................ 90
Table 4.4 Statement object methods............................................................................................................. 91
Table 4.5 [Link] methods........................................................................................................... 97
Table 4.6 Prepared Statement Object Methods........................................................................................... 103
Table 4.7 [Link]-Parameter-Related Methods........................................................... 104
Table 4.8 CallableStatement-OUT Parameter Register Methods............................................................... 106
Table 4.9 CallableStatement parameter access methods............................................................................. 107
Table 6.1 Attributes of the page directive................................................................................................... 144
Table 6.2 Attributes for the include directive.............................................................................................. 145
Table 6.3 WebSphere scripting language extensions.................................................................................. 147
Table 6.4 Summary of implicitly declared objects..................................................................................... 147
Table 6.5 jsp:useBean attributes................................................................................................................. 153
Table 6.6 jsp:getProperty attributes............................................................................................................ 153
Table 6.7 jsp:setProperty attibutes.............................................................................................................. 155
Table 6.8 tsx:dbconnect attributes............................................................................................................... 156
Table 6.9 tsx:dbquery attributes.................................................................................................................. 156
Table 6.10 tsx:dbmodify attributes............................................................................................................. 157
Table 6.11 tsx:repeat attributes................................................................................................................... 158

XI/ADTU OLE
Abbreviations
3D - 3 Dimensional
ANSI - American National Standards Institute
API - Application Programming Interface
AWT - Abstract Window Toolkit
BDK - Bean Development Kit
BSF - Bean Scripting Framework
CD - Compact Disk
CGI - Common Gateway Interface
CLI - Common Language Infrastructure
CPU - Central Processing Unit
DBMS - Database Management System
DDL - Data Definition Language
DML - Data Manipulation Language
DSN - Data Source Name
EJB - Enterprise JavaBeans
FTP - File Transfer Protocol
GJ - Generic Java
GUI - Graphical User Interface
GUI - Graphical User Interface
HQL - Hibernate Query Language
HTML - Hipertext Markup Language
HTTP - Hipertext Transfer Protocol
I/O - Input/Output
IFC - Internet Foundation Classes
JCP - Java Community Process
JDBC - Java Database Connectivity
JDK - Java Development Kit
JMX - Java Management Extensions
JNDI - Java Naming and Directory Interface
JSDK - Java Servlet Development Kit
JSP - Java Server Pages
JSR - Java Specification Request
JTAPI - Java Telephony Application Programming Interface
JVM - Java Virtual Machine
JVM - Java Virtual Machine
LAN - Local Area Network
LPGL - Lesser General Public License
MIDI - Musical Instrument Digital Interface
MP - Multiprocessor
MVC - Model View Controller
ODBC - Open Database Connectivity
OOP - Object-Oriented Programming
ORM - Object-Relational Mapping
ORM - Object-Relational Mapping
OS - Operating System
RAD - Rapid Application Development
RDBMS - Relational Database Management Systems
RMI - Remote Method Invocation
SQL - Structured Query Language
SSI - Server Side Includes
UI - User Interface
URL - Uniform Resource Locator
XML - Extensible Mark-up Language

XII/ADTU OLE
Chapter I
Advanced Java

Aim
The aim of this chapter is to:

• elucidate basics of core java and OOPS concept

• introduce advanced java and its components

• explain the threads and its components

Objectives
The objectives of this chapter are to:

• explain base of terminologies like encapsulation, information hiding, modularity and so on

• explicate file system related to java

• elucidate Abstract Window Toolkit and Swing

Learning outcome
At the end of this chapter, you will be able to:

• understand code that highlights some of Java’s inherently object-oriented features

• identify the difference between core java and advanced java

• enlist various operations on threads

1/ADTU OLE
Advanced Java

1.1 Introduction to Basic Java


Java is an object-oriented programming language with a built-in application programming interface (API) that can
handle graphics and user interfaces and that can be used to create applications or applets. Because of its rich set of
API’s, similar to Macintosh and Windows, and its platform independence, Java can also be thought of as a platform
in itself. Java also has standard libraries for doing mathematics.

Much of the syntax of Java is the same as C and C++. One major difference is that Java does not have pointers.
However, the biggest difference is that we must write object oriented code in Java. Procedural pieces of code can
only be embedded in objects. In the following we assume that the reader has some familiarity with a programming
language. In particular, some familiarity with the syntax of C/C++ is useful.

In Java, we distinguish between applications, which are programs that perform the same functions as those written
in other programming languages, and applets, which are programs that can be embedded in a Web page and accessed
over the Internet. Our initial focus will be on writing applications. When a program is compiled, a byte code is
produced that can be read and executed by any platform that can run Java.

1.2 Advanced Java


The Java programming language has continued to grow both in popularity and scope since its initial release. Java in
its current form is the culmination of several years work, dating back to 1991 when it was conceived as a modular
and extensible programming language.

Java is based on the C and C++ programming languages, but differs from these languages in some important ways.
The main difference between C/C++ and Java is that in Java all development is done with objects and classes. This
main difference provides distinct advantages for programs written in Java, such as multiple threads of control and
dynamic loading.

Another advantage to Java is its extensibility. Since the original release of Java, several extensions have been added
to the core code, providing greater flexibility and power to applications. These extensions add objects and classes
that improve the Java programmer’s ability to use such features as:
• Java Swing: A component set to create graphical user interfaces with a cross-platform look and feel.
• Java Sound: For high-quality 32-channel audio rendering and MIDI-controlled sound synthesis.
• Java 3D: For advanced geometry and 3D spatial sound.
• Java Media Framework: For components to play and control time-based media such as audio and video.
• Java Telephony (JTAPI): For computer-telephony applications.
• Java Speech: For including speech technology into Java applets and applications.

1.3 Object-Oriented Design Using Java


In Java, we declare classes as a collection of operations performed on a set of data. Because data cannot be passed
by reference (Java is a pointer-free language). Java classes are needed to contain data so that it can be modified
within other classes.

1.3.1 Classes vs. Interfaces


The prevailing assumption about Java is that we are unable to separate implementations from interfaces. However,
this assumption is false. Java provides an interface component that is similar to its class counterpart except that
it is not permitted to have member functions. Indeed, other objects that will implement its method and variable
definitions, as illustrated in the following snippet, must reuse this interface.

2/ADTU OLE
public interface MyAdvancedJavaInterface
{
public abstract void methodOne();
[Link]();
}
public class MyAdvancedJavaClass implements MyAdvancedJavaInterface
{
MyAdvancedJavaClass()
{
}
public void methodOne()
{
...
}
public void methodTwo()
{
...
}
}

All member functions declared within interfaces are, by default, public and abstract. This means that they are available
for public consumption and must be implemented in a class before they can be used. Furthermore, interfaces do not
have constructors and must be extended before they can be used.

1.3.2 Data Members


Good object-oriented style dictates that all data members of a class should be declared private, hidden from any
operations other than those included in the class itself. But, any experienced object-oriented (OO) programmer will
tell us in no uncertain terms that this is often stupid and inane for small classes. Because structs are not available in
Java, we can group data into one container by using a class. Whether we subscribe to the artificially enforced private
data member scheme of C++ or the language enforced scheme of Smalltalk is entirely up to on user. Java, however,
assumes that data members are public unless otherwise instructed, as given in the following snippet.

public class MyAdvancedJavaClass


{
public int numItems;
private int itemArray[];
};

1.3.3 Methods
Another important component of the Java class is the operation, or method. Methods allow outside classes to perform
operations on the data contained in the class. By forcing other classes to utilise data through the classes, we can
enforce implementation hiding. It doesn’t matter to other classes that our collection of data is an array, for as far as
those classes are concerned, it could be a Vector. Somewhere down the line, we could change the implementation
to a Hash Table if efficiency becomes a concern. The bottom line is that the classes that use our methods don’t
care, and don’t need to know, so long as the method signature. The method name and its accompanying parameters
remains the same. The following code shows how a method can be introduced within a class.

3/ADTU OLE
Advanced Java

public class MyAdvancedJavaClass


{
public int numItems;
private int itemArray[];
public void addItem(int item )
{
itemArray[numItems] = item;
numItems++;
};
};

1.3.4 Constructors
Constructors set up a class for use. Classes don’t need to specify a constructor; indeed a constructor is, by default,
simply a function call to nothing. In this case, however, our class must call a constructor because our data needs
to be initialised before it can be used. In Java, everything is inherited from the superclass Object. All Objects must
be initialised, or allocated, before they are used. For example, the declaration public int numItems; specifies an
integer value.

The int is a primitive type, but just like an Object, and therefore int needs to be initialised. We can do so in the
declaration itself public int numItems = 0; or we can use the constructor and initialise the array as well.

public class MyAdvancedJavaClass


{
public int numItems;
private int itemArray[];
MyAdvancedJavaClass()
{
numItems = 0;
itemArray = new int[10];
}
public void addItem(int item)
{
itemArray[numItems] = item;
numItems++;
};
};

Initialising a variable at its declaration affords little flexibility for any classes or methods that subsequently use
object. A constructor can be modified easily to accept incoming data as well, enabling us to modify our object
depending on the context of its use:

4/ADTU OLE
public class MyAdvancedJavaClass
{
public int numItems;
private int itemArray[];
MyAdvancedJavaClass(int initialValue,int arrayLength)
{
numItems = initialValue;
itemArray = new int[arrayLength];
}
public void addItem(int item)
{
itemArray[numItems] = item;
numItems++;
};
};

An object is allowed to have several constructors, so long as no two constructors have the same method signature
(parameter list):

public class MyAdvancedJavaClass


{
public int numItems;
private int itemArray[];
MyAdvancedJavaClass()
{
numItems = 0;
itemArray = new int[10];
}
MyAdvancedJavaClass(int initialValue,int arrayLength)
{
numItems = initialValue;
itemArray = new int[arrayLength];
}
public void addItem(int item)
{
itemArray[numItems] = item;
numItems++;
};
};

Sometimes, confusion may arise when there are several constructors that all do the same thing, but with different sets
of data. In Java, constructors are allowed to call themselves, eliminate duplicate code, and enable us to consolidate
all our constructor code in one place:

5/ADTU OLE
Advanced Java

MyAdvancedJavaClass()
{
/* Insteadof…
numItems = 0;
itemArray = new int[10];
*/
// call the more specific constructor
this(0, 10);
}
MyAdvancedJavaClass(int initialValue,int arrayLength)
{
numItems = initialValue;
itemArray = new int[arrayLength];
}

Constructors are powerful tools. They enable to create classes and use them dynamically without any significant
hard-coding. Good constructor design is essential to an object-oriented architecture that works.

1.3.5 Creating and Initialising an Object


We mentioned earlier that all Java classes inherit from the Object superclass. The constructor for an Object is invoked
using the new operation. This initialisation operation is used at object creation and is not used again during the
object’s lifecycle. One example of an object being initialised is the array initialisation in our sample class. The new
operation first allocates memory for the object and then invokes the object’s constructor.

Because we created two kinds of constructors, our sample class can be invoked in one of two ways:

myAdvancedJavaInstance1 = new MyAdvancedJavaClass();


myAdvancedJavaInstance2 = new MyAdvancedJavaClass(10, 100);

The first instance of our class is initialised to the default values 0 and 10. When we invoked the new operation on
this instance, the new operation set the values appropriately, and created a new instance of Array within the class
instance. The second instance of our class set numItems to 10 and created a 100-item Array. This kind of dynamic
class creation is very flexible. We could just as easily create another instance of our class with entirely different (or
the same) initial values. This is one of the basic principles of object-oriented design espoused by languages such
as Java.

Each instance of the object maintains a similar-looking but entirely different set of variables. Changing the values in
one instance does not result in a change in the values of the variables of the other instances. Remember, an instance
of a class is like ourr BMW 328i convertible. As the analogy in Fig. 1.1 illustrates, it looks as cool as every other
BMW 328i, but just because of our modification to remove the annoying electronic inhibition of speed, that doesn’t
mean every other Beemer also will be changed!

6/ADTU OLE
BMW

MyBMW HerBMW YourBMW

Instances of BMW

Fig. 1.1 Just as customising our BMW makes it different from other BMWs

1.3.6 Inheritance
Consider an example, our Z3, and every other car on the road, is a car, pure and simple. All cars have accelerators,
brakes, steering wheels, and, even though we don’t use them in Beemer, turn signals. If we take this analogy further,
we can say that every car inherits from the same “base class,” as illustrated in the following figure. In any object-
oriented environment, classes inherit the characteristics of their base classes.

Car

Subaru
BMW Z3 VW Bug
Justy

Fig. 1.2 Figure for given example

A base class is a special kind of object that forms the foundation for other classes. In Java, a base class is usually
inherited later on. Think of derived classes as “kinds of” base classes. In other words, “a BMW Z3 is a kind of car.”
With that in mind, we create the following class structure:

public class Car


{
}
public class BMWZ3 extends Car
{
}

The extends keyword tells the BMWZ3 class to utilise the properties, values, and behaviour of the Car base class.
But there is one small problem. Can we ever drive a generic “car”? No, because there is no such thing. There are
always kinds of cars, but never a specific thing that is known simply as a car. Java gives us the notion of an “abstract
base class.”

7/ADTU OLE
Advanced Java

An abstract base class is, quite simply, a class that must be inherited from. It can never be used as a stand-alone
class. In Java, the abstract keyword gives a class this unique property.

public abstract class Car


{
int topSpeed;
}
public class BMWZ3 extends Car
{
}

In this situation, the Car class can never be instantiated or used as is. It must be inherited. When the BMWZ3 class
inherits from Car, it also obtains all the variables and methods within the Car class. So, our BMWZ3 class gets to
use top Speed as if it were its own member variable.

Somewhere in our code we might want to check what type of variable we are using. Java provides the instance of
keyword to enable us to inquire as to what the abstract base class of an object is. For example, the following two
code snippets would return the value true:

BMWZ3 bmwVariable;
FordTaurus fordVariable;
if(bmwVariable instanceof Car) . . .
if (fordVariable instanceof Object) . . .

whereas the following code snippet would return the value false.

if (bmwVariable instanceof PandaBear)

Notice that Java’s inheritance model is quite simple. In C++, objects are allowed to inherit from one or more
abstract base classes and can be made to inherit the implementation of those interfaces as well. Java, as a matter of
simplicity, does not allow this, nor does it plan to at any time in the future. There are ways to get around multiple
implementation inheritance, but they do not really involve inheritance at all. The bottom line is that if we need to
use multiple implementation inheritance, we probably won’t want to use Java.

1.3.7 Code Reuse


Let’s say that you are putting together your son’s bicycle on Christmas morning. The instructions call for you to
use a Phillips-head screwdriver. You take the screwdriver out of the toolbox, use it, and put it back. A few minutes
later, you need the screwdriver again. Surely you would use the same screwdriver, not go to the hardware store and
buy a new one!

Likewise, code reuse is of vital importance to the programmer on a tight schedule. We will need to streamline our code
so that we can distribute commonly used tasks to specific modules. For example, many of the online demonstrations
we provide with this book include animation examples. Rather than recreate the animation routines, we reused the
same set of animation tools we developed beforehand. Because we coded the animators with reuse in mind, we were
able to take advantage of a strong interface design and an effective inheritance scheme.

8/ADTU OLE
1.4 OOP -Strong, Efficient, and Effective
There are three steps to creating an object that can be use time to time:
• Strong interface design
• Efficient class implementation
• Effective inheritance

With the fundamentals of object-oriented programming under our belt, we are ready to explore the simplicity with
which we can create programs in Java that handle input and output. The Java I/O routines are not only easy, but
extremely powerful. Bringing our C++ I/O to Java will result in as little functional loss as migrating object-oriented
design techniques to Java from C++.

1.5 Java I/O Routines


Java provides several tools for the input and output of data, ranging from the Abstract Window Toolkit (AWT) or
the Swing Components to the core System functions of Java classes. The AWT is exactly what it says it is: a set of
components for designing windows and graphical user interfaces that uses the peer components of the underlying
operating system for their implementation. The Swing Components do the same thing, but rather than using the peer
components of the host operation system, all the components are 100% pure Java components and can take on the
look and feel of the components of the host operating system or have their own “custom” look and feel. The core
System classes are built-in routines for gathering and disseminating information from Java objects.

1.6 Streams
Imagine your grandfather fishing in a stream. He knows that as long as he stays there, he’s going to get a bite.
Somewhere, somehow, sometime a fish is going to come down that stream, and your grandfather is going to get
it. Just as your grandfather is the consumer of fish, your applications are either consumers or providers of data. In
Java, all input and output routines are handled through streams. An input stream is simply a flow of data, just as
your grandfather’s stream is a flow of fish. We can write our application to fish for data out of our input stream and
eventually to produce data as well. When our application spits out information, it does so through a stream. This
time, our application is the producer, and the consumer is another application or device down the line.

Java provides several different kinds of streams, each designed to handle a different kind of data. The standard input
and output streams form the basis for all the others. InputStream and OutputStream are both available for use and
we can derive more complicated stream schemes from them. In order to create the other kinds of Java streams, first
we must create and define the basic streams.

Perhaps the most-used stream formats are the DataInputStream and the DataOutputStream. Both of these streams
enable us to read or write primitive data types, giving the flexibility within our application to control the results of
our application’s execution. Without this kind of functionality, we would have to write specific bytes rather than
reading specific data.

File buffers are a method commonly used to increase performance in an input/output scheme. BufferedInputStreams
and BufferedOutputStreams read in chunks of data, the size of which can be defined at a time. When we read from or
write to the buffered streams, we are actually playing with the buffer, not the actual data in the stream. Occasionally,
we must flush the buffers to make sure that all the data in the buffer is completely read from or written to the file
system.

Sometimes we will want to exchange information with another application using a stream. In this case, we can set
up a pipe. A pipe is a two-way stream, sort of. The input end of a pipe in one application is directly connected to
the output end of the same pipe on another application. If we write to the input of the pipe, we will read the same
exact data at the pipe’s output end. Study the following figure this is a pretty nifty way to promote inter application
communication.

9/ADTU OLE
Advanced Java

Input Output

“Hey Dude” “Hey Dude”

Application One Application Two

Fig. 1.3 Pipes enable interaction between two or more applications

We can eventually fiddle files on our local file system. The FileInputStream and FileOutputStream enable to open,
read, and write files. Remember that Java has strict restrictions on applet security, so most file streams can be
manipulated only by applications.

1.7 The Java Core System


In Java, applications are allowed to write to the standard output devices on a machine. If we use a Web browser
such as Netscape, the standard output to which Java writes is the “Java Console” mentioned in one of Navigator’s
windows. If we write a Java application such as, a stand-alone applet, the standard output device is the command
line from which we can execute the program.

1.8 The System Class


One of the classes Java includes in every applet or application, which specifies that it do so or not, is the System
class. The System class provides support for input/output (I/O) using the Java console; we are to provide the ability
to write to the console, read from the console, and write errors to the user. The Java console is provided in two ways,
one for browsers and one for applications. In the browser environment the console is a separate browser window
that has controls for scrolling and clearing. For applications run from the operating system (OS) command line,
the console is the text interface and suffers the same problems as the text base OS environment (lack of scrolling
backwards). The Java console is really intended to provide the same level of user interactivity as the C++ cin, cout,
and cerr objects.

The names of the standard Java streams are in, out, and err; these names can be changed using the System classes setIn,
setOut, and setErr methods. Changing the names of these streams can only be done by the SecurityManager.

1.8.1 Input Using the System Class


Input in the System class is actually handled by the InputStream class contained in the Java I/O routines. System.
in is an object of type InputStream that is created, maintained, and initialised by the System class.

The InputStream class assumes that it will be reading from the standard input stream for example, the keyboard we
are using. A stream is a sequence of characters retrieved from somewhere. The standard input stream is the location
that our operating system uses to get data from us. Because streams are defined as characters from a source, it is
entirely conceivable that a stream could be a file, a modem, a microphone, or even a connection to another process
running on our computer or another computer. As a matter of fact, Java treats files and other peripherals as streams.
This abstraction of a stream simplifies I/O programming by reducing all I/O to a stream.

So, how do we get input from the user? Simply use the System class’s input stream to get the information required.
The input stream is an object with several methods to facilitate data input. For example, there are primitive, yet useful,
routines to get characters and strings, to read integers and other numbers, and even to get a stream of unfiltered and
not translated bytes. Deciding which routine to use is simply a matter of which kind of data we wish to read. In our
example, we will read and write strings:

10/ADTU OLE
public class InputOutputTest()
{
String str; //private data
public void getInput(){
// read a string from the Java console keyboard (sysin)
str = [Link]();
}
}

1.8.2 Output Using the System Class


As with input, output is handled through streams. How can output be a stream if a stream is a sequence of characters
from a source? Well, the source is our application, and the stream is routed to a device known as the standard output.
The standard output is usually our monitor, but it could be other things as well. Most notably, the standard output
is set to be the Java console when an applet runs within Netscape Navigator. When we run the following example
from within an applet; watch our Java console for the output. If we run it from within an application, the output
should show up on the command line.

public class InputOutputTest(){


String str; // classdata
public void getInput(){
// read a string from the keyboard
str = [Link]();
}
public void drawOutput(){
// write a string to the console screen
[Link](str);
}
}

1.9 Files
The stream classes would be pretty useless if we couldn’t manipulate files as well. There are several security
mechanisms defined in the security model used by Java capable browsers for running applets. These mechanisms
prevent unguarded file access. Here consider the thing as long as we are not writing an applet, we will be able to
manipulate files. In the purest sense, standard input and output are files. As such, they are sometimes subject to the
same applet security restrictions, so be forewarned.

1.9.1 The Basics


When reading and writing to and from files, there are three steps that must be followed:
• Open the file for reading or writing.
• Read or write from the file.
• Close the file

It is important to do each step. Failing to open a file will, obviously, prevent us from reading. But perhaps not as
intuitively, we must still close the file or we may wreck file system. Every application is allowed a certain number
of file descriptors (handles) that maintain the status of a file. If we run out of available file descriptors, we will no
longer be able to open any other files. The following snippet uses the FileReader class to read the contents of a file
specified on the command line and the PrintWriter class to write it to the Java console:

11/ADTU OLE
Advanced Java

import java. io.*;


public class ShowFile{
public static void main (Stringargs[]){
try{
FileReader fin = new FileReader(args[0]);
PrintWriter consoleOut = new PrintWriter([Link], true);
char c[] = new char[512];
int count = 0;
while ((count=[Link](c))!=-1)
[Link](c,0,count);
[Link]();
[Link]();
[Link]();
}
catch(FileNotFoundException e){
[Link]([Link]());
}
catch(IOException e) {
[Link]([Link]());
}
}

We have three options to open a file. We can open the file for reading so we can extract data from it, but we will
be prevented from writing to the file unless we close it and open it for writing. We can open it for writing, but we
will be prevented from reading from it. Finally, we can append to a file, which is similar to writing except that it
preserves any data already in the file.

1.9.2 Taking Files One Step Further


So what do files have to do with networked computing? The diagram in the following figure offers a graphical
representation of input and output streams. Remember that streams are merely interfaces to collections of data. What
if that data is located on a network connection rather than in a flat file or a keyboard?

Console

In

Device

Application

File

Out

Network

Fig. 1.4 Graphical representation of input and output streams

12/ADTU OLE
The standard interface to a network in the computer world is a socket. A socket is a connection between processes
across a network. The processes can be located on the same physical machine, the same Local Area Network, or
even across the world on different LANs. The three basic steps still apply:
1. Open a connection to the remote process.
2. Read or write data.
3. Close the connection.

Again, as with file manipulation, we can use the InputStream and OutputStream objects to interface to the socket.
In fact, sockets are nothing but files in the purest sense. The advantage to this file-centric hierarchy is perhaps not as
obvious as it should be. In the end, all three forms of input sources are completely interchangeable. We should not
write applications to be specific to a specific kind of file. In an object-oriented design, the objects we create should
simply know that they will have to read or write data down the line.

1.10 The Abstract Window Toolkit and Swing Classes


The AWT is a half-baked attempt to create a user interface toolbox for programmers. Because all the various classes,
containers, and widgets in the toolkit are capable of being used both in the applets embedded in Web pages and in the
stand-alone applications on the desktop, it is a powerfully extensible tool. At the heart of this kind of flexibility is the
idea that the toolkit is an abstraction, in other words, a layer on top of our current windowing system. This abstraction
is more understandable if we know the background behind it. When Sun was courting its early customers,

Netscape insisted that the Java Virtual Machine (JVM) included in its browser must create widgets that had the
exact look and feel of the host operating system’s widgets. Since “Swing” wasn’t yet a gleam in its father’s eye, the
only way to accomplish this was to use the peer components of the host operating system. Thus we can truly say
that the AWT is an abstraction of the windowing system of the operating system.

Our current windowing system may be anything from X11/Motif to Windows 95’s own window system. In any
event, the AWT ensures that native calls are made to these windowing systems in order to allow applications to run
on top of the desktop. For applets within a Web page, the browser manufacturer essentially creates a windowing
system that renders the AWT’s widgets within itself.

The end result of all this is that eventually a native call is made for each action taken by the AWT. Our applications
need not be aware of this, for Java’s platform independence ensures that, no matter the platform on which we execute
byte codes, the results will be identical.

One of the problems with this approach to user interface (UI) implementation is that when making a UI that must be
rendered the same way on all the platforms it is to be targeted to, small differences in the way that components are
rendered on each of the targeted systems may cause the overall effect to have problems. For instance, a UI having
several closely aligned text fields may look good on Windows platforms but appear over lay on UNIX machines.

One of the major complaints about the AWT by people used to building user interfaces for enterprise applications
was that it had a relatively small set of widgets and low functionality. AWT provided only slightly more functionality
than the widgets provided in HTML’s forms controls. In early 1997 the work on JDK 1.1 incorporated a number of
new pieces including Netscape Corporation’s Internet Foundation Classes (IFC), components from IBM’s Taligent
Division, and Lighthouse Design. The first release of Swing 1.0 in early 1998 contained almost 250 classes and 80
interfaces.

The art of user interface creation had been raised to a new level and was now able to go head to head with platform-
specific development tools. The Java 1.2 platform provides a set of components (Swing) that eliminate this problem
by eliminating the use of peer components. The Swing components are pure Java and will render reliably on all host
platforms. With Swing the native look and feel of Windows, Motif, or Mac widgets are options from a predefined
list of look and feels that are extensible by the user.

13/ADTU OLE
Advanced Java

1.10.1 Input Alternatives


The AWT and Swing contain widgets designed to elicit response from the user. From simple text areas to more
complex dialog boxes, each one is designed to funnel information from the user’s keyboard to our application. Most
of them are very easy to use and program.

Remember that input in a windowing system is not limited to typing words on the screen. Every push button,
checkbox, or scroll bar event is a form of input that we may or may not choose to deal with. Every AWT class has
some way or another of checking the status of its input mechanism. For example, scroll bar will be able to tell if it
has been moved. We may choose then to take some action, or let the AWT do it for us. There is no need to implement
scrolling text for a scroll bar when the AWT is fully capable of doing it.

1.10.2 Output Alternatives


Obviously, the easiest way to display output with the AWT is to display something graphically. The AWT supports
simple graphics routines for drawing, as well as for the usual suite of labels, multimedia, and widget manipulation.
Output is significantly easier using the AWT. Without the toolkit, we would have to manage not only what to do
with the input we receive, but also how to display our response.

1.10.3 I/O in Short


Input and output are at the heart of every program we create. No matter what the objective of our application, somehow
we will need either to get a response from the user, to display a response, or maybe even both. To take things one
step farther, our input or output need not reside on the same physical machine as that on which our application is
running. By stretching our applications to fit a networked model, we will be able to take full advantage of the input
and output schemes offered to us by Java.

When the applications receive several inputs, they often get inundated with processing. To alleviate this, Java
provides a full suite of threading utilities. Threads allow our applications to execute steps in parallel. So, when
application receives two different inputs simultaneously, we can use threads to simultaneously resolve them and
produce output.

1.11 Thread Basics


Nearly every operating system supports the concept of processes independently running programs that are isolated
from each other to some degree. Threading is a facility to allow multiple activities to coexist within a single process.
Most modern operating systems support threads, and the concept of threads has been around in various forms for
many years. Java is the first mainstream programming language to explicitly include threading within the language
itself, rather than treating threading as a facility of the underlying operating system. Threads are sometimes referred to
as lightweight processes. Like processes, threads are independent, concurrent paths of execution through a program,
and each thread has its own stack, its own program counter, and its own local variables.

However, threads within a process are less insulated from each other than separate processes are. They share
memory, file handles, and other per-process state. A process can support multiple threads, which appear to execute
simultaneously and asynchronously to each other. Multiple threads within a process share the same memory address
space, which means they have access to the same variables and objects, and they allocate objects from the same
heap. While this makes it easy for threads to share information with each other, we must take care to ensure that
they do not interfere with other threads in the same process.

The Java thread facility and API is deceptively simple. However, writing complex programs that use threading
effectively is not quite as simple. Because multiple threads coexist in the same memory space and share the same
variables, we must take care to ensure that our threads don’t interfere with each other.

• Every Java program uses threads.


• Every Java program has at least one thread the main thread. When a Java program starts, the JVM creates the
main thread and calls the program’s main() method within that thread.

14/ADTU OLE
• The JVM also creates other threads that are mostly invisible to us for example, threads associated with garbage
collection, object finalisation, and other JVM housekeeping tasks.
• Other facilities create threads too, such as the AWT (Abstract Windowing Toolkit) or Swing UI toolkits, servlet
containers, application servers, and RMI (Remote Method Invocation).

1.12 Why Use Threads?


There are many reasons to use threads in our Java programs. If we use Swing, servlets, RMI, or Enterprise JavaBeans
(EJB) technology, we definitely have used threads without realising it. Some of the reasons for using threads are
that they can help to:

Presented by developerWorks, our source for great tutorials [Link]/developerWorks


• Make the UI more responsive
• Take advantage of multiprocessor systems
• Simplify modelling
• Perform asynchronous or background processing

1.12.1 More responsive UI


Event-driven UI toolkits, such as AWT and Swing, have an event thread that processes UI events such as keystrokes
and mouse clicks. AWT and Swing programs attach event listeners to UI objects. These listeners are notified when a
specific event occurs, such as a button being clicked. Event listeners are called from within the AWT event thread.
If an event listener were to perform a lengthy task, such as checking spelling in a large document, the event thread
would be busy running the spelling checker, and thus would not be able to process additional UI events until the
event listener completed. This would make the program appear to freeze, which is disconcerting to the user.

To avoid stalling the UI, the event listener should hand off long tasks to another thread so that the AWT thread can
continue processing UI events (including requests to cancel the long-running task being performed) while the task
is in progress.

1.12.2 Take Advantage of Multiprocessor Systems


Multiprocessor (MP) systems are much more common than they used to be. Once they were found only in large
data centres and scientific computing facilities. Now many low-end server systems and even some desktop systems
have multiple processors. Modern operating systems, including Linux, Solaris, and Windows NT/2000, can take
advantage of multiple processors and schedule threads to execute on any available processor.

The basic unit of scheduling is generally the thread; if a program has only one active thread, it can only run on one
processor at a time. If a program has multiple active threads, then multiple threads may be scheduled at once. In a
well-designed program, using multiple threads can improve program throughput and performance.

1.12.3 Simplicity of Modelling


In some cases, using threads can make our programs simpler to write and maintain. Consider a simulation application,
where we simulate the interaction between multiple entities. Giving each entity its own thread can greatly simplify
many simulation and modelling applications.

Another example where it is convenient to use separate threads to simplify a program is when an application has
multiple independent event-driven components. For example, an application might have a component that counts
down the number of seconds since some event and updates a display on the screen. Rather than having a main loop
check the time periodically and update the display, it is much simpler and less error-prone to have a thread that does
nothing but sleep until a certain amount of time has elapsed and then update the on-screen counter. This way the
main thread doesn’t need to worry about the timer at all.

15/ADTU OLE
Advanced Java

1.12.4 Asynchronous or Background Processing


Server applications get their input from remote sources, such as sockets. When we read from a socket, if there is no
data currently available, the call to [Link]() will block until data is available. If a single-threaded
program were to read from the socket and the entity on the other end of the socket were never to send any data, the
program would simply wait forever, and no other processing would get done. On the other hand, the program could
poll the socket to see if data was available, but this is often undesirable for performance reasons.

If, instead, we created a thread to read from the socket, the main thread could perform other tasks while the other
thread waited for input from the socket. We can even create multiple threads so we can read from multiple sockets
at once. In this way, we are notified quickly when data is available because the waiting thread is awakened without
having to poll frequently to check if data is available. The code to wait on a socket using threads is also much simpler
and less error-prone than polling would be.

1.12.5 Simple But Sometimes Risky


While the Java thread facility is very easy to use, there are several risks we should try to avoid when we create
multithreaded programs. When multiple threads access the same data item, such as a static field, an instance field
of a globally accessible object, or a shared collection, we need to make sure that they coordinate their access to
the data so that both see a consistent view of the data and neither steps on the other’s changes. The Java language
provides two keywords for this purpose:
• synchronised
• volatile

We will explore the use and meaning of these keywords later in this tutorial. When accessing variables from more
than one thread, we must ensure that the access is properly synchronised. For simple variables, it may be enough
to declare the variable volatile, but in most situations, we will need to use synchronisation. If we are going to use
synchronisation to protect access to shared variables, we must make sure to use it everywhere in our program where
the variable is accessed.

1.12.6 Don’t Overdo It


While threads can greatly simplify many types of applications, overuse of threads can be hazardous to our program’s
performance and its maintainability. Threads consume resources. Therefore, there is a limit on how many threads we
can create without degrading performance. In particular, using multiple threads will not make a CPU-bound program
run any faster on a single-processor system. For example using a thread for timing and using a thread to do work.

The following example uses two threads, one for timing and one to do actual work. The main thread calculates
prime numbers using a very straightforward algorithm. Before it starts, it creates and starts a timer thread, which
will sleep for ten seconds, and then set a flag that the main thread will check. After ten seconds, the main thread
will stop. Note that the shared flag is declared volatile.

/**
* CalculatePrimes -- calculate as many primes as we can in ten seconds
*/
public class CalculatePrimes extends Thread {
public static final int MAX_PRIMES = 1000000;
public static final int TEN_SECONDS = 10000;
public volatile boolean finished = false;
public void run() {
int[] primes = new int[MAX_PRIMES];
int count = 0;
for (int i=2; count<MAX_PRIMES; i++) {
// Check to see if the timer has expired

16/ADTU OLE
if (finished) {
break;
}
boolean prime = true;
for (int j=0; j<count; j++) {
if (i % primes[j] == 0) {
prime = false;
break;
}
}
if (prime) {
primes[count++] = i;
[Link](“Found prime: “ + i);
}
}
}
public static void main(String[] args) {
CalculatePrimes calculator = new CalculatePrimes();
[Link]();
try {
[Link](TEN_SECONDS);
}
catch (InterruptedException e) {
// fall through
}
[Link] = true;
}
}

1.13 Creating Threads


There are several ways to create a thread in a Java program. Every Java program contains at least one thread: the
main thread. Additional threads are created through the Thread constructor or by instantiating classes that extend
the Thread class. Java threads can create other threads by instantiating a Thread object directly or an object that
extends Thread.

When we talk about threads in Java programs, there are two related entities we may be referring to: the actual thread
that is doing the work or the Thread object that represents the thread. The running thread is generally created by the
operating system; the Thread object is created by the Java VM as a means of controlling the associated thread.

Creating threads and starting threads are not the same. A thread doesn’t actually begin to execute until another thread
calls the start() method on the Thread object for the new thread. The Thread object exists before its thread actually
starts, and it continues to exist after its thread exits. This allows us to control or obtain information about a thread
we’ve created, even if the thread hasn’t started yet or has already completed.

It’s generally a bad idea to start() threads from within a constructor. Doing so could expose partially constructed
objects to the new thread. If an object owns a thread, then it should provide a start() or init() method that will start
the thread, rather than starting it from the constructor.

17/ADTU OLE
Advanced Java

1.13.1 Ending Threads


A thread will end in one of three ways:
• The thread comes to the end of its run() method.
• The thread throws an Exception or Error that is not caught.
• Another thread calls one of the deprecated stop() methods. Deprecated means they still exist, but we shouldn’t
use them in new code and should strive to eliminate them in existing code. When all the threads within a Java
program complete, the program exits.

1.13.2 Joining With Threads


The Thread API contains a method for waiting for another thread to complete: the join() method. When we call
[Link](), the calling thread will block until the target thread

completes. [Link]() is generally used by programs that use threads to partition large problems into smaller
ones, giving each thread a piece of the problem. The example at the end of this section creates ten threads, starts
them, then uses [Link]() to wait for them all to complete.

1.13.3 Scheduling
Except when using [Link]() and [Link](), the timing of thread scheduling and execution is nondeterministic.
If two threads are running at the same time and neither is waiting, we must assume that between any two instructions,
other threads may be running and modifying program variables. If our thread will be accessing data that may be
visible to other threads, such as data referenced directly or indirectly from static fields such as global variables, we
must use synchronisation to ensure data consistency. In the simple example below, we’ll create and start two threads,
each of which prints two lines to [Link]:

public class TwoThreads {


public static class Thread1 extends Thread {
public void run() {
[Link](“A”);
[Link](“B”);
}
}
public static class Thread2 extends Thread {
public void run() {
[Link](“1”);
[Link](“2”);
}
}
public static void main(String[] args) {
new Thread1().start();
new Thread2().start();
}
}

We have no idea in what order the lines will execute, except that “1” will be printed before “2” and “A” before “B.”
The output could be any one of the following:
12AB
1A2B
1AB2
A12B

A1B2
AB12

18/ADTU OLE
Not only the results vary from machine to machine, but running the same program multiple times on the same
machine may produce different results. Never assume one thread will do something before another thread does,
unless we’ve used synchronisation to force a specific ordering of execution.

1.13.4 Sleeping
The Thread API includes a sleep () method, which will cause the current thread to go into a wait state until the
specified amount of time has elapsed or until the thread is interrupted by another thread calling [Link]()
on the current thread’s Thread object. When the specified time elapses, the thread again becomes runnable and goes
back onto the scheduler’s queue of runnable threads.

If a thread is interrupted by a call to [Link](), the sleeping thread will throw an InterruptedException so that
the thread will know that it was awakened by an interrupt and won’t have to check to see if the timer expired. The
[Link]() method is like [Link](), but instead of sleeping, it simply pauses the current thread momentarily
so that other threads can run. In most implementations, threads with lower priority will not run when a thread of
higher priority calls [Link]().

The CalculatePrimes example used a background thread to calculate primes, then slept for ten seconds. When the
timer expired, it set a flag to indicate that the ten seconds had expired.

1.13.5 Daemon Threads


We mentioned that a Java program exits when all of its threads have completed, but this is not exactly correct. What
about the hidden system threads, such as the garbage collection thread and others created by the JVM? We have no
way of stopping these. If those threads are running, how does any Java program ever exit?

These system threads are called daemon threads. A Java program actually exits when all its non-daemon threads
have completed. Any thread can become a daemon thread. We can indicate a thread is a daemon thread by calling
the [Link]() method. We might want to use daemon threads for background threads that we create in
our programs, such as timer threads or other deferred event threads, which are only useful while there are other
non-daemon threads running.

Example: Partitioning a large task with multiple threads


In this example, TenThreads shows a program that creates ten threads, each of which do some work. It waits for
them all to finish, then gathers the results.

/**
* Creates ten threads to search for the maximum value of a large matrix.
* Each thread searches one portion of the matrix.
*/
public class TenThreads {
private static class WorkerThread extends Thread {
int max = Integer.MIN_VALUE;
int[] ourArray;
public WorkerThread(int[] ourArray) {
[Link] = ourArray;
}
// Find the maximum value in our particular piece of the array
public void run() {
for (int i = 0; i < [Link]; i++)
max = [Link](max, ourArray[i]);
}
public int getMax() {
return max;

19/ADTU OLE
Advanced Java

}
}
public static void main(String[] args) {
WorkerThread[] threads = new WorkerThread[10];
int[][] bigMatrix = getBigHairyMatrix();
int max = Integer.MIN_VALUE;
// Give each thread a slice of the matrix to work with
for (int i=0; i < 10; i++) {
threads[i] = new WorkerThread(bigMatrix[i]);
threads[i].start();
}
// Wait for each thread to finish
try {
for (int i=0; i < 10; i++) {
threads[i].join();
max = [Link](max, threads[i].getMax());
}
}
catch (InterruptedException e) {
// fall through
}
[Link](“Maximum value was “ + max);
}
}

1.13.6 Who Creates Threads?


Even if we never explicitly create a new thread, we may find ourselves working with threads anyway. Threads are
introduced into our programs from a variety of sources. There are a number of facilities and tools that create threads
for us, and we should understand how threads interact and how to prevent threads from getting in the way of each
other if we’re going to use these facilities.

1.14 AWT and Swing


Any program that uses AWT or Swing must deal with threads. The AWT toolkit creates a single thread for handling
UI events, and any event listeners called by AWT events execute in the AWT event thread. Not only do we have
to worry about synchronising access to data items shared between event listeners and other threads, but we have
to find a way for long-running tasks triggered by event listeners such as checking spelling in a large document or
searching a file system for a file to run in a background thread so the UI doesn’t freeze while the task is running
(which would also prevent the user from cancelling the operation).

A good example of a framework for doing this is the SwingWorker class. The AWT event thread is not a daemon
thread; this is why [Link]() is often used to end AWT and Swing apps.

1.15 Using TimerTask


The TimerTask facility was introduced to the Java language in JDK 1.3. This convenient facility allows executing
a task at a later time that is, for example, run a task once ten seconds from now, or to execute a task periodically
that is, running a task every ten seconds. Implementing the Timer class is quite straightforward: it creates a timer
thread and builds a queue of waiting events sorted by execution time.

The TimerTask thread is marked as a daemon thread so it doesn’t prevent the program from exiting. Because timer
events execute in the timer thread, we must make sure that access to any data items used from within a timer task
is properly synchronised. In the CalculatePrimes example, instead of having the main thread sleep, we could have
used a TimerTask as follows:

20/ADTU OLE
public static void main(String[] args) {
Timer timer = new Timer();
final CalculatePrimes calculator = new CalculatePrimes();
[Link]();
[Link](
new TimerTask() {
public void run()
{
[Link] = true;
}
}, TEN_SECONDS);
}

1.16 Servlets and Java Server Pages Technology


Servlet containers create multiple threads in which servlet requests are executed. As the servlet writer, we have no
idea (nor should we) in what thread our request will be executed; the same servlet could be active in multiple threads
at once if multiple requests for the same URL come in at the same time. When writing servlets or Java Server Pages
(JSP) files, we must assume at all times that the same servlet or JSP file may be executing concurrently in multiple
threads. Any shared data accessed by a servlet or JSP file must be appropriately synchronised; this includes fields
of the servlet object itself.

1.17 Implementing an RMI Object


The RMI facility allows invoking operations on objects running in other JVMs. When we call a remote method, the
RMI stub, created by the RMI compiler, packages up the method parameters and sends them over the network to
the remote system, which unpacks them and calls the remote method. Suppose we are creating an RMI object and
register it in the RMI registry or a Java Naming and Directory Interface (JNDI) namespace. When a remote client
invokes one of its methods, in what thread does that method execute?

The common way to implement an RMI object is to extend UnicastRemoteObject. When a UnicastRemoteObject
is constructed, the infrastructure for dispatching remote method calls is initialised. This includes a socket listener
to receive remote invocation requests, and one or more threads to execute remote requests.

So when we receive a request to execute an RMI method, these methods will execute in an RMI-managed thread.
• Sharing access to data
• Sharing variables

For multiple threads to be useful in a program, they have to have some way to communicate or share their results
with each other. The simplest way for threads to share their results is to use shared variables. They should also use
synchronisation to ensure that values are propagated correctly from one thread to another and to prevent threads
from seeing inconsistent intermediate results while another thread is updating several related data items.

The example that calculated prime numbers in Thread basics used a shared Boolean variable to indicate that the
specified time period had elapsed. This illustrates the simplest form of sharing data between threads: polling a shared
variable to see if another thread has finished performing a certain task.

21/ADTU OLE
Advanced Java

1.18 All Threads Live in the Same Memory Space


As we discussed earlier, threads have a lot in common with processes, except that they share the same process
context, including memory, with other threads in the same process. This is a tremendous convenience, but also a
significant responsibility. Threads can easily exchange data among themselves simply by accessing shared variables
static or instance fields, but threads must also ensure that they access shared variables in a controlled manner, lest
they step on each other’s changes.

Any reachable variable is accessible to any thread, just as it is accessible to the main thread. The prime numbers
example used a public instance field, called finished, to indicate that the specified time had elapsed. One thread
wrote to this field when the timer expired; the other read from this field periodically to check if it should stop. Note
that this field was declared volatile, which is important to the proper functioning of this program. We’ll see why
later in this section.

1.19 Synchronisation for Controlled Access


The Java language provides two keywords for ensuring that data can be shared between threads in a controlled manner:
synchronised and volatile. Synchronised has two important meanings: it ensures that only one thread executes a
protected section of code at one time (mutual exclusion or mutex), and it ensures that data changed by one thread is
visible to other threads (visibility of changes). Without synchronisation, it is easy for data to be left in an inconsistent
state. For example, if one thread is updating two related values (say, the position and velocity of a particle), and
another thread is reading those two values, it is possible that the second thread could be scheduled to run after the
first thread has written one value but not the other, thus seeing one old and one new value. Synchronisation allows
us to define blocks of code that must run atomically, in which they appear to execute in an all-or-nothing manner,
as far as other threads can tell.

The atomic execution or mutual exclusion aspect of synchronisation is similar to the concept of critical sections in
other operating environments.

1.20 Ensuring Visibility of Changes to Shared Data


Synchronisation allows us to ensure that threads see consistent views of memory. Processors can use caches to
speed up access to memory or compilers may store values in registers for faster access. On some multiprocessor
architecture, if a memory location is modified in the cache on one processor, it is not necessarily visible to other
processors until the writer’s cache is flushed and the reader’s cache is invalidated.

This means that on such systems, it is possible for two threads executing on two different processors to see two
different values for the same variable! This sounds scary, but it is normal. It just means that we have to follow some
rules when accessing data used or modified by other threads. Volatile is simpler than synchronisation and is suitable
only for controlling access to single instances of primitive variables, integers, Booleans, and so on. When a variable
is declared volatile, any write to that variable will go directly to main memory, bypassing the cache, while any read
of that variable will come directly from main memory, bypassing the cache.

This means that all threads see the same value for a volatile variable at all times. Without proper synchronisation,
it is possible for threads to see stale values of variables or experience other forms of data corruption.

1.21 Atomic Code Blocks Protected by Locks


Volatile is useful for ensuring that each thread sees the most recent value for a variable, but sometimes we need to
protect access to larger sections of code, such as sections that involve updating multiple variables. Synchronisation
uses the concepts of monitors, or locks, to coordinate access to particular blocks of code.

Every Java object has an associated lock. Java locks can be held by no more than one thread at a time. When a
thread enters a synchronised block of code, the thread blocks and waits until the lock is available, acquires the lock
when it becomes available, and then executes the block of code. It releases the lock when control exits the protected
block of code, either by reaching the end of the block or when an exception is thrown that is not caught within the
synchronised block.

22/ADTU OLE
In this way, only one thread can execute a block protected by a given monitor at one time. The block can be considered
atomic because, from the perspective of other threads, it appears to either have executed entirely or not at all. Using
synchronised blocks allows us to perform a group of related updates as a set without worrying about other threads
interrupting or seeing the intermediate results of a computation. The following example code will either print “1 0”
or “0 1.” In the absence of synchronisation, it could also print “1 1” (or even “0 0,” believe it or not).

public class SyncExample {


private static lockObject = new Object();
private static class Thread1 extends Thread {
public void run() {
synchronised (lockObject) {
x = y = 0;
[Link](x);
}
}
}
private static class Thread2 extends Thread {
public void run() {
synchronised (lockObject) {
x = y = 1;
[Link](y);
}
}
}
public static void main(String[] args) {
new Thread1().run();
new Thread2().run();
}
}

We must use synchronisation in both threads for this program to work properly.

1.22 Java Locking


Java locking incorporates a form of mutual exclusion. Only one thread may hold a lock at one time. Locks are used
to protect blocks of code or entire methods, but it is important to remember that it is the identity of the lock that
protects a block of code, not the block itself. One lock may protect many blocks of code or methods.

Conversely, just because a block of code is protected by a lock does not mean that two threads cannot execute that
block at once. It only means that two threads cannot execute that block at once if they are waiting on the same lock. In
the following example, the two threads are free to execute the synchronised block in setLastAccess() simultaneously
because each thread has a different value for thingie. Therefore, the synchronised block is protected by different
locks in the two executing threads.

public class SyncExample {


public static class Thingie {
private Date lastAccess;
public synchronised void setLastAccess(Date date) {
[Link] = date;
}
}
public static class MyThread extends Thread {

23/ADTU OLE
Advanced Java

private Thingie thingie;


public MyThread(Thingie thingie) {
[Link] = thingie;
}
public void run() {
[Link](new Date());
}
}
public static void main() {
Thingie thingie1 = new Thingie(),
thingie2 = new Thingie();
new MyThread(thingie1).start();
new MyThread(thingie2).start();
}
}

1.22.1 Synchronised Methods


The simplest way to create a synchronised block is to declare a method as synchronised. This means that before
entering the method body, the caller must acquire a lock:

public class Point {


public synchronised void setXY(int x, int y) {
this.x = x;
this.y = y;
}
}

For ordinary synchronised methods, this lock will be the object on which the method is being invoked. For static
synchronised methods, this lock will be the monitor associated with the Class object in which the method is declared.
Just because setXY() is declared as synchronised doesn’t mean that two different threads can’t still execute setXY()
at the same time, as long as they are invoking setXY() on different Point instances. Only one thread can execute
setXY(), or any other synchronised method of Point, on a single Point instance at one time.

1.22.2 Synchronised Blocks


The syntax for synchronised blocks is a little more complicated than for synchronised methods because we also
need to explicitly specify what lock is being protected by the block. The following version of Point is equivalent to
the version shown in the previous panel:

public class Point {


public void setXY(int x, int y) {
synchronised (this) {
this.x = x;
this.y = y;
}
}
}

24/ADTU OLE
It is common, but not required, to use the this reference as the lock. This means that the block will use the same lock
as synchronised methods in that class. Because synchronisation prevents multiple threads from executing a block
at once, it has performance implications, even on uniprocessor systems. It is a good practice to use synchronisation
around the smallest possible block of code that needs to be protected. Access to local (stack-based) variables never
needs to be protected, because they are only accessible from the owning thread.

1.22.3 Most Classes are Not Synchronised


Because synchronisation carries a small performance penalty, most general-purpose classes, like the Collection
classes in [Link], do not use synchronisation internally. This means that classes like HashMap cannot be used from
multiple threads without additional synchronisation. We can use the Collections classes in a multithreaded application
by using synchronisation every time We access a method in a shared collection. For any given collection, We must
synchronise on the same lock each time. A common choice of lock would be the collection object itself.

The example class SimpleCache in the next panel shows how We can use a HashMap to provide caching in a
thread-safe way. Generally, however, proper synchronisation doesn’t just mean synchronising every method. The
Collections class provides us with a set of convenience wrappers for the List, Map, and Set interfaces. We can wrap
a Map with [Link] and it will ensure that all access to that map is properly synchronised.
If the documentation for a class does not say that it is thread-safe, then We must assume that it is not. Example: A
simple thread-safe cache.

As shown in the following code sample, [Link] uses a HashMap to provide a simple cache for an object
loader. The load() method knows how to load an object by its key. After an object is loaded once, it is stored in the
cache so subsequent accesses will retrieve it from the cache instead of loading it all over each time. Each access to
the shared cache is protected by a synchronised block. Because it is properly synchronised, multiple threads can
call the getObject and clearCache methods simultaneously without risk of data corruption.

public class SimpleCache {


private final Map cache = new HashMap();
public Object load(String objectName) {
// load the object somehow
}
public void clearCache() {
synchronised (cache) {
[Link]();
}
}
public Object getObject(String objectName) {
synchronised (cache) {
Object o = [Link](objectName);
if (o == null) {
o = load(objectName);
[Link](objectName, o);
}
}
return o;
}
}

25/ADTU OLE
Advanced Java

Summary
• Java is an object-oriented programming language with a built-in application programming interface.
• Much of the syntax of Java is the same as C and C++.
• Java is based on the C and C++ programming languages, but differs from these languages in some important
ways.
• Since the original release of Java, several extensions have been added to the core code, providing greater
flexibility and power to applications these features are known as advanced java.
• Good object-oriented style dictates that all data members of a class should be declared private, hidden from any
operations other than those included in the class itself.
• Constructors set up a class for use. Classes don’t need to specify a constructor; indeed a constructor is, by default,
simply a function call to nothing.
• In Java, everything is inherited from the superclass object.
• A constructor can be modified easily to accept incoming data as well, enabling us to modify our object depending
on the context of its use.
• An object is allowed to have several constructors, so long as no two constructors have the same method
signature.
• A base class is a special kind of object that forms the foundation for other classes.
• Java provides several tools for the input and output of data, ranging from the Abstract Window Toolkit
(AWT).
• Java provides several different kinds of streams, each designed to handle a different kind of data.
• In Java, applications are allowed to write to the standard output devices on a machine.
• One of the classes Java includes in every applet or application, which specifies that it do so or not, is the System
class.
• The standard interface to a network in the computer world is a socket.
• Our current windowing system may be anything from X11/Motif to Windows 95’s own window system.
• Input and output are at the heart of every program we create.
• Nearly every operating system supports the concept of processes independently running programs that are
isolated from each other to some degree.
• The TimerTask facility was introduced to the Java language in JDK 1.3.

References
• Liang D. Y., 2012. Introduction to Java Programming, Brief Version, 9th ed. Pearson Education, Limited.
• Wong, H. and Oaks, S., 2004. Java threads, 3rd ed. O’Reilly Media, Inc Publication.
• Goetz, B., 2002. Introduction to Java Threads, [pdf] Available at: <[Link]
tutorials/j-threads/[Link]> [Accessed 10 April 2012].
• Fletcher, J., AWT vs SWING, [Online] Available at: <[Link] [Accessed 10
April 2012].
• 2010. Java Programming Tutorial Session 1 Introduction to oop and Java Programming for Beginners Part 1,
[Video Online] Available at: <[Link] [Accessed
10 April 2012].
• 2010. Java swings and awt, [Video Online] Available at: <[Link]
feature=results_main&playnext=1&list=PL91DBCBD1A8242D8A> [Accessed 10 April 2012].

26/ADTU OLE
Recommended Reading
• Berge, J. C., 2000. Advanced Java 2: Development for Enterprise Applications, 2nd ed. Sun Microsystems
Press Publication.
• Shaw, P., Java Threads FAQ, One Percent Better Publication.
• Zukowski, J., 2005. The Definitive Guide To Java Swing, 3rd ed. Apress Publication.

27/ADTU OLE
Advanced Java

Self Assessment
1. Which of the following statements is false?
a. Java is a pointer-free language.
b. Java is exactly similar to C and C++ programming languages.
c. Method is one of the important components of the Java class.
d. Constructors set up a class for use.

2. All Java classes inherit from the Object _________.


a. superclass
b. class
c. constructor
d. methods

3. _______ is a set of components for designing windows and graphical user interfaces.
a. Swing
b. I/O Routine
c. AWT
d. Thread

4. File buffers are the ________commonly used to increase performance in an input/output scheme.
a. constructors
b. swing
c. class
d. method

5. Which of the following operation is not performed on the file?


a. Transfer
b. Open
c. Read
d. Close

6. Which of the following statements is false?


a. Sockets are nothing but files in the purest sense
b. InputStream and OutputStream can not be used for file manipulation.
c. Streams are designed to handle a different kind of data.
d. More complicated stream schemes can be derived from InputStream and OutputStream.

7. Any program that uses AWT or Swing must deal with _________.
a. threads
b. swing
c. AWT toolkit
d. UI

28/ADTU OLE
8. The _____ facility allows invoking operations on objects running in other JVMs.
a. UI
b. AWT
c. RMI
d. Swing

9. A thread can be indicated daemon thread by calling the______________method.


a. [Link]()
b. [Link]()
c. [Link]()
d. [Link]()

10. Java ______are used to protect blocks of code or entire methods.


a. threads
b. files
c. locks
d. blocks

29/ADTU OLE
Advanced Java

Chapter II
Introduction to Swing

Aim
The aim of this chapter is to:

• explain Java user interfaces

• elucidate swing and its role in Java

• enlist various swing widgets

Objectives
The objectives of this chapter are to:

• explain Java components

• explicate applications of Java components and widgets

• elucidate Model-View-Controller

Learning outcome
At the end of this chapter, you will be able to:

• understand all the models of Java swing

• identify applications using Java swing models

• recognise swing widgets

30/ADTU OLE
2.1 Introduction to UIs
Before we start to learn Swing, we must know “What is a UI?” As a beginner the answer for this question is a “user
interface.” But the more advanced definition of UI is that, these are the buttons we press, the address bar we type
in, and the windows we open and close, which are all elements of a UI, but there’s more to it than just things we see
on the screen. The mouse, keyboard, volume of the music, colours on the screen, fonts used, and the position of an
object compared to another object are all included in the UI. Basically, any object that plays a role in the interaction
between the computer and the user is part of the UI. That seems simple enough, but we would be surprised how
many people and huge corporations have screwed this up over the years. In fact, there are now college majors whose
sole coursework is studying this interaction.

2.2 Swing’s Role


Swing is the Java platform’s UI; it acts as the software to handle all the interaction between a user and the computer.
It essentially serves as the middleman between the user and the guts of the computer. How exactly does Swing do
this? It provides mechanisms to handle the UI aspects described in the previous panel:
• Keyboard: Swing provides a way to capture user input.
• Colours: Swing provides a way to change the colours we see on the screen.
• The address bar we type into: Swing provides text components that handle all the commonplace tasks.
• The volume of the music: Swing is not so perfect in it.

In any case, Swing gives all the tools we need to create our own UI.

2.3 MVC
Swing even goes a step further and puts a common design pattern on top of the basic UI principles. This design
pattern is called Model-View-Controller (MVC) and seeks to “separate the roles.” MVC keeps the code responsible
for how something looks separate from the code to handle the data separate from the code that reacts to interaction
and drives changes.

Consider, a non technical example to know it easily, think about a fashion show. Consider this is our UI and act
as if that the clothes are the data, the computer information we present to our user. Now, imagine that this fashion
show has only one person in it. This person designed the clothes, modified the clothes, and walked them down the
runway all at the same time. That doesn’t seem like a well-constructed or efficient design.

Now, consider this same fashion show using the MVC design pattern. Instead of one person doing everything, the
roles are divided up. The fashion models (not to be confused with the model in the acronym MVC of course) present
the clothes. They act as the view. They know the proper way to display the clothes (data), but have no knowledge
at all about how to create or design the clothes. On the other hand, the clothing designer works behind the scenes,
making changes to the clothes as necessary. The designer acts as the controller. This person has no concept of
how to walk a runway but can create and manipulate the clothes. Both the fashion models and the designer work
independently with the clothes, and both have an area of expertise.

That is the concept behind the MVC design pattern: Let each aspect of the UI deal with what it’s good at. The basic
principle of MVC is that: Visual components display data, and other classes manipulate it.

31/ADTU OLE
Advanced Java

2.4 JComponent
The basic building block of the entire visual component library of Swing is the JComponent. It’s the super class of
every component. It’s an abstract class, so we can’t actually create a JComponent, but it contains literally hundreds
of functions every component in Swing can use as a result of the class hierarchy.
• JComponent is the base class not only for the Swing components but also for custom components as well.
• It provides the painting infrastructure for all components something that comes in handy for custom
components.
• It knows how to handle all keyboard presses. Subclasses then only need to listen for specific keys.
• It contains the add() method that lets add other JComponents.

There is also another way to add swing component to any other Swing component, to build nested components. For
example, a JPanel containing a JButton, or even weirder combinations such as a JMenu containing a JButton.

2.5 Simple Swing Widgets


Swing components are basic building blocks of an application. Swing toolkit has a wide range of various widgets.
Buttons, check boxes, sliders, list boxes etc. everything a programmer needs for his job. These components are
described here:

2.5.1 JLabel
The most basic component in the Swing library is the JLabel. It does exactly what we’d expect: It sits there and
looks pretty and describes other components. The image below shows the JLabel in action:

This is a label

Fig. 2.1 The JLabel

It is not very exciting, but still very useful. In fact, JLabels are being used throughout applications not only as text
descriptions, but also as picture descriptions. If we come across a picture in a Swing application, there are chances
that it is a JLabel. JLabel doesn’t have many methods for a Swing beginner outside of what we might expect. The
basic methods involve setting the text, image, alignment, and other components the label describes:
• get/setText(): Gets/sets the text in the label.
• get/setIcon(): Gets/sets the image in the label.
• get/setHorizontalAlignment(): Gets/sets the horizontal position of the text.
• get/setVerticalAlignment(): Gets/sets the vertical position of the text.
• get/setDisplayedMnemonic(): Gets/sets the mnemonic (the underlined character) for the label.
• get/setLabelFor(): Gets/sets the component this label is attached to; so when a user presses Alt+mnemonic, the
focus goes to the specified component.

2.5.2 JButton
The basic action component in Swing, a JButton, is the push button given below with the OK and Cancel in every
window; it does exactly what we expect a button to do; if we click it some actions will get perform. A JButton in
action looks like the snapshot below:

OK

Fig. 2.2 The JButton

32/ADTU OLE
The methods we use to change the JButton properties are similar to the JLabel methods and these are generally
similar across most Swing components. They control the text, the images, and the orientation:
• get/setText(): Gets/sets the text in the button.
• get/setIcon(): Gets/sets the image in the button.
• get/setHorizontalAlignment(): Gets/sets the horizontal position of the text.
• get/setVerticalAlignment(): Gets/sets the vertical position of the text.
• get/setDisplayedMnenomic(): Gets/sets the mnemonic (the underlined character) that when combined with the
Alt button, causes the button to click.

In addition to these methods, there is another group of methods the JButton contains. These methods take advantage
of all the different states of a button. A state is a property that describes a component, usually in a true/false setting.
In the case of a JButton, it contains the following possible states: active/inactive, selected/not selected, mouse-over/
mouse-off, pressed/unpressed. In addition, we can combine states, so that, for example, a button can be selected
with a mouse-over. Now to see the practical application of all these states we will see an example, go up to the Back
button on browser. Notice how the image changes when mouse over it, and how it changes when we press it. This
button takes advantage of the various states. Using different images with each state is a popular and effective way
to indicate to a user that interaction is taking place. The state methods on a JButton are:
• get/setDisabledIcon()
• get/setDisabledSelectedIcon()
• get/setIcon()
• get/setPressedIcon()
• get/setRolloverIcon()
• get/setRolloverSelectedIcon()
• get/setSelectedIcon()

2.5.3 JTextField
The basic text component in Swing is the JTextField, and it allows a user to enter text into the UI. Use one to enter
the user name and password to learn this example. Once we enter text, delete text, highlight text, and move the
caret around swing takes care of all of those actions we entered to perform. As a UI developer, there’s really little
we need to do to take advantage of the JTextField. The JTextField looks like in action as follows:

This is a JTextField

Fig. 2.3 The JTextField

We need to concern our self with only one method when we deal with a JTextField and that should be obvious the
one that sets the text: get/setText(), which gets/sets the text inside the JTextField.

2.5.4 JFrame
We have seen three basic building blocks of Swing, the label, button, and text field; now we will learn how to put
them together. They can’t just float around on the screen, hoping the user knows how to deal with them. The JFrame
class does just that it’s a container that lets add other components to it in order to organise them and present them
to the user. It contains many other bonuses, see the snapshot given below:

33/ADTU OLE
Advanced Java

Fig. 2.4 The JFrame

A JFrame actually does more than the components we have placed on it and present it to the user. For all its apparent
simplicity, it’s actually one of the most complex components in the Swing packages. To greatly simplify why, the
JFrame acts as bridge between the OS-independent Swing parts and the actual OS it runs on. The JFrame registers
as a window in the native OS and by doing so gets many of the familiar OS window features: minimise/maximise,
resizing, and movement. Some of the methods we can call on a JFrame to change its properties are:
• get/setTitle(): Gets/sets the title of the frame.
• get/setState(): Gets/sets the frame to be minimised, maximised, etc.
• is/setVisible(): Gets/sets the frame to be visible, in other words, appear on the screen.
• get/setLocation(): Gets/sets the location on the screen where the frame should appear.
• get/setSize(): Gets/sets the size of the frame.
• add(): Adds components to the frame.

2.5.5 A Simple Application


We will see the simple HelloWorld demonstration. This example, however, is useful not only to see how a Swing
app works but also to ensure that our setup is correct. Once we get this simple app to work, every example after this
one will work as well. The image below shows the completed example:

Fig. 2.5 HelloWorld example

34/ADTU OLE
The first step is to create the class. A Swing application that places components on a JFrame needs to subclass the
JFrame class, like this:

public class HelloWorld extends JFrame

By doing this, we get all the JFrame properties outlined above, most importantly native OS support for the window.
The next step is to place the components on the screen. In this example, we use a null layout. For this example
though, the numbers indicate the pixel position on the JFrame:

public HelloWorld()
{
super();
[Link](300, 200);
[Link]().setLayout(null);
[Link](getJLabel(), null);
[Link](getJTextField(), null);
[Link](getJButton(), null);
[Link](“HelloWorld”);
}
private [Link] getJLabel() {
if(jLabel == null) {
jLabel = new [Link]();
[Link](34, 49, 53, 18);
[Link](“Name:”);
}
return jLabel;
}
private [Link] getJTextField() {
if(jTextField == null) {
jTextField = new [Link]();
[Link](96, 49, 160, 20);
}
return jTextField;
}
private [Link] getJButton() {
if(jButton == null) {
jButton = new [Link]();
[Link](103, 110, 71, 27);
[Link](“OK”);
}
return jButton;
}

Now that the components are laid out on the JFrame, we need the JFrame to show up on the screen and make our
application runnable. As in all Java applications, we must add a main method to make a Swing application runnable.
Inside this main method, we simply need to create HelloWorld application object and then call setVisible() on it:

35/ADTU OLE
Advanced Java

public static void main(String[] args)


{
HelloWorld w = new HelloWorld();
[Link](true);
}

These are the steps to create the application.

2.6 Additional Swing Widgets


In additional swing widgets we’ll cover all the other components in the Swing library, how to use them, and what
they look like, which will give a better idea of the power Swing as a UI developer.

2.6.1 JComboBox
A combo box is the familiar drop-down selection, where users can either select none or one (and only one) item
from the list. In some versions of the combo box, we can type in our own choice. A good example is the address
bar in our browser; that is a combo box that lets us type in our own choice. Here’s what the JComboBox looks like
in Swing:

This is a Combobox

Fig. 2.6 The JComboBox

The important functions with a JComboBox involve the data it contains. We need a way to set the data in the
JComboBox, change it, and get the users’ choice once they’ve made a selection. We can use the following JComboBox
methods:
• addItem(): Adds an item to the JComboBox.
• get/setSelectedIndex(): Gets/sets the index of the selected item in JComboBox.
• get/setSelectedItem(): Gets/sets the selected object.
• removeAllItems(): Removes all the objects from the JComboBox.
• remoteItem(): Removes a specific object from the JComboBox.

2.6.2 JTabbedPane
Tabbed pane is used to show the component from a group of same components if one of the tab of a pane is selected
that is when the tab is selected it shows corresponding component and so on. Extended portion of tab may have a
title, an icon or both together. Tab may get highlighted when selection is made. Tabbed panes are generally used to
save the space by having multiple components separated by a tab. In Java Swing we can create tabbed panes using
JTabbedPane. JTabbedPane comes with three constructor flavours.

JTabbedPane()

Above constructor constructs an empty tabbed pane with default tab placement which is at the tab and denoted by
[Link].

JTabbedPane( int tabPlacement )

36/ADTU OLE
In above constructor we can specify the tab placement which is specified by either [Link], JTabbedPane.
BOTTOM, [Link], [Link].

JTabbedPane ( int tabPlacement, int tabLayoutPolicy )

In above constructor with tab placement option we can also specify the tab layout policy which is the policy which
decides how to layout the panes when all tabs do not fit on the go. Follow the procedure below to create the tabbed
panes using JTabbedPane.
1. JFrame tabbedFrame = new JFrame(“Tabbed Pane Example”);
2. [Link](JFrame.EXIT_ON_CLOSE);
3. JTabbedPane tabEx = new JTabbedPane();
4. [Link]( tabEx, [Link] );
5. JButton button = new JButton( “1st tab selected” );
6. [Link]( “1st Tab”, button );
7. button = new JButton( “2nd tab selected” );
8. [Link](“2nd Tab”, button);
9. [Link]( 300,200 );
10. [Link]( true );

Output:

In above example we have used add method which adds a component to JTabbedPane with a specified title. Here
we have used method with two arguments, first is the title which is the title to be displayed for the tab and second
argument is the component which need to be shown up when we select the tab.

2.6.3 JPasswordField
A slight variation on the JTextField is the JPasswordField, which lets to hide all the characters displayed in the
text field area. After all, what good is a password everyone can read as we type it in? Probably not very good one
at all, and in this day and age when our private data is susceptible, we need all the help we can get. Here’s how a
JPasswordField looks in Swing:

37/ADTU OLE
Advanced Java



Fig. 2.7 The JPasswordField

The additional “security” methods on a JPasswordField change the behaviour of a JTextField slightly so that we
can’t read the text:
• get/setEchoChar(): Gets/sets the character that appears in the JPasswordField every time a character is entered.
The “echo” is not returned when we get the password; the actual character is returned instead.
• getText(): We should not use this function, as it poses possible security problems (for those interested, the String
would be kept in memory, and a possible heap dump could reveal the password).
• getPassword(): This is the proper method to get the password from the JPasswordField, as it returns a char[]
containing the password. To ensure proper security, the array should be cleared to 0 to ensure it does not remain
in memory.

2.6.4 JCheckBox/JRadioButton
The JCheckBox and JRadioButton components present options to a user, usually in a multiple-choice format. What’s
the difference? From a practical standpoint, they aren’t that different. They behave in the same way. However, in
common UI practices, they have a subtle difference: JRadioButtons are usually grouped together to present to the
user a question with a mandatory answer, and these answers are exclusive (means there can be only one answer to
the question).

The JRadioButton’s behaviour enforces this use. Once we select a JRadioButton, we cannot deselect it unless we
select another radio button in the group. This, in effect, makes the choices unique and mandatory. The JCheckBox
differs by letting us select/deselect at random, and allowing us to select multiple answers to the question. Consider
an example. The question “Are you a guy or a girl?” leads to two unique answer choices “Guy” or “Girl.” The user
must select one and cannot select both. On the other hand, the question “What are your hobbies?” with the answers
“Running,” “Sleeping,” or “Reading” should not allow only one answer, because people can have more than one
hobby.

The class that ties groups of these JCheckBoxes or JRadioButtons together is the ButtonGroup class. It allows us
to group choices together (such as “Guy” and “Girl”) so that when one is selected, the other one is automatically
deselected. Here’s what JCheckBox and JRadioButton look like in Swing:

 This is a Checkbox

This is a RadioButton

Fig. 2.8 JCheckBox and JRadioButton

38/ADTU OLE
The important ButtonGroup methods to remember are:
• add(): Adds a JCheckBox or JRadioButton to the ButtonGroup.
• getElements(): Gets all the components in the ButtonGroup, it allows to iterate through them to find the one
selected.

2.6.5 JMenu/JMenuItem/JMenuBar
The JMenu, JMenuItem, and JMenuBar components are the main building blocks of developing the menu system
on the JFrame. The base of any menu system is the JMenuBar. It’s plain and boring, but it’s required because every
JMenu and JMenuItem builds off it. Use the setJMenuBar() method to attach the JMenuBar to the JFrame.

Once it’s anchored onto the JFrame, we can add all the menus, submenus, and menu items we want.

The JMenu/JMenuItem difference might seem obvious, but is in fact underneath the covers and isn’t what it appears
to be. If we look at the class hierarchy, JMenu is a subclass of JMenuItem. However, on the surface, they have a
difference: Use JMenu to contain other JMenuItems and JMenus; JMenuItems, when chosen, trigger actions. The
JMenuItem also supports the notion of a shortcut key. As in most applications we’ve used, Swing applications
allow us to press Ctrl+ (a key) to trigger an action as if the menu item itself was selected. Think of the Ctrl+ X and
Ctrl+ V we use to cut and paste. In addition, both JMenu and JMenuItem support mnemonics. Use the Alt key in
association with a letter to mimic the selection of the menu itself for example pressing Alt+F then Alt+x closes an
application in Windows.

Here’s what a JMenuBar with JMenus and JMenuItems looks like in Swing: JMenuBar,

Fig. 2.9 JMenu, and JMenuItem.

The important methods you need for these classes are:


• JMenuItem and JMenu:
• get/setAccelerator(): Gets/sets the Ctrl+key you use for shortcuts.
• get/setText(): Gets/sets the text for the menu.
• get/setIcon(): Gets/sets the image used in the menu.
• JMenu only:
• add(): adds another JMenu or JMenuItem to the JMenu (creating a nested menu).

39/ADTU OLE
Advanced Java

2.6.6 JSlider
We use the JSlider in applications to allow for a change in a numerical value. It’s a quick and easy way to let users
visually get feedback on not only their current choice, but also their range of acceptable values. We can provide a
text field and allow user to enter a value, but then we’d have the added hassle of ensuring that the value is a number
and also that it fits in the required numerical range. As an example, if we have a financial Web site, and it asks what
percent we’d like to invest in stocks, we’d have to check the values typed into a text field to ensure they are numbers
and are between 0 and 100. If we use a JSlider instead, we are guaranteed that the selection is a number within the
required range. In Swing, a JSlider looks like this:

Fig. 2.10 The JSlider

The important methods in a JSlider are:


• get/setMinimum(): Gets/sets the minimum value you can select.
• get/setMaximum(): Gets/sets the maximum value you can select.
• get/setOrientation(): Gets/sets the JSlider to be an up/down or left/right slider.
• get/setValue(): Gets/sets the initial value of the JSlider.

2.6.7 JSpinner
Much like the JSlider, we can use the JSpinner to allow a user to select an integer value. One major advantage of
the JSlider is its compact space compared to the JSlider. Its disadvantage, though, is that we cannot easily set its
bounds. However, the comparison between the two components ends there. The JSpinner is much more flexible and
can be used to choose between any groups of values. Besides choosing between numbers, it can be used to choose
between dates, names, colours, anything. This makes the JSpinner extremely powerful by allowing us to provide a
component that contains only predetermined choices.

In this way, it is similar to JComboBox, although their use shouldn’t be interchanged. We should use a JSpinner only
for logically consecutive choices numbers and dates being the most logical choices. A JComboBox, on the other
hand, is a better choice to present seemingly random choices that have no connection between one choice and the
next. A JSpinner looks like following snapshot:

The JSpinner

Fig. 2.11 The JSpinner

The important methods are:


• get/setValue(): Gets/sets the initial value of the JSpinner, which in the basic instance, needs to be an integer.
• getNextValue(): Gets the next value that will be selected after pressing the up-arrow button.
• getPreviousValue(): Gets the previous value that will be selected after pressing the down-arrow button.

40/ADTU OLE
2.6.8 JToolBar
The JToolBar acts as the palette for other components like JButtons, JComboBoxes etcetera that together form the
toolbars we are familiar with in most applications. The toolbar allows a program to place commonly used commands
in a quick-to-find location and groups them together in groups of common commands. Often times, but not always,
the toolbar buttons have a matching command in the menu bar.

The JToolBar also offers another function which we can see in other toolbars, the ability to “float” that is, become
a separate frame on top of the main frame. The image below shows a non-floating JToolBar:

Non-floating JToolBar

Fig. 2.12 Non-floating JToolBar

The important method to remember with a JToolBar is: is/setFloatable(), which gets/sets whether the JToolBar can
float.

2.6.9 JToolTip
JToolTip are kind of like the plastic parts at the end of shoelaces they’re everywhere, but we don’t know the proper
name for it or they can be called aglets. JToolTips are the little “bubbles” that pop up when we hold our mouse over
something. They can be quite useful in applications, providing help for difficult-to-use items, extending information,
or even showing the complete text of an item in a crowded UI. They are triggered in Swing by leaving the mouse
over a component for a set amount of time; they usually appear about a second after the mouse becomes inactive.
They stay visible as long as the mouse remains over that component.

The great part about the JToolTip is its ease of use. The setToolTip() method is a method in the JComponent class,
meaning every Swing component can have a tool tip associated with it. Although the JToolTip is a Swing class itself,
it really provides no additional functionality for our needs at this time, and shouldn’t be created itself. We can access
and use it by calling the setToolTip() function in JComponent. The JToolTip looks like snap below:

Fig. 2.13 A JToolTip

2.6.10 JOptionPane
The JOptionPane is something of a “shortcut” class in Swing. Often times as a UI developer we’d like to present a
quick message to our users, letting them know about an error or some information. We might even be trying to get
some quick data, such as a name or a number. In Swing, the JOptionPane class provides a shortcut for these rather
commonplace tasks. Rather than make every developer recreate the wheel, Swing has provided this basic but useful
class to give UI developers an easy way to get and receive simple messages. The given below is the JOptionPane:

41/ADTU OLE
Advanced Java

Fig. 2.14 A JOptionPane

The somewhat tricky part of working with JOptionPane is all the possible options we can use. While simple, it still
provides numerous options that can cause confusion. One of the best ways to learn JOptionPane is to play around
with it; code it and see what pops up. The component lets us change nearly every aspect of it: the title of the frame,
the message itself, the icon displayed, the button choices, and whether or not a text response is necessary. There are
far too many possibilities to list here in this tutorial, and our best bet is to visit the JOptionPane API page to see its
many possibilities.

2.6.11 JTextArea
The JTextArea takes the JTextField a step further. While the JTextField is limited to one line of text, the JTextArea
extends that capability by allowing for multiple rows of text. Think of it as an empty page allowing to type anywhere
in it. As we can probably guess, the JTextArea contains many of the same functions as the JTextField; after all, they
are practically the exact same component. However, the JTextArea offers a few additional important functions that
set it apart. These features include the ability to word wrap that is wrapping a long word to the next line instead
of cutting it off mid-word and the ability to wrap the text that is move long lines of text to the next line instead of
creating a very long line that would require a horizontal scroll bar. A JTextArea in Swing looks like following text
area:

This is an example of how a text


area works and how it wraps longer
words.

Fig. 2.15 A JTextArea

The important methods to enable line wrapping and word wrapping are:
• is/setLineWrap(): Sets whether the line should wrap when it gets too long.
• is/setWrapStyleWord(): Sets whether a long word should be moved to the next line when it is too long.

42/ADTU OLE
2.6.12 JScrollPane
Building off of the example above, suppose that the JTextArea contains too much text to contain in the given space.
Then what? If you think that scroll bars will appear automatically, unfortunately, you are wrong. The JScrollPane
fills that gap, though, providing a Swing component to handle all scroll bar-related actions. So while it might be a
slight pain to provide a scroll pane for every component that could need it, once we add it, it handles everything
automatically, including hiding/showing the scroll bars when needed.

We don’t have to deal with the JScrollPane directly, outside of creating it using the component to be wrapped.
Building off the above example, by calling the JScrollPane constructor with the JTextArea, we create the ability for
the JTextArea to scroll when the text gets too long:

JScrollPane scroll = new JScrollPane(getTextArea()); add(scroll); This updated example looks like this:

Fig. 2.16 JScrollPane example

The JScrollPane also exposes the two JScrollBars it will create. These JScrollBar components also contain methods
we can use to change their behaviour.

The methods we need to work with JScrollPane are:


• getHorizontalScrollBar(): Returns the horizontal JScrollBar component.
• getVerticalScrollBar(): Returns the vertical JScrollBar component.
• get/setHorizontalScrollBarPolicy(): This “policy” can be one of three things: Always, Never, or As Needed.
• get/setVerticalScrollBarPolicy(): The same as the horizontal function.

2.6.13 JList
The JList is a useful component for presenting many choices to a user. We can think of it as an extension to the
JComboBox. JList provides more choices and adds the capability for multiple choices. The choice between a JList
and JComboBox often comes down to these two features: If we require multiple choices or if the options include
more than 15 choices (although that number is not a general rule), we should always choose a JList.

We should use the JList in conjunction with the JScrollPane, as demonstrated above, because it can present more
options than its space can contain. The JList contains the notion of a selection model, where we can set our JList
to accept different types of choices. These types are the single selection, where we can only select one choice, the
single interval selection, where we can only select contiguous choices, but as many as desired, or the multiple
interval selection, where we can select any number of choices in any combination.

43/ADTU OLE
Advanced Java

The JList is the first of what we call the “complex components,” which also include the JTable and the JTree that
allow a large amount of custom changes, including changing the way the UI looks and how it deals with data. The
JList appears like this in Swing:

Fig. 2.17 The JList

There are many functions in the JList to deal with the data, and as I said, these just touch the surface of everything
required to work in detail with the JList. Here are the basic methods:
• get/setSelectedIndex(): Gets/sets the selected row of the list; in the case of multiple-selection lists, an int[] is
returned.
• get/setSelectionMode(): As explained above, gets/sets the selection mode to be either single, single interval,
or multiple interval.
• setListData(): Sets the data to be used in the JList.
• get/setSelectedValue(): Gets the selected object (as opposed to the selected row number).

2.6.14 JTable
Excel spreadsheet gives the idea of a JTable and that should give a clear picture of what the JTable does in Swing.
It shares many of the same characteristics: cells, rows, columns, moving columns, and hiding columns. The JTable
takes the idea of a JList a step further. Instead of displaying data in one column, it displays it in multiple columns.
Let’s use a person as an example. A JList would only be able to display one property of a person his or her name for
instance. A JTable, however, would be able to display multiple properties like a name, an age, an address etcetera.
The JTable is the Swing component that allows us to provide the most information about our data.

Unfortunately, as a trade-off, it is also notoriously the most difficult Swing component to tackle. Many UI developers
have gotten headaches trying to learn every detail of a JTable. Many of the same concepts in JLists extend to JTables
as well, including the idea of different selection intervals, for example. But the one-row idea of a JList changes to
the cell structure of a JTable. This means we have different ways to make these selections in JTables, as columns,
rows, or individual cells. In Swing, a JTable looks like this:

44/ADTU OLE
Fig. 2.18 A JTable

Ultimately, a majority of the functionality of a JTable is beyond the scope of this tutorial; “Intermediate Swing”
will go into more detail on this complex component.

2.6.15 JTree
The JTree is another complex component that is not as difficult to use as the JTable but isn’t as easy as the JList
either. The tricky part of working with the JTree is the required data models. The JTree takes its functionality from
the concept of a tree with branches and leaves. This concept is in Internet Explorer in Windows we can expand and
collapse a branch to show the different leaves we can select and deselect.

We will most likely find that the tree is not as useful in an application as a table or a list, so there aren’t as many
helpful examples on the Internet. In fact, like the JTable, the JTree does not have any beginner-level functions.
JTree, helps to learn the concepts that go with it. On that note, the example application does not cover the JTree, so
unfortunately, neither the beginner nor the intermediate tutorial will delve into this less popular component.

However, there are times when a tree is the logical UI component for our needs. File/directory systems are one
example, as in Internet Explorer, and the JTree is the best component in the case where data takes a hierarchical
structure in other words, when the data is in the form of a tree. In Swing, a JTree looks like this:

Fig. 2.19 A JTree

45/ADTU OLE
Advanced Java

2.7 Swing Concepts


Most of the components we can use to make a UI, we have to actually do something with them. We can’t just place them
randomly on the screen and expect them to instantly work. We must place them in specific spots, react to interaction
with them, update them based on this interaction, and populate them with data. More learning is necessary to fill in
the gaps of our UI knowledge with the other important parts of a UI. Therefore, following should be examined:
• Layouts: Swing includes a lot of layouts, which are classes that handle where a component is placed on the
application and what should happen to them when the application is resized or components are deleted or
added.
• Events: We need to respond to the button presses, the mouse clicks, and everything else a user can do to a UI.
Think about what would happen if we users would click and nothing would change.
• Models: For the more advanced components (Lists, Tables, Trees), and even some easier ones such as the
JComboBox, models are the most efficient way to deal with the data. They remove most of the work of handling
the data from the actual component itself think back to the earlier MVC discussion and provide a wrapper for
common data object classes such as Vector and ArrayList.

2.7.1 Easy Layouts


A layout handles the placement of components on the application. “Can I just tell it where to go by using pixels?”
Well, I can, but then I’d immediately be in trouble if the window was resized, or worse, when users changed their
screen resolutions, or even when someone tried it on another OS. Layout managers take all those worries away.
Not everyone uses the same settings, so layout managers work to create “relative” layouts, letting to specify how
things should get resized relative to how the other components are laid out. Here’s the good part: it’s easier than it
sounds.

We can call setLayout (yourLayout) to set up the layout manager. Subsequent calls to add() add the component to
the container and let the layout manager take care of placing it where it belongs. Numerous layouts are included in
Swing nowadays; it seems there’s a new one every release that serves another purpose. However, some tried-and-
true layouts that have been around forever and by forever, forever means since the first release of the Java language
back in 1995. These layouts are the FlowLayout, GridLayout, and BorderLayout.

The FlowLayout lays out components from left to right. When it runs out of space, it moves down to the next line.
It is the simplest layout to use, and conversely, also the least powerful layout:

setLayout(new FlowLayout());
add(new JButton(“Button1”));
add(new JButton(“Button2”));
add(new JButton(“Button3”));

Button1 Button2

Button3

Fig. 2.20 The FlowLayout at work

46/ADTU OLE
The GridLayout does exactly what we’d think: it lets to specify the number of rows and the number of columns and
then places components in these cells as they are added:

setLayout(new GridLayout(1,2));
add(new JButton(“Button1”));
add(new JButton(“Button2”));
add(new JButton(“Button3”));

Button1 Button2

Button3

Fig. 2.21 The GridLayout at work

The BorderLayout is still a very useful layout manager, even with all the other new ones added to Swing. Even
experienced UI developers use the BorderLayout often. It uses the notions of North, South, East, West, and Center
to place components on the screen:

setLayout(new BorderLayout());
add(new JButton(“Button1”), “North”);
add(new JButton(“Button2”), “Center”);
add(new JButton(“Button3”), “West”);

Button1

Button3 Button2

Fig. 2.22 The BorderLayout at work

47/ADTU OLE
Advanced Java

2.7.2 GridBagLayout
While the examples from above are good for easy layouts, more advanced UIs need a more advanced layout
manager. That’s where the GridBagLayout comes into play. Unfortunately, it is extremely confusing and difficult
to work with, and anyone who has worked with it will agree. It’s probably the best way to create a clean-looking UI
with the layout managers built into Swing. In the newest versions of Eclipse, there’s a built-in visual builder that
automatically generates the required GridBagLayout code needed for each screen. It will save countless hours of
fiddling around with the numbers to make it just right.

2.7.3 Events
Events are one of the most important parts of Swing, dealing with events and reacting to interaction with the UI.
Swing handles events by using the event/listener model. This model works by allowing certain classes to register
for events from a component. This class that registers for events is called a listener, because it waits for events to
occur from the component and then takes an action when that happens.

The component itself knows how to “fire” events that is it knows the types of interaction it can generate and how
to let the listeners know when that interaction happens. It communicates this interaction with events, classes that
contain information about the interaction. With the technical babble aside, let’s look at some examples of how events
work in Swing. Consider a simple example, a JButton and printing out “Hello” on the console when it is pressed.

The JButton knows when it is pressed; this is handled internally, and there’s no code needed to handle that. However,
the listener needs to register to receive that event from the JButton so we can print out “Hello.” The listener class
does this by implementing the listener interface and then calling addActionListener() on the JButton:

// Create the JButton


JButton b = new JButton(“Button”);
// Register as a listener
[Link](new HelloListener());
class HelloListener implements ActionListener
{
// The interface method to receive button clicks
public void actionPerformed(ActionEvent e)
{
[Link](“Hello”);
}
}
A JList works in a similar way. When someone selects something on a JList, you
want to print out what object is selected to the console:
// myList is a JList populate with data
[Link](new ListSelectionListener()
{
public void valueChanged(ListSelectionEvent e)
{
Object o = [Link]();
[Link]([Link]());
}
}
);

From these two examples, we should be able to understand how the event/listener model works in Swing. In fact,
every interaction in Swing is handled this way, so by understanding this model, we can instantly understand how
every event is handled in Swing and react to any possible interaction a user might throw.

48/ADTU OLE
2.7.4 Models
One should know about the java Collections before studying models, a set of Java classes that handle data. These
classes include an ArrayList, a HashMap, and a Set. Most applications use these classes ubiquitously as they shuttle
data back and forth. However, one limitation arises when we need to use these data classes in a UI. A UI doesn’t
know how to display them. Think about it for a minute. If we have a JList and an ArrayList of some data object
such as a Person object, how does the JList know what to display? Does it display the first name or both the first
name and the last name?

That’s where the idea of a model comes in. While the term model refers to the larger scope, in this tutorial’s examples
I use the term UI model to describe the classes that components use to display data. Every component that deals
with a collection of data in Swing uses the concept of a model, and it is the preferable way to use and manipulate
data. It clearly separates the UI work from the underlying data. The model works by describing to the component
how to display the collection of data. What do I mean by describing? Each component requires a slightly different
description:
• JComboBox requires its model to tell it what text to display as a choice and how many choices exist.
• JSpinner requires its model to tell it what text to display, and also what the previous and next choices are.
• JList also requires its model to tell it what text to display as a choice and how many choices exist.
• JTable requires much more: It requires the model to tell it how many columns and rows exist, the column names,
the class of each column, and what text to display in each cell.
• JTree requires its model to tell it the root node, the parents, and the children for the entire tree.

Why do all this work? Why do we need to separate all this functionality? Imagine this scenario: We have a complicated
JTable with many columns of data, and we use this table in many different screens. If suddenly decided to get rid of
one of the columns, what would be easier, changing the code in every single JTable instance we used, or changing
it in one model class we created to use with every JTable instance. Obviously, changing fewer classes is better.

2.7.5 Model Examples


Let’s take a look at how a model works by using it with an easy example, the JComboBox. In the previous slide
of a JComboBox, It is given how to add items to the data by calling setItem(). While this is acceptable for simple
demonstrations, it isn’t much use in a real application. After all, when there are 25 choices, and they are continually
changing, no one would really want to loop through them each time calling addItem() 25 times? The JComboBox
contains a method call setModel() that accepts an instance of the ComboBoxModel class. We should use this method
instead of the addItem() method to create the data in a JComboBox.

49/ADTU OLE
Advanced Java

Suppose you have an ArrayList with the alphabet as its data (“A”, “B”, “C”, etc.):

MyComboModel model = new MyComboModel(alphaList);


[Link](model);
public class MyComboModel implements ComboBoxModel
{
private List data = new ArrayList();
private int selected = 0;
public MyComboModel(List list)
{
data = list;
}
public void setSelectedItem(Object o)
{
selected = [Link](o);
}
public Object getSelectedItem()
{
return [Link](selected);
}
public int getSize()
{
return [Link]();
}
public Object getElementAt(int i)
{
return [Link](i);
}
}

The great part about using a model is that we can reuse it over and over again. As an example, say the JComboBox’s
data needs to change from letters of the alphabet to the numbers 1 to 27. We can achieve this change in one simple
line that uses the new List of data to populate the JComboBox without using additional code:

[Link](new MyComboModel(numberList));

Models are a beneficial feature in Swing as they provide the ability for code reuse and make dealing with data much
easier. As is often the case in large-scale applications, the server-side developers create and retrieve the data and
pass it to the UI developer. It’s up to the UI developer to deal with this data and display it properly, and models are
the tools to get this done.

2.8 Application
To see all the above stuffs in action consider the example below. Here’s the concept for the example application:
a simple flight reservation system. It lets the user type in a departure and arrival city and then presses a button to
search. It has a fake database with flights stored in it. This database can be searched, and a table is used to display
the results of the search. Once the table populates, users can select flights from the table and buy tickets by changing
the number of tickets they desire and clicking a button.

It’s a seemingly simple application that allows us to see all the parts of Swing in practice. This example application
should answer any questions we might have had from previous sections. Before I start, let’s look at the finished
product:

50/ADTU OLE
Example application

Step 1: Lay out the components


As I mentioned earlier, there’s little need to learn complex layouts because you can use a visual editor.

Step 2: Initialise the data


The application can’t work without data. Let’s think about what kind of data we need in this application. First, we
need a list of cities to choose from for the departure and destination cities. Then, we need a list of flights to search.
For this example, someone use some fake data because the focus of the application is on Swing not on the data. We
create all the data in the DataHandler class. This class manages the departure and destination cities and also handles
flight search and record retrieval.

The cities are stored as simple Strings. The flights however, are stored in data objects called Flights that contain
fields for the departure city, destination city, flight number, and number of available tickets. Now, with all that red
tape out of the way, let’s get back to the application.

Step 3: Handling events


Let’s examine the application and consider what actions must take place. First, we need to know when a user presses
the Search button, so we can search the data for flights. Second, we need to know when a user selects the table of
records to prevent possible errors when a user tries to buy a record with no records selected. Finally, we must be
aware of when a user presses the Purchase button to send the purchasing data back to the data handler class.

Let’s start with the Search button. As outlined above, you must call the addActionListener() method on the button
to register for events from a button press. To keep things simple, use the FlightReservation class to listen for all
possible events. Here’s the code to handle the Search button press:

String dest = getComboDest().getSelectedItem().toString();


String depart = getComboDepart().getSelectedItem().toString();
List l = [Link](depart, dest);
[Link](l);

51/ADTU OLE
Advanced Java

The two cities are gathered from the combo boxes and used to search the records for the corresponding flights. Once
the flights are found, they are passed to the table’s table model; more on how the table models work below. But
know that once the table model has the updated data, it will display the results. Next, let’s examine what happens
when a user presses the Purchase button:

Object o = [Link]().get(getTblFlights().getSelectedRow());
int tixx = [Link](getTxtNumTixx().getText());
[Link](o, tixx);

Now, conversely, when a user presses the Purchase button, the table model figures out which flight the user selected
and then passes this record and the number of tickets the user wishes to purchase to the data handler. Finally, we
need to error-check and ensure that someone doesn’t try to purchase a ticket without selecting a flight in the table.
The easiest way to do this is to disable the components a user would use to purchase tickets the text field and button
and only enable them when a user selects a row:

boolean selected = getTblFlights().getSelectedRow() > -1;


getLblNumTixx().setEnabled(selected);
getTxtNumTixx().setEnabled(selected);
getBtnPurchase().setEnabled(selected);

Step 4: Models
Next, let’s look at the models used to handle all the data flying back and forth in this application. By analyzing
the application and going through this demo, we should clearly see that we need two models: a model for the
JComboBoxes and a model for the JTable. Let’s begin with the easiest, the JComboBox’s model.

Remember the advantage of using models, those are used here. Although we only have one model class, we reuse it
by creating two instances of it and supplying one to each of the JComboBoxes. That way both instances can handle
their own data, but of course, only one class should be written to do it. Here it is given how to set it up:

comboModel1 = new CityComboModel([Link]());


comboModel2 = new CityComboModel([Link]());

Let’s move on to the JTable’s model. This model is a bit more complicated than the JComboBox and requires a little
more inspection. Let’s start with knowledge of the ComboBoxModel and see what we need to add for a JTable.
Because a JTable contains data like a ComboBox, but in multiple columns, we need a lot more information from the
model dealing with the column information. So, in addition to knowing the number of rows of data, we need to know
the number of columns, the column names, and the value at an individual cell, instead of just the object itself.

This allows us to not only display a data object, but also to display fields of a data object. In the case of this example,
we don’t display the Flight object; we instead display the fields of a departure city, destination city, flight number,
and the number of tickets available. Below is the code we use to create the TableModel and how to set it on the
JTable:

flightModel = new FlightTableModel();


getTblFlights().setModel(flightModel);

Because of the amount of code we need to create a TableModel.

52/ADTU OLE
Step 5: Bells and whistles
Users have come to expect a certain amount of bells and whistles in any application, both as extra functionality and
also as a way to prevent the occurrence of errors. In this example, although the basic functionality of searching for
a flight and purchasing tickets works, we haven’t addressed possible errors that might happen. For error-proofing,
we need to add an error message when a user attempts to order more tickets than are available. How to display
errors? If we think back to the slide on the JOptionPane, Swing has a ready-made component for this type of instant
feedback. Let’s look at the error condition and see what triggers the error message:

try
{
[Link](o, tixx);
}
catch (Exception ex) {
// display error message here
}

Now let’s take care of the error message. Remember the JOptionPane and its plentiful amount of options. Let’s lay
out the options we want in our error message before we decide what kind of JOptionPane to create. It should be an
error message and not an informative message. Use a simple title such as “Error.” The detailed message consists of
what the exception says. And finally, the users have made an error, so simple OK and Cancel buttons should suffice.
Here’s the code to create that exact JOptionPane:

[Link](this, [Link](), “Error”,


JOptionPane.OK_CANCEL_OPTION, JOptionPane.ERROR_MESSAGE);

And here’s what it looks like:

Example error message

53/ADTU OLE
Advanced Java

Summary
• UIs are the buttons we press, the address bar we type in, and the windows we open and close, which are all
elements of a UI, but there’s more to it than just things we see on the screen.
• Swing is the Java platform’s UI; it acts as the software to handle all the interaction between a user and the
computer.
• The basic building block of the entire visual component library of Swing is the JComponent.
• Swing components are basic building blocks of an application.
• The basic text component in Swing is the JTextField, and it allows a user to enter text into the UI.
• A JFrame actually does more than the components we have placed on it and present it to the user.
• A combo box is the familiar drop-down selection, where users can either select none or one item from the
list.
• Tabbed pane is used to show the component from a group of same components if one of the tab of a pane is
selected.
• Once we select a JRadioButton, we cannot deselect it unless we select another radio button in the group.
• The JMenu, JMenuItem, and JMenuBar components are the main building blocks of developing the menu
system on the JFrame.
• One major advantage of the JSlider is its compact space compared to the JSlider.
• The JSpinner is much more flexible and can be used to choose between any groups of values.
• JToolTip are kind of like the plastic parts at the end of shoelaces they’re everywhere, but we don’t know the
proper name for it or they can be called aglets.
• The JOptionPane is something of a “shortcut” class in Swing.
• The JList is a useful component for presenting many choices to a user.
• Excel spreadsheet gives the idea of a JTable and that should give a clear picture of what the JTable does in
Swing.
• The JTree is another complex component that is not as difficult to use as the JTable but isn’t as easy as the JList
either.
• Events are one of the most important parts of Swing, dealing with events and reacting to interaction with the
UI.
• One should know about the Java Collections before studying models, a set of Java classes that handle data.

References
• Cornell, G. and Horstman S. C., 2011. Core Java 2: Fundamentals, 5th ed. Prentice Hall Professional.
• Abernethy, M., 2005. Introduction to Swing, [Online] Available at:< [Link]
[Link]> [Accessed 10 April 2012].
• Tutorial 12 – Advanced Swing, [Online] Available at:< [Link] [Accessed
10 April 2012].
• Eckstein, R. and Loy, M., 2002. Java Swing, 2nd ed. O’Reilly Media, Inc. Publication.
• John, 2012. Advanced Java: Swing (GUI) Programming Part 4 – GridBagLayout, [Video Online] Available
at:< [Link]
DF2257751F> [Accessed 10 April 2012].
• John, 2012. Advanced Java: Swing (GUI) Programming Part 2 -- Adding Components, [Video Online] Available
at:<[Link] > [Accessed 10 April 2012].

54/ADTU OLE
Recommended Reading
• Bates, B. and Sierra, K., 2005. Head First Java, 2nd ed. O’Reilly Media, Inc. Publication.
• Topley, K., 2000. Core Swing: Advanced Programming, Prentice Hall Professional Publication.
• Buyya, 2009. Object Oriented Prog With Java, Tata McGraw-Hill Education Publication.

55/ADTU OLE
Advanced Java

Self Assessment
1. ______ acts as the software to handle all the interaction between a user and the computer.
a. Swing
b. UI
c. AWT
d. MVC

2. The basic building block of the entire visual component library of Swing is the_________.
a. JQuerry
b. JComponent
c. Combo box
d. JMenu

3. Which of the following states are not contained in JButton?


a. Active/inactive
b. Selected/not selected
c. Mouse-over/mouse-off
d. Deleted/not deleted

4. The important functions with a JComboBox involve the ________ it contains.


a. file
b. memory
c. data
d. list

5. _____________are generally used to save the space by having multiple components separated by a tab.
a. JComboBox
b. JFrame
c. JTextField
d. Tabbed panes

6. The JCheckBox and JRadioButton components present options to a user, usually in a ________format.
a. multiple-choice
b. list
c. table
d. file

7. We use the ________in applications to allow for a change in a numerical value.


a. JButton
b. JSlider
c. JMenu
d. JToolkit

56/ADTU OLE
8. A ________handles the placement of components on the application.
a. event
b. gridBagLayout
c. layout
d. easy layouts

9. The base of any menu system is the__________.


a. JMenu
b. JMenuBar
c. JMenuItem
d. JCheckBox

10. A common design pattern put on top of the basic UI principles is called as ______.
a. MVC
b. UI
c. Swing
d. JComponents

57/ADTU OLE
Advanced Java

Chapter III
Database and SQL Fundamentals

Aim
The aim of this chapter is to:

• introduce DBMS standardisation

• elucidate ODBC and JDBC drivers

• explain database and SQL fundamentals

Objectives
The objectives of this chapter are to:

• explain query processing rules of SQL

• explicate uing SQL as a Data Definition Language

• elucidate benefits of the Database Approach

Learning outcome
At the end of this chapter, you will be able to:

• understand project development using database

• identify Java applications and applets that serve as database clients

• describe database-client interaction

58/ADTU OLE
3.1 Introduction
Every organisation has a pool of resources that it must manage effectively to achieve its objectives. Although their
rule differs all resources human, financial and material share a common characteristic. The organisation that fails
to treat data or information as resource and to manage it effectively will be handicapped in how it manages its,
manpower, material and financial resources. In order to satisfy the information requirements of management, the
data should be stored in an organised form.

3.2 What is a Database?


A brief definition can be given as “the information held over a period of time, in computer readable form”. Typical
examples of information stored for some practical purpose are: Information collected for the sake of making a
statistical analysis, for example, the national census. Operational and administrative information required for running
an organisation or a commercial concern this will take the form of stock records, personnel records, customer
records etcetera.

Held Over a Period of Time


Because of the investment involved in setting up a database, the expectation must be that it will continue to be useful,
over years rather than months. But the relationship with time varies from one type of information to another An
organisational database may not change very drastically in size, but it will be subject to frequent updating (deletions,
amendments, insertions) following relevant actions within the organisation itself. Ensuring the accuracy, efficiency
and security of this process is the main concern of many database designers and administrators. The function of the
DBMS is to store and retrieve information as required by applications programs or users.

3.3 Data vs Information


Data are facts concerning people, places, events or other objects or concepts. Data are often relatively useless to
decision-makers until they have been processed or refined in some manner. Information is data that have been
processed and refined and then given in the format that is convenient for decision making or other organisational
activities. For example, report about student fee paid details is useful information for finance section. Actually
data are the facts stored in the record of a database. But the processed facts are presented in a form for usage is
information.

3.4 Data Base Concepts


A database is a shared collection of interrelated data designed to meet the varied information needs of an organisation.
Consider an example in a payroll application each person’s record has NAME, AGE, DESIGNATION, BASIC PAY
etcetera as columns. So payroll database has collection of all employees of all employee records that are interrelated.
From the database, various reports like payslip, persons with particular designation, service report etcetera can be
obtained. The database acts as a media to store the data in an organised way so that it can be managed effectively.
A database has two important properties: It is integrated and shared.

3.5 Benefits of the Database Approach


The data base approach offers a number of important advantages compared to traditional approach. These benefits
include minimal data redundancy, consistency of data, integration of data, sharing of data, enforcement of
standards, ease of application development, uniform security, privacy and integrity controls, data accessibility and
responsiveness, data independence, and reduced program maintenance.

Minimum data redundancy: With the data base approach, previously separate data files are integrated into a single,
logical structure. So each item is ideally recorded in only one place in the database. Hence in a data base system,
the data redundancy is controlled.

Consistency of data: By eliminating data redundancy, the consistency of data has greatly improved. If any change
in the data, it can be incorporated in one place than the traditional file system.

59/ADTU OLE
Advanced Java

Integration of data: In a database, data are organised into a single, logical structure, with logical relationships defined
between associated data entities.

Sharing of data: In this the database is intended to be shared by all authorised users in the organisation. Since all
the data are integrated,

DBMS Functions: The DBMS functions are explained with the help of following points.

Data definition: Data can be defined as FILES to RECORD STRUCTURES FIELD NAMES, TYPES and SIZES
RELATIONSHIPS between records of different types Extra information to make searching efficient, for example,
INDEXES.

Data entry and validation: Validation may include TYPE CHECKING, RANGE CHECKING, CONSISTENCY
CHECKING In an interactive data entry system, errors should be detected immediately some can be prevented
altogether by keyboard monitoring and recovery and re-entry permitted. If the database is error bound then it will
be the main cause to make the program error prone.

Updating: Updating of data is very important otherwise it will be waste in a long run. Updating involves: Record
INSERTION, Record MODIFICATION, and Record DELETION. Updating may take place interactively, or by
submission of a file of transaction records; handling these may require a program of some kind to be written, either
in a conventional programming language or in a language supplied by the DBMS for constructing command files.

3.6 Data Retrieval on the Basis of Selection Criteria


For this purpose most systems provide a QUERY LANGUAGE with which the characteristics of the required
records may be specified. Query languages differ enormously in power and sophistication but a standard, which is
becoming increasingly common, is based on the so called RELATIONAL operations.
• These allow Selection of records on the basis of particular field values.
• Selection of particular fields from records to be displayed.
• Linking together records from two different files on the basis of matching field values.
• Arbitrary combinations of these operators on the files making up a database can answer a very large number of
queries without requiring users to go into one record at a time processing.

Report Definition
Most systems provide facilities for describing how summary reports from the database are to be created and laid out
on paper. These may include obtaining: COUNTS, TOTALS, AVERAGES, MAXIMUM and MINIMUM values.
On a table over particular CONTROL FIELD above layouts have to be found out. Also specification of PAGE and
LINE LAYOUT, HEADINGS, PAGE-NUMBERING and other narrative to make the report comprehensible have
to be found out.

Security
This has several aspects: Ensuring that only those authorised can see and modify the data, generally by some extension
of the password principle. Ensuring the consistency of the database where many users are accessing and up-dating
it simultaneously also ensuring the existence and INTEGRITY of the database after hardware or software failure.
At the very least this involves making provision for back-up and re-loading.

3.7 Why have Databases (and a DBMS)?


An organisation uses a computer to store and process information because it hopes for speed, accuracy, efficiency,
economy etcetera. beyond what could be achieved using clerical methods. The objectives of using a DBMS must
in essence be the same although the justifications may be more indirect.

60/ADTU OLE
3.8 DBMS Standardisation
Early computer applications were based on existing clerical methods and stored information was partitioned in
much the same way as manual files. But the computer’s processing speed gave a potential for RELATING data
from different sources to produce valuable management information, provided that some standardisation could be
imposed over departmental boundaries. The idea emerged of the integrated database as a central resource. Data is
captured as close as possible to its point of origin and transmitted to the database, then extracted by anyone within
the organisation who requires it.

However, many provisos have become attached to this idea in practice, it still provides possibly the strongest
motivation for the introduction of a DBMS in large organisations. The idea is that any piece of information is
entered and stored just once, eliminating duplications of effort and the possibility of inconsistency between different
departmental records. Data redundancy has to be removed at the most possible.

Advantages
Organisational requirements change over time, and applications programs laboriously developed need to be
periodically adjusted. A DBMS gives some protection against change by taking care of basic storage and retrieval
functions in a standard way, leaving the applications developer to concentrate on specific organisational requirements.
Changes in one of these areas need not affect elsewhere. In general a DBMS is a substantial piece of software, the
result of many man-years of effort. Provide more facilities than would be economic in a one-off product.

The points discussed above are probably most relevant to the larger organisation using a DBMS for its administrative
functions and the environment in which the idea of databases first originated. In other words the convenience of a
DBMS may be the primary consideration. The purchaser of a small business computer needs all the software to run
it in package form, written so that the minimum of expertise is required to use it. The same applies to departments for
example, Research & Development with special needs that cannot be satisfied by a large centralised system. When
comparing database management systems it is obvious that some are designed in the expectation that professional
staff will be available to run them, while others are aimed at the total novice. Actual monetary costs vary widely
from, for instance, a large multi-user Oracle system to a small

3.9 Data Base Project Development


The conventional SYSTEMS LIFE CYCLE of project Development consists of: Analysis, Design, Development,
Implementation, and Maintenance.

3.9.1 Analysis
A Conceptual Data Model describing the information which is used inside the organisation but not in computer-
related terms. The conceptual data model provides a context within which more detailed design specifications
can be produced, and should help in maintaining consistency from one application area to another. A Conceptual
Process Model describing the functions of the organisation in terms of events for example, a purchase, a payment,
a booking and the processes which must be performed within the organisation to handle them. This may lead to a
more detailed functional specification describing the organisational requirements which must be satisfied, but not
how they are to be achieved.

3.9.2 Design
A Logical Data Model is a description of the data to be stored in the database, using the conventions prescribed by
the particular DBMS to be used. This is sometimes referred to as a SCHEMA and some DBMS also give facilities
for defining SUB-SCHEMA or partitions of the overall schema. A SYSTEM SPECIFICATION, describing in some
detail what the proposed system should do. This will now refer to COMPUTER PROCESSES, but probably in
terms of INPUT and OUTPUT MESSAGES rather than internal logic. By the end it should give the outline, how
the DBMS should be.

61/ADTU OLE
Advanced Java

3.9.3 Development
This is the actual coding phase. Specification of the database itself must now come down another level, to decisions
about physical data storage in particular files on particular devices, etcetera. Conventional program development,
coding, testing, debugging etcetera may also be done. It will simply be a matter of discovering how to use the
command and query language already supplied to store and retrieve data, generate reports and other outputs. Even
here an element of testing and debugging may be involved, since it is unlikely that the new user of a system will
get it exactly right the first time.

3.9.4 Implementation
This puts the work of the previous three phases into everyday use. It involves such things as loading the database
with live rather than test data, staff training, probably the introduction of new working practices.

3.9.5 Maintenance
Systems once implemented generally require further work done on them as time goes by, either to correct original
design faults or to accommodate changes in user requirements or in the system level. One of the objectives of using a
DBMS is to reduce the impact of such changes for example the data can be physically re-arranged without affecting
the logic of the programs which use it. Some DBMS provide utility programs to re-organise the data when either
its physical or logical design must be altered.

3.10 Conceptual Data Modelling


Conceptual Data Modelling is the first stage in the process of TOP-DOWN database design. The aim is to describe
the information used by an organisation in a way, which is not governed by implementation-level issues and details.
It should make it easy to see the overall picture so that non-technical staff can contribute to discussions.

A common method of analysis involves identifying:


Entities (persons, places, things etcetera) which the organisation has to deal with Attributes the items of information
which characterise and describe these entities relationships between entities which exist and must be taken into
account when processing information In the abstract, or illustrated by superficial examples, this looks a very
simple idea. An explanation may put forward a car as a typical entity, point to make, colour, registration number as
obvious attributes, and suggest owning and driving as relationships in which it takes part. But applying the method
of analysis to some useful purpose in a working organisation will be difficult, simply because the world does not
fit so neatly into boxes.

Entity
It is any object or event about which the organisation chooses to collect and store data. Any entity may be tangible
object, such as an employee, a product, a computer, or a customer, or it may be an intangible item, such as bank
account, a part failure of a flight.

Attribute
An attribute is a property of an entity that we choose to record shown in the figure below:

Enrol No. Name Course Mark Result

Attribute 1 Attribute 2

62/ADTU OLE
In other words, an entity or a record is nothing but collection of attributes or fields.

Key
A key is a data item used to identify a record. There are two basic types of keys namely Primary and Secondary
keys. A Primary key is a data item that uniquely identifies a record. For example, in the student record, ENRL_NO
is a primary key that uniquely identify a student record. Each student record has different ENRL_NO that is no two
students are having the same ENRL_NO.

A Secondary Key is a data item that normally does not uniquely identify a record but identifies a group or records
in a set that share the same property. For example, in the student record, COURSE is a secondary key that identifies
a set of record, having same course. Learn the following diagram.

Enrol No. Name Course Mark Result

Primary Key Secondary Key

3.11 Types of Relationship Between Data Item


A database is nothing but collection of records and a record is a collection of fields or data item and fields is an
attribute about the record. When collection of data items are involved there exists a relationship. If the database
contains N data items, then there exist N (N-1) possible associations among the data items.

The various types of association that exists among the data items are:
• One to one association
• One to many association
• Many to many association

3.11.1 One to One Association


It means that, at a given instant of time, each value of data item A is associated with exactly one value of data item
A is associated with exactly one value of data item B, conversely each value of B is associated with one value of
A. For example each student has a name in the student record.

63/ADTU OLE
Advanced Java

Students Record Name

A B

Fig. 3.1 One to one association


(Source: [Link]

Each Student is assigned with one Name and in reverse each Name is assigned to one Student, so one to one
association exists between Students and Names.

3.11.2 One to Many Association


One to many association is, at a given instant of time, each value of data item A is associated with zero, one or more
than one value of data item B. However, each value of B is associated with exactly one value of A. The mapping
from B to A is said to be many to one, since there may be many values of B associated with one value of A.

Course Students

A B

Fig. 3.2 One to many association


(Source: [Link]

The course and students association is one to many since in a course more than one student is engaged.

64/ADTU OLE
3.11.3 Many to Many Association
Many to many association means that, at a given instant of time, each value of data item A is associated with zero,
one, or many values of data item B. Also each value of B is associated with zero, one or many values of A.

Student Teacher
A B

Fig. 3.3 Many to many association


(Source: [Link]

The Student Teacher association is many to many. Since a Student can have more than one Teacher, in the same
way a Teacher can have more than one Student.

Relationships
In many applications one external event or process may affect several related entities, requiring the setting of LINKS
from one part of the database to another. Important information to be recorded is:

The Relational Model


The relational model consists of three components:
1. A Structural component: It is a set of TABLES (also called RELATIONS).
2. Manipulative component consisting of a set of high-level operations which act upon and produce whole
tables.
3. A set of rules for maintaining the integrity of the database.

3.12 Codd’s Rules


As the benefits of the relational approach become more widely perceived, vendors of DBMSs increasingly often
claim that their products are ‘relational’. In 1985 Codd produced the following set of ‘rules’ by which systems
should be judged:

Information
Data retrieved from the database should be informative. All information represented in each column should be of
specific type.

Guaranteed Access
Each datum (atomic value) in a relational database is guaranteed to be logically accessible through a combination
of table-name, primary key value and column-name.

65/ADTU OLE
Advanced Java

Systematic Treatment of Null Values


Null values are distinct from the empty character string or a string of blank characters and distinct from zero or
any other numbers are supported in a fully relational DBMS. Null values are of two types for representing missing
information and inapplicable information.

Database Description
All information stored in the form of table. It is stored in a table, so that authorised users can apply the same relational
language to its interrogation as they apply to the regular data.

Comprehensive Sub-Language
A relational system may support several languages. However, there must be at least one language (SQL) and that
is comprehensive in supporting all the following items:
• Data definition
• View definition
• Data manipulation (interactive and by program)
• Integrity constraints
• Authorisation
• Transaction boundaries (begin, commit and rollback)

View Updating
All theoretically updateable views are also updateable by the system. Using the structured query language one should
be able to Add, delete and modify.

Insert and Update


The capability of handling a base table or a derived table as a single operand applies not only to retrieval of data but
also to insertion, updating, and deletion. This allows the system to optimise its execution sequence by determining
the best access paths.

Physical Data Independence


Application programs and terminal activities, there is no need to specify the physical location of the database. That
is path should not be mentioned. There must be a clear distinction between logical and physical design levels.

Logical Data Independence


This rule permits logical database design to be changed dynamically, for example, by splitting or joining base tables
in ways which do not entail loss of information. During the retrieval we can change the field orders.

Integrity Independence
Integrity constraints must be definable in the relational data and storable in the catalogue, notion the applications
program. Certain integrity constraints hold for every relational database, further application-specific rules may be
added. The general rules relate to:
• Entity integrity: no component of a primary key may have a null value.
• Referential integrity: for each distinct non-null ‘foreign key’ value in the database, there must exist a matching
primary key value from the same domain.

Distribution Independence
A relational DBMS has distributional independence that is if a distributed database is used it must be possible to
execute all relational operations upon it without knowing the physical locations of data. This must apply both when
distribution is originally introduced, and when data is redistributed.

66/ADTU OLE
Non-Subversion
A low-level (single record-at-a-time) language cannot be used to subvert or bypass the integrity rules and constraints
expressed in the higher-level (multiple record-at-a-time) language.

3.13 Structured Query Language


The JDBC requires JDBC-compliant drivers to support the American National Standards Institute (ANSI) SQL-92
Entry Level version of the standard that was adopted in 1992. SQL is mainly classified into Data Definition Language
(DDL) and Data Manipulation Language (DML).

3.13.1 Using SQL as a Data Definition Language


Using SQL to define a database means creating a database, creating tables and adding them to a database, updating
the design of existing tables, and removing tables from a database. The Create Database Statement. The CREATE
DATABASE Statement can be used to create a database:

3.14 The CREATE DATABASE DatabaseName


Substitute the name of the table to be created for databaseName. For example, the following statement created a
database named Salesreps Create Database Salesreps The Create Table Statement: The CREATE TABLE statement
creates a table and adds it to the database:

CREATE TABLE tableName (columnDefinition,… , columnDefinition) Each columnDefinition is of the form


ColumnName columnType The columnName is unique to a particular column in the table. The columnType identifies
the type of data that may be contained in the table. Common data types are:
Char(n) - An n character text string
Int - An integer value
Float - A floating point value
Bit - A boolean (1 or 0) value
Date - A date value
Time - A time value

The following is an example of a CREATE TABLE statement:

CREATE TABLE Customers (


CustName char(30),
Company char(50),
Cust_rep integer,
Credit_limit money
)

The preceding statement creates a customers table with the following columns:
CustName - A 30-character-wide text field
Company - A 20-character-wide text field
Cust_rep - A integer type
Credit_limit - A money data type to represent currency values.

The ALTER TABLE Statement


The ALTER TABLE statement adds a row to an existing table or to change the table definitions. ALTER TABLE
tableName ADD (columnDefinition… columnDefinition). The row values of the newly added columns are set to
NULL. Columns are defined as described in the previous section. The following is an example of the ALTER TABLE
statement that adds a column named Fax to the Contacts table:

ALTER TABLE CUSTOMERS ADD (CONTACT_NAME VARCHAR(20))

67/ADTU OLE
Advanced Java

The DROP TABLE Statement


The DROP TABLE statement deletes a table from the database: DROP TABLE tableName. The dropped table is
permanently removed from the database. The following is an example of the DROP TABLE statement:

DROP TABLE CUSTOMERS

The preceding statement removes the CUSTOMERS table from the database. Tables once dropped cannot be
retrieved.

Using SQL as a Data Manipulation Language


One of the primary uses of SQL is to update the data contained in a database. There are SQL statements for inserting
new rows into a database, deleting rows from a database, and updating existing rows.

The INSERT Statement


The INSERT statement inserts a row into a table: INSERT INTO tableName VALUES (‘values 1 ‘ , …, ‘valuen’ )
In the preceding form of the INSERT statement, value 1 through value n identify all column values of a row. Values
should be surrounded by single quotes.

The following is an of the preceding form of the INSERT statement:

INSERT INTO SALESREPS VALUES (


1008,
‘Joy Anand’,
29,
‘23’,
‘Executive’,
105,
500000,
420000
)

The preceding statement adds a row to the SALESREP table. All columns of this row are filled in. An alternative
form of the INSERT statement may be used to insert a partial row into a table. The following is an example of this
alternative form of the INSERT statement:

INSERT INTO tableName (columnName1,….,columnNamem) VALUE (‘value1’,…,’valuem’) An alternative


form of the INSERT statement may be used to insert a partial row into a table. The following is an example of this
alternative form of the INSERT statement:

INSERT INTO tableName (columnName1,….,columnNamem) VALUE (‘value1’,…,’valuem’) The values of


columnName1 through columnNamem are set to value 1 through valuem. The value of the other columns of a row
is set to NULL. An example of this form of the INSERT statement follows:

INSERT INTO ORDERS (ORDER_DATE, PRODUCT)


VALUES
(
‘4-DEC-1999’,
‘Microprocessor’
)

68/ADTU OLE
The preceding statement adds an order with the date 4th December 1999 and the product Microprocessor to the
Order table. The other columns of the table are null.

The DELETE Statement


The DELETE statement deletes a row from a table:

DELETE FROM tableName [WHERE condition]

All rows of the table that meet the condition of the WHERE clause is deleted from the table.

Warning
If the WHERE clause is omitted, all rows of the table are deleted. The following is an example of the DELETE
statement:

DELETE FROM orders


WHERE Order_Date = ‘14-FEB-2000’

The preceding statement deletes all ORDERS on 14th February 2000 from the Orders table.

The UPDATE Statement


The UPDATE Statement is used to update an existing row of a table:

UPDATE tableName SET columnName1 = ‘value1”, …...,columnName = ‘value’


[WHERE condition]

All the rows of the table that satisfy the condition of the WHERE clause are updated by setting the value of the
specified values. If the WHERE clause is omitted, all rows of the table are updated.

An example of the UPDATE statement follows:

UPDATE Customers
SET Credit_Limit = 1200000
WHERE Company = ‘Axes Technologies’

The preceding statement changes the Credit Limit of the company Axes Technologies with the new Credit Limit
of Rs 12, 00,000.

3.15 Using SQL as a Dataquery Language


The most important use of SQL for many users is for retrieving data contained in a database. The SELECT statement
specifies a database query:

SELECT columnList1 FROM table1 ,…, tablem [WHERE condition]

An asterisk (*) may replace columnList1 to indicate that all columns of the table(s) are to be returned.

69/ADTU OLE
Advanced Java

Example:

SELECT CITY, SALES FROM OFFICES


SELECT * FROM CUSTOMERS

Some relational and logical comparisons can also be included. They are classified mainly into 6 categories. They
are
Comparison Test
Comparison test makes use of the relational operators. They are =, <>, <, <=, >, >= used to compare equal to, not
equal to, less than, less than or equal to, greater than, greater than or equal to respectively.

Range Test
This test is used to test whether the value lies within the range or not. The key word is
BETWEEN, NOT BETWEEN

Set Membership Test


This is to test whether the value is present in the list of values. The keyword is IN.

Pattern Matching Test


This test is employed to find the name of person starting like Raj. The keyword is LIKE. %, _ are the wildcard
characters used in the pattern matching test. % is equivalent to * in DOS. _ (Underscore) is equivalent to ? in DOS.
Escape characters $ is used to use legal %, _.

Example:

WHERE PRODUCT LIKE ‘A%BC_’

This will look for first character A Second character anything third and fourth should be B and C respectively.
Ending with any number of any characters. WHERE PRODUCT LIKE ‘$%%BC_’ This will search for the first
character %.

Null Value Test


This is to test whether the column contains null value. The keyword is ‘IS NULL’.

Compound Search Conditions


This is to test for more than one condition. The keyword AND/OR/NOT is used.

3.16 The Where Clause


The WHERE clause is a Boolean expression consisting of column names, column values, relational operators
and logical operators. For example, suppose we have columns Department, Salary, and Bonus. We could use the
following WHERE clause to match all employees in the Engineering department that have a salary over 100,000
and a bonus less than 5,000:

WHERE Department = ‘Engineering ‘ AND Salary >’100000’ AND Bonus <’5000’


SELECT * FROM CUSTOMERS
WHERE CREDIT_LIMIT BETWEEN 10000 AND 50000
SELECT NAME, REP_OFFICE, QUOTA, SALES
WHERE SALES>QUOTA
[ORDER BY columnList2]

In the preceding syntax description, columnList1 and columnList2 are comma-separated lists of column names from
the table’s table1 through table. The SELECT statement returns a result set consisting of the specified columns of
the table1 through table, such that the rows of these tables meet the condition of the WHERE clause. If the WHERE
clause is omitted, all rows are returned.

70/ADTU OLE
The ORDER BY clause is used to order the result set by the columns of columnSet2. Each of the column names
in the column list may follow by the ASC or DESC keywords. If DESC is specified, the result set is ordered in
descending order. Otherwise, the result set is ordered in ascending order.

SELECT * FROM CUSTOMERS


ORDER BY COMPANY

3.17 Union
It is used to combine two or more tables. The necessary criteria is:
• The tables must contain same number of columns.
• Data type of each should match that of the other
• Neither can be stored but combined can be stored.

UNION ALL Produces duplicates


UNION Default produces Distinct

Example:

SELECT * FROM A
UNION (SELECT * FROM B
UNION SELECT * FROM C)
ORDER BY NAME

3.18 Simple Joins


Simple joins are required when data is to be retrieved from more than one table.

Example:

Order table
ORDERNUM ORDER_DATE CUST REP QTY AMOUT
Customer Table
CUST_NUM COMPANY CUST_REP CREDIT LIMIT

List all orders showing [Link] number 2amount 3 customer name 4customers credit limit.

SELECT ORDERNUM, AMOUNT, CUST_NUM, CREDIT_LIMIT


FROM ORDER, CUSTOMER
WHERE CUST = CUST_NUM

71/ADTU OLE
Advanced Java

3.19 Parent/Children Relationships


In the parent child query, every parent column can have one or more child and every child should have only one
parent. In the above example order has one customer and every customer has one or more orders. Therefore Order
Child Customer Parent.

Example:
List each salesperson and the city and region where they work

SELECT NAME, CITY, REGION


FROM SALESREPS, OFFICES
WHERE REP_OFFICE = OFFICE

Foreign Keys: A column in one table whose value matches the primary key in some other table is called a foreign
key.

Primary Keys: In a well-designed relational database every database has some column, ore combination of
columns whose values uniquely identify each row in the table. This column (or columns) is called primary key of
the table.

Once Again Parent Child Relation: The table containing the foreign key is the child in the relationship, the table
with the primary key is the parent.

Example:
List all offices with target over 5, 00,000

SELECT CITY, NAME, CITY


FROM SALESREPS, OFFICES
WHERE OFFICE = REP_OFFICE
AND TARGER >=5, 00,000

Example Multiple matching columns:


List all the orders showing amounts and product description

SELECT ORDER_NUM, PRODUCT, DESCRIPTION, AMOUNT


FROM ORDERS, PRODUCTS
WHERE MFR = MFR_ID AND
PRODUCT = PRODUCT_ID

Example Queries with three or more tables:


List orders over 25,000 including, the name of the salesperson who took the order and the name of the customer
who placed it.

SELECT NAME, COMPANY, ORDER_NUM, AMOUNT


FROM ORDERS, CUSTOMERS, SALESREPS
WHERE REP = EMPL_NUM AND
CUST = CUST_NUM AND
AMOUNT > 25000

72/ADTU OLE
Example Equi Joins:
Find all orders received on days when a new salesperson was hired.

SELECT ORDER_NUM, ORDER_DATE, AMOUNT, NAME


FROM ORDERS, SALESREPS
WHERE ORDER_DATE = HIRE_DATE

Example Non-Equi Joins:


List all combinations of salespeople and offices where the salesperson’s quota is more than the office target

Qualified Column Names


When two or more table contains the same column name, duplicate column name occurs. An error message will
be displayed, when using such columns. To overcome use [Link] When using wildcards use
tablename.*

Example Duplicate table using one alias:


List of salespeople and their managers

SELECT [Link], [Link]


FROM SALESREPS, SALESPREPS MGR
WHERE [Link] = SALESREPS.EMPL_NUM

The same query using alias table can be written as following:

SELECT [Link], [Link]


FROM SLALESREPS REP, SALESREPS MGR
WHERE [Link] = REP.EMPL_NUM

Example:
List sales people with a higher quota than their managers.

SELECT [Link], [Link],


[Link], [Link]
FROM SALESREPS, [Link]
WHERE [Link] = MGR.EMPL_NUM AND
[Link] > [Link]

Rules for Multi Table Query Processing are as follows:


• If the statement is a UNION of SELECT statements, apply step 2 to 5 to each statement to generate their
individual query results.
• From the product of the tables named in the FROM clause names a single table, the product is that table.
• If there is a WHERE clause, apply its search condition to each row of this product table, retaining those rows
for which the search condition is true and discard for FALSE or NULL.
• For each remaining row, calculate the value of each item in the select list to produce a single row of query
results. For each column references, use the value of the column in the current row.
• If SELECT DISTINCT is specified, eliminate any duplicate rows of query results that were produced.
• If the statement is a UNION of select statements merge the query results for individual statements into a single
table of query results. Eliminate duplicate rows unless union all is specified.
• If there is an ORDER BY clause, sort the query results as specified.

73/ADTU OLE
Advanced Java

3.20 Functions
Functions are used to act upon single column or multicolumn for a specified job. Some of the important functions
are:
• SUM() totals the column.
• AVG() average of the column.
• MIN() returns the minimum value of the column.
• MAX() returns the maximum value of the column.
• COUNT() counts the specified condition.
• COUNT(*) counts the number of elements in the column.

Example:
Calculate the total orders for each customer of each salesperson, sorted by customer of each salesperson, sorted by
customer, and within each customer by salesperson.

SELECT CUST, REP, SUM (AMOUNT)


FROM ORDERS
ORDER BY CUST, REP

Example:
Calculate the total orders for each customer of each salesperson, sorted by salesperson, and within each salesperson
by customer.

SELECT REP, CUST, SUM (AMOUNT)


FROM ORDERS
ORDER BY REP, CUST
COMPUTE SUM (AMOUNT) BY REP,
COMPUTE SUM (AMOUNT), AVG (AMOUNT) BY REP

3.21 Query Processing Rules with HAVING


If the statement is a union of SELECT statements, apply steps 2 to 7 to each of the statements to generate their
individual query results from the product of the tables named in the FROM clause. If the FROM clause names a
single table, the product is that table. If there is a WHERE clause, apply its search condition to each row of product
table retaining those rows for which the search condition is TRUE discarding those FALSE or NULL. If there is
a group by clause arrange the remaining rows of the product table into row groups so that the rows in each group
have identical values in all of the grouping columns. If there is a HAVING clause, apply its search condition to each
row group, retaining those groups for which the search condition is TRUE

For each remaining row or row group calculate the value of each item in the select list to produce a single row of
query results. For a simple column reference, use the value of the column in the current row. For a column function,
use the current row group as its argument if GROUP BY is specified otherwise use the entire set of rows. If SELECT
DISTINCT is specified, eliminate any duplicate rows of query results that were produced. If the statement is a union
of SELECT statement, merge the query results for the individual statements into a single table of query results.
Eliminate duplicate rows unless UNION ALL is specified. If there is an ORDER BY clause, sort the query results
as specified.

74/ADTU OLE
3.22 Introduction :Remote Database Access
Most useful databases are accessed remotely. In this way, shared access to the database can be provided to multiple
users at the same time. For example, we can have a single database server that is used by all employees in the
accounting department. In order to access databases remotely, users need a database client. A database client
communicates to the database server on the user’s behalf. It provides the user with the capability to update with
new information or to retrieve information from the database. The database clients talk to database servers using
SQL statements. For this study the following figure.

User data SQL


Database
Driver
Database Client Database Server
program program

Database

Fig. 3.4 A Database client talks to a Database server on the user’s behalf
(Source: [Link]

3.23 ODBC and JDBC drivers


Database clients use database drivers to send SQL statements to database servers and to receive result set and other
responses from the servers. JDBC drivers are used by Java applications and applets to communicate with database
servers. Officially, Sun says that JDBC is an acronym that does not stand for anything. However, it is associated
with “Java database connectivity”.

3.23.1 Microsoft’s ODBC


Many database servers use vendor-specific protocols. This means that a database client has to learn a new language
to talk to a different database server. However, Microsoft established a common standard for communicating with
databases, called Open Database Connectivity (ODBC). Until ODBC, most database clients were server-specific.
ODBC drivers abstract away vendor-specific protocols, providing a common application-programming interface
to database clients. By writing our database clients to the ODBC API, we can enable our programs to access more
database servers as shown in figure below:

75/ADTU OLE
Advanced Java

ODBC Driver DatabaseServer


(Vendor A)

Database ODBC Driver


Client
ODBC API

DatabaseServer
(Vendor B)
ODBC Driver

DatabaseServer
(vendor C)

Fig. 3.5 A Database client can talk to many database servers via ODBC drivers
(Source: [Link]

3.23.2 JDBC
JDBC provides a common database-programming API for Java programs. However, JDBC drivers do not directly
communicate with as many databases using ODBC. In fact, one of the first JDBC drivers was the JDBC-ODBC
bridge driver developed by JavaSoft and Intersolv. Why did JavaSoft create JDBC? What boil down to the simple
fact that ODBC is a better solution for Java applications and applets?
• ODBC is a C language API, not a Java (object-oriented and C is not) API. C uses pointers and other “dangerous”
programming constructs that Java does not support. A Java version of ODBC would require a significant rewrite
of the ODBC API.
• ODBC drivers must be installed on client machines. This means that applet access to databases would be
constrained by the requirement to download and install a JDBC driver. A pure solution allows JDBC drivers to
be automatically downloaded and installed along with applet. This greatly simplifies database access for applet
users.

Since, the release of the JDBC API, a number of JDBC drivers have been developed. These drivers provide varying
levels of capability. JavaSoft has classified JDBC drivers into the following four types:
• JDBC-ODBC bridge plus ODBC driver:This driver category refers to the original JDBCODBC bridge driver.
The JDBC-ODBC bridge driver uses Microsoft’s ODBC driver to communicate with database servers. It is
implemented in both binary code and Java and must be preinstalled on a client computer before it can be used.
JavaSoft created the Java-ODBC bridge driver as a temporary solution to database connectivity until suitable
JDBC drivers were developed. The JDBC-ODBC bridge driver translates the JDBC API into the ODBC API
and it used with an ODBC driver. The JDBCODBC bridge driver is not an elegant solution, but it allows Java
developers to use existing ODBC drivers. The JDBC-ODBC Bridge lets Java clients talk to databases via ODBC
drivers.

76/ADTU OLE
DBC Driver DatabaseServer
(Vendor A)
ODBC Driver
Java
JDBC
Database
ODBC
Client
Bridge
DatabaseServer
(Vendor B)
ODBC Driver

DatabaseServer
(vendor C)

Fig. 3.6 A Database client can talk to many database servers via JDBC ODBC drivers
(Source: [Link]

• Native-API partly Java driver (also called Type 2 Driver): This driver category consists of drivers that talk
to database servers in the server’s native protocol. For example, an Oracle driver would speak SQLNet, while
a DB2 driver would use an IBM database protocol. These drivers are implemented in a combination of binary
code and Java, and they must be installed on client machines. A type 2 JDBC driver uses a vendor-specific
protocol and must be installed on client machines.

Java Database Client


Type 2 JDBC Driver Database Server
Database Server
Vendor
Specific Protocol

Fig. 3.7 A Database client can talk to many database Servers via JDBC type2 drivers
(Source: [Link]

• JDBC-Net pure Java driver: This driver category consists of pure Java drivers that speak a standard network
protocol (such as HTTP) to a database access server. The database access server then translates the network
protocol into a vendor-specific database protocol (possibly using an ODBC driver).

77/ADTU OLE
Advanced Java

Vendor (A) DatabaseServer

Java Database
Database Access
Client Server
DatabaseServer
(Vendoer B)

DatabaseServer (vendor C)

Fig. 3.8 A Database client can talk to many database access servers via JDBC drivers
(Source: [Link]

• Native-protocol pure Java driver: This driver category consists of a pure Java driver that speaks the vendor-
specific database protocol of the database server that it is designed to interface with A type 4 JDBC driver is a
pure Java driver that uses a vendor-specific protocol to talk to database servers.

Java Database Type 4 JDBC Vendor Database


Client Driver
Specific Protocol Server

Fig. 3.9 A Database client can talk to many database Servers via JDBC type4 drivers
(Source: [Link]

Of the four types of drivers, only Type 3 and Type 4 are pure Java drives. This is important to support zero installation
for applets. The Type 4 driver communicates with the database server using a vendor-specific protocol, such as
SQLNet. The Type 3 driver make as use of a separate database access server. It communicates with the database
access server using a standard network protocol, such as HTTP. The database access server communicates with
database servers using vendor-specific protocols or ODBC drivers. The IDS JDBC driver Connect to Databases
with the [Link].

78/ADTU OLE
Summary
• A brief definition of database can be given as “the information held over a period of time, in computer - readable
form”.
• Data are facts concerning people, places, events or other objects or concepts.
• Data are often relatively useless to decision-makers until they have been processed or refined in some
manner.
• A database is a shared collection of interrelated data designed to meet the varied information needs of an
organisation.
• Most systems provide facilities for describing how summary reports from the database are to be created and
laid out on paper.
• A database is nothing but collection of records and a record is a collection of fields or data item and fields is an
attribute about the record.
• As the benefits of the relational approach become more widely perceived, vendors of DBMSs increasingly often
claim that their products are ‘relational’.
• Null values are distinct from the empty character string or a string of blank characters and distinct from zero or
any other numbers are supported in a fully relational DBMS.
• Integrity constraints must be definable in the relational data and storable in the catalogue, notion the applications
program.
• A relational DBMS has distributional independence that is if a distributed database is used it must be possible
to execute all relational operations upon it without knowing the physical locations of data.
• The JDBC requires JDBC-compliant drivers to support the American National Standards Institute (ANSI) SQL-
92 Entry Level version of the standard that was adopted in 1992.
• Database clients use database drivers to send SQL statements to database servers and to receive result set and
other responses from the servers.
• Many database servers use vendor-specific protocols.
• One of the primary uses of SQL is to update the data contained in a database.
• A low-level (single record-at-a-time) language cannot be used to subvert or bypass the integrity rules and
constraints expressed in the higher-level (multiple record-at-a-time) language.
• Integrity constraints must be definable in the relational data and storable in the catalogue, notion the applications
program.

References
• Bai, Y., 2011. Practical Database Programming with Java, John Wiley & Sons Publication.
• 2007. Java 6 Programming Black Book, New Ed, Dreamtech Press.
• Eisenberg, A. and Melton, J., 2000. Understanding SQL and Java Together: A Guide to Sqlj, Jdbc, and Related
Technologies, Morgan Kaufmann Publication.
• Advanced Java Programming with Database Application, [Online] Available at: <[Link]
[Link]> [Accessed 10 April 2012].
• , 2009. A Brief History of Java and JDBC, [Video Online] Available at:<[Link]
Ay9mgEYb6o&feature=related> [Accessed 10 April 2012].
• 2011. JDBC with SQL Server, [Video Online] Available at:< [Link]
Y&feature=related> [Accessed 10April 2012].

79/ADTU OLE
Advanced Java

Recommended Reading
• Horton, I., 2005. Ivor Horton’s Beginning Java 2: JDK, 5th ed, John Wiley & Sons Publication.
• Bharat, V. and Wehling, J., 1996. Late night advanced Java, Ziff-Davis Press Publication.
• Speegle, D. G., 2001. Jdbc: Practical Guide for Java Programmers, Morgan Kaufmann publication.

80/ADTU OLE
Self Assessment
1. A _________is a shared collection of interrelated data designed to meet the varied information needs of an
organisation.
a. database
b. DBMS
c. SQL
d. storage system

2. A ___________is a data item that uniquely identifies a record.


a. secondary key
b. primary key
c. key
d. ternary key

3. Match the following columns

A. Many to Many Association


1.

B. One to Many Association


2.

C. One to One Association

3.
a. 1-A, 2-B, 3-C
b. 1-A, 2-C, 3-B
c. 1-C, 2-A, 3-B
d. 1-B, 2-A, 3-C

4. Match the following columns


1. JDBC-ODBC bridge plus ODBC driver A. Pure Java drivers that speak a standard network protocol

2. Native-API partly Java driver B. Original JDBCODBC bridge driver

3. JDBC-Net pure Java driver C. Drivers that talk to database servers


a. 1-A, 2-B, 3-C
b. 1-B, 2-C, 3-A
c. 1-C, 2-A, 3-B
d. 1-C, 2-B, 3-A

81/ADTU OLE
Advanced Java

5. _______ is any object or event about which the organisation chooses to collect and store data.
a. Entity
b. Attribute
c. Key
d. Data

6. An ________is a property of an entity that we choose to record.


a. entity
b. key
c. data
d. attribute

7. A _______ is a data item used to identify a record.


a. primary key
b. key
c. secondary key
d. attribute

8. The ___________statement adds a row to an existing table or to change the table definitions.
a. DROP TABLE
b. CREATE TABLE
c. ALTER TABLE
d. DELETE TABLE

9. The ___________statement deletes a table from the database.


a. CREATE TABLE
b. DELETE TABLE
c. ALTER TABLE
d. DROP TABLE

10. The database clients talk to database servers using _______ statements.
a. SQL
b. DBMS
c. ODBC
d. JDBC

82/ADTU OLE
Chapter IV
JDBC Fundamentals

Aim
The aim of this chapter is to:

• introduce Java database connectivity

• elucidate connection of an ODBC data source

• explain query operations on the data

Objectives
The objectives of this chapter are to:

• explain JDBC-ODBC bridge

• explicate Java database connectivity model

• elucidate Callable Statement

Learning outcome
At the end of this chapter, you will be able to:

• understand SQL transactions and manage queries

• implement Java database connectivity

• identify various operations on data from the database

83/ADTU OLE
Advanced Java

4.1 Introduction
JDBC is a Java database connectivity API that is a part of the Java Enterprise APIs from Java Soft. From a developer’s
point of view, JDBC is the first standardised effort to integrate relational databases with Java programs. JDBC has
opened all the relational power that can be mustered to Java applets and applications.

4.2 Model
JDBC is designed on the CLI model. JDBC defines a set of API objects and methods to interact with the underlying
database. A Java program first opens a connection to a database, makes a statement object, passes SQL statements
to the underlying DBMS through the statement object, and retrieves the results as well as information about the
result sets. Typically, the JDBC class files and the Java applet reside in the client. To minimise the latency during
execution, it is better to have the JDBC classes in the client. As a part of JDBC, Java Soft also delivers a driver to
access ODBC data sources from JDBC.

This driver is jointly developed with Intersolv and is called the JDBC-ODBC Bridge. The JDBC-ODBC Bridge
is implemented as the [Link] and a native library to access the ODBC driver. For the Windows platform,
the native library is a DLL ([Link]). As JDBC is close to ODBC in design, the ODBC Bridge is a thin
layer over JDBC. Internally, this driver maps JDBC methods to ODBC calls and, thus, interacts with any available
ODBC driver. The advantage of this bridge is that now JDBC has the capability to access almost all databases, as
ODBC drivers are widely available. The JDBC-ODBC Bridge allows JDBC driver to be used as ODBC drivers by
converting JDBC method calls into ODBC function calls.

4.3 Drivers
Using the JDBC-ODBC Bridge requires three things: The JDBC-ODBC bridge driver included with Java2: sun.
[Link] an ODBC driver. An ODBC data source that has been associated with the driver using
software such as the ODBC Data Source Administrator.

ODBC data sources can be set up from within some database programs. When a new database file is created in any
ODBC supported application system, users have the option of associating it with an ODBC driver. All ODBC data
sources must be given a short descriptive name. This name will be used inside Java programs when a connection is
made to the database that the source refers to. In Windows environment, once an ODBC driver is selected and the
database is created, they will show up in the ODBC Data Source Administrator.

4.4 Connecting to an ODBC Data Source


Java application that uses a JDBC-ODBC bridge to connect to a database file either a dbase, Excel, FoxPro, Access,
SQL Server, Oracle and many more. First open the ODBC Data Source 32Bit from the Control Panel. Switch to
System DSN. System DSN lists the System Data Sources. This list shows all system DSNs, including the name of
each DSN and the driver associated with the DSN. Click the Add button to create new Data Source as shown in
figure below:

84/ADTU OLE
Fig. 4.1 Create new data source
(Source: [Link]

Select Oracle ODBC Driver or any other and click the Finish button to finish. This will pop up with a new window
Oracle8 ODBC Driver Setup. Give the Data Source name as oraodbc, UserID Scott and click OK to finish. As
shown in the following snapshot.

Fig. 4.2 Oracle8 ODBC driver setup


(Source: [Link]

85/ADTU OLE
Advanced Java

Fig. 4.3 ODBC data source administrator


(Source: [Link]

After finishing Oracle8 ODBC Driver set up, the ODBC Data Source Administrator will be displaying the following.
Now the ODBC Driver Connection has been established. To display the driver-specific data source setup dialog box
for a user data source, double-click the system DSN. Now the dialog box will look like the figure above. Click OK
buttons to complete the Connection.

4.5 JDBC Connection


Sun offers a package [Link] that allows java program to access relational database management systems (RDBMS).
Through the JDBC a relational database can be accessed using the sql. To communicate with a relational database
the following steps have to be followed. Establish a connection between the Java program and the database manager.
Send a sql statement to the database by using a statement object. Read the results back from the database and use
them in the program.

4.5.1 Working With the Driver Manager


JDBC is designed to work with many different database managers from different applications. In order to establish
a connection with a database the Java runtime environment must load the driver for the specified database. The
driver manager class is responsible for loading and unloading drivers.

4.5.2 Loading Drivers


JDBC drivers are typically written by a database vendor; they accept JDBC connections and statements from one
side and issue native calls to the database from the other. To use a JDBC driver (including the JDBC-ODBC bridge
driver) first thing is to loading it. Preloading from Command line the command for the command line is Java -Djdbc.
drivers=[Link] orajdbc

86/ADTU OLE
4.5.3 Preloading from Program
The command line command will not be of much use for programs and applications. A sample programmatic version
is given below. Usually the following statements will form the first block in the JDBC programming.

try
{
[Link](“[Link]”);
}
catch(ClassNotFoundException e)
{
[Link](“Unable to find JDBC driver”);
}

4.6 JDBC Implementation


JDBC is implemented as the [Link] package. This package contains all of the JDBC classes and methods, as shown
in table below:

Type Class

Driver [Link] [Link] [Link]

Connection [Link]

Statements [Link] [Link] [Link]

ResultSet [Link]

Errors/Warning [Link] [Link]

Metadata [Link] [Link]

Date/Time [Link] [Link] [Link]

Miscellaneous [Link] [Link]

Table 4.1 JDBC Classes

4.6.1 Using the Connection Class


Once a driver has registered with the DriverManager connection to a database is made simple. To invoke the driver
and return a reference to a connection a new connection is set. First specify the location of the database, then the
user name and password. The sample code for connection is

Connection myConnection = [Link]


(“jdbc:odbc:MyDataSource”, “Administrator”, “Password”);

When DriverManager gets a getconnection() request, it takes the JDBC URL and passes it to each registered Driver
in turn. The first Driver to recognise the URL and say that it can connect gets to establish the connection. If no Driver
can handle the URL, DriverManager throws a SQLException, reporting “no suitable driver”. To check whether Driver
has been installed correctly, check for throwsexception error. Use the connection object to connect to databases. By
default, the new connection is set to auto-commit every statement is instantly committed to the database.

87/ADTU OLE
Advanced Java

4.6.2 DBC URL


True to the nature of the Internet, JDBC identifies a database with an URL. The URL is of the form:

jdbc:<subprotocol>:<subname related to the DBMS/Protocol>

For databases on the Internet or intranet, the subname can contain the Net URL //hostname:port/ The <subprotocol>
can be any name that a database understands. The odbc subprotocol name is reserved for ODBC style data sources
and a normal ODBC database.

JDBC URL looks like the following:

jdbc:odbc:<ODBC DSN>;User=<username>;PW=<password>

To develop a JDBC driver with a new subprotocol, it is better to reserve the subprotocol name with JavaSoft, which
maintains an informal subprotocol registry.

Return Type Method Name Parameter

[Link]
(String url, [Link]
Connection connect
info)
Boolean AcceptsURL (String url)
(String url, [Link]
DriverPropertyInfo[] GetPropertyInfo
info)
Int GetMajorVersion ()

Int GetMinorVersion ()

Boolean jdbcCompliant ()

[Link]

(String url, [Link]


Connection getConnection
info)

(String url, String user, String


Connection getConnection
password)

Connection getConnection (String url)

Driver getDriver (String url)

void registerDriver ([Link] driver)

void deregisterDriver (Driver driver)

[Link] getDrivers ()

void setLoginTimeout (int seconds)

int getLoginTimeout ()

88/ADTU OLE
void setLogStream ([Link] out)

[Link] getLogStream ()

Void println (String message)

Class Initialisation
Routine

Void Initialise ()

Table 4.2 Driver, Driver Manager and Related Methods

The Connection class is one of the major classes in JDBC. It packs a lot of functionality ranging from transaction
processing to creating statements, in one class as seen in table above.

Return Type Method Name Parameter

Statement-Related Methods

Statement createStatement ()

PreparedStatement prepareStatement (String sql)

CallableStatement prepareCall (String sql)

String nativeSQL (String sql)

void close ()

Boolean isClosed ()
Metadata-Related
Methods
DatabaseMetaData getMetaData ()

void SetReadOnly (boolean readOnly)

Boolean IsReadOnly ()

void setCatalog (String catalog)

String getCatalog ()

SQLWarning getWarnings ()

void clearWarnings ()
Transaction-Related
Methods
void setAutoCommit (booleanautoCommit)

Boolean getAutoCommit ()

89/ADTU OLE
Advanced Java

void commit ()

void rollback ()

void SetTransactionIsolation (int level)

Int GetTransactionIsolation ()

Table 4.3 [Link] Methods and Constants

4.6.3 Managing SQL Transactions


Use connection’s set autocommit() method to disable auto_commit.

Issue sql statements

To commit the changes to the database, call commit() the transactions. To abandon all the statements made since last
commit(), call rollback(). By default the Connection automatically commits changes after executing each statement.
If auto commit has been disabled, an explicit commit must be done or database changes will not be saved.

4.6.4 Using the Statement


Use a Statement object to hold sql statements. When a statement object is send to the database, the database runs
the sql and returns a ResultSet.

Resultset myset = [Link](“SELECT * FROM CUSTOMERS”);


Or by
Resultset myset;
if([Link](“SELECT * FROM CUSTOMERS”))
myset = [Link]();

The execute() method returns a Boolean true if the Statement returned a ResultSet and false if it returned an integer.
The execute() method is included in JDBC 2.0 and we will be using executequery () and executeupdate () and will
be discussed later.

4.6.5 Statement
A Statement object is created using the createStatement() method in the Connection object. Table below shows all
methods available for the Statement object.

Return Type Method Name Parameter

ResultSet executeQuery (String sql)

int executeUpdate (String sql)

boolean execute (String sql)

boolean getMoreResults ()

90/ADTU OLE
void close ()

int getMaxFieldSize ()

void setMaxFieldSize (int max)

int getMaxRows ()

void setMaxRows (int max)

void setEscapeProcessing (boolean enable)

int getQueryTimeout ()

void setQueryTimeout (int seconds)

void cancle ()

[Link] getWarnings ()

void clearWarnings ()

void setCursorName (String name)

ResultSet getResultSet ()

Int getUpdateCount ()

Table 4.4 Statement object methods

The most important methods are executeQuery (), executeUpdate () and execute(). When creating a Statement object
with a SQL statement, the executeQuery () method takes a SQL string. It passes the SQL string to the underlying
data source through the driver manager and gets the ResultSet back to the application program. The executeQuery
() method returns only one ResultSet. For those cases that return more than one ResultSet, the execute() method
should be used.

4.6.6 Complete Program


Now we shall look at some complete programs. sql stament to to create a table named customers.

CREATE TABLE CUSTOMERS


(
CUST_NUM INTEGER,
COMPANY VARCHAR(20),
CUST_REP INTEGER,
CREDIT_LIMIT NUMBER(7,2)
)

91/ADTU OLE
Advanced Java

The following Java Program can create the same table Customers.

import [Link].*;
import [Link].*;
class Create
{
public static void main(String[] args)
{
Try
{
[Link](“[Link]”);
Connection con = [Link]
(“jdbc:odbc:oraodbc”,”scott”,”tiger”);
Statement stmt = [Link]();
[Link](“create table
customers(CUST_NUM int, COMPANY
char(20), CUST_REP int, CREDIT_LIMIT number(7,2))”);
[Link]();
[Link]();
[Link](“Table Successfully created”);
}catch(Exception e)
{
[Link]();
}
}
}

The output of the program is

Table Successfully created

First statement import [Link].* ; imports all classes that belong to the package sql. All the JDBC code will be
delimited in the try block to avoid any exceptional handling.

[Link](“[Link]”);

Specifies the type of driver to the JRT as JdbcOdbcDriver

[Link](“[Link]”);

When the method getConnection is called, the DriverManager will attempt to locate a suitable driver from
amongst those loaded at initialisation and those loaded explicitly using the same classloader as the current applet
or application.

Connection con = [Link]


(“jdbc:odbc:oraodbc”,”scott”,”tiger”);

The above code snippet Creates Connection object named con.

92/ADTU OLE
A Connection’s database is able to provide information describing its tables, its supported SQL grammar, its stored
procedures, the capabilities of this connection, and so on. This information is obtained with the getMetaData
method.

4.6.7 DriverManager
As part of its initialisation, the DriverManager class will attempt to load the driver classes referenced in the “jdbc.
drivers” system property. This allows a user to customise the JDBC Drivers used by their applications.

4.6.8 Getconnection
Attempts to establish a connection to the given database URL. The DriverManager attempts to select an appropriate
driver from the set of registered JDBC drivers.

Parameters:
• url:- a database url of the form jdbc:subprotocol:subname
• info:- a list of arbitrary string tag/value pairs as connection arguments; normally at least a “user” and “password”
property should be included
• Returns: a Connection to the URL

Statement stmt = [Link]();

The object used for executing a static SQL statement and obtaining the results produced by it. Only one ResultSet
per Statement can be open at any point in time. Therefore, if the reading of one ResultSet is interleaved with the
reading of another, each must have been generated by different Statements. All statement executes methods implicitly
close a statment’s current ResultSet if an open one exists.

4.6.9 CreateStatement
Creates a Statement object for sending SQL statements to the database. SQL statements without parameters are
normally executed using Statement objects. If the same SQL statement is executed many times, it is more efficient
to use a PreparedStatement JDBC 2.0 Result sets created using the returned Statement will have forward-only type,
and read-only concurrency, by default.

Returns: a new Statement object

4.6.10 ExecuteUpdate
Executes an SQL INSERT, UPDATE or DELETE statement. In addition, SQL statements that return nothing, such
as SQL DDL statements, can be executed.
Parameters:
• Sql:- a SQL INSERT, UPDATE or DELETE statement or a SQL statement that returns nothing
• Returns:- either the row count for INSERT, UPDATE or DELETE or 0 for SQL statements that return
nothing

[Link]();

Releases this Statement object’s database and JDBC resources immediately instead of waiting for this to happen
when it is automatically closed.

[Link]();

93/ADTU OLE
Advanced Java

Releases a Connection’s database and JDBC resources immediately instead of waiting for them to be automatically
released.

Every object in sql package throws an exception. It is handled by the try catch (e Exception) block.
Each SQLException provides several kinds of information:
• a string describing the error. This is used as the Java Exception message, available via the method getMessage
().
• a “SQLstate” string, which follows the XOPEN SQLstate conventions. The values of the SQLState string are
described in the XOPEN SQL spec.
• an integer error code that is specific to each vendor. Normally this will be the actual error code returned by the
underlying database.
• a chain to a next Exception. This can be used to provide additional error information.
• [Link]();
• Prints a message to the current JDBC log stream.

4.6.11 Selecting Rows


Selecting Rows from Customers table has the following sql code.

SELECT * FROM CUSTOMERS

Gives the following result. And the equivalent java code is given below:
CUST_NUM COMPANY CUST_REP CREDIT_LIMIT
101 NY TRADERS 5009 40000
102 RAVI AND CO 5008 50000
103 RAM BROTHERS 5007 23000

94/ADTU OLE
import [Link].*;
import [Link].*;
class SelectRow
{
public static void main(String[] args)
{
ResultSet rs;
try
{
[Link](“[Link]”);
Connection con = [Link]
(“jdbc:odbc:oraodbc”,”scott”,”tiger”);
Statement stmt = [Link]();
rs = [Link](“select * from
CUSTOMERS”);
[Link](“CUST_NUM” + “\tCOMPANY” +
“\t\tCUST_REP” + “\tCREDIT_LIMIT”);
while([Link]())
{
[Link]([Link](“CUST_NUM”) + “\t\t” +
[Link](“COMPANY”)+ “\t”+ [Link](“CUST_REP”) + “\t” +
[Link](“CREDIT_LIMIT”));
}
[Link]();
[Link]();
[Link](“Records successfully selected”);
}catch(Exception e)
{
[Link]();
}
}
}

The output of the program is


CUST_NUM COMPANY CUST_REP CREDIT_LIMIT
101 NY TRADERS 5009 40000
102 RAVI AND CO 5008 50000
103 RAM BROTHERS 5007 23000

Records successfully selected.

4.7 Resultset Processing: Retrieving Results


Here, we are using a new object ResultSet. A ResultSet provides access to a table of data. A ResultSet object is usually
generated by executing a Statement. The ResultSet object is actually a tabular data set; that is, it consists of rows of
data organised in uniform columns. The table below shows the methods associated with the ResultSet object.

In JDBC, the Java program can see only one row of data at one time. The program uses the next() method to go to
the next row. JDBC does not provide any methods to move backwards along the ResultSet or to remember the row
positions (called bookmarks in ODBC). A ResultSet maintains a cursor pointing to its current row of data. Initially
the cursor is positioned before the first row. The ‘next’ method moves the cursor to the next row. So in this program
we are using while([Link]()). The method [Link]() returns a boolean value depending on the recordset. If it reaches
last record false in returned and loop lapses.

95/ADTU OLE
Advanced Java

For maximum portability, ResultSet columns within each row should be read in left-to-right order and each column
should be read only once. The JDBC driver attempts to convert the underlying data to the specified Java type and
returns a suitable Java value through the getXXX methods. See the JDBC specification for allowable mappings
from SQL types to Java types with the [Link] methods.

Column names used as input to getXXX methods are case insensitive. When performing a getXXX using a column
name, if several columns have the same name, then the value of the first matching column will be returned. The
column name option is designed to be used when column names are used in the SQL query. For columns that are
NOT explicitly named in the query, it is best to use column numbers. If column names are used, there is no way for
the programmer to guarantee that they actually refer to the intended columns.

A ResultSet is automatically closed by the Statement that generated it when that Statement is closed, re-executed,
or used to retrieve the next result from a sequence of multiple results.

Return Type Method Name Parameter

Boolean next ()

void close ()

Boolean wasNull ()
Get Data By Column Posi-
tion
[Link] getAsciiStream (int columnIndex)

[Link] getBinaryStream (int columnIndex)

boolean getBoolean (int columnIndex)

byte getByte (int columnIndex)

byte[] getByte (int columnIndex)

[Link] getDate (int columnIndex)

double getDouble (int columnIndex)

float getFloat (int columnIndex)

int getInt (int columnIndex)

long getLong (int columnIndex)

[Link] getBignum (int columnIndex, int scale)

Object getObject (int columnIndex)

short getShort (int columnIndex)

String getString (int columnIndex)

[Link] getTime (int columnIndex)

[Link] getTimestamp (int columnIndex)

[Link] getUnicodeStream (int columnIndex)

96/ADTU OLE
Get Data By Column
Name
[Link] getAsciiStream (String columnName)

[Link] getBinaryStream (String columnName)

Boolean getBooleanv (String columnName)

Byte getByte (String columnName)

Byte[] getBytes (String columnName)

[Link] getDate (String columnName)

double getDouble (String columnName)

float getFloat (String columnName)

int getInt (String columnName)

long getLong (String columnName)


(String columnName,
[Link] getBignum
int scale)
Object getObject (String columnName)

short getShort (String columnName)

String getString (String columnName)

[Link] getTime (String columnName)

[Link] getTimestamp (String columnName)

[Link] getUnicodeStream (String columnName)

int findColumn (String columnName)

SQLWarning getWarnings ()

void clearWarnings ()

String getCursorName ()

ResultSetMetaData getMetaData ()

Table 4.5 [Link] methods

The ResultSet methods even though there are many are very simple. The major ones are the getXXX() methods.
The getMetaData() method returns the meta data information about a ResultSet. The DatabaseMetaData also returns
the results in the ResultSet form. The ResultSet also has methods for the silent SQLWarnings. It is a good practice
to check any warnings using the getWarning() method that returns a null if there are no warnings.
Once the program has a row, it can use the positional index (1 for the first column, 2 for the second column, and so
on) or the column name to get the field value by using the getXXXX() methods.

97/ADTU OLE
Advanced Java

The getXXX methods retrieve column values for the current row. Retrieve values using either the index number
of the column or the name of the column. In general, using the column index will be more efficient. Columns are
numbered from 1. Here is the revised version of Selecting Row using the column number.

import [Link].*;
import [Link].*;
class SelectRow
{
public static void main(String[] args)
{
ResultSet rs;
try
{
[Link](“[Link]”);
Connection con = [Link]
(“jdbc:odbc:oraodbc”,”scott”,”tiger”);
Statement stmt = [Link]();
rs = [Link](“select * from CUSTOMERS”);
[Link](“CUST_NUM” + “\tCOMPANY” +
“\t\tCUST_REP” + “\tCREDIT_LIMIT”);
while([Link]())
{
int no=[Link](1);
String company=[Link](2);
int rep=[Link](3);
double credit=[Link](4);
[Link](no+”\t\t”+company+”\t”+rep+”\t\t”+credit);
}
[Link]();
[Link]();
[Link](“Records successfully selected”);
}catch(Exception e)
{
[Link]();
}
}
}

4.7.1 Deleting a Record


In thin proogram records are being deleted from the customers. Here we are using both the executeUpdate() and
executeQuery() to deleting and retriving records from the Customers table. The executeUpdate() returns void and
executeQuery() returns a ResultSet object. Here is the complete program.

98/ADTU OLE
//PROGRAM TO DELETE A RECORD
import [Link].*;
import [Link].*;
class Deleterecord
{
public static void main(String[] args)
{
ResultSet rs;
try
{
[Link](“[Link]”);
Connection con = [Link]
(“jdbc:odbc:oraodbc”,”scott”,”tiger”);
Statement stmt = [Link]();
[Link]
(“delete from CUSTOMERS where CUST_NUM = 101”);
rs = [Link](“select * from customers”);
[Link](“CUST_NUM” + “\tCOMPANY” +
“\t\tCUST_REP” + “\tCREDIT_LIMIT”);
while([Link]())
{
int no=[Link](1);
String company=[Link](2);
int rep=[Link](3);
double credit=[Link](4);
[Link]( no + “\t\t”+company + “\t” + rep + “\t\t” + credit);
}
[Link]();
[Link]();
[Link](“Record Successfully deleted”);
}catch(Exception e)
{
[Link]();
}
}
}

The result of the program

CUST_NUM COMPANY CUST_REP CREDIT_LIMIT


102 RAVI AND CO 5008 50000.0
103 RAM BROTHERS 5007 23000.0
Record successfully deleted

Inserting values into the database, this program is very similar to the delete records program.

99/ADTU OLE
Advanced Java

4.7.2 Inserting a Record


Following is the program for inserting a record in a database

//PROGRAM FOR INSERTING A RECORD


import [Link].*;
import [Link].*;
class Insert
{
public static void main(String[] args)
{
try
{
[Link](“[Link]”);
Connection con = [Link]
(“jdbc:odbc:oraodbc”,”scott”,”tiger”);
Statement stmt = [Link]();
[Link](“insert into CUSTOMERS values
(1,’CHARLIE AND CO’,20,45000)”);
[Link](“insert into CUSTOMERS values
(2,’ARVIND MILLS’,30,50000)”);
[Link](“insert into CUSTOMERS values
(3,’PANDY BROTHERS’,20,12500)”);
ResultSet rs = [Link](“select * from CUSTOMERS”);
[Link](“CUST_NUM” + “\tCOMPANY” +
“\t\tCUST_REP” + “\tCREDIT_LIMIT”);
while([Link]())
{
int no=[Link](1);
String company=[Link](2);
int rep=[Link](3);
double credit=[Link](4);
[Link]( no + “\t\t”+company + “\t” + rep + “\t\t” +
credit);
}
[Link]();
[Link]();
[Link](“Records successfully
inserted”);
}catch(Exception e)
{
[Link]();
}
}
}

The output of the program

100/ADTU OLE
CUST_NUM COMPANY CUST_REP CREDIT_LIMIT
2 ARVIND MILLS 30 50000
102 RAVI AND CO 5008 50000
103 RAM BROTHERS 5007 23000
1 CHARLIE AND CO 20 45000
3 PANDY BROTHERS 20 12500
Records successfully inserted

4.7.3 Updating Records


This program updates records in the customer table. Here the credit_limit of the Arvind Mills (whose CUST_NUM
is 2) has been updated from 50,000 to 2,00,000.

//PROGRAM FOR UPDATING A RECORD


import [Link].*;
import [Link].*;
class UpdateCust
{
public static void main(String[] args)
{
try
{
[Link](“[Link]”);
Connection con = [Link]
(“jdbc:odbc:oraodbc”,”scott”,”tiger”);
Statement stmt = [Link]();
[Link](“update CUSTOMERS set
CREDIT_LIMIT = 200000 where CUST_NUM =2”);
ResultSet rs = [Link](“select * from
CUSTOMERS”);
[Link](“CUST_NUM” + “\tCOMPANY” +
“\t\tCUST_REP” + “\tCREDIT_LIMIT”);
while([Link]())
{
int no=[Link](1);
String company=[Link](2);
int rep=[Link](3);
double credit=[Link](4);
[Link](no + “\t\t”+company + “\t” + rep + “\t\t” +
credit);
}
[Link]();
[Link]();
[Link](“Records successfully updated”);
}catch(Exception e)
{
[Link]();
}
}
}

101/ADTU OLE
Advanced Java

CUST_NUM COMPANY CUST_REP CREDIT_LIMIT


2 ARVIND MILLS 30 200000
102 RAVI AND CO 5008 50000
103 RAM BROTHERS 5007 23000
1 CHARLIE AND CO 20 45000
3 PANDY BROTHERS 20 12500

Records successfully updated

4.7.4 Deleting a Table


Following is the program to delete a program from a database

//PROGRAM TO DROP A TABLE


import [Link].*;
import [Link].*;
class Drop
{
public static void main(String[] args)
{
try
{
[Link](“[Link]”);
Connection con = [Link]
(“jdbc:odbc:oraodbc”,”scott”,”tiger”);
Statement stmt = [Link]();
[Link](“drop table CUSTOMERS”);
ResultSet rs = [Link](“select * from
tab”);
[Link](“TNAME” + “\t\tTABTYPE” +
“\tCLUSTERID”);
while([Link]())
{
String name = [Link](1);
String type = [Link](2);
String clus = [Link](3);
[Link]( name + “\t\t” + type + “\t” + clus);
}
[Link]();
[Link]();
[Link](“Customer Table successfully dropped”);
}catch(Exception e)
{
[Link]();
}
}
}

102/ADTU OLE
The output of the program would be similar to this.
TNAME TABTYPE CLUSTERID
BONUS TABLE null
DEPT TABLE null
EMP TABLE null
EMP1 TABLE null
SALGRADE TABLE null
SAL_DET TABLE null

Customer Table successfully dropped

4.8 Prepared Statement


In the case of a PreparedStatement object, as the name implies, the application program prepares a SQL statement
using the [Link]()method. The PreparedStatement() method takes a SQL string,
which is passed to the underlying DBMS. The DBMS goes through the syntax run, query plan optimisation, and
the execution plan generation stages, but does not execute the SQL statement. Possibly, it returns a handle to the
optimised execution plan that the JDBC driver stores internally in the PreparedStatement object.

The methods of the PreparedStatement object are shown in table below. Notice that the executeQuery(),
executeUpdate(), and execute() methods do not take any parameters. They are just calls to the underlying DBMS
to perform the already-optimised SQL statement.

Return Type Method Name Parameter


ResultSet executeQuery ()
Int executeUpdate ()
Boolean execute ()

Table 4.6 Prepared Statement Object Methods

One of the major features of a PreparedStatement is that it can handle IN types of parameters. The parameters are
indicated in a SQL statement by placing the “?” as the parameter marker instead of the actual values. In the Java
program, the association is made to the parameters with the setXXXX() methods, as shown in Table 4.7 All of the
setXXXX() methods take the parameter index, which is 1 for the first “?,” 2 for the second “?,” and so on.

Return Type Method Name Parameter

void ClearParameters ()

void SetAsciiStream (int parameterIndex, [Link] x, int length)

void SetBinaryStream (int parameterIndex, [Link] x, int length)

void SetBoolean (int parameterIndex, boolean x)

void setByte (int parameterIndex, byte x)

void 1setBytes (int parameterIndex, byte x[])

void setDate (int parameterIndex, [Link] x)

void setDouble (int parameterIndex, double x)

103/ADTU OLE
Advanced Java

void setFloat (int parameterIndex, float x)

void setInt (int parameterIndex, int x)

void setLong (int parameterIndex, long x)

void setLong (int parameterIndex, int sqlType)

void SetBignum (int parameterIndex, Bignum x)

void setShort (int parameterIndex, short x)

void setString (int parameterIndex, String x)

void setTime (int parameterIndex, [Link] x)

void SetTimestamp (int parameterIndex, [Link] x)

void SetUnicodeStream (int parameterIndex, [Link] x, int length)


Advanced
Features-Object
Manipulation
void setObject (int parameterIndex, Object x, int targetSqlType, int scale)

void setObject (int parameterIndex, Object x, int targetSqlType)

void setObject (int parameterIndex, Object x)

Table 4.7 [Link]-Parameter-Related Methods

In the case of the PreparedStatement, the driver actually sends only the execution plan ID and the parameters
to the DBMS. This results in less network traffic and is well-suited for Java applications on the Internet. The
PreparedStatement should be used when needed to execute the SQL statement many times in a Java application.
But remember, even though the optimised execution plan is available during the execution of a Java program, the
DBMS discards the execution plan at the end of the program. So, the DBMS must go through all of the steps of
creating an execution plan every time the program runs.

The PreparedStatement object achieves faster SQL execution performance than the simple Statement object, as the
DBMS does not have to run through the steps of creating the execution plan. The following example program shows
how to use the PreparedStatement class to access a database. The simple Statement example can be improved in a few
major ways. First, the DBMS goes through building the execution plan every time, so make it a PreparedStatement.
Secondly, the query lists all courses, which could scroll away.

104/ADTU OLE
//PROGRAM FOR PREPARE STATEMENT
import [Link].*;
import [Link].*;
class PrepareSt
{
public static void main(String[] args)
{
try
{
[Link](“[Link]”);
Connection con = [Link]
(“jdbc:odbc:oraodbc”,”scott”,”tiger”);
PreparedStatement ps = [Link](“Select * from CUSTOMERS
where CREDIT_LIMIT >= ?”);
[Link](1,50000);
ResultSet rs=[Link]();
// ResultSet rs = [Link](“select * from
CUSTOMERS”);
[Link](“CUST_NUM” + “\tCOMPANY” +
“\t\tCUST_REP” + “\tCREDIT_LIMIT”);
while([Link]())
{
int no=[Link](1);
String company=[Link](2);
int rep=[Link](3);
double credit=[Link](4);
[Link](no+”\t\t”+company+”\t”+rep+”\t\t”
+credit);
}
[Link]();
[Link]();
[Link]();
}catch(Exception e)
{
[Link]();
}
}
}

The output of the program may be equal to


CUST_NUM COMPANY CUST_REP CREDIT_LIMIT
2 ARVIND MILLS 30 900000.0

4.9 Callable Statement


For a secure, consistent, and manageable multi-tier client/server system, the data access should allow the use of
stored procedures. Stored procedures centralise the business logic in terms of manageability and also in terms of
running the query. JDBC allows the use of stored procedures by the CallableStatement class and with the escape
clause string.

A CallableStatement object is created by the prepareCall() method in the Connection object. The prepareCall()
method takes a string as the parameter. This string, called an escape clause, is of the form

105/ADTU OLE
Advanced Java

{[? =] call <stored procedure name>


[<parameter>,<parameter> ...]}

The CallableStatement class supports parameters. These parameters are of the OUT kind from a stored procedure
or the IN kind to pass values into a stored procedure. The parameter marker (question mark) must be used for the
return value (if any) and any output arguments because the parameter marker is bound to a program variable in the
stored procedure. Input arguments can be either literals or parameters. For a dynamic parameterised statement, the
escape clause string takes the form.

{[? =] call <stored procedure name> [<?>,<?> ...]}

The OUT parameters should be registered using the registerOutparameter() method as shown in Table 4.8 before
the call to the executeQuery(), executeUpdate(), or execute() methods.

Return Type Method Name Parameter

Void RegisterOutParameter (int parameterIndex, int sqlType)

Void RegisterOutParameter (int parameterIndex, int sqlType, int scale)

Table 4.8 CallableStatement-OUT Parameter Register Methods

After the stored procedure is executed, the DBMS returns the result value to the JDBC driver. This return value is
accessed by the Java program using the methods in Table 4.9

Return Type Method Name Parameter

Boolean getBoolean (int parameterIndex)

Byte getByte (int parameterIndex)

byte[] getBytes (int parameterIndex)

[Link] getDate (int parameterIndex)

double getDouble (int parameterIndex)

float getFloat (int parameterIndex)

int getInt (int parameterIndex)

long getLong (int parameterIndex)


(int parameterIndex,
[Link] getBignum
int scale)
Object getObject (int parameterIndex)

short getShort (int parameterIndex)

String getString (int parameterIndex)

[Link] getTime (int parameterIndex)

106/ADTU OLE
[Link] getTimestamp (int parameterIndex)
Miscellaneous
Functions
boolean wasNull ()

Table 4.9 CallableStatement parameter access methods

EMPNO NAME AGE SAL DEPTNO


101 aaa 24 9400 10
102 bbb 25 12400 20
103 ccc 27 11400 30

Creating a procedure

The code given below crates a procedure named proc, which increases the credit limit by n.

create or replace procedure proc(n number)


as
begin
update customers set CREDIT_LIMIT = CREDIT_LIMIT + n;
commit;
end;
//Program for procedure
import [Link].*;
import [Link].*;
public class Procedure
{
public static void main(String args[])
{
try
{
[Link](“[Link]”);
Connection con=[Link]
(“jdbc:odbc:oraodbc”,”scott”,”tiger”);
[Link](“Enter Credit limit increment:”);
BufferedReader br=new BufferedReader(new
InputStreamReader([Link]));
String str=[Link]();
int p=[Link](str);
CallableStatement cs=[Link](“{ call proc(?)
}”);
[Link](1,100);
[Link]();
[Link](“Procedure Executed”);
[Link]();
Statement st = [Link]();
ResultSet rs=[Link](“Select * from
Customers”);
while([Link]())

107/ADTU OLE
Advanced Java

{
int eno=[Link](1);
String name=[Link](2);
int ag=[Link](3);
double sal=[Link](4);
[Link](eno+”\t”+name+”\t”+ag+”\t”+sal);
}
[Link]();
[Link]();
[Link]();
}
catch(SQLException es)
{
[Link](es);
}
catch(Exception e)
{
[Link](e);
}
}
}

The output of the program will be similar to Enter Credit limit increment: 1000
Procedure Executed

1 CHARLIE AND CO 20 47200.0


2 ARVIND MILLS 30 902200.0
3 PANDY BROTHERS 20 14700.0

108/ADTU OLE
Summary
• JDBC is a Java database connectivity API that is a part of the Java Enterprise APIs from Java Soft.
• A Java program first opens a connection to a database, makes a statement object, and passes SQL statements
to the underlying DBMS.
• Java application that uses a JDBC-ODBC bridge to connect to a database file either a dbase, Excel, FoxPro,
Access, SQL Server, Oracle and many more.
• JDBC is designed to work with many different database managers from different applications.
• JDBC drivers are typically written by a database vendor; they accept JDBC connections and statements from
one side and issue native calls to the database from the other.
• To use a JDBC driver (including the JDBC-ODBC bridge driver) first thing is to loading it. Preloading from
Command line the command for the command line is Java -[Link]=[Link]
orajdbc.
• The command line command will not be of much use for programs and applications.
• JDBC is implemented as the [Link] package. This package contains all of the JDBC classes and methods.
• Once a driver has registered with the DriverManager connection to a database is made simple.
• The Connection class is one of the major classes in JDBC.
• A Statement object is created using the createStatement() method in the Connection object.
• A Connection’s database is able to provide information describing its tables, its supported SQL grammar, its
stored procedures, the capabilities of this connection, and so on.
• In JDBC, the Java program can see only one row of data at one time.
• The ResultSet object is actually a tabular data set; that is, it consists of rows of data organised in uniform
columns.
• Stored procedures centralise the business logic in terms of manageability and also in terms of running the
query.

References
• Thomas, M. T., 2002. Java data access: JDBC, JNDI, and JAXP, M&T Books Publication.
• Gupta, G., 2006. Advanced Java, Laxmi Publications.
• Advanced Java Programming with Database Application [Online] Available at: <[Link]
[Link]> [Accessed 11 April 2012].
• Database Connectivity ODBC, JDBC and SQLJ, [pdf] Available at: <[Link]
Teaching/cs2312/Lectures/Handouts/[Link]> [Accessed 11 April 2012].
• Java database connectivity - JDBC Module 20, [Video online] Available at: <[Link]
hz8TGEQULc> [Accessed 10 April 2012].
• 2012. Java - JDBC Databases - GUI and SQL Statements - 3 of 3, [Video online] Available at: <[Link]
[Link]/watch?v=Of4LRHOZoII> [Accessed 10 April 2012].

Recommended Reading
• Haecke, V. B., 2002. Jdbc 3.0: Java Database Connectivity, John Wiley & Sons Publication.
• Horstmann, 2008. Core Java, Volume 2-Advanced Features, 8/E, Pearson Education India Publication.
• McManus, A. & Hunt, J., 1998. Key Java: Advanced Tips and Techniques, Springer Publication.

109/ADTU OLE
Advanced Java

Self Assessment
1. Which of the following is not a method?
a. executeQuery ()
b. executeUpdate ()
c. execute()
d. Result()

2. Which of the following statements is false?


a. In JDBC, the Java program can see all rows of data at a time.
b. The program uses the next() method to go to the next row.
c. A ResultSet provides access to a table of data.
d. The ‘next’ method moves the cursor to the next row.

3. Column names used as input to _________methods are case insensitive.


a. Columnget
b. getXXX
c. setXXX
d. getColumn

4. PreparedStatement can handle _____types of parameters.


a. OUT
b. GET
c. IN
d. EXIT

5. A __________provides access to a table of data.


a. ResultSet
b. [Link]()
c. [Link]()
d. getXXX

6. The getMetaData() method returns the meta data information about a__________.
a. getWarning()
b. DatabaseMetaData
c. getWarning()
d. ResultSet

7. executeQuery() method is used for:


a. Deleting and retrieving records from the customers table.
b. Adding records to the customer table.
c. Inserting values in to the database.
d. Execution of plan that the JDBC driver stores internally.

110/ADTU OLE
8. JDBC allows the use of stored procedures by the_____________.
a. sqlStatement
b. CallableStatement
c. Createstatement
d. PrepareStatement

9. A CallableStatement object is created by the _________method in the Connection object.


a. getWarning()
b. ResultSet()
c. prepareCall()
d. registerOutparameter()

10. The CallableStatement class supports ______ parameters.


a. IN
b. EXIT
c. EXECUTE
d. OUT

111/ADTU OLE
Advanced Java

Chapter V
Servlets

Aim
The aim of this chapter is to:

• explain Java servlet concepts

• explicate the Java Servlet API

• elucidate secure programming environment using servlet

Objectives
The objectives of this chapter are to:

• explain servlet runtime environment and life-cycle

• enlist some common servlet interaction techniques

• elucidate servlet process flow

Learning outcome
At the end of this chapter, you will be able to:

• understand servlet filtering and chaining

• identify how to run the servlet

• recognise how to use cookies and session objects in servlets

112/ADTU OLE
5.1 Introduction of Java Servlets
Servlets are protocol and platform independent server-side software components, written in Java. They run inside a
Java enabled server or application server, such as the WebSphere Application Server. Servlets are loaded and executed
within the Java Virtual Machine (JVM) of the Web server or application server, in much the same way that applets
are loaded and executed within the JVM of the Web client. Since servlets run inside the servers, however, they do
not need a graphical user interface (GUI). In this sense, servlets are also faceless objects.

Servlets more closely resemble Common Gateway Interface (CGI) scripts or programs than applets in terms of
functionality. As in CGI programs, servlets can respond to user events from an HTML request, and then dynamically
construct an HTML response that is sent back to the client.

5.2 Servlet Process Flow


Servlets implement a common request/response paradigm for the handling of the messaging between the client and
the server. The Java Servlet API defines a standard interface for the handling of these request and response messages
between the client and server.

The figure below shows a high-level client-to-servlet process flow:


• The client sends a request to the server.
• The server sends the request information to the servlet.
• The servlet builds a response and passes it to the server. That response is dynamically built, and the content of
the response usually depends on the client’s request. External resources may also be used.
• The server sends the response back to the client.

Request Ex: JDBC


Servlet
Client Resources
Response
Web Server

Fig. 5.1 High-level client-to-servlet process flow


(Source: [Link]

Servlets are powerful tools for implementing complex business application logic. Written in Java, servlets have
access to the full set of Java API’s, such as JDBC for accessing enterprise databases. As mentioned above, servlets
are similar to CGI in that they can produce dynamic Web content. Servlets, however, have the following advantages
over traditional CGI programs:

Portability and platform independence: Servlets are written in Java, making them portable across platforms and
across different Web servers, because the Java Servlet API defines a standard interface between a servlet and a Web
server.

Persistence and performance: A servlet is loaded once by a Web server, and invoked for each client request. This
means that the servlet can maintain system resources, like a database connection, between requests. Servlets don’t
incur the overhead of instantiating a new servlet with each request. CGI processes typically must be loaded with
each invocation.

Java based: Because servlets are written in Java, they inherit all the benefits of the Java language, including a strong
typed system, object-orientation, and modularity, to name a few.

113/ADTU OLE
Advanced Java

5.3 The Java Servlet API


The Java Servlet API is a set of Java classes which define a standard interface between a Web client and a Web
servlet. Client requests are made to the Web server, which then invokes the servlet to service the request through
this interface. The Java Servlet API is a Standard Java Extension API, meaning that it is not part of the core Java
framework, but rather, is available as an add-on set of packages. We will be using the Java Servlet Development
Kit API (JSDK) V2.1 conventions throughout this chapter.

The API is composed of two packages:


• [Link]
• [Link]

The [Link] package contains classes to support generic protocol-independent servlets. This means that servlets
can be used for many protocols, for example, HTTP and FTP. The [Link] package extends the functionality
of the base package to include specific support for the HTTP protocol. In this chapter, we will concentrate on the
classes in the [Link] package.

The Servlet interface class is the central abstraction of the Java Servlet API. This class defines the methods which
servlets must implement, including a service() method for the handling of requests. The GenericServlet class
implements this interface, and defines a generic, protocol-independent servlet. To write an HTTP servlet for use
on the Web, we will use an even more specialised class of GenericServlet called HttpServlet. HttpServlet provides
additional methods for the processing of HTTP requests such as GET (doGet method) and POST (doPost method).
Although our servlets may implement a service method, in most cases we will implement the HTTP specific request
handling methods of doGet and doPost.

5.4 The Servlet Life Cycle


A client of a servlet-based application does not usually communicate directly with a servlet, but requests the servlet’s
services through a Web server or application server that invokes the servlet through the Java Servlet API. The server’s
role is to manage the loading and initialisation of the servlet, the servicing of the request, and the unloading or
destroying of the servlet. This is generally provided by a servlet manager function of the application server.

Typically, there is one instance of a particular servlet object at a time in the Web servers’ environment. This is the
underlying principle to the persistence of the servlet. The Web server is responsible for handling the initialisation
of this servlet when the servlet is first loaded into the environment, where it remains active (or persistent) for the
life of the servlet.

Each client request to the servlet is handled via a new thread against the original instance object. The Web server is
responsible for creating the new threads to handle the requests. The Web server is also responsible for the unloading
or reloading of the servlets. This may happen when the Web application is brought down, or the underlying class
file for the servlet changes, depending on the underlying implementation of the server.

The following figure shows a basic client-to-servlet interaction:


• Servlet1 is initially loaded by the Web application server. Instance variables are initialised, and remain active
(persistent) for the life of the servlet.
• Two Web browser clients have requested the services of Servlet1. A handler thread is spawned by the server
to handle each request. Each thread has access to the originally loaded instance variables that were initialised
when the servlet was loaded.
• Each thread handles its own requests, and responses are sent back to the calling client.

114/ADTU OLE
Servlet1
Client1 Thread1 Servlet1
Thread2

* loaded before
Client2 Servlet1 Instance

Web Application Server

Fig. 5.2 Basic client-to-servlet interaction


(Source: [Link]

The life cycle of a servlet is expressed in the Java Servlet API in the init, service (doGet or doPost), and destroy
methods of the Servlet interface. We will discuss the functions of these methods in more detail and the objects that
they manipulate. The following figure is a visual diagram of the life-cycle of an individual servlet.

Create Initialize

(Initializationfailed)
Available Unavailable
for for
service service

(Unavailable
exception
Servicing thrown)
requests Destroy Unload

Fig. 5.3 Servlet life-cycle


(Source: [Link]

The WebSphere administrator can set an application and its servlets to be unavailable for service. In such cases, the
application and servlets remain unavailable until the administrator changes them to available.

5.4.1 Understanding the Life-Cycle


The life cycle of the servlets are described in detail some of the important servlet life-cycle methods of the Java
Servlet API. These are explained in detail below:

5.4.2 Servlet Initialisation: Init Method


Servlets can be dynamically loaded and instantiated when their services are first requested, or the Web server can
be configured so that specific servlets are loaded and instantiated when the Web server initialises. In either case, the
init method of the servlet performs any necessary servlet initialisation, and is guaranteed to be called once for each
servlet instance, before any requests to the servlet are handled. An example of a task which may be performed in
the init method is the loading of default data parameters or database connections.

115/ADTU OLE
Advanced Java

The most common form of the init method of the servlet accepts a ServletConfig object parameter. This interface
object allows the servlet to access name/value pairs of initialisation parameters that are specific to that servlet. The
ServletConfig object also gives us access to the SevletContext object that describes information about our servlet
environment. Each of these objects will be discussed in more detail in the servlet examples sections.

5.4.3 Servlet Request Handling


Once the servlet has been properly initialised, it may handle requests although it is possible that a loaded servlet
may get no requests. Each request is represented by a ServletRequest object and the corresponding response by a
ServletResponse object in the Java Servlet API. Since we will be dealing with HttpServlets, we will deal exclusively
with the more specialised HttpServletRequest and HttpServletResponse objects.

The HttpServletRequest object encapsulates information about the client request, including information about the
client’s environment and any data that may have been sent from the client to the servlet. The HttpServletRequest
class contains methods for extracting this information from the request object.

The HttpServletResponse is often the dynamically generated response, for instance, an HTML page which is sent back
to the client. It is often built with data from the HttpServletRequest object. In addition to an HTML page, a response
object may also be an HTTP error response, or a redirection to another URL, servlet, or JavaServer Page.

Each time a client request is made, a new servlet thread is spawned which services the request. In this way, the
server can handle multiple concurrent requests to the same servlet. For each request, usually the service, doGet,
or doPost methods will be called. These methods are passed the HttpServletRequest and HttpServletResponse
parameter objects.

doPost: Invoked whenever an HTTP POST request is issued through an HTML form. The parameters associated
with the POST request are communicated from the browser to the server as a separate HTTP request. The doPost
method should be used whenever modifications on the server will take place.

doGet: Invoked whenever an HTTP GET method from a URL request is issued, or an HTML form. An HTTP GET
method is the default when a URL is specified in a Web browser. In contrast to the doPost method, doGet should be
used when no modifications will be made on the server, or when the parameters are not sensitive data. The parameters
associated with a GET request are appended to the end of the URL, and are passed into the QueryString property
of the HttpServletRequest. Other servlet methods worth mentioning

destroy: The destroy method is called when the Web server unloads the servlet. A subclass of HttpServlet only
needs to implement this method if it needs to perform cleanup operations, such as releasing database connections
or closing files.

getServletConfig: The getServletConfig method returns a ServletConfig instance that can be used to return the
initialisation parameters and the ServletContext object.

getServletInfo: The getServletInfo method is a method that can provide information about the servlet, such as its
author, version, and copyright. This method is generally overwritten to have it return a meaningful value for your
application. By default, it returns an empty string.

116/ADTU OLE
5.5 Basic Servlet Examples
In this section, we will build on the foundation in the previous sections, by describing some servlets that demonstrate
additional capabilities and concepts of the Java Servlet API. Following are the types and examples of some
servlets:

5.5.1 Simple HTTP Servlet


We begin with a look at a very simple servlet, SimpleHttpServlet is given below:

package [Link];
import [Link].*;
import [Link].*;
import [Link].*;
public class SimpleHttpServlet extends HttpServlet {
protected void service(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {
[Link](“text/html”);
PrintWriter out = [Link]();
[Link](“<HTML><TITLE>SimpleHttpServlet</TITLE><BODY>”);
[Link](“<H2>Servlet API Example - SimpleHttpServlet</H2><HR>”);
[Link](“<H4>This is about as simple a servlet as it gets!</H4>”);
[Link](“</BODY><HTML>”);
[Link]();
}
}

Program: Simple HTTP servlet


As the title indicates, SimpleHttpServlet is a very simple HTTP servlet that accepts a request and writes a response.
Let’s break out the components of this servlet so we can discuss them individually.

5.5.2 Basic Servlet Structure


The following code snippet shows that we have defined this servlet to be part of an [Link] Java
package. This is the naming convention used for all the servlet examples given in this chapter.

package [Link];

SimpleHttpServlet package declaration


The following code snippet shows the import statements used to give us access to other Java packages. The import
of [Link] is so that we have access to some standard IO classes. More importantly, the [Link].* and javax.
[Link].* import statements give us access to the Java Servlet API set of classes and interfaces

import [Link].*;
import [Link].*;
import [Link].*;

SimpleHttpServlet import statements


SimpleHttpServlet class declaration. We extend the HttpServlet class ([Link]) to make our
class an HTTP protocol servlet.

public class SimpleHttpServlet extends HttpServlet {

117/ADTU OLE
Advanced Java

The SimpleHttpServlet class declaration


The code given below is the heart of this servlet, the implementation of the service method for the handling of the
request and response objects of the servlet.

protected void service (HttpServletRequest req, HttpServletResponse res)


throws ServletException, IOException {
[Link](“text/html”);
PrintWriter out = [Link]();
[Link](“<HTML><TITLE>SimpleHttpServlet</TITLE><BODY>”);
[Link](“<H2>Servlet API Example - SimpleHttpServlet</H2><HR>”);
[Link](“<H4>This is about as simple a servlet as it gets!</H4>”);
[Link](“</BODY><HTML>”);
[Link]();
}

SimpleHttpServlet service method

5.5.3 What the Service Method Does?


Let’s examine this service method in more detail. Notice that the method accepts two parameters, HttpServletRequest
and HttpServletResponse. The request object contains information about and from the client. In this example, we
don’t do anything with the request. This method is declared Abstract in the basic GenericServlet class, and so
subclasses, such as HttpServlet, must override it. In our subclass of HttpServlet, when using this method, we must
implement this method according to the signature defined in HttpServlet, namely, that it accepts HttpServletRequest
and HttpServletResponse arguments.

We do some handling of the response object, which is responsible for sending our response back to the client.
Our response here is a formatted HTML page, so we first set the response content type to text/html by coding res.
setContentType(“text/html”). Next, we request a PrintWriter object to write text to the response by coding PrintWriter
out = [Link](). We could also have used a ServletOutputStream object to write out our response, but getWriter
gives us more flexibility with Internationalisation. In either case, the content type of the response must be set before
references to these objects can be made.

The remaining [Link] statements write our HTML to the PrintWriter, which is sent back to the client as our
response. It is pretty simple HTML, so we do not display it here. We use [Link] more for completeness, because
the Web application server automatically closes the PrintWriter when the service method exits.

5.5.4 How the Servlet Gets Invoked


We could invoke this servlet with either a GET or POST form action method; the service method will execute for
either. If we knew something about how this servlet was ultimately to be called, for instance, what the HTML form
method was going to be, we could have implemented the above functionality through specific doGet or doPost
methods. The result would be the same.

The simplest way to invoke the servlet would be by specifying a URL in the Web browser. This does not work for
every servlet, but would work for the above example. A URL forces the Web browser to send the request using
GET, similar to the way a standard HTML page is requested. The above servlet could be invoked from the Web
browser with the URL:

[Link]
[Link]

The second form invokes a servlet in a Web application.

118/ADTU OLE
5.5.5 Running the Servlet
At this point we have not discussed the specifics of running servlets in a Web server environment. If we want to run
this servlet, we should be able to follow the steps in “Development and testing with VisualAge for Java”, code the
SimpleHttpServlet, and run it under the WebSphere Test Environment. The WebSphere Test Environment provides
a simulated Web server environment within the VisualAge for Java product and enables us to test and debug our
servlets.

5.6 HTML form Generator Servlet


Another simple HTTP servlet is HTMLFormGenerator. It is coded as below.

package [Link];
import [Link].*;
import [Link].*;
import [Link].*;
public class HTMLFormGenerator extends HttpServlet {
public void init(ServletConfig config) throws ServletException {
[Link](config);
[Link](“In the init() method of HTMLFormGenerator”);
}
public void doGet(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {
performTask(req, res, “POST”,
“[Link]”);
// “/itsoservjsp/servlet/[Link]”);
}
public void performTask(HttpServletRequest req, HttpServletResponse res,
String method, String url) throws ServletException, IOException {
[Link](“text/html”);
PrintWriter out = [Link]();
[Link](“<HTML><TITLE>HTMLFormGenerator</TITLE><BODY>”);
[Link](“<H2>Servlet API Example - HTMLCreatingServlet</H2><HR>”);
[Link](“<FORM METHOD=\”” + method + “\” ACTION=\”” + url + “\”>”);
[Link](“<H2>Tell us something about yourself: </H2>”);
[Link](“<B>Enter your name: </B>”);
[Link](“<INPUT TYPE=TEXT NAME=firstname><BR>”);
[Link](“<B>Select your title: </B>”);
[Link](“<SELECT NAME=title>”);
[Link](“<OPTION VALUE=\”Web Developer\”>Web Developer”);
[Link](“<OPTION VALUE=\”Web Architect\”>Web Architect”);
[Link](“<OPTION VALUE=\”Other\”>Other”);
[Link](“</SELECT><BR>”);
[Link](“<B>Which tools do you have experience with: </B><BR>”);
[Link](“<INPUT TYPE=checkbox NAME=\”tools\”
VALUE=\”WebSphere Application Server\”>WebSphere Application Server<BR>”);
[Link](“<INPUT TYPE=checkbox NAME=\”tools\”
VALUE=\”WebSphere Studio\”>WebSphere Studio<BR>”);
[Link](“<INPUT TYPE=checkbox NAME=\”tools\”
VALUE=\”VisualAge for Java\”>VisualAge for Java<BR>”);
[Link](“<INPUT TYPE=checkbox NAME=\”tools\”
VALUE=\”IBM Http Web Server\”>IBM Http Web Server<BR>”);
[Link](“<INPUT TYPE=checkbox NAME=\”tools\” VALUE=\”DB2 UDB\”>DB2 UDB<BR>”);
[Link](“<INPUT TYPE=\”SUBMIT\” NAME=\”SENDPOST\” NAME=\”SENDPOST\”>”);

119/ADTU OLE
Advanced Java

[Link](“</FORM>”);
[Link](“</BODY><HTML>”);
[Link]();
[Link](“In the doGet method”);
}
}

HTML form generator servlet

Init method
This servlet implements the init method. The init method only prints a message to standard output and calls the
super-class constructor. As we mentioned before, the init method is called only once, when the servlet is loaded.
This message, therefore, should only be printed to the Web server’s console or log once wherever standard output
is defined; regardless of how many times the servlet is actually invoked.

doGet Method
We decided that this servlet is always called through a GET request; we have chosen to implement the doGet method,
instead of the more generic service method. We developed a performTask method to which we pass a method posting
type and a target URL.

5.6.1 Response Object


The HTML page that this servlet generates is a bit more complex than the previous example. It actually builds an
HTML form that can be used in the future to call other servlets. This is not the same as a servlet calling a servlet,
which is a server-side process. Here, we are just using one servlet to generate the HTML back to the browser, so we
can call our other example servlets, and we do not have to create separate HTML files for each servlet.

This servlet has many [Link] statements. This is just the HTML that is written back to the browser. Despite the
size of this servlet, it is still only doing one simple thing, writing HTML output.

5.6.2 Invoking the Servlet


This servlet can be invoked directly by a URL command:

[Link]
[Link] <== with web application

The output line for the form that this servlet generates in the performTask method:

<FORM METHOD=”POST”
ACTION=”[Link]”>

This line demonstrates another way of invoking a servlet, in this case from a Web browser using a form action event.
The form is generated by the HTMLFormGenerator servlet. The relative URL in the action is added to the current
prefix of the generating servlet, such as [Link]

120/ADTU OLE
5.6.3 Servlet Output
The HTML Page that this servlet generates is shown in figure below:

Fig. 5.4 HTML form generator servlet: response output


(Source: [Link]

5.7 HTML Form Processing Servlet


We will see the servlet that processes HTML. The following two code snippets show the HTMLFormHandler
servlet.

package [Link];
import [Link].*;
import [Link].*;
import [Link].*;
import [Link].*;
public class HTMLFormHandler extends HttpServlet {
public void init (ServletConfig srvCfg) throws ServletException {
[Link](srvCfg);
}

HTML form handler servlet (part 1)

121/ADTU OLE
Advanced Java

public void doPost(HttpServletRequest req, HttpServletResponse res)


throws ServletException, IOException {
[Link](“text/html”); //must be before first ref to PrintWriter
PrintWriter out = [Link]();
[Link](“<HTML><TITLE>HTMLFormHandler</TITLE></BODY>”);
[Link](“<H2>Servlet API Example - HTMLFormHandler</H2><HR>”);
//Retrieving the single-value parameters
[Link](“Hi <B>” + [Link](“firstname”) + “,</B><P>”);
[Link](“I see you are a <B>” + [Link](“title”) + “,</B><P>”);
[Link](“And have worked with the following tools: <BR>”);
//Retrieving the multi-value parameters
String vals[] = (String []) [Link](“tools”);
if (vals != null) {
for(int i = 0; i<[Link]; i++)
[Link](“<B>” + vals[i] + “</B><BR>”);
}
else [Link];n(“<B> None </B><BR>”);
[Link](“<HR>”);
getReqInfo(req, out); //gets the standard request information
[Link](“</BODY></HTML>”);
[Link]();
}
public void getReqInfo(HttpServletRequest req, PrintWriter out)
throws ServletException, IOException {
[Link](“<H4><B>Additional Request Information:</B></H4>”);
[Link](“<B>Request method:</B> “ + [Link]() + “<BR>”);
[Link](“<B>Request URI:</B> “ + [Link]() + “<BR>”);
[Link](“<B>Request protocol:</B> “ + [Link]() + “<BR>”);
[Link](“<B>Request scheme:</B> “ + [Link]() + “<BR>”);
[Link](“<B>Servlet path:</B> “ + [Link]() + “<BR>”);
[Link](“<B>Servlet name:</B> “ + [Link]() + “<BR>”);
[Link](“<B>Servlet port:</B> “ + [Link]() + “<BR>”);
[Link](“<B>Path info:</B> “ + [Link]() + “<BR>”);
[Link](“<B>Path translated:</B> “ + [Link]() + “<BR>”);
[Link](“<B>Character encoding:</B> “+[Link]()+ “<BR>”);
[Link](“<B>Query string:</B> “ + [Link]() + “<BR>”);
[Link](“<B>Content length:</B> “ + [Link]() + “<BR>”);
[Link](“<B>Content type:</B> “ + [Link]() + “<BR>”);
[Link](“<B>Remote user:</B> “ + [Link]() + “<BR>”);
[Link](“<B>Remote address:</B> “ + [Link]() + “<BR>”);
[Link](“<B>Remote host:</B> “ + [Link]() + “<BR>”);
[Link](“<B>Authorization scheme:</B> “ + [Link]() + “<BR>”);
}
} //end of class

HTML form handler servlet (part 2)

Request Object Handling


So far, all of our servlet examples have only used the response object, but not the request object. This example shows
how to process the data in the request. We assume that this servlet is always called using a POST request, and have
therefore chosen to implement the doPost request handling method.

122/ADTU OLE
doPost Method
Incidentally, this servlet has been designed to handle the particular type of request from the HTML page that was
generated in the previous servlet example. In that HTML page, the user could fill out information in the form and
submit it. The action in the HTML form causes the HTMLFormHandler servlet to be invoked, and the doPost request
handler method to be called:

<FORM METHOD=”POST”
ACTION=”[Link]”>

In the doPost method, we handle the HttpServletResponse in the same way as before, except that this time, we are
also handling the HttpServletRequest.

5.7.1 Getting Form Values


We use the getParameter method of the request to extract the values of the request parameters (name/value fields
passed in from the HTML page). We extract parameters named firstname and title from the request:

[Link](“firstname”)
[Link](“title”)

These are two of the input fields that were passed from the HTML form. The getParameter method requires as an
argument the name of the parameter that we want to extract (so it must be known), and returns the value of that
parameter, or null. To get a list of the all parameter names, we could use the getParameterNames method. This
method returns an enumeration of all the parameter names in the request, which we could then iterate through to
get the individual parameter values.

To extract the value of the tools parameter, however, we must apply a slightly different technique. The tools’ parameter
is a multi-value input field (in this case, a checkbox). Because there could be more than one value to extract, we use
the getParameterValues method, which returns an array of values.

5.7.2 General Request Properties


We can pull environment properties and other information about the client from the HttpServletRequest object and
echo them to the response. We choose to put all this code in a separate method, getReqInfo, for ease of use.

123/ADTU OLE
Advanced Java

The HTML page that this servlet generates is shown in Figure below.

Fig. 5.5 HTML form handler servlet response output


(Source: [Link]

124/ADTU OLE
5.8 Simple Counter Servlet
SimpleCounter is another simple servlet, but here we have an instance counter variable that is initialised in the init
method.

package [Link];
import [Link].*;
import [Link].*;
import [Link].*;
public class SimpleCounter extends HttpServlet {
private int calledCount;
public void init(ServletConfig config) throws ServletException {
[Link](config);
calledCount = 0;
}
protected void service(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {
[Link](“text/html”);
PrintWriter out = [Link]();
[Link](“<HTML><BODY>”);
[Link](“<H2>Servlet API Example - SimpleCounter</H2><HR>”);
++calledCount;
[Link](“<H4>This servlet has been called: “ + calledCount +
“ times.</H4>”);
[Link](“</BODY><HTML>”);
[Link]();
}
}

Simple counter servlet

Every time this servlet is invoked, we increment this counter variable, calledCount, by one. The first time this servlet
loads, we initialise the counter to 0. Subsequent invocations keep incrementing the counter.

5.8.1 Persistence
This example demonstrates the persistence property of servlets, where an instance variable can remain active for the
life of the servlet. Every time a servlet thread is spawned to handle the servlet request, it has access to this global
instance variable. This could be useful in the case where these instance variables take a long time to initialise, such
as database connections, and we want to set them once and reuse them with each invocation, without having to incur
the initialisation overhead each time.

This is a commonly used technique, particularly when we are only initialising data, and then reading global variables,
as is the case with database connections. In this example, however, we are reading and updating this global variable.
This introduces some issues that we have to consider while designing our servlets.

5.8.2 Multi-Threaded
Because our requests to this servlet are handled in threads against the same servlet object, we must implement
mechanisms to guarantee thread safety for these shared instance variables, because we can update them in separate
threads. In other words, there is no guarantee that the line that increments the counter and the line that prints out
the counter will be executed asynchronously within a thread. So, we must identify critical sections of code, and
synchronise these sections if appropriate. There are many books that deal with concurrent programming issues,
therefore we do not describe how to do this, but it is an important point to remember when designing our servlets.

125/ADTU OLE
Advanced Java

5.9 Servlet Initialisation Parameters


The SimpleInitServlet servlet shows how to retrieve initialisation parameters from the servlet configuration object
shown in the code below.

5.9.1 ServletConfig object


The ServletConfig object is a parameter that can be passed into the init method of the servlet. We can also get the
ServletConfig object from the request object through the getServletConfig method, but it is most commonly used in
the init method to initialise the servlet’s instance variables. Methods of the ServletConfig object allow us to extract
the parameter information from this object. This parameter information is in a name/value pair’s format, and can be
stored in a file in XML format. We do not have to read the file, however, because the methods of the class provide
us with some handy helper methods.

5.9.2 What this Servlet does?


This servlet simply extracts the parameter information from the configuration file, and stores those values in instance
variables. It then echoes this information back to the client that invoked the servlet. In a real-life application, these
variables would most likely be used to make a connection to the database, and this connection would be stored in
a global instance variable for later use in the doGet method.

package [Link];
import [Link].*;
import [Link].*;
import [Link].*;
public class SimpleInitServlet extends HttpServlet {
protected String mydriver;
protected String myurl;
protected String myuserID;
protected String mypassword;
public void init(ServletConfig config) throws ServletException {
[Link](config);
mydriver = [Link](“driver”);
myurl = [Link](“URL”);
myuserID = [Link](“userID”);
mypassword = [Link](“password”);
}
public void doGet(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {
[Link](“TEXT/HTML”);
PrintWriter out = [Link]();
[Link](“<HTML>”);
[Link](“<TITLE>Date Display</TITLE>”);
[Link](“<BODY>”);
[Link](“<H2>Servlet Initialisation Parameters (ServletConfig):
</H2><HR>”);
[Link](“<B>driver: </B>” + mydriver + “</BR>”);
[Link](“<B>url: </B>” + myurl + “</BR>”);
[Link](“<B>password: </B>” + mypassword + “</BR>”);
[Link](“<B>userID: </B>” + myuserID + “</BR>”);
[Link](“</BODY></HTML>”);
[Link]();
}
}

Simple initialisation servlet source: ServletConfig parameters

126/ADTU OLE
5.9.3 Servlet Configuration File
The statement mydriver = [Link](“driver”) extracts the driver parameter by name from the
configuration file, and stores it in a global instance variable. The parameter information itself is actually stored in
XML format, in a file called [Link]. This file must be found through the class path. Where this file
actually exists depends on our application server implementation, and is given in “Testing the servlets and JSPs”.

For VisualAge for Java testing, the file can be put into

d:\IBMVJava\ide\project_resources\..yourproject..\itso\servjsp\servletapi.

The XML configuration file used in this example is shown in code snippet below. Here we have specified four
parameters, for demonstration purposes only. These could be used to make a connection to a database.

<?xml version=”1.0”?>
<servlet>
<code>[Link]</code>
<init-parameter value=”[Link].DB2Driver” name=”driver”/>
<init-parameter value=”itso” name=”password”/>
<init-parameter value=”jdbc:db2:sample” name=”URL”/>
<init-parameter value=”itso” name=”userID”/>
</servlet>

Servlet configuration file for simple initialisation servlet

5.9.4 Understanding the Configuration File Format


The code below shows the XML format of a configuration file. The WebSphere Application Server supports XML
configuration files in this format.

<?xml version=”1.0”?>
<servlet>
<code>[Link]</code>
<description>Shows how to use PageListServlet class</description>
<init-parameter name=”name1” value=”value1”/>
<page-list>
<default-page>
<uri>/[Link]</uri>
</default-page>
<error-page>
<uri>/[Link]</uri>
</error-page>
<page>
<uri>/itso/[Link]</uri>
<page-name>pageA</page-name>
</page>
<page>
<uri>itso/[Link]</uri>
<page-name>pageB</page-name>
</page>
</page-list>
</servlet>

General XML configuration file format

127/ADTU OLE
Advanced Java

The elements are also known as tags that are:


• servlet: The root element. The XMLServletConfig class automatically generates this element.
• code: The class name of the servlet (without the .class extension), even if the servlet is in a JAR file.
• init-parameter: The attributes of this element specify a name/value pair to be used as an initialisation parameter.
A servlet can have multiple initialisation parameters, each within its own init-parameter element.
• page-list: The elements within this tag specify JavaServer Pages that may be called by the servlet.

5.10 HTTP Request Handling Utility Servlet


This is a good utility servlet that extracts a lot of information from the request, and echoes its contents back to the
client in the response. Learn the source code to see what kind of data can be extracted from a request object, and how
to manipulate that data. Use this servlet as a future reference. The ServletEnvironmentSnoop servlet demonstrates
the handling of the following request data:

Request information—HTTP specific request information.


• Request header— data passed in the header of the request, such as the character and encoding sets.
• Request parameters—name/value pairs of parameter data.
• Request attribute names—attributes of the class.
• Request cookies—an array containing all cookies present in the request.
• Servlet configuration—values used for initialising the servlet.
• Servlet context attributes—information about the environment where the application server is running.
• Session information—session data associated with the request.

5.11 Additional Servlet Examples


Now that we have covered some servlet basics, we will demonstrate some additional servlet techniques. We do
not go into painstaking detail about how some of these work, and we can research the details by reading a more
comprehensive book on servlets. Instead, we will focus on the important concepts each servlet demonstrates.

5.11.1 Cookie Servlet


A cookie is a piece of data passed between a Web server and a Web browser. The Web server sends a cookie that
contains data it requires the next time the browser accesses the server. This is one way to maintain state between
a browser and a server. The CookieServlet demonstrates a servlet which gets and sets a cookie stored at a client.
Initially, the browser may not have sent the cookie as part of the request, for example, the first time it is called, so
we just initialise a local calledCount variable to 0. If we are able to get this cookie from the request, we set the local
calledCount to the value of the cookie.

The servlet first tries to get the calledCount by iterating through the cookies it received as part of the request. If
no cookie contains the calledCount item, then the servlet initialises the calledCount value to 0. This value is then
incremented, and a new cookie instance is created for calledCount and added to the response.

If we call this servlet from a URL, we find that the first time we call it, the calledCount is 0. Subsequent calls to
the same servlet from this Web browser will show that we keep incrementing the counter, and storing it into the
cookie sent back to the browser. This is one way by which we can maintain state between the Web browser and the
server. The major drawback with cookies is that most browsers enable the user at the client machine to deactivate
(not accept) cookies.

128/ADTU OLE
package [Link];
import [Link].*;
import [Link].*;
import [Link].*;
public class CookieServlet extends HttpServlet {
protected void service(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {
int calledCount = 0;
[Link](“text/html”);
PrintWriter out = [Link]();
[Link](“<HTML><TITLE>CookiesServlet</TITLE><BODY>”);
[Link](“<H2>Servlet Cookie Example:</H2><HR>”);
if (getReqCookie(req, out, “calledCount”) == null)
calledCount = 0;
else
calledCount = new Integer(getReqCookie(req, out,
“calledCount”)).intValue();
[Link](“The value of the cookie calledCount sent in on the request: “);
if (calledCount == 0) [Link]
(“null - value not sent in on request<HR>”);
else [Link](calledCount + “<HR>”);
calledCount++;
Cookie cookie = new Cookie(“calledCount”,
new Integer(calledCount).toString());
[Link](cookie);
[Link](“The value of the cookie calledCount set on the response: “ +
calledCount);
[Link](“</BODY><HTML>”);
[Link]();
}
private String getReqCookie(HttpServletRequest req, PrintWriter out,
String name) {
Cookie[] cookies = [Link]();
if (cookies != null && [Link] > 0) {
for(int i=0; i<[Link]; i++) {
if (cookies[i].getName().equals(name))
return (cookies[i].getValue());
}
}
return null;
}
}

Cookie servlet: State tracking using cookies

129/ADTU OLE
Advanced Java

5.12 URL Rewriting Servlet


URL rewriting is another way to support state tracking. With URL rewriting, the parameter that we want to pass
back and forth between the Web browser and client is appended to the URL. URL rewriting is the lowest common
denominator of session tracking, and is used when a client does not accept cookies. We modified the CookieServlet
to implement the same state tracking mechanism technique, but by using URL rewriting. The URLServlet given in
code below demonstrates this technique.

package [Link];
import [Link].*;
import [Link].*;
import [Link].*;
public class URLServlet extends HttpServlet {
protected void service(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {
int calledCount = 0;
[Link](“text/html”);
PrintWriter out = [Link]();
[Link](“<HTML><TITLE>URLServlet</TITLE><BODY>”);
[Link](“<H2>Servlet URL Rewriting Example:</H2><HR>”);
calledCount = getReqURLInt(req, “calledCount”);
[Link](“The value of the url-parm calledCount received in the
request:”);
if (calledCount == 0) [Link](“null - value not received <HR>”);
else [Link](calledCount + “<HR>”);
calledCount++;
[Link](“The value of the url-parm calledCount sent back: “ +
calledCount);
[Link](“<HR><P><A HREF=\”[Link]”);
[Link](“?calledCount=” + calledCount +
“\”> Click to reload</A>”);
[Link](“</BODY><HTML>”);
[Link]();
}
public int getReqURLInt(HttpServletRequest req, String name) {
int val = 0;
if ([Link](name) != null)
val = new Integer([Link](name)).intValue();
return val;
}
}

URL servlet: state tracking using URL rewriting

5.13 A Real Persistent Servlet Between Servlet Life-Cycle


In the SimpleCounter servlet we introduced a servlet that incremented a counter with every request to the servlet.
We wanted to demonstrate that the servlet is persistent between requests.

The problem
If the server is brought down, however, the servlet would be reloaded, and the counter set back to zero. What if we
wanted to store this counter between servlet life-cycle sessions? Every time the servlet initialises, we want to be
able to reset it to the value of the last servlet life-cycle session.

130/ADTU OLE
A solution
We could do this by storing the counter variable in a file, and then loading this file into the counter variable in the
next initialisation. In this way, we have persistence between servlet life-cycle sessions. The PersistentCounter servlet
demonstrates how we might do this. We create our own object type, SaveServletStats, with a calledCount variable.
We make the SaveServletStats object Serialisable, so that we can save it to an ObjectOutputStream file we use an
object here because serialisation is not supported for native data types, such as int.

The init method gets the file name of the stats file from the ServletConfig, and then rebuilds the SaveServletStats
object from the serialised file by using the ObjectInputStream. Once the SaveServletStats object has been rebuilt,
we now have restored the calledCount value from our last servlet life-cycle session. If the file does not exist, we
initialise it for the first time to zero. The [Link] file is given in code below.

<?xml version=”1.0”?>
<servlet>
<code>[Link]</code>
<init-parameter value=”statsfile” name=”filename”/>
</servlet>

Servlet configuration file for persistent counter servlet

The PersistentCounter servlet is shown in code below. In the doGet method we save the file after each invocation
which would slow down performance slightly. To be thread safe, we synchronised this block. We could have put
saving the file in the destroy method, but if the server crashed, we would not have the interim values.

package [Link];
import [Link].*;
import [Link].*;
import [Link].*;
public class PersistentCounter extends HttpServlet {
private int calledCount;
private SaveServletStats stats;
private String filename;
public void init(ServletConfig config) throws ServletException {
[Link](config);
calledCount = 0;
filename = [Link](“filename”);
stats = new SaveServletStats();
if (filename != null) {
try { ObjectInputStream in = new ObjectInputStream(
new FileInputStream(filename + “.ser”));
stats = (SaveServletStats) [Link]();
[Link](); }
catch (Exception e) { [Link](); }
}
}
public void doGet(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {
[Link](“TEXT/HTML”);
PrintWriter out = [Link]();
calledCount++;
[Link](“<HTML><TITLE>PersistentCounter</TITLE><BODY>”);

131/ADTU OLE
Advanced Java

[Link](“<H4>This servlet has been called: </H4><BR>”);


[Link](“<B>” + calledCount + “</B> times since the servlet was loaded
THIS servlet life-cycle session<BR>”);
[Link](“<B>” + [Link] + “</B> times since the servlet was
loaded ALL servlet life-cycle sessions<BR>”);
[Link](“</BODY></HTML>”);
[Link]++;
synchronised (this) {
if (filename != null) {
ObjectOutputStream outstats = new ObjectOutputStream(
new FileOutputStream(filename + “.ser”));
[Link](stats);
[Link](“Saving stats file: “ + [Link]);
[Link](); } }
[Link]();
}}

Persistent counter servlet: state tracking in a file

Synchronising access to our instance variables slows down the performance of this servlet, but it guarantees that
only one thread can update the data at a time. This trade-off between servlet performance and data integrity is a
common issue we must deal with when designing servlets. The object that we are saving in serialised format is of
type SaveServletStats.

package [Link];
import [Link].*;
public class SaveServletStats implements Serialisable {
public int calledCount = 0;
}

SaveServletStats: serialised object

The file that stores the serialised object is written to the directory:

d:\IBMVJava\ide\project_resources\IBM WebSphere Test Environment <== VA Java


c:\Winnt\system32 <== WebSphere

We can delete this file to restart the counter at zero.

5.14 User Sessions


We have introduced several approaches to session and state tracking between Web browsers and the Web server. One
limitation with our first two counter servlet examples, SimpleCounter and PersistentCounter, is that they maintain
the counter variable globally, within the servlet session, not by user.

We also showed a couple of session tracking mechanisms at the user level, CookieServlet and URLServlet, where we
maintain the counter variable per user, between multiple requests from the same Web browser to the Web server. In
these methods, the developer is responsible for manually managing all of the session information within the code.

132/ADTU OLE
Httpsession
Luckily, the Java Servlet API has a class, HttpSession, which supports built-in session tracking between the client and
the server, by user. HTTP is, by design, a stateless protocol. The HttpSession interface allows a server to use several
approaches to track a user’s session, or state, and makes it easy for the developer to use. The session information
is managed at the user level.

The Java Servlet API supports two ways to associate multiple requests with a session: URL rewriting and cookies.
In either case, the implementation details in the servlet are the same. A unique session ID is used to track multiple
requests from the same client to the server, and this is what is passed as the URL or cookie parameter. The actual
session object that we are tracking is maintained on the server.

Cookies
Session tracking through HTTP cookies is the most commonly used session tracking mechanism. In this way, the
servlet container sends a cookie to the client, and the client will return the cookie on each subsequent request. The
name of the session tracking cookie is JSESSIONID. Although it is sent as a cookie, we as the developer do not
need to manipulate it as such; the HttpSession class does all that for us.

Using HttpSession
Using HttpSession makes it easy for the developer to maintain and access session information within a servlet. It
associates an HTTP client with an HTTP session, and it persists over multiple connections by the same user.

5.15 User Session Counter Servlet


The UserSessionCounter servlet demonstrates how to keep a session counter by user, using the HttpSession tracking
technique. The flow of this servlet can be described in the following steps:
• We get a handle to a session object using the getSession method of the request. This method returns the current
valid session associated with this request and user. This method takes a boolean argument, true means a new
session should be created if none exists, false only returns an existing session, or null.
• If it is a new session, or if the session does not contain our object, we must add an object into the session of the
type that we want to keep around, using the putValue method of HttpSession. In this case, the SaveServletStats
object contains the counter variable.
• We now have to create a reference to the SaveServletStats object in the servlet. We use the getValue method
of HttpServlet to retrieve this object. Once we have a reference to our object through getValue, we can just
manipulate the object as needed; updates to the object are automatically stored as part of the session object.

package [Link];
import [Link].*;
import [Link].*;
import [Link].*;
import [Link].*;
import [Link].*;
public class UserSessionCounter extends HttpServlet {
private int calledCount;
public void init(ServletConfig config) throws ServletException {
[Link](config);
calledCount = 0;
}
public void doGet(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {
[Link](“TEXT/HTML”);
PrintWriter out = [Link]();
HttpSession session = [Link](true);

133/ADTU OLE
Advanced Java

if ([Link]() || [Link](“usersession”)==null) {
[Link](“usersession”, new SaveServletStats());
}
SaveServletStats ustats =
(SaveServletStats)[Link](“usersession”);
calledCount++;
[Link]++;
[Link](“<HTML><TITLE>SessionCounter</TITLE><BODY>”);
[Link](“<H4>This servlet has been called: </H4><BR>”);
[Link](“<B>” + calledCount + “</B> times since the servlet was loaded
THIS servlet life-cycle session<BR>”);
[Link](“<B>” + [Link] + “</B> times since the servlet was
loaded by this user<BR>”);
[Link](“</BODY></HTML>”);
[Link]();
}
}

User session servlet: state tracking by user

Session Object Types


As we have seen, we can store different object types in a session, distinguished by name. We used the SaveServletStats
class as a session object.

5.16 JDBC Servlet


In JDBCInitServlet we extend the SimpleInitServlet example actually make a connection to a DB2 database from
the variables we initialise from the servlet configuration file. This example demonstrates how to make a connection
to an external resource, and print the results back in the response.

package [Link];
import [Link].*;
import [Link].*;
import [Link].*;
import [Link].*;
public class JDBCInitServlet extends SimpleInitServlet {
protected Connection conn = null;
public void init(ServletConfig config) throws ServletException {
[Link](config);
try {
// load JDBC driver
[Link](mydriver).newInstance();
conn = [Link](myurl, myuserID, mypassword);
[Link](“Connection successful..”);
}
catch (SQLException se) { [Link](se); }
catch (Exception e) { [Link](); }
}
public void doGet(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {
[Link](“TEXT/HTML”);
PrintWriter out = [Link]();

134/ADTU OLE
[Link](“<HTML>”);
[Link](“<TITLE>JDBC Init Connection</TITLE>”);
[Link](“<BODY>”);
try { executeSQL(out); }
catch (SQLException se) { [Link](); }
[Link](“</BODY></HTML>”);
[Link]();
}

JDBC servlet: part 1 (connecting to a JDBC database)

public void executeSQL(PrintWriter out) throws SQLException{


Statement stmt = [Link]();
String sql = “SELECT * FROM DEPARTMENT”;
[Link](sql);
ResultSet rs = [Link]();
int count = 1;
while ([Link]()) {
[Link](“<B>”+[Link](“DEPTNAME”)+”</B><BR><BLOCKQUOTE>”);
String sql2 = “SELECT * FROM EMPLOYEE WHERE WORKDEPT = ‘” +
[Link](“DEPTNO”) + “’”;
Statement stmt2 = [Link]();
[Link](sql2);
ResultSet rs2 = [Link]();
while([Link]()) {
[Link]([Link](“FIRSTNME”) + “ “ +
[Link](“LASTNAME”) + “<br>”);
}
[Link](“</BLOCKQUOTE>”);
}
}}

JDBC servlet: part 2(SQL access)

The JDBCInitServlet extends the SimpleInitServlet. This demonstrates that we can consider designing base servlet
classes at an application level and then extend them for a specific function. This servlet was built primarily to
demonstrate functionality; exception handling has been left out in order to keep the code concise. We choose to
extend the SimpleInitServlet, and override the doGet method to make our processing specific to this example. The
executeSQL method performs the actual SQL database calls.

This servlet connects to the SAMPLE database that is installed with DB2. It must first load up the database driver
and make the connection. In this case, we choose to make the connection object (Connection conn) a shared instance
variable, which we reuse from servlet request to servlet request, but initialise only once. The connection information
(user ID, password, URL, and driver) is specified in the [Link] file, which must be copied to the
appropriate directory.

135/ADTU OLE
Advanced Java

5.17 Servlet Tag with SHTML


With the SHTMLServlet, we demonstrate how to make the Web application server dynamically generate part of its
HTML file. Using the servlet tag technique, the server converts a section of an HTML file into a dynamic portion
each time the document is sent to the client. This dynamic portion invokes an appropriate servlet, and inserts the
response of that server in the HTML page that is sent to the Web client. Initialisation and other servlet parameters
can be passed through the tag syntax, similar to the way an applet’s parameters are set in the HTML. Here, the Web
browser is calling the servlet indirectly, through the SHTML page. The Web server is responsible for including the
output of the specified servlet in the HTML response.

The HTML syntax is as follows:

<servlet> name=”myServlet” code=”[Link]” </servlet>

Following code shows the HTML that we used to call our servlet, and SHTML servlet: included servlet shows the
servlet whose response is dynamically included between the tags. Notice that this servlet only generates a part of
the total response back to the Web client.

<HTML><BODY>
<H2>Start of SHTML Servlet Example, the following lines are from the servlet:
</H2> <HR>
<SERVLET name=”SHTMLServlet”
CODE=”[Link]”> </SERVLET>
<HR> <H2>ENd of servlet include</H2>
</HTML></BODY>

SHTML file: servlet include ([Link])

The <SERVLET> tag has been replaced with <jsp:include> in JSP 1.0. Invoking a servlet from a JSP is a more
modern technique to accomplish the same purpose. To get this example working in WebSphere and VisualAge for
Java, we must associate the .shtml extension with the JSP 0.91 compiler (it does not work with JSP 1.0). Because
this technique is not commonly used, we do not elaborate further on this technique, but rather focus on JavaServer
Pages (JSPs) and other server-side techniques in the chapters that follow.

package [Link];
import [Link].*;
import [Link].*;
import [Link].*;
public class SHTMLServlet extends HttpServlet {
public void service(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {
PrintWriter out = [Link]();
[Link](“<HR><H4>Servlet API Example - SHTMLServlet</H4>”);
[Link](“<H4>Basic included servlet...</H4><HR>”);
}
}

SHTML servlet: included servlet

136/ADTU OLE
5.18 Servlet Interaction Techniques
In our examples so far, we have demonstrated various servlet concepts and techniques. In most cases, these examples
consisted of stand-alone servlet programs that handled a request and returned a response. In the real world, servlets
would not be stand-alone programs, but rather, they would be grouped together as part of an application; and the
application components could consist of servlets, shared objects, and other resource files, such as HTML and JSPs.
We call this our Web application in the WebSphere Application Server Environment.

It would be expected that the servlets of an application would need some way to communicate and interact, either
with each other or with the resources of the application. The ServletContext object provides a way for us to define
this Web application level, and the resources that it can access and interact with. Various techniques for servlet
interaction and communication are given below. The following types are included in it:
• Servlet collaboration: Two techniques for servlet collaboration are servlet filtering and chaining. Here multiple
servlets collaborate on producing a single response for a client. The servlets themselves are not really interacting
directly with each other, rather, the Web application server is responsible for tying the servlets together.
• Calling servlets from servlets: Since servlets are Java programs, they can do anything a standard Java program
can do, such as make a network connection. In this way, we have implicit servlet interaction. Additionally,
because a servlet is just a Java class, we can instantiate and call a servlet’s public methods.
• Response redirection: We can redirect the servlet response to another application resource, such as another
servlet or an error page (HTML or JSP). We discuss JSPs, and their interactions with servlets.
• Request dispatching: Through the RequestDispatcher object, we can forward a request to another servlet, which
can handle the request and return the response. Additionally, we can include directly another servlet’s response
within the context of a calling servlet. We can use request dispatching to dispatch the handling to another active
application resource.
• Resource usage: We can interact with an application’s resources through the servlet context. The ServletContext
object allows us access to these resources through the getResource method.
• Sharing of objects in scope: There are three levels of object scope for a servlet. Application scope is between
all servlets in the same application, and is accessed through the ServletContext object. User session objects are
accessed through the HttpSession object, and request level objects through the servlet request.

137/ADTU OLE
Advanced Java

Summary
• Servlets are protocol and platform independent server-side software components, written in Java.
• Servlets are loaded and executed within the Java Virtual Machine (JVM) of the Web server or application server,
in much the same way that applets are loaded and executed within the JVM of the Web client.
• Servlets implement a common request/response paradigm for the handling of the messaging between the client
and the server.
• Servlets are powerful tools for implementing complex business application logic written in Java.
• The Java Servlet API is a set of Java classes which define a standard interface between a Web client and a Web
servlet.
• Each client request to the servlet is handled via a new thread against the original instance object.
• The simplest way to invoke the servlet would be by specifying a URL in the Web browser.
• The init method only prints a message to standard output and calls the super-class constructor.
• We can pull environment properties and other information about the client from the HttpServletRequest object
and echo them to the response.
• Servlet simply extracts the parameter information from the configuration file, and stores those values in instance
variables.
• A cookie is a piece of data passed between a Web server and a Web browser.
• Java Servlet API has a class, HttpSession, which supports built-in session tracking between the client and the
server, by user. HTTP is, by design, a stateless protocol.
• Session tracking through HTTP cookies is the most commonly used session tracking mechanism.
• The UserSessionCounter servlet demonstrates how to keep a session counter by user, using the HttpSession
tracking technique.
• In the real world, servlets would not be stand-alone programs, but rather, they would be grouped together as part
of an application; and the application components could consist of servlets, shared objects, and other resource
files, such as HTML and JSPs.

References
• Perry, W. B., 2004. Java servlet and JSP cookbook, O’Reilly Media, Inc Publication.
• Crawford, W. & Hunter, J., 2001. Java servlet programming, 2nd ed. O’Reilly Media, Inc. Publication.
• Wahli, U., Fielding, M., Mackown G., Shaddon D. & Hekkenberg, G., Servlet and JSP Programming, [Online]
Available at: <[Link] [Accessed 11 April 2012].
• , Chapter 4 Continued: Servlets, [Online] Available at: <[Link]
Programming/JDCBook/[Link]> [Accessed 11 April 2012].
• 2010. Java Servlets, [Video Online] Available at: <[Link] [Accessed
12 April 2012].
• 2009. Java Servlet Definition, [Video Online] Available at: <[Link]
[Accessed 12April 2012].

Recommended Reading
• Callaway, Inside Servlets, Pearson Education India Publication.
• Farley, J., Crawford, W., Malani, P., Norman, J. & Gehtland, J., 2005. Java Enterprise in a Nutshell, 3rd ed.
O’Reilly Media, Inc. Publication.
• Hall, 2008. Core Servlets And Javaserver Pages,Vol 2: Advanced Technologies, 2/E, Pearson Education India
Publication.

138/ADTU OLE
Self Assessment
1. Servlets are loaded and executed within the _____________of the Web server or application server.
a. Java Virtual Machine
b. Hipertext Markup Language
c. Graphical User Interface
d. Common Gateway Interface

2. Which of the following is composed [Link] and [Link] packages?.


a. API
b. Servlet
c. JSDK
d. HTTP

3. The ________method is called when the Web server unloads the servlet.
a. doPost
b. getServletConfig
c. doGet
d. destroy

4. The _________method is a method that can provide information about the servlet.
a. getServletConfig
b. getServletInfo
c. doGet
d. destroy

5. The ______method only prints a message to standard output and calls the super-class constructor.
a. do
b. get
c. init
d. post

6. A _______is a piece of data passed between a Web server and a Web browser.
a. packet
b. cookie
c. servlet
d. database

7. ______rewriting is another way to support state tracking.


a. UI
b. Cookie
c. Servlet
d. URL

139/ADTU OLE
Advanced Java

8. We get a handle to a session object using the ________method of the request.


a. getSession
b. getServletInfo
c. doGet
d. destroy

9. The __________invoked whenever an HTTP POST request is issued through an HTML form.
a. doGet
b. doPost
c. destroy
d. init

10. Filtering and chaining are servlet ___________ techniques.


a. calling
b. collaboration
c. redirection
d. dispatching

140/ADTU OLE
Chapter VI
JSP

Aim
The aim of this chapter is to:

• explain Java server pages

• introduce various jsp bean attributes

• elucidate extensions to JSP language

Objectives
The objectives of this chapter are to:

• explain the jsp directives

• explicate how Java server pages work

• explicit attributes of page directives

Learning outcome
At the end of this chapter, you will be able to:

• understand Java Server Page specification .91 and 1.0

• identify and create dynamic content in JSPs

• describe attributes of page directives

141/ADTU OLE
Advanced Java

6.1 Introduction
Java Server Pages (JSPs) are similar to HTML files, but provide the ability to display dynamic content within Web
pages. JSP technology was developed by Sun Microsystems to separate the development of dynamic Web page
content from static HTML page design. The result of this separation means that the page design can change without
the need to alter the underlying dynamic content of the page. This is useful in the development life-cycle because
the Web page designers do not have to know how to create the dynamic content, but simply have to know where to
place the dynamic content within the page.

To facilitate embedding of dynamic content, JSPs use a number of tags that enable the page designer to insert the
properties of a JavaBean object and script elements into a JSP file. A number of development tools, such as the
WebSphere Studio Page Designer, can be used to visually create a page containing dynamic contents based on the
properties of Java beans.

Here, are some of the advantages of using JSP technology over other methods of dynamic content creation:
Separation of dynamic and static content: This allows for the separation of application logic and Web page design,
reducing the complexity of Web site development and making the site easier to maintain.

Platform independence: Because JSP technology is Java-based, it is platform independent. JSPs can run on any
nearly any Web application server. JSPs can be developed on any platform and viewed by any browser because the
output of a compiled JSP page is HTML.

Component reuse: Using JavaBeans and Enterprise JavaBeans, JSPs leverage the inherent reusability offered by
these technologies. This enables developers to share components with other developers or their client community,
which can speed up Web site development.

Scripting and tags: JSPs support both embedded JavaScript and tags. JavaScript is typically used to add page-level
functionality to the JSP. Tags provide an easy way to embed and modify JavaBean properties and to specify other
directives and actions.

6.2 How Java Server Pages Work?


Java Server Pages are made operable by having their contents (HTML tags, JSP tags and scripts) translated into a
servlet by the application server. This process is responsible for translating both the dynamic and static elements
declared within the JSP file into Java servlet code that delivers the translated contents through the Web server output
stream to the browser.

Because JSPs are server-side technology, the processing of both the static and dynamic elements of the page occurs
in the server. The architecture of a JSP/servlet-enabled Web site is often referred to as thin-client because most of
the business logic is executed on the server. The following process outlines the tasks performed on a JSP file on the
first invocation of the file or when the underlying JSP file is changed by the developer:
• The Web browser makes a request to the JSP page.
• The JSP engine parses the contents of the JSP file.
• The JSP engine creates temporary servlet source code based on the contents of the JSP. The generated servlet
is responsible for rendering the static elements of the JSP specified at design time in addition to creating the
dynamic elements of the page.
• The servlet source code is compiled by the Java compiler into a servlet class file.
• The servlet is instantiated. The init and service methods of the servlet are called, and the servlet logic is
executed.
• The combination of static HTML and graphics combined with the dynamic elements specified in the original
JSP page definition are sent to the Web browser through the output stream of the servlet’s response object.

142/ADTU OLE
Web Web Server
Browser
JSP JSP Java

Request Source Parser Source

Web JSP Java


Page
Servlet Compiler
Result (HTML)

Fig. 6.1 The JSP processing life-cycle on first-time invocation


(Source: [Link]

Subsequent invocations of the JSP file will simply invoke the service method of the servlet created by the above
process to serve the content to the Web browser. The servlet produced as a result of the above process remains in
service until the application server is stopped, the servlet is manually unloaded, or a change is made to the underlying
file, causing recompilation.

6.3 Components of Java Server Pages


Java Server Pages are composed of standard HTML tags and JSP tags. The available JSP tags defined in the JSP 1.0
specification are categorised as follows:
• Directives
• Declarations
• Scriptlets
• Comments
• Expressions

HTML tags: JavaServer Pages support all HTML tags. We will see the detailed description of these.

6.3.1 JSP Directives


A JSP directive is a global definition sent to the JSP engine that remains valid regardless of any specific requests
made to the JSP page. A directive always appears at the top of the JSP file, before any other JSP tags. This is due to
the way the JSP parsing engine produces servlet code from the JSP file.

The syntax of a directive is:

<%@ directive directive_attr_name = value %>

Directives are grouped as follows:


page
The page directive defines page dependent attributes to the JSP engine.

<%@ page language=”java” buffer=”none” isThreadSafe=”yes”


errorPage=”/[Link]” %>

143/ADTU OLE
Advanced Java

The attributes of the page directive are listed in table below.

Attribute Name Description


Identifies the scripting language used in scriptlets in the JSP
file or any of its included files. JSP supports only the value of
language “java”. WebSphere extensions provide support for other
scripting languages.
<%@ page language = “java” %>
The fully-qualified name of the superclass for which this JSP
page will be derived. Using this attribute can effect the JSP
extends
engine’s ability to select specialised superclasses based on the
JSP file content, and should be used with care.
When the language attribute of “java” is defined, the import
attribute specifies the additional files containing the types used
import
within the scripting environment.
<%@ page import = “[Link].*” %>
If true, specifies that the page will participate in an HTTP
session
session and enables the JSP file access to the implicit session
“true” | “false”
object. The default value is true.
Indicates the buffer size for the JspWriter. If none, the output
from the JSP is written directly to the ServletResponse
buffer
PrintWriter object. Any other value results in the JspWriter
“none” |
buffering the output up to the specified size. The buffer is
“sizekb”
flushed in accordance with the value of the autoFlush attribute.
The default buffer size is no less than 8kb.
If true, the buffer will be flushed automatically. If false, an
autoFlush
exception is raised when the buffer becomes full.
“true” | “false”
The default value is true.
If true, the JSP processor may send multiple outstanding client
requests to the page concurrently. If false, the JSP processor
isThreadSafe
sends outstanding client requests to the page consecutively, in
“true” | “false”
the same order in which they were received.
The default is true.
Allows the definition of a string value that can be retrieved
info
using [Link]().
Specifies the URL to be directed to for error handling if an
exception is thrown and not caught within the page
errorPage
implementation. In the JSP 1.0 specification, this URL must
point to a JSP page.
Identifies that the JSP page refers to a URL identified in
another JSP’s errorPage attribute. When this value is true, the
isErrorPage
implicit variable exception is defined, and its value set to
“true” | “false”
reference the Throwable object of the JSP source file which
causes the error.
Specifies the character encoding and MIME type of the JSP
response. Default value for contentType is text/html. Default
contentType
value for charSet is ISO-8859-1. The syntax format is:
contentType=”text/html; charSet=ISO-8859-1”

Table 6.1 Attributes of the page directive

144/ADTU OLE
include
The include directive allows substitution of text or code to occur at translation time. We can use the include directive
to provide a standard header on each JSP page, for example:

<%@ include file=”[Link]” %>

The include directive has the attributes shown in Table 2.

Attribute Name Description


Directs the JSP engine to substitute the text or code specified by
file file or URL reference. The URL reference can be another JSP
file.

Table 6.2 Attributes for the include directive

taglib
The taglib directive allows custom extensions to be made to the tags known to the JSP engine. This tag is an advanced
feature.

6.3.2 Declarations
A declaration block contains Java variables and methods that are called from an expression block within the JSP
file. Code within a declaration block is usually written in Java; however, the WebSphere application server supports
declaration blocks containing other script syntax. Code within a declaration block is often used to perform additional
processing on the dynamic data generated by a JavaBean property. The syntax of a declaration is:

<%! declaration(s) %>

For example:

<%!
private int getDateCount = 0;
private String getDate(GregorianCalendar gc1)
{ ...method body here...}
%>

6.3.3 Scriptlets
JSP supports embedding of Java code fragments within a JSP by using a scriptlet block. Scriptlets are used to embed
small code blocks within the JSP page, rather than to declare entire methods as performed in a declarations block.
The syntax for a scriptlet is:

<% scriptlet %>

The following example uses a scriptlet to output an HTML message based on the time of day. We can see that the
HTML elements appear outside the script declarations.

145/ADTU OLE
Advanced Java

<% if ([Link]().get(Calendar.AM_PM) == [Link])


{%>
How are you this morning ?
<% } else
{ %>
How are you this afternoon ?
<% } %>

6.3.4 Comments
You can use two types of comments within a JSP. The first comment style, known as an output comment, enables
the comment to appear in the output stream on the browser. This comment is an HTML formatted comment whose
syntax is:

<!-- comments ... -->

The second comment style is used to fully exclude the commented block from the output and is commonly used when
uncommenting a block of code that so that the commented block is never delivered to the browser. The syntax is:

<%-- comment text --%>

We can also create comments containing dynamic content by embedding a scriptlet tag inside a comment tag. For
example:

<!-- comment text <%= expression %> more comment text ->

6.3.5 Expressions
Expressions are scriptlet fragments whose results can be converted to String objects and subsequently fed to the
output stream for display in a browser. The syntax for an expression is:

<%= expression %>

Typically, expressions are used to execute and display the String representation of variables and methods declared
within the declarations section of the JSP, or from JavaBeans that are accessed by the JSP. If the conversion of the
expression result is unsuccessful, a ClassCastException is thrown at the time of the request. The following example
calls the incrementCounter method declared in the declarations block and prints the result.

<%= incrementCounter() %>

All primitive types such as short, int, and long can be automatically converted to Strings. Your own classes must
provide a toString method for String conversion.

146/ADTU OLE
6.4 WebSphere Extensions to JSP Scripting
WebSphere Application Server Version 3 offers a number of enhancements over the JSP 1.0 specification and
includes the ability to:
• Use non-Java scripting languages within JSP pages.
• Use multiple scripting languages within the same JSP file.

We can use any of the Bean Scripting Framework (BSF) 1.0 compliant languages in our JSP by specifying it within
the language_name attribute of the page directive. The table below gives semantics of using multiple scripting
languages within a JSP.

SpecifySyntax
<jsp:scriptlet language=”language_name”>
<jsp:expr language=”language_name”>
<jsp:declaration language=”language_name”>

Table 6.3 WebSphere scripting language extensions

6.5 Accessing Implicit Objects


When we write scriptlets or expressions, there are a number of objects that we have automatic access to as part of
the JSP standard without having to fully declare them or import them. Table 4 summarises these implicit objects
available in JSP 1.0. We can use these implicit objects directly in our code. The following code snippet is an example
of accessing the out implicit object to display a line of text in the browser:

[Link](“Here is the <b>Date Display JSP</b>”);

Object name Type Description

request [Link] The request triggering the service invocation

response [Link] The response to the request

Page context of this JSP. By accessing this object,


you have access to a number of convenience objects
pageContext [Link] and methods such as getException, getPage, and
getSession providing an explicit method of accessing
JSP implementation-specific objects.

session [Link] Session object created for the requesting client


[Link] The servlet context as
application [Link]
obtained from the servlet configuration object
out [Link] Output stream writer

config [Link] ServletConfig for this JSP

Instance of this page’s implementation class


page [Link]
processing the current request

Table 6.4 Summary of implicitly declared objects

147/ADTU OLE
Advanced Java

6.6 JSP Interactions


There are a number of methods that a JSP can use to interact with the Web environment. Primarily, a JSP will
use a JavaBean object to present dynamic content. However, a JSP can also invoke another JSP page by URL, by
including another JSP or HTML page in the include directive, or by calling a servlet. This section describes these
interactions.

6.7 Invoking a JSP by URL


A JSP can be invoked by URL, from within the <FORM> tag of a JSP or HTML page, or from another JSP. To
invoke a JSP by URL, use the syntax:

[Link]

For example, to invoke the [Link], use this URL:

[Link] <== WebSphere


[Link] <== VA Java

6.8 Calling a servlet from a JSP


We can invoke a servlet from a JSP either as an action on a form, or directly through the jsp:include or jsp:forward
tags.

Form action
Typically, we want to call a servlet as a result of an action performed on a JavaServer Page. For example, we may
want to process some data entered by the user in an HTML form when they click on the Submit button. To invoke
a servlet within the HTML <FORM> tag, the syntax is:

<FORM METHOD=”POST|GET” ACTION=”application_URI/JSP_URL”>


<!-- Other tags such as text boxes and buttons go here -->
</FORM>

For example:

<form method=”POST”
action=”/itsoservjsp/servlet/[Link]”>

The code snippet above shows the code to call the DateDisplayServlet from within a JSP.

148/ADTU OLE
<HTML>
<HEAD> <TITLE> Call Servlet from JSP </TITLE> </HEAD>
<CENTER>
<H1> Call Servlet from JSP </H1>
<FORM method=”POST”
action=”/itsoservjsp/servlet/[Link]”>
<H2> DateDisplay Servlet Launcher </H2>
Click the button below to display the current date
<P> <INPUT type=”submit” name=”CALL_SERVLET” value=”Call the Servlet”>
</FORM>
</CENTER>
</BODY></HTML>

Sample JSP invoking a servlet from a form ([Link])

JSP Include Tag


You can include the output of a servlet in a JSP using the [Link] tag:

<jsp:include page=”/servlet/[Link]” />

The example below shows a JSP that includes the servlet.

<HTML><BODY>
<H2> JSP to Servlet </H2>
<HR>
<jsp:include page=”/servlet/[Link]” />
<HR>
<H2>End of servlet include</H2>
</HTML></BODY>

Sample JSP including a servlet ([Link])

When we run this JSP the output of the servlet is imbedded in the JSP output. JSP forward tag we can forward
processing from a JSP to a servlet using the [Link] tag:

<jsp:forward page=”/servlet/[Link]” />

Following code shows a JSP that forwards processing to the servlet.

<HTML><BODY>
<H2> JSP to Servlet </H2>
<HR>
<jsp:forward page=”/servlet/[Link]” />
<HR>
<H2>End of servlet include</H2>
</HTML></BODY>

Sample JSP forwarding processing to a servlet ([Link])

149/ADTU OLE
Advanced Java

When we run this JSP, the output of the processing servlet replaces the output of the JSP. All output of the JSP is
lost.

6.9 Calling a JSP from a Servlet


The code snippet below shows the DateDisplayServlet’s doPost method, which is called when the Submit button is
clicked. The servlet simply calls the sendRedirect method of the HttpServletResponse object, directing the response
to the [Link]. This example simply demonstrates the redirection capability of the response object. In reality,
the doPost method could invoke other methods which process the form data, instantiate other beans that perform
the business logic, and finally redirect the user to the JSP.

import [Link].*;
public class DateDisplayServlet extends HttpServlet {
public void doPost(HttpServletRequest req, HttpServletResponse resp)
throws [Link], [Link] {
// Redirect to the DateDisplay JSP page
[Link](“/[Link]”);
// alternate call to JSP
// getServletContext().getRequestDispatcher(“/[Link]”).forward(req,resp);
}

DateDisplayServlet demonstrating simple redirection

We can also use the RequestDispatcher object to invoke a JSP:

getServletContext().getRequestDispatcher(“/[Link]”).forward(req,resp);

PageListServlet Class
IBM provides the PageListServlet class in the [Link] package. This is a subclass of HttpServlet that
provides a callPage method to invoke JSPs. Servlets generated by the WebSphere Studio wizards are subclasses of
the PageListServlet class. Such a servlet must have an associated servlet configuration file (.servlet) that specifies
all the possible JSPs that the servlet may invoke. A typical call to invoke a JSP from a PageListServlet is:

callPage(“myJSP”, request, response);

The name of the JSP can be a short name (alias) that is assigned to the real file name of the JSP in the servlet
configuration file.

150/ADTU OLE
<?xml version=”1.0”?>
<!-- This file was generated by IBM WebSphere Studio 3.0.2 -->
<servlet>
<page-list>
<default-page>
<uri>/itsoservjsp/photo/[Link]</uri>
</default-page>
<error-page>
<uri>/itsoservjsp/photo/[Link]</uri>
</error-page>
<page>
<uri>/itsoservjsp/photo/[Link]</uri>
<page-name>[Link]</page-name>
</page>
<page>
<uri>/itsoservjsp/photo/[Link]</uri>
<page-name>myJSP</page-name>
</page>
</page-list>
<code>[Link]</code>
</servlet>

Servlet configuration file with JSP names

Because the JSP names used in the callPage method of the servlet are aliases, a change of directory can be
accomplished by changing the servlet configuration file, without touching the servlet code.

6.10 Invoking a JSP from a JSP


To invoke a JSP file from another JSP file, you can:
• Specify the URL of the second JSP file on the FORM ACTION attribute: <FORM action=”/itsoservjsp/
[Link]”>
• Specify the URL of the second JSP file in an anchor tag HREF attribute: <a href=”JSP_URL”> reference-text
</a>
• Use the [Link] method to invoke the second JSP file (see “Request
dispatching” on page 81). This is the same as using the jsp:forward tag

6.11 Creating Dynamic Content in JSPs


In this we will discuss more commonly used tags available in the JSP 1.0 specification which assists in creating
dynamic content within a JSP. In addition to describing some of the more commonly used JSP tags we also describe
how to use the WebSphere-specific tags that provide support for relational database access. For a complete description
of all tags supported by the JSP 1.0 specification, please refer to the Sun JavaServer Pages Specification Version
1.0 available on the Sun Web site.

6.12 Standard JSP Tags


jsp:useBean: The jsp:useBean tag is used to declare a JavaBean object that we want to use within the JSP. Before we
can use the jsp:getProperty and jsp:setProperty tags, we must have first declared our JavaBean using the jsp:useBean
tag. When the jsp:useBean tag is processed, the application server performs a lookup of the specified given Java
object using the values specified in the id and scope attributes. If the object is not found, it will attempt to create it
using the values specified in the scope and class attributes.

151/ADTU OLE
Advanced Java

The syntax for inserting a JavaBean is:

<jsp:useBean id=”beanInstanceName” scope=”page|request|session|application”


typespec>
optional scriptlets and tags
</jsp:useBean>

Here, typespec can be declared using any of the following variations:

class=”[Link]”
type=”[Link]”
type=”[Link]” beanName=”[Link]”

We can also embed scriptlets and tags such as jsp:getProperty within the jsp:useBean declaration which will be
executed upon creation of the bean. This is often used to modify properties of a bean immediately after it has been
created. An example of a simple form of bean instantiation is:

<jsp:useBean id =”DateDisplayBean”
class=”[Link]”/>

This example tries to locate an instance of the DateDisplayBean class. If no instance exists, a new instance is created.
The instance can then be accessed within the JSP using the specified id of DateDisplayBean.

The table below describes the jsp:useBean attributes.

Parameter Name Description

Identifies the object name within the name space of the specified scope. This name is
id
used to reference the bean throughout the JSP file and is case sensitive.

Valid values are page, request, session, and application. If omitted, the value defaults
to page scope.
page: Objects declared with page scope are only valid until the response is sent back
from the server or until the request is forwarded elsewhere. References to objects in
page scope are only valid within the page where the object is declared. Objects declared
in page scope are stored in the pagecontext object. request: Objects declared within
request scope are valid for the duration of the request and are accessible if the request
scope is forwarded to a resource in the same runtime. Objects referenced in request scope
are stored in the request object.
session: Session-scope objects are available for the duration of the session provided
that the page is made “session aware” using the page directive.
application: Application-scope objects are available from pages that are processing
requests within the same Web application (as defined in the application server setup)
and are valid until the ServletContext object is reclaimed by the application server.
Objects with this scope are stored in the application object.

The name of the object’s implementation class, for example:


[Link]. This value is case
class
sensitive. Specify the class attribute if you want to instantiate the bean
if it does not already exist within the specified scope.

152/ADTU OLE
Specifies the class name or serialised file (.ser) containing the
beanName
bean which is used when first creating the bean.

Identifies the type of the specified object. This allows the


scripting variables type to be declared as the class itself, the
superclass or an interface implemented by the class.
By specifying the type attribute, you can avoid automatic
instantiation of the bean if it does not already exist within the
type
specified scope, effectively reproducing the behavior of the JSP
.91 create=”yes/no” attribute on the <BEAN> tag.
The default value is the value specified in the class attribute.
If the object is not of the specified type, you may receive a
[Link].

Table 6.5 jsp:useBean attributes

If we do not want to automatically instantiate a bean if it does not already exist within the specified scope, use the
type attribute rather than the beanName or class attributes. The following line will result in an InstantiationException
if the object specified by the type attribute does not exist in the session scope, and as a result, the bean will not be
instantiated.

<jsp:useBean id=”DateDisplayBean”
type=”[Link]” scope=”session”/>
jsp:getProperty

Once the bean has been declared with jsp:useBean, we can access its exposed properties through the jsp:getProperty
tag, which inserts the String value of the primitive type or object into the output stream. For primitive types, the
conversion to String is performed automatically. For object types, the toString method of the object is called. The
syntax for the jsp:getProperty tag is:

<jsp:getProperty name=”beanName” property=”propertyName”/>

The jsp:getProperty tag has a number of attributes as defined in table below.

Attribute Name Description

The name (id) of the bean instance specified in the jsp:useBean


name
tag.

property The name of the property to get.

Table 6.6 jsp:getProperty attributes

The code given below shows the source code of a JavaBean called DateDisplayBean that we are referencing in a
JSP.

153/ADTU OLE
Advanced Java

package [Link];
import [Link].*;
public class DateDisplayBean {
private int counter = 0;
private String dateString = null;
public DateDisplayBean() {
super();
dateString = buildDateString(new GregorianCalendar());
counter = 0;
}
public String buildDateString(GregorianCalendar gcalendar) {
StringBuffer dateStr = new StringBuffer();
[Link]([Link]([Link]));
[Link](“/”);
[Link]([Link]([Link]) + 1);
[Link](“/”);
[Link]([Link]([Link]));
return [Link]();
}
public int getCounter() {
return counter;
}
public void setCounter(int newCounter) {
counter = newCounter;
}
public [Link] getDateString() {
counter++;
return dateString;
}
}

JavaBean to be used by a JSP ([Link])

The example JSP file in the code below declares the DateDisplayBean and displays the two properties, dateString
and counter.

<html> <title>Date Display Bean </title> <body>


<H1> Date Display with JSP and JavaBean </H1>
<jsp:useBean id=”DateDisplayBean”
class=”[Link]” scope=”session” />
<H2> Today’s Date is:
<jsp:getProperty name=”DateDisplayBean” property=”dateString”/>
</H2>
<H2> This page has been called:
<jsp:getProperty name=”DateDisplayBean” property=”counter”/>
time(s)
</H2>
</body> </html>

JSP with jsp:useBean and jsp:getProperty ([Link])

154/ADTU OLE
jsp:setProperty
The properties of beans can be set by using the jsp:setProperty tag. The syntax for this tag is:

<jsp:setProperty name=”beanName” prop_expr/>

For example, to initialise the counter variable used in Figure 85, you could use the code:

<jsp:setProperty name=”DateDisplayBean” property=”counter” value=”0”/>

The jsp:setProperty tag has a number of attributes, as defined in table below.

Attribute Name Description

name The name (id) of the bean instance specified in the jsp:useBean tag.

The name of the property to set. By setting this value to “*“, you can automate the
setting of properties, provided that form-element names match the property name. For
example, if a bean has a property called dateString, and the JSP page contains a text
property
box named dateString, then the dateString property of the bean will be looked up and
set automatically. For this feature to work, your beans must conform to the JavaBeans
API specification 1.0.

The request parameter name to give to the Bean property. Request parameters usually
refer to the names of HTML form elements, and are used to implicitly set the value of
param
a particular bean property based on the value of the HTML form element. This attribute
cannot be used with the value attribute.
value The new value for the property.

Table 6.7 jsp:setProperty attibutes

6.13 WebSphere-specific tags


WebSphere provides a number of extensions to the JSP language.

tsx:dbconnect
The tsx:dbconnect tag is required to connect to JDBC or ODBC databases. This tag does not actually make the
connection, but rather sets the connection attributes used by the tsx:dbquery and tsx:dbmodify tags, which are
responsible for making the database connection before interacting with the database.

The syntax of the tsx:dbconnect tag is:

<tsx:dbconnect id=”connection_id”
userid=”db_user” passwd=”db_password”
url=”jdbc:subprotocol:database”
driver=”database_driver_name” >
</tsx:dbconnect>

The tsx:dbconnect tag has the attributes shown in Table 8.

155/ADTU OLE
Advanced Java

Attribute Name Description


The name of the connection. This tag is used by the tsx:dbquery and tsx:dbmodify
id
tags as a reference to the connection.

A valid database user ID. If omitted, the user ID and password should be specified
userid
using the tsx:userid tag

The password for the [Link] omitted, the user ID and password should be
password
specified using the tsx:password tag.
url The JDBC URL of the database, for example: url=”jdbc:db2:sample”
driver The name of the driver used to establish the connection: driver=”[Link].db2.
[Link].DB2Driver”

Table 6.8 tsx:dbconnect attributes

The tsx:dbconnect tag does not support JNDI datasource lookup, as in the example:

url=”jdbc/sample”
tsx:dbquery

The tsx:dbquery tag provides the mechanism to get a result set containing database data. It relies on the connection
attributes specified by the tsx:dbconnect tag, which must be defined before this tag can be [Link] responsibilities
of the tsx:dbquery tag are to:
• Reference the connection object attributes created by tsx:dbconnect.
• Establish the database connection.
• Retrieve and cache the result set data.
• Release the connection resource.

The tsx:dbquery tag has the following syntax:

<tsx:dbquery id=”query_id” connection=”connection_id” limit=”value”>


SELECT statement ....
</tsx:dbquery>

The tsx:dbquery tag has the attributes shown in table below.

Attribute Name Description

id. The name of the query. This becomes the name of the result bean.

The name given to the id attribute specified in the


connection
tsx:dbconnect tag.

limit Specifies the maximum number of rows to return in the result

set This attribute is optional.

Table 6.9 tsx:dbquery attributes

156/ADTU OLE
When a tsx:dbquery tag is compiled by the JSP engine, the name specified in the id parameter is used to create a
JavaBean of that name containing the result set. The bean will also have properties that match the names of the
database columns returned in the result set. If we want to customise the property names within the bean, we can
use a column name alias in the SQL query. The SQL statement below will create a bean with a property of Dept
rather than WORKDEPT:

Select WORKDEPT As Dept from Department

tsx:dbmodify
The tsx:dbmodify tag enables you to perform INSERT and UPDATE SQL commands on a database. Similar to
the tsx:dbquery tag, it relies on the connection attributes specified by the tsx:dbconnect tag, which must be defined
before this tag can be used. The tsx:dbmodify tag has the following syntax:

<tsx:dbmodify connection=”connection_id”>
INSERT/UPDATE/DELETE SQL statement ....
</tsx:dbmodify>

The attributes for the tsx:dbmodify tag are defined in table below.

Attribute Name Description


The name given to the id attribute specified in the
connection
tsx:dbconnect tag.

Table 6.10 tsx:dbmodify attributes

The example in Figure 86 demonstrates how to insert a row into the EMPLOYEE table.

<tsx:dbmodify connection=”conn” >


insert into EMPLOYEE
(EMPNO, FIRSTNME, MIDINIT, LASTNAME, WORKDEPT, EDLEVEL)
values (
‘<%= [Link](“EMPNO”) %>’,
‘<%= [Link](“FIRSTNME”) %>’,
‘<%= [Link](“MIDINIT”) %>’,
‘<%= [Link](“LASTNAME”) %>’,
‘<%= [Link](“WORKDEPT”) %>’,
‘<%= [Link](“EDLEVEL”) %>’)
</tsx:dbmodify>

Using the tsx:dbmodify tag to insert a row in the sample database

tsx:getProperty
The tsx:getProperty tag is a WebSphere extension to the jsp:getProperty tag. This implementation includes all the
functionality of jsp:getProperty and adds the ability to introspect a database bean created by the tsx:dbquery or
tsx:dbmodify tags. We can use this tag to get properties from our own JavaBeans, or to get properties from the
JavaBeans created by a call to tsx:dbquery where the beans properties refer to database columns, as in the following
example:

157/ADTU OLE
Advanced Java

<tsx:getProperty name=”queryid” property=”DEPTNAME”/>


tsx:repeat

The tsx:repeat tag is used to iterate over a database query result set using the optional start and end values as the
bounding indexes for the iteration. The syntax is:

<tsx:repeat index=name start=start_index end=end_index>


</tsx:repeat>

The start and end attributes are optional attributes that can be implicitly or explicitly set. By default, these values
are 0 and the upper bound of the result set respectively. We can use either attribute on its own or as a pair. The
iteration is complete when either the end value has been reached or an ArrayIndexOutOfBounds exception is thrown.
No output is written until a complete iteration of the [Link] block is complete. If an ArrayIndexOutOfBounds
exception is thrown during iteration no output is written, and the repeat block is terminated. The attributes for the
tsx:repeat tag are listed in given table.

Attribute Name Description

index The name of the index. This name has JSP file scope and is case sensitive.

start The optional start index for the iteration, with a default of 0.
The optional end index for the interaction. The maximum value for this attribute
end is 2,147,483,647. If the end attribute is less than the start attribute, it is ignored.
The default is the number of available values in the bean.

Table 6.11 tsx:repeat attributes

Nesting of tsx:repeat tags is permissible and can be used to provide sub-category information during a query. For
example, for each department in the department table, we might wish to list each employee associated with the
department. We would do this by nesting tsx:repeat tags as coded below.

158/ADTU OLE
<HTML>
<HEAD> <TITLE>Call Servlet</TITLE> </HEAD>
<H1> Department Listing with a JSP and TSX tags </H1>
<tsx:dbconnect id=”conn”
userid=”itso” passwd=”itso”
url=”jdbc:db2:sample”
driver=”[Link].DB2Driver”>
</tsx:dbconnect>
<tsx:dbquery id=”dept” connection=”conn” >
SELECT * FROM DEPARTMENT ;
</tsx:dbquery>
<tsx:repeat index=”deptidx”>
<H2> <tsx:getProperty name=”dept” property=”DEPTNAME” /> </H2>
<tsx:dbquery id=”emp” connection=”conn” >
SELECT FIRSTNME, LASTNAME FROM EMPLOYEE
WHERE WORKDEPT = ‘<tsx:getProperty name=”dept” property=”DEPTNO”/>’;
</tsx:dbquery>
<tsx:repeat index=”empidx”>
<LI> <tsx:getProperty name=”emp” property=”FIRSTNME” />
<tsx:getProperty name=”emp” property=”LASTNAME” />
</tsx:repeat>
</tsx:repeat>
</BODY>
</HTML>

Database access JSP demonstrating WebSphere tsx tags

In this example we use the tsx:dbquery tag to select all the departments and then all the employees within one
department. For the second query we use the deptno property of a department in the WHERE clause. In the inner
repeat loop we list the first name and last name of each employee.

Repeating Over Nondatabase Properties


The tsx:repeat tag is not limited to iterating over the properties provided by the tsx:dbquery tag. We can also use this
tag to iterate over any indexed property within a JavaBean class or repeatedly call any method in a JavaBean until
an ArrayIndexOutOfBounds exception is thrown. Program below shows a JSP that iterates over a JavaBean using a
tsx:repeat tag. The code below shows the source code of the JavaBean with a vector where each element is an array
of two values. The bean provides two get methods to return the values from the array of a vector element.

<HTML>
<HEAD> <TITLE> JSP with Repeating Bean </TITLE> </HEAD>
<H1> CD Listing </H1>
<jsp:useBean id=”vectorBean”
class=”[Link]” scope=”session” />
<tsx:repeat index=”i”>
<LI> <%= [Link](i) %> by
<B> <%= [Link](i) %> </B>
</tsx:repeat>
</BODY></HTML>

JSP using a bean with repeating attributes

159/ADTU OLE
Advanced Java

package [Link];
public class VectorBean {
[Link] cdList = new [Link]();
public VectorBean() {
[Link]( new String[] {“Woman In Me”,”Shania Twain”} );
[Link]( new String[] {“Come On Over”,”Shania Twain”} );
[Link]( new String[] {“When I Call Your Name”,”Vince Gill”} );
}
public String getArtist(int ix) {
try { return ( (String[])[Link](ix) )[1]; }
catch (Exception e) { throw new ArrayIndexOutOfBoundsException(); }
}
public String getTitle(int ix) {
try { return ( (String[])[Link](ix) )[0]; }
catch (Exception e) { throw new ArrayIndexOutOfBoundsException(); }
}}

JavaBean withsting attributes

6.14 Differences Between Java Server Page specification .91 and 1.0
The JSP 1.0 specification contains the following changes and additions over the JSP .91 specification:
• Tags use XML formatting. For example, the JSP bean declaration tag <BEAN> is now declared using the syntax
<jsp:useBean ...>. Similarly, WebSphere specific tags such as <REPEAT> are now declared using the syntax
<tsx:repeat>.
• Tags are case sensitive.
• Standard tags use the mixed-case convention of Java code, for example, jsp:useBean.
• Server-side includes (SSI) have been replaced with the <%@ include %> directive.
• jsp:getProperty and jsp:setProperty tags have been defined.
• jsp:request has been added, providing runtime forward and include functionality.
• jsp:include has been added to include resources from other files.
• jsp:plugin has been added.
• Implementation of LOOP, ITERATE, INCLUDEIF and EXCLUDEIF tags have been postponed pending
enhancements to the tag extension mechanism.
• <SCRIPT> </SCRIPT> tags have been superseded with <%! ... %>

There have been other releases of the JSP specification such as .92 and .93.

160/ADTU OLE
Summary
• JSP technology was developed by Sun Microsystems to separate the development of dynamic Web page content
from static HTML page design.
• Web page designers do not have to know how to create the dynamic content, but simply have to know where
to place the dynamic content within the page.
• To facilitate embedding of dynamic content, JSPs use a number of tags that enable the page designer to insert
the properties of a JavaBean object and script elements into a JSP file.
• A number of development tools, such as the WebSphere Studio Page Designer, can be used to visually create a
page containing dynamic contents based on the properties of Java beans.
• JSPs are server-side technology, the processing of both the static and dynamic elements of the page occur in
the server.
• JavaServer Pages are composed of standard HTML tags and JSP tags.
• A JSP directive is a global definition sent to the JSP engine that remains valid regardless of any specific requests
made to the JSP page.
• A declaration block contains Java variables and methods that are called from an expression block within the
JSP file.
• Scriptlets are used to embed small code blocks within the JSP page, rather than to declare entire methods as
performed in a declarations block.
• Expressions are scriptlet fragments whose results can be converted to String objects and subsequently fed to
the output stream for display in a browser.
• We can use any of the Bean Scripting Framework (BSF) 1.0 compliant languages in our JSP by specifying it
within the language_name attribute of the page directive.
• When we write scriptlets or expressions, there are a number of objects that we have automatic access to as part
of the JSP standard without having to fully declare them or import them.
• If we want to customise the property names within the bean, we can use a column name alias in the SQL
query.
• Server-side includes (SSI) have been replaced with the <%@ include %> directive.
• Implementation of LOOP, ITERATE, INCLUDEIF and EXCLUDEIF tags have been postponed pending
enhancements to the tag extension mechanism.

References
• Geary, M., D. & Microsystems, S., 2001. Advanced JavaServer pages, Prentice Hall PTR Publication.
• Bollinger, G. & Natarajan, B., 2001. JSP: A beginner’s guide, Osborne/McGraw-Hill Publication.
• JSP Tutorial, [Online] Available at: < [Link] > [Accessed 12 April 2012].
• A Servlet and JSP Tutorial, [Online] Available at: < [Link] >
[Accessed 12 April 2012].
• sharman2101, 2009. JSP (Java Server pages) video tutorial [Video online] Available at: <[Link]
com/watch?v=6MV6dfLZ0Ts> [Accessed 12 April 2012].
• superboysales, 2010. Java server pages (JSP) [Video online] Available at: <[Link]
=bMjx8zuJNfY&feature=related> [Accessed 12 April 2012].

Recommended Reading
• Ruvalcaba, Z. & Pizzi, M., 2003. Macromedia Dreamweaver Mx Unleashed, Sams Publication.
• Steflik, D. & Sridharan, P., 2000. Advanced Java Networking, 2nd ed. Prentice Hall Professional Publication.
• Brunner, J. R., 2003. Jsp: Practical Guide for Java Programmers, Elsevier Publication.

161/ADTU OLE
Advanced Java

Self Assessment
1. A JSP uses a __________object to present dynamic content.
a. Servlet
b. HTML
c. JavaBean
d. URL

2. The _________tag is used to declare a JavaBean object that we want to use within the JSP.
a. jsp:useBean
b. jsp:getProperty
c. jsp:setProperty
d. scriptlets

3. The properties of beans can be set by using the _____________tag.


a. jsp:useBean
b. jsp:getProperty
c. jsp:setProperty
d. tsx:dbconnect

4. Match the following columns


Object name Type
1. session A. [Link]
2. request B. [Link]
3. out C. [Link]
4. config D. [Link]
a. 1-A, 2-C, 3-B, 4-D
b. 1-C, 2-A, 3-D, 4-B
c. 1-D, 2-B, 3-A, 4-C
d. 1-B, 2-D, 3-C, 4-A

5. The _________directive allows substitution of text or code to occur at translation time.


a. page
b. taglib
c. jsp
d. include

6. The syntax for a scriptlet is_______________.


a. <% scriptlet %>
b. <%! Declarations(s)%>
c. <%-- comment text --%>
d. <%= expression %>

162/ADTU OLE
7. Which one of the following is not an advantage of using JSP technology?
a. Separation of dynamic and static content
b. Directives and comments
c. Component reuse
d. Scripting and tags

8. Java Server Pages are composed of standard _______tags and _____tags.


a. HTML, JSP
b. SHTML, JSP
c. SQL, DBMS
d. AJAX, HTML

9. The ______directive allows custom extensions to be made to the tags known to the JSP engine.
a. page
b. jsp
c. include
d. taglib

10. The ________directive defines page dependent attributes to the JSP engine.
a. jsp
b. include
c. page
d. taglib

163/ADTU OLE
Advanced Java

Chapter VII
Java Beans

Aim
The aim of this chapter is to:

• explain software components and their need

• elucidate enterprise Java beans

• explicit development of various kinds of beans

Objectives
The objectives of this chapter are to:

• explain event dispatch and event handling

• explicit Java bean persistence

• elucidate working of program using bean properties

Learning outcome
At the end of this chapter, you will be able to:

• understand development of Java beans

• describe the syntax for various Java components

• classify software components

164/ADTU OLE
7.1 Introduction to Software Components
Software components are self-contained, reusable software units. Software development with a component object
model is like building with Legos building blocks. Instead of building an entire application from scratch, we build
an application by hooking together our existing building blocks. This approach not only saves time, money, and
effort, but it produces more consistent, reliable applications.

Software components raise the level of software reuse, moving its emphasis from the level of the skilled programmer
to the level of the business application creator. Note this term “business application creator.” What it means is that
software component can be assembled into applications by people skilled in the business, but almost certainly not
skilled in programming.

7.1.1 Need for Software components


Think of a hi-fi system of separate components. Skilled electronics engineers build each component: amplifier, CD
player, speakers, and so on from small parts (integrated circuits, wires, circuit boards, and so on). On the amplifier
are user controls, on/off switches, volume control, etc., and, at the back, connections. The connections use different
types of plugs for different functions to stop me from plugging the speakers into the wrong CD input socket. As the
user, one is expected to be able to understand the controls and to work out which cable plugs in where. He need not
know how the electronic circuitry operates.

There are numerous similarities between a hi-fi system and the ideal of computer software built from components.
Consider an HTML page, to be delivered across the World Wide Web, which allows us to select an item from a
catalogue and to buy it using a credit card. The page must contain a way for us to enter my credit card details, a
way to indicate user’s product choice, and a way to allow us to say “buy.” In this ideal world, the page is created
by somebody skilled in publishing on the Web, and not by a programmer.

The publisher builds up the Web page and includes on it three software components. One that takes credit card details,
one that allows selecting an item, and one that displays a button with the word “buy” on it. The publisher “wires”
the components together by connecting the “credit card details available” event from the credit card component
and the “product selection” event from the selector component to the “buy” component. Now, when the user has
entered his or her credit card details and selected an item and clicked on the “buy” button, a request is sent to the
Web server. The constructor of the HTML page knows nothing of how the credit card component verifies its details
or of how the transaction component processes the request; the HTML author simply plugs the pieces together to
provide the desired end result: a functional Web page.

7.1.2 Classifications of Software Components


Software components can be broadly classified into visual and non-visual components. Non- Visual Components:
An alarm is an example of a typical non-graphical component. When we add it to an application, we can graphically
choose how frequently the alarm goes off and can easily edit the alarm code. But when the applications runs, alarm
component has no visual appearance.

Visual Components: Developing software with a component object model allows purchasing or developing software
components and then integrating them in a graphical environment (GUI builder tool) to create a complete application.
Reusable software components can be simple, such as buttons, text fields, listboxes, scrollbars, and dialogs. For
example, Font selectors, Database viewers etcetera. The following is a slider component created in Java. This slider
can be integrated with any other components to get a complete application.

165/ADTU OLE
Advanced Java

Fig. 7.1 Slider created in Java


(Source: [Link]

The above components are traditionally sold by third parties. More recently, vendors sell more complex software
components, such as calendars and spreadsheets.

7.2 Software Component Model


A simple definition: A software component model is a specification for how to develop reusable software components
and how these component objects can communicate with each other. We can now focus on how component models
work in a general sense. Component developers must deal with the low-level details of implementing a component
and its associated classes.

Application developers can then simply hook together existing components in a visual development environment.
This is what we call rapid application development (RAD) existing codebase can be easily reused or purchased
from an independent vendor and integrated in a third-party development environment.

7.2.1 Features of Software Component


Understanding the Software Components themselves in order for a software component model to work, each software
component must provide several features:
• The component must be able to describe itself. This means that a component must be able to identify any
properties that can be modified during its configuration and also the events that it generates. This information
is used by the development environment to seamlessly integrate third-party components. The component must
allow graphical editing of its properties. A RAD environment is intensely graphical; the configuration of a
software component is done almost exclusively through control panels that expose accessible properties.
• The component must be directly customisable from a programming language. Because components also can be
connected by scripting languages or other environments that can only access the components from a code level,
this feature also allows software components to be manipulated in non-visual development projects.
• The component must generate events or provide some other mechanism that lets programmers semantically
link components. This means that the programmer can easily add the appropriate action code to buttons so that
button clicks will properly affect other components.

7.3 Javabean
A JavaBean is a reusable software component that is written in Java programming language. It can be visually
manipulated in builder tools. A JavaBean is often referred to simply as a Bean.

7.3.1 Importance of Java Component Model


Cross platform deployment: The promise of the Java environment is the software producer’s nirvana, write it once
and execute it anywhere. The platform-independent nature of Java and its standardised class library finally make it
possible to develop a single version of an application and have it execute on any Java-compatible system without
the need for recompilation or addition of special logic. Components created with existing component models, such
as Microsoft’s ActiveX and OpenDoc; do not meet the needs of cross-platform deployment.

166/ADTU OLE
Secured: OpenDoc is available on Apple Macintosh, OS/2, and Windows, but again, one component executable does
not fit all! Existing components are installed and registered as part of the operating system. If this model is extended
to the World Wide Web, the security implications are extremely scary! An ActiveX or OpenDoc component loaded
dynamically as part of a Web page has access to the full range of operating system interfaces and, therefore, once
installed and registered, may do whatever it pleases with the user’s system. A Java component loaded from the Web
executes within the Java “padded cell” or “sandbox,” where its access to the user’s system can be strictly controlled
and where, by default, it can do no damage.

7.3.2 JavaBeans Objectives


Given the failings of the existing component models, some of the aims of JavaBeans are fairly obvious. Here are a
few of the targeted characteristics:
• Portable: Written in Java with no platform-native code.
• Lightweight: It should be possible to implement a component as small as a push button or as large as a complete
spreadsheet or word processor.
• Simple to create: It should be a simple job to create a Java component without implementing countless methods.
Creation should be possible with or without development tools. It should be simple to migrate from a simple
applet to a Java component.
• Hostable in other component models: It should be possible to use a JavaBean as a first-class ActiveX, OpenDoc,
or other component. A JavaBean may be contained within an ActiveX or OpenDoc container, such as a word
processor, and will behave exactly as if it were a native component. Thus a JavaBean chart component can be
embedded in a word processor document to interact with a spreadsheet in the same document. The creator of the
JavaBean need not provide special logic to deal with being hosted in another environment, and, indeed, the bean
may not even know it is happening, because all communication and conversion is provided by a “bridge.”
• Able to access remote data: A Java component may use any of the standard distributed objects (JavaIDL or
Remote Method Invocation) or distributed data (JDBC) mechanisms to access remote data. In fact, a bean may
use any of the standard environment facilities.

7.3.3 Basic Bean Concepts


JavaBeans, regardless of their functionality, are defined by the following features. Introspection Beans support
introspection, which allows a builder tool to analyze how Beans work. They adhere to specific rules called design
patterns for naming Bean features. Each Bean has a related Bean information class, which provides property, method,
and event information about the Bean itself. Each Bean information class implements a BeanInfo interface, which
explicitly lists the Bean features that are to be exposed to application builder tools.
• Properties: Properties control a Bean’s appearance and behaviour. Builder tools introspect on a Bean to discover its
properties and to expose them for manipulation. As a result, we can change a Bean’s property at design time.
• Customisation: The exposed properties of a Bean can be customised at design time. Customisation allows a
user to alter the appearance and behaviour of a Bean. Beans support customisation by using property editors or
by using special, sophisticated Bean customisers.
• Events: Beans use events to communicate with other Beans. Beans may fire events, which mean the Bean sends
an event to another Bean. When a Bean fires an event it is considered a source Bean. A Bean may receive an
event, in which case it is considered a listener Bean. A listener Bean registers its interest in the event with the
source Bean. Builder tools use introspection to determine those events that a Bean sends and those events that
it receives.
• Persistence: Beans use Java object serialisation, implementing the [Link] interface, to save and
restore state that may have changed as a result of customisation. State is saved, for example, when we customise
a Bean in an application builder, so that the changed properties can be restored at a later time.
• Methods: All JavaBean methods are identical to methods of other Java classes. Bean methods can be called by
other Beans or via scripting languages. A JavaBean public method is exported by default.

167/ADTU OLE
Advanced Java

While Beans are intended to be used primarily with builder tools, they need not be. Beans can be manually manipulated
by text tools through programmatic interfaces. All key APIs, including support for events, properties, and persistence,
are designed to be easily read and understood by programmers, as well as by builder tools.

7.4 Bean Development Kit


The Bean Development kit is a tool that allows one to configure and interconnect a set of Beans. Using it, we can
change the properties of a Bean, link two or more Beans, and watch Beans Execute. Therefore the BDK provides
an easy way for us to test Beans that we write and to explore the Capabilities of Beans written by others. The BDK
also includes a set of demonstration Components and their source code. The BDK is a java application.

For creating the first JavaBean, let’s look at the BDK BeanBox. We can create a JavaBean and then use the BeanBox
to test that it runs properly. If a JavaBean runs properly in the BeanBox, it is sure that it works properly with other
commercial builder tools.

7.4.1 Starting the BeanBox


Type cd root_directory:\bdk1.1\beanbox (say c:/bdk1.1/beanbox) to get to the appropriate directory. Then, type run
to start the BDK. When the BeanBox is started, we can see three windows:
• ToolBox window
• BeanBox window
• Properties window

The ToolBox window displays the JavaBeans that are currently installed in the BeanBox, such as the Beans the
come with the BeanBox demo. When the BeanBox starts, it automatically loads its ToolBox with the Beans in
the JAR files contained in the bean/jars directory. We can add additional Beans, such as our own Beans, to the
ToolBox. The BeanBox window itself appears initially as an empty window. We use this empty window for building
applications.

The Properties window displays the current properties for the selected Bean. If no Bean is selected, such as when
we first start the BeanBox or if we click in the BeanBox window’s background, then the Properties window displays
the BeanBox properties. We can use the Properties window or sheet to edit a Bean’s properties.

7.4.2 Using the BDK BeanBox and the Demo JavaBeans


The easiest way to understand how the BeanBox works is to use it. The BeanBox enables us to construct simple
Beans applications without writing any Java code.

Example: Juggling Duke


As a first example, we will build a simple “Juggling Duke” application in which Duke will start or stop juggling
depending on which of two buttons we push. Follow the steps given below in the same order.

STEP 1: Click on Juggler Bean to select from the list of Beans in the Toolbox window and notice the cursor
change.

STEP 2: Place the cursor anywhere in the BeanBox, then click the mouse. This inserts a Juggler Bean into the BeanBox
window. The highlighted box surrounding the Juggler indicates the Juggler is the currently selected bean.

168/ADTU OLE
Fig. 7.2 Demonstration Juggler Bean
(Source: [Link]

STEP 3: Next we’ll look at adding a start button to control the Juggler. This button Bean is an instance of the
OurButton Bean class. Click the OurButton Bean name in the ToolBox, then place an instance of the button in the
BeanBox.

STEP 4: Select the button in the BeanBox so that the button’s properties display in the Property sheet. Edit the label
field in the button’s Property sheet so that the button’s label reads “start.”

STEP 5: Use the BeanBox Edit menu to select an action event to be fired by the start button. Before choosing the
event action, be sure that we have selected the start button. Notice that once we select the actionPerformed menu
item, BeanBox enters a state where a line emanates from the start button and follows the mouse as we move it around
the window. This indicates that the button is the selected source for the action event, and that our next mouse press
should be over the target Bean, which defines appropriate eventhandler methods, in this case the Juggler Bean.

STEP 5: Drag the line from the start button and release it over the Juggler Bean. A dialog appears listing applicable
event handlers defined by the Juggler Bean.

STEP 6: Select the startJuggling method as the target for the event, then press OK. Now, when we press the start
button Duke should start tossing beans around in a circle over his head like a professional juggler. We can control
Duke’s juggling speed by manually setting the property value labelled animationRate in the Juggler’s property sheet
editor. For the appropriate property sheet editor to appear, the Juggler must be the currently selected Bean within
the BeanBox frame. To complete the example program, add a stop button. Repeat the steps taken while addition of
the start button and connected it to the appropriate Juggler action for the new button.

169/ADTU OLE
Advanced Java

STEP 7: Edit the label field of the property sheet to read “stop.”

STEP 8: Hook up the action event from the stop button to the Juggler’s stopJuggling event-handler method. Make
sure the stop button is the currently selected bean.

STEP 9: Select the actionPerformed event from the Edit/Events menu.

STEP 10: Drag the event line from the stop button source to the Juggler Bean target. Press and release the mouse
button with the connection line over the Juggler. The dialog of applicable event-handler methods defined for the
Juggler Bean displays; select the stopJuggling event and click OK.

Fig. 7.3 Demonstration Beans bound with each other by Event Handling mechanism.
(Source: [Link]

We should now be able to start and stop the juggler by pressing the appropriate button.

From the above example we have learnt,


• Dropping Beans from the ToolBox into the BeanBox and changing their properties using the Properties
sheet and associated property editors.
• One Bean can fire an event and another Bean can react to the fired event.

170/ADTU OLE
7.5 Building the First Bean
Here we are going to construct a Bean called Spectrum. The component displays square 100 pixels wide and 100
pixels high, and fills it with colours of the spectrum. The component has one Boolean property named vertical. If this
property is true, the colours are arranged in a vertical direction. Otherwise, the colours are oriented in a horizontal
direction. Follow the instructions in the following sections to develop and test this Bean.

STEP 1: Create the source code Create a directory named spectrum anywhere on the computer. Create the source
code Enter the source code shown in the listing at the end of this paragraph. We must name this file Spectrum.
java and place it in the spectrum directory. The package statement at the beginning of the file places this class in a
package named spectrum.

Listing [Link]
import [Link].*;
public class Spectrum extends Canvas {
private boolean vertical;
public Spectrum() {
vertical=true;
setSize (100,100);
}
public boolean getVertical() {
return (vertical);
}
public void setVertical(boolean vertical) {
[Link]=vertical;
repaint ();
}
public void paint(Graphics g) {
float saturation=1.0f;
float brightness=1.0f;
Dimension d=getSize ();
if (vertical) {
for (int y=0;y<[Link];y++) {
float hue=(float) y/([Link]-1);
[Link]([Link](hue,saturation,brightness));
[Link] (0,y, [Link]-1, y);
}
}
else {
for (int x=0;x<[Link]; x++) {
float hue=(float) x/([Link]-1);
[Link]([Link](hue,
saturation,brightness));
[Link] (x, 0,x, [Link]-1);
}
}
} // method ends
}// class ends

171/ADTU OLE
Advanced Java

7.5.1 How the Program Works?


The above Spectrum class is a subclass of Canvas. The private Boolean variable named vertical is one of its properties.
The constructor initialises that property to true and sets the size of the component.

The method to access the property are getVertical () and setVertical (). When the property is changed via the setVertical
() method, the repaint () method is invoked to update this display. The paint () method fills the square with the
colours of the spectrum. A specific colour can be uniquely represented by its hue, saturation, and brightness. Each
of these parameters is a float and ranges from 0.0 to 1.0f. In this code, the saturation and the brightness are set to
1.0f and the hue is varied from 0.0 to 1.0f. This is the mechanism used to compute the complete range of colours.
The getSize () method is invoked to determine the dimensions of this Bean.

The vertical property is then checked to determine if the colours should change in the vertical or horizontal dimension.
If the vertical is true, the square is filled by drawing horizontal lines of different colours. The hue of each line is
calculated by scaling its y coordinate to a value between 0.0 to 1.0f. The getHSBColor () static method of the Color
class accepts hue, saturation, and brightness parameters for a color and returns a reference to the Colour object.
That object is used to set the current colour of the graphics context. Then a horizontal line of that colour is drawn. If
the vertical is false, the square is filled by drawing vertical lines of different colours. The logic to do this is analogous
to that described in the previous paragraph, except that the hue of each line is calculated by scaling its x coordinate
to a value between 0.0 and 1.0f.

STEP 2: Compile the source code


Change to the parent directory of spectrum and type,

javac spectrum\[Link]

Check that [Link] file has been created in the spectrum directory. Note: Each code example in this Course material
exists in a separate package. Java requires that the directory hierarchy mirror the package hierarchy. Therefore, we
must always be in the parent directory when compiling a code example with javac or executing an application with
java. Our CLASSPATH environment variable must include this parent directory. This is necessary so the .class files
can be found.

STEP 3: Create the manifest template file


All Beans must be specified in a manifest template file. This file is used in the next step by the tool that packages our
Bean into a JAR file. In this example, we must create a manifest template file in order to indicate that [Link]
is a Bean. The contents of this file always use forward slashes in the path name of a file. Name the file spectrum.
mft and place it in the spectrum directory.

Name: spectrum\[Link]
Java-Bean: True

Briefly, a manifest template file is the basis for a manifest file, which is the first element in a JAR file and describes
its contents. In cases where we’ve to package several Beans into one JAR file, the manifest template file includes
a separate entry for each Bean.

STEP 4: Create a JAR file


All Beans must be stored within a JAR file. Change to the parent directory of spectrum and enter the following
command to create a JAR file containing the Spectrum Bean:

jar cfm c:\bdk1.1\jars\[Link] spectrum\*.mft spectrum\*.class

172/ADTU OLE
This command creates a jar file named [Link] and places it in the C:\bdk\jars directory. This is the directory
in which the BDK looks for JAR files. The manifest template file and the .class files in the spectrum directory are
used.

STEP 5: Start the BDK


Type cd c:\bdk1.1\beanbox to get to the appropriate directory. Then type run to start the BDK. Toolbox should have
an entry labeled “Spectrum”

STEP 6: Test the Spectrum Bean


Create an instance of Spectrum in the BeanBox. We should see a square with the colours of the spectrum oriented
in a vertical direction. Use the property window to change the vertical property to false. Observe that the display
changes immediately. We may create several instances of Spectrum in BeanBox. The vertical property for each can
be changed independently.

The properties window also presents several other properties for this Bean for example, background, foreground
and font. These properties are defined by the Component class. Since our Bean is a subclass of Component, it also
has these properties. However the values of these properties are not relevant to this Bean because it completely fills
the square with colours and does not display text.

Fig. 7.4 creating an instance of Spectrum in the BeanBox


(Source: [Link]

173/ADTU OLE
Advanced Java

In this example, the BDK used introspection to examine our new Bean and to automatically infer that vertical was
one of its properties. This was possible because the access methods getVertical() and setVertical() followed a simple
naming pattern. The property vertical is called Simple property because it has got only one get method getVertical
() and one set method setVertical ().

From the above example we have learnt,


• To create a bean of our own.
• To use getter and setter method to work on the property of a bean.

7.6 Event Handling


A Bean that wants to generate events needs to keep track of interested event targets. In the delegation event model,
the event mechanism is broken up conceptually into event dispatch and event handling. Event dispatch is the
responsibility of the event source; event handling is the responsibility of the event listener. Any object that wants
to know when an event is fired by a Bean can tell the Bean it wants to be informed about particular events. In other
words, an event listener registers interest in an event by calling a predetermined method in the event source.

Event x

receiveEvent(EventType x)
fireEvent ()

Source Listener

Fig. 7.5 Event handling


(Source: [Link]

7.6.1 Registering Event Listeners


Consider a typical button Bean that generates events when pressed. An interested listener Bean might increment a
counter object each time the button is pressed. If the button Bean wants to be an event source, it must provide two
methods that can be called by interested objects. One method adds the caller to the list of listeners who are notified
when the event occurs.

public synchronised void addActionListener


(ActionListener l) {...}

The other method removes the caller from the list of interested listeners.

public synchronized void removeActionListener


(ActionListener l) {...}

174/ADTU OLE
7.6.2 Naming Event Listeners
Similar to properties, the signature of the method names must follow specific patterns. The Java introspection
mechanism detects the pattern of the method’s signature and can determine the events the source Bean generates
from the name of the registration methods, together with the type of the arguments of the registration methods. Java’s
introspection mechanism recognises the following general pattern for event generation capabilities:

public synchronised
void addTYPE(TYPE listener);
public synchronised
void removeTYPE(TYPE listener);

The TYPE is replaced by the class name of the particular event listener; for example, MouseListener or
MouseMotionListener.

7.6.3 Following the ActionEvent


When the above event registration methods are defined for our button Bean, Java’s introspection mechanism is able
to determine that an ActionEvent can be generated by the button. If the counter object wants to be notified when an
ActionEvent occurs, it calls the button’s addActionListener method, giving itself as an argument. For this to work,
the counter object has to first implement the ActionListener interface, because the argument to addActionListener
is an ActionListener object.

The button Bean needs to track the listeners who register to receive notification of ActionEvents. This is where the
Vector import statement comes into play. The button Bean maintains a list (or Vector) of listeners. Thus, the source
Bean declares the following line:

private Vector listeners = new Vector();

When the Bean’s addActionListener is called, the listener supplied as an argument to the call is appended to the
Vector of listeners, as follows:

public synchronised void addActionListener


(ActionListener l) {
[Link](l);
}
Similarly, when removeActionListener is called, the listener supplied as an argument to the
method is removed from the list of listeners:
public synchronised void removeActionListener
(ActionListener l) {
[Link](l);
}

7.6.4 Dispatching Events to Event Listeners


When an event is fired, the event source (the button Bean) iterates over the list of listeners and sends each listener
a notification of the ActionEvent.

175/ADTU OLE
Advanced Java

7.7 Bean Persistence


Saving and restoring Beans in the BDK To better understand persistence, let’s begin with an example:
• Start the BDK and create an instance of the Spectrum Bean. Its vertical property is initially true. Changes this
value too false. An immediate change in the apperance of the Bean can be seen.
• Now select the file1 save menu options in BeanBox. A file dialog box titled “Save As” appears. Press the
save button to serialise this Bean to the default file [Link] the File Exit menu options to exit the
BDK.
• Start the BDK again. Select the file Load options in BeanBox. A file dialog box titled “Open” appears. Press
the Open buttons to restore the Bean from the default file [Link] that the component appears,
and its vertical property is false. From the above example we have learnt.
• How a simple Bean with one property could be serialised and deserialised.
• The essence of persistence, the ability to save the state of a Bean and restore it later.

7.7.1 Serialisation and Deserialisation


Serialisation is the ability to save the state of several objects to a stream. The stream is typically assosiated with a
file. This allows an application to start execution, read a file, and terminate. Deserialisation is the ability to restore
the state of several objects from a stream. This allows and applications to start execution, read a file, restore a
set object from the data in that file, and continue. If an object contains references to other objects, these are also
saved. This is done automatically. The process is recursive, so an attempt to serialise one object can result in the
serialisation of many other objects. The serialisation mechanisms are designed to correctly handle sets of objects
that have circular references to each other.

Only the nonstatic and nontransient parts of an object’s state are saved by the serialisation mechanisms. Static fields
of an object are not saved, because they are considered part of the state of the class, not the state of an object. In
addition, static fields are some times initialised by static initialisation blocks that are executed when the class is
loaded.

Transient fields of an object are not saved, saved since they contain temporary data not needed to corectly restore
that object later. In addition to the object state data, some type information is saved so the object can be reconstructed
properly. It is important to understand that when an object is deserialised, none of its constructors is invoked. Instead,
memory is allocated and the variables are set directly from the data that is read from the serial stream.

Example: Object Graphs


Consider the collection of objects as shown in figure below. There are five objects that hold references to each
other as depicted by the arrows. This arrangement is called an object graph. Note that there are cycles in the graph.
That is, it is possible to reach some objects by more than one path. For example, D can reach some objects by
starting at A and following the references labelled “2,”6,”and “8.”It can be accessed by starting at A and following
the references labelled “2” and”5.” We can also transverse the references labelled “1” and”3” to access D. If we
attempt to serialise ‘A’ the reference among these objects cause all of them to be saved. Although an object may
be encountered several times during this process, it is extremely important that it be saved only once in the serial
stream. Otherwise, multiple copies of the same object will be created during deserialisation.

176/ADTU OLE
Fig. 7.6 Circle Bean

The Java persistence mechanisms have been designed to operate in this manner. When a second time, another
complete copy of it is not written to the stream. Instead, a handle is written. This is a reference to an object that has
already been written to the stream.

A 2
1
C

B 7
4
5
6
8
3
E
D Object graph
9

Fig. 7.7 Example of circle bean


(Source: [Link]

177/ADTU OLE
Advanced Java

7.7.2 Serialisable Bean


This section develops a Bean called graph that shows six nodes positioned at the corners of a hexagon. We can
between nodes by moving the mouse to a node, pressing the mouse button, and dragging the mouse to another node
and then releasing it. This Bean is serialisable because all of its classes either directly or indirectly implement the
Serialisable interface. It illustrates several issues relating to persistence. The source code for the example is located
in three files.
1. [Link]
2. [Link]
3. [Link]

STEP 1: Creating Graph class


Here we are going to do the following: Creating a class which extends Canvas and implements MouseListener
and MouseMotionListener. The graph class is serialisable because it inherits from the Component class, which
implements the Serialisable interface.

References to the Node and Link objects that make up the graph are maintained in vectors named nodes and links.
Variable node1 and node2 are used only when the user is drawing a link between two nodes. They are transient
because we do not want to store this data as part of the serialisation process. Variables x and y are used only to track
the current position of the mouse and it being dragged. These are also transient variables because we do not want
to store as part of the serialisation process.

The constructor begins by setting the size of the Bean to 200 x 200 pixels and initialising the nodes and links
vectors. The object registers itself to receive mouse and mouse motion events. Finally, the makenodes() method is
called to create the six nodes at the appropriate positions. Impementations are provided for all of the methods in the
MouseListener and MouseMotionLIstener interfaces.

The doMousePressed () method checks if the mouse is positioned within a node. If so, the variable node1 is set to
reference that node. Otherwise, node1 is set to null. The doMousedragged () method updates the x and y variables
to tack the position of the mouse and invokes repaint(), so that a rubber-band line can be drawn from the center of
the first node to the current mouse position.

The doMouseReleased() method checks if node1 has been set. If so, it then checks if the mouse is positioned within
a node. If so, makeLink() is called to create a Link object connecting node1 and node2. In any case, node1 and
node2 are set to null, and repaint() is called to update the display.

The paint() method draws the nodes, links, and a rubber-band line if needed. The makeNodes() method generates a
display that shows the nodes of the graph and adds these to the nodes vector. The makeLink() method returns if a link
already exists between node1 and node2. Otherwise, it creates a new Link object and adds it to the links vector. The
linkExists() methods retirns true if a link already exists between two specified nodes. Otherwise, it returns false.

7.7.3 Listing [Link]

Package graphs;
import [Link]. *;
import [Link]. *;
import [Link]. *;
import [Link]. *;
public class Graph extends canvas
implements mouseListener,mouseMotionListener
{
private final static int NNODES = 6;
private Vector nodes;

178/ADTU OLE
private Vector links;
private transient Node node1, node2;
private transient int x, y;
public Graph() {
setSize(200, 200);
nodes = new Vector();
inks = new Vector();
addMouseListener(this);
addMouseMotionListener(this);
makeNodes();
}
public void mouseClicked(MouseEvent me) {
}
public void mouseEntered(MouseEvent me) {
}
public void mouseExited(MouseEvent me) {
}
public void mousePressed(MouseEvent me) {
doMousePressed(me);
}
public void mouseReleased(MouseEvent me) {
doMouseReleased(me);
}
public void mouseDragged(MouseEvent me) {
doMouseDragged(me);
}
public void mouseMoved(MouseEvent me) {
}
public void doMousePressed(MouseEvent me) {
// check if node1 should be initialised
X = [Link]();
Y = [Link]();
enumeration e = [Link]();
while ([Link]()) {
node1 = (Node)[Link]();
if ([Link] (x, y)) {
return;
}
}
node1 = null;
}
public void doMouseDragged(MouseEvent me) {
X = [Link]();
Y = [Link]();
repaint ();
}
public void doMouseReleased(MouseEvent me) {
// make a link between node1 and node2
X = [Link]();
Y = [Link]();
if (node1! = null) {
enumeration e = [Link]();

179/ADTU OLE
Advanced Java

while ([Link]()) {
node2 = (Node)[Link]();
if (node 2. Contains (x, y)) {
makeLink([Link](), [Link]());
break;
}
}
node1 = node2 = null;
repaint();
}
}
public void paint (graphics g) {
// Draw nodes
enumeration e = [Link]();
while ([Link]()) {
((node) [Link]()).draw(g);
}
// Draw links
e = [Link]();
while ([Link]()) {
((link)[Link]()).draw(g);
}
// Draw rubber band line (if any)
if (node 1! = null) {
[Link]([Link](), [Link](), x, y);
}
}
private void makenodes() {
// Initialise nodes variable
Dimension d = getSize();
int width = [Link];
int height = [Link];
int centerx = width/2;
int centery = height/2;
double radius = (width < height)? 0.4 * width: 0.4 * height;
for (int i = 0; i < NNODES; i++) {
Double theta = i * 2 * [Link]/NNODES;
int x = (int)(centerx + radius * [Link](theta));
int y = (int)(centery - radius * [Link](theta));
[Link](new Node(x, y));
}
}
private void makeLink(int id1, int id2) {
// Return if a link already exists between these nodes
if(linkExists(id1, id2)) {
return;
}
// otherwise, create a new link
node n1 = (Node)[Link](id1);
node n2 = (Node)[Link](id2);
[Link](new Link(n1, n2));
}

180/ADTU OLE
private boolean linkExists(int i, int j) {
// check if a link exists between nodes i and j
enumeration e = [Link]();
while ([Link]()) {
link link = (Link)[Link]();
int id1 = link.getNode1 ().getId();
int id2 = link.getNode2 ().getId();
if((id1 == i && id2 == j)||(id1 == j && id2 == i)) {
return true;
}
}
return false;
}
}

STEP 2: Creating Node class


Note that this class must implement Serialisable. Because the Graph Object holds references to Node objects, any
Attempt to serialise the Bean also cause the Node object to be serialised.

The radius of the node is defined by an int constant NODERADIUS. Each Node object has an instance variable
named id that contains unique value to identify that node. The Node class has a static variable named count that is
incremented each time a Node Object is created. This is the mechanism used to assign a unique id value for each
node. The x and y variables define the centre position of the node.

The Constructor initialises the instance variable. Note that the id variable is set from the current value of the static
count variable. Access methods for the x, y and id variables follow the constructor.

The contains() method returns true if a point is within node. Otherwise, it returns false. The draw() method displays
the node.

181/ADTU OLE
Advanced Java

7.7.4 Listing [Link]

package graphs;
import [Link].*;
import [Link].*;
public class Node implements Serialisable {
private final static int NODERADIUS = 10;
private static int count = 0;
private int x, y, id;
public Node(int x, int y) {
this.x = x;
this.y = y;
id = count++;
}
public int getX() {
return x;
}
public int getY () {
return y;
}
public int getId () {
return id;
}
public boolean contains (int x, int y) {
int deltax = this.x - x;
int deltay = this.y - y;
int a = deltax * deltax + deltay * deltay;
int b = NODERADIUS * NODERADIUS;
return (a <= b);
}
public void draw (graphics g) {
int w = 2 * NODERADIUS;
int h = w;
[Link] (x - NODERADIUS, y - NODERADIUS, w, h);
}
}

STEP 3: Creating Link class


Note that this class must be serialisable. Because the graph object holds references to Link objects, any attempt to
serialise the Bean will also cause Link objects to be serialised.

The node1 and node2 variables hold references to the two nodes connected by this link. The getNode1() and
getNode2() methods provide access to these variables. The draw() method draws a line connecting the centers of
the two nodes.

182/ADTU OLE
package graphs;
import [Link].*;
import [Link].*;
public class Link implements serialisable {
private Node node1,node2;
public link(node node1, node node2) {
this.node1 = node1;
this.node2 = node2;
}
public node getNode1() {
return node1;
}
public node getNode2() {
return node2;
}
public void draw(graphics g) {
int x1 = [Link]();
int y1 = [Link]();
int x2 = [Link]();
int y2 = [Link]();
[Link](x1,y1,x2,y2);
}
}

Note that the Link objects have references to Node objects. Furthermore, a given Node object may be referenced by
more than one Link Object. To run the application, create separate manifest and jar files for each bean and instantiate
them in the beanbox. Note that the Link objects have references to Node objects. Furthermore, a given Node object
may be referenced by more than one Link Object. This example has illustrated that object graphs are correctly saved
and restored. To confirm this try saving and restoring the state of this Bean. From this example we have learnt that,
each bean is capable of storing and restoring its state.

183/ADTU OLE
Advanced Java

Summary
• Software development with a component object model is like building with Legos building blocks.
• In software development instead of building an entire application from scratch, we build an application by
hooking together our existing building blocks.
• There are numerous similarities between a hi-fi system and the ideal of computer software built from
components.
• Software component can be assembled into applications by people skilled in the business, but almost certainly
not skilled in programming.
• Software components can be broadly classified into visual and non-visual components.
• A software component model is a specification for how to develop reusable software components and how these
component objects can communicate with each other.
• A JavaBean is a reusable software component that is written in Java programming language.
• Beans can be manually manipulated by text tools through programmatic interfaces.
• BDK provides an easy way to test Beans that cab be written and explore the Capabilities of Beans written by
others.
• The easiest way to understand how the BeanBox works is to use it.
• A Bean that wants to generate events needs to keep track of interested event targets.
• Event dispatch is the responsibility of the event source; event handling is the responsibility of the event
listener.
• When an event is fired, the event source (the button Bean) iterates over the list of listeners and sends each listener
a notification of the ActionEvent.
• The Bean Development kit is a tool that allows one to configure and interconnect a set of Beans.
• A component must be able to identify any properties that can be modified during its configuration and also the
events that it generates.
• Application developers can simply hook together existing components in a visual development environment.
• The component must generate events or provide some other mechanism that lets programmers semantically
link components.
• The component must be directly customisable from a programming language.

References
• Englander, R., 1997. Developing Java Beans, O’Reilly Media, Inc. Publication.
• Haefel, M., E. & Burke, B., 2006. Enterprise JavaBeans 3.0, 5th ed. O’Reilly Media, Inc. Publication.
• Voss, G., Java Beans: Introducing Java Beans, [Online] Available at: <[Link]
onlineTraining/Beans/Beans1/> [Accessed 12 April 2012].
• JavaBeans, JavaBean as a Software Component Model, [Online] Available at: < [Link]
javase/[Link]> [Accessed 12 April 2012].
• 2010. Java beans, [Video Online] Available at: <[Link] [Accessed
12 April 2012].
• 2010. [Video Online] Available at: <[Link]
&playnext=1&list=PLEFB2BACD4935A80F> [Accessed 12 April 2012].

184/ADTU OLE
Recommended Reading
• Valesky, Enterprise Java Beans, Pearson Education India Publication.
• Anderson, P. & Anderson, G., 2002. Enterprise JavaBeans Component Architecture: Designing and Coding
Enterprise Applications, Prentice Hall Professional Publication.
• Matena, V., Krishnan, S. & Strearns, B., 2003. Applying Enterprise JavaBeans: Component-Based Development
for the J2EE Platform, 2nd ed. Addison-Wesley Professional Publication.

185/ADTU OLE
Advanced Java

Self Assessment
1. A ___________ is a reusable software component that is written in Java programming language.
a. JavaBean
b. BeanInfo
c. [Link]
d. BeanBox

2. Spectrum is a type of ____________.


a. java program
b. java bean
c. java file
d. java component

3. __________is the ability to save the state of several objects to a stream.


a. Deserialisation
b. Association
c. Serialisation
d. Transient

4. _______ hooks together existing components in a visual development environment.


a. JDBC
b. ODBC
c. CD
d. RAD

5. ___________control a Bean’s appearance and behaviour.


a. Properties
b. Persistence
c. Events
d. Customs

6. Beans use _______to communicate with other Beans.


a. source
b. events
c. properties
d. files

7. The ____________is a tool that allows one to configure and interconnect a set of Beans.
a. toolkit
b. javakit
c. Bean Development Kit
d. Toolbox

186/ADTU OLE
8. A Java component uses the ________to access remote data.
a. JavaIDL
b. JavaBean
c. JavaXML
d. JavaDL

9. A _______________is a specification for how to develop reusable software components and how these component
objects can communicate with each other.
a. software component model
b. software component
c. software development
d. software application

10. __________is hostable in other component models.


a. JDK
b. Javabean
c. JavaIDL
d. Beanbox

187/ADTU OLE
Advanced Java

Chapter VIII
Hibernate and Struts

Aim
The aim of this chapter is to:

• explicate hibernate architecture

• explain the concept of struts and its attributes

• elucidate the MVC architecture

Objectives
The objectives of this chapter are to:

• explain setting of an application using Struts

• explicate hibernate communication with RDBMS

• explicit use of Struts for using forms

Learning outcome
At the end of this chapter, you will be able to:

• understand generics in Java and how we can use it

• identify the MVC architecture

• recognise generic parameters and real types naming conventions

188/ADTU OLE
8.1 Introduction to Hibernate
Hibernate is an Object-Relational Mapping (ORM) solution for JAVA. It is a powerful, high performance object/
relational persistence and query service. It allows us to develop persistent classes following object-oriented idiom
including association, inheritance and polymorphism.

8.2 Hibernate Architecture


• Hibernate itself opens connection to database.
• It converts HQL (Hibernate Query Language) statements to database specific statement.
• It receives result set.
• It then performs mapping of these databases specific data to Java objects which are directly used by Java
application.

Hibernate uses the database specification from Hibernate Properties file. Automatic mapping is performed on the
basis of the properties defined in hbm XML file defined for particular Java object.

Hibernate Architecture

Application

Persistence Object

Hibernate

Hibernate properties XML Mapping

Database

Fig. 8.1 Hibernate architecture


(Source: [Link]

For Hibernate communication with RDBMS General Steps are given below:
Step 1: Load the Hibernate configuration file and create configuration object. It will automatically load all hbm
mapping files.
Step 2: Create session factory from configuration object.
Step 3: Get one Session from this session factory.
Step 4: Create HQL query.
Step 5: Execute query to get list containing Java objects.

189/ADTU OLE
Advanced Java

Example: Retrieve list of employees from Employee table using Hibernate.


/* Load the hibernate configuration file */
Configuration cfg = new Configuration();
[Link](CONFIG_FILE_LOCATION);
/* Create the session factory */
SessionFactory sessionFactory = [Link]();
/* Retrieve the session */
Session session = [Link]();
/* create query */
Query query = [Link](“from EmployeeBean”);
/* execute query and get result in form of Java objects */
List<EmployeeBean> finalList = [Link]();
[Link] File
<?xml version=”1.0” encoding=”utf-8” ?>
<!DOCTYPE hibernate-mapping PUBLIC
“-//Hibernate/Hibernate Mapping DTD 3.0//EN”
“[Link]
<hibernate-mapping>
<class name=”[Link]”
table=”t_employee”>
<id name=”id” type=”string” unsaved-value=”null”>
<column name=”id” sql-type=”varchar(32)” not-null=”true”/>
<generator class=”uuid”/>
</id>
<property name=”name”>
<column name=”name” />
</property>
<property name=”salary”>
<column name=”salary” />
</property>
</class>
</hibernate-mapping>

8.3 Hibernate Communication with RDBMS


General steps:
Step 1: Load the Hibernate configuration file and create configuration object. It will automatically load all hbm
mapping files.
Step 2: Create session factory from configuration object
Step 3: Get one session from this session factory.
Step 4: Create HQL query.
Step 5: Execute query to get list containing Java objects.

Example: Retrieve list of employees from Employee table using Hibernate.

190/ADTU OLE
/* Load the hibernate configuration file */
Configuration cfg = new Configuration();
[Link](CONFIG_FILE_LOCATION);
/* Create the session factory */
SessionFactory sessionFactory = [Link]();
/* Retrieve the session */
Session session = [Link]();
/* create query */
Query query = [Link](“from EmployeeBean”);
/* execute query and get result in form of Java objects */
List<EmployeeBean> finalList = [Link]();

[Link] File

<?xml version=”1.0” encoding=”utf-8” ?>


<!DOCTYPE hibernate-mapping PUBLIC
“-//Hibernate/Hibernate Mapping DTD 3.0//EN”
“[Link]
<hibernate-mapping>
<class name=”[Link]”
table=”t_employee”>
<id name=”id” type=”string” unsaved-value=”null”>
<column name=”id” sql-type=”varchar(32)” not-null=”true”/>
<generator class=”uuid”/>
</id>
<property name=”name”>
<column name=”name” />
</property>
<property name=”salary”>
<column name=”salary” />
</property>
</class>
</hibernate-mapping>

8.4 What Does Hibernate Offer?


Hibernate is an open source (released under LPGL) product for providing seamless persistence for Java objects. It
uses reflections and yet provides excellent performance. It has support for over 30 different dialects (like drivers
for different databases). It provides a rich query language to access objects, provide caching and JMX support. It is
intended to provide high performance transparent persistence with low resource contention and small foot print.

JDO uses byte code enhancement while Hibernate uses runtime reflection to determine persistent properties of
classes. A mapping property or configuration file is used to generate database schema and provide persistence.
Figure below shows the mapping mechanism used by Hibernate:

191/ADTU OLE
Advanced Java

Configuration
Session Factory

Mapping
Documents

Wraps JDBC Connection


Session Used by single thread Spans
DB TXN

Fig. 8.2 Mapping mechanism used by Hibernate


(Source: [Link]

A SessionFactory creates a Session object for transaction in a single threaded interaction. The Session acts as an
agent between the application and the data store. This is the object we will interact with to create, update and load
objects. A Query class allows us to manage our queries and allows for parameterised queries as well.

192/ADTU OLE
8.5 Using Hibernate
Let us proceed with the example we started with. How do we create objects of Person and Dog and make it persistent?
The [Link] code shown below does just that:

package [Link];
import [Link].*;
import [Link].*;
public class CreatePerson
{
public static void main(String[] args)
{
try
{
Configuration config = new Configuration()
.addClass([Link])
.addClass([Link]);
SessionFactory sessionFactory = [Link]();
Session session = [Link]();
Transaction txn = [Link]();
Person john = new Person();
[Link](“John”);
[Link](“Smith”);
Dog rover = new Dog();
[Link](“Rover”);
[Link](rover);
[Link](john);
[Link](john);
[Link]();
[Link]();
}
catch(Exception ex)
{
[Link](“Error: “ + ex);
}
}
}

A Configuration object is first created. This object is used to create the SessionFactory. Each of the persistent types
is introduced to the configuration object. The appropriate mapping files ([Link]) will be consulted at
runtime. The SessionFactory is used to open a Session, which in turn is used to start a transaction. It is important
how the objects of Person and Dog are created without any regard to persistence. The objects of Person (john) is
finally made persistent by calling the save method on the Session object. We will interact with to create, update and
load objects. A Query class allows us to manage our queries and allows for parameterised queries as well.

8.6 Pros and Cons of Hibernate


Hibernate provides highly efficient transparent persistence for Java objects. It leaves behind a very small footprint;
has low resource requirements. It provides for high concurrency. Caching and lazy loading can further improve
performance. Also, instead of saving an entire object, it updates only modified fields of an object. This leads to
more optimised and efficient code than coding with JDBC. Further given a mapping property file, automatic code
generation and schema generation tools are also available. On the downside, mapping an object to multiple tables
is harder to realise.

193/ADTU OLE
Advanced Java

8.7 JDBC Vs Hibernate


There arises a question that “Why Hibernate is better than JDBC?” and the answer for this question is given with
following points:

8.7.1 Relational Persistence for JAVA


Working with both Object-Oriented software and Relational Database is complicated task with JDBC because there
is mismatch between how data is represented in objects versus relational database. So with JDBC, developer has to
write code to map an object model’s data representation to a relational data model and its corresponding database
schema. Hibernate is flexible and powerful ORM solution to map Java classes to database tables. Hibernate itself
takes care of this mapping using XML files so developer does not need to write code for this.

8.7.2 Transparent Persistence


The automatic mapping of Java objects with database tables and vice versa is called Transparent Persistence.
Hibernate provides transparent persistence and developer does not need to write code explicitly to map database
tables tuples to application objects during interaction with RDBMS. With JDBC this conversion is to be taken care
of by the developer manually with lines of code.

8.7.3 Support for Query Language


JDBC supports only native Structured Query Language (SQL). Developer has to find out the efficient way to
access database that is to select effective query from a number of queries to perform same task. Hibernate provides
a powerful query language Hibernate Query Language (independent from type of database) that is expressed in a
familiar SQL like syntax and includes full support for polymorphic queries. Hibernate also supports native SQL
statements. It also selects an effective way to perform a database manipulation task for an application.

8.7.4 Database Dependent Code


Application using JDBC to handle persistent data (database tables) having database specific code in large amount.
The code written to map table data to application objects and vice versa is actually to map table fields to object
properties. As table changed or database changed then it’s essential to change object structure as well as to change
code written to map table-to-object/object-to-table. Hibernate provides this mapping itself. The actual mapping
between tables and application objects is done in XML files. If there is change in Database or in any table then the
only need to change XML file properties.

8.7.5 Maintenance Cost


With JDBC, it is developer’s responsibility to handle JDBC result set and convert it to Java objects through code
to use this persistent data in application. So with JDBC, mapping between Java objects and database tables is
done manually. Hibernate reduces lines of code by maintaining object-table mapping itself and returns result to
application in form of Java objects. It relieves programmer from manual handling of persistent data, hence reducing
the development time and maintenance cost.

8.7.6 Optimise Performance


Caching is retention of data, usually in application to reduce disk access. Hibernate, with Transparent Persistence,
cache is set to application work space. Relational tuples are moved to this cache as a result of query. It improves
performance if client application reads same data many times for same write. Automatic Transparent Persistence
allows the developer to concentrate more on business logic rather than this application code. With JDBC, caching
is maintained by hand-coding.

8.7.7 Automatic Versioning and Time Stamping


By database versioning one can be assured that the changes done by one person is not being roll backed by another
one unintentionally. Hibernate enables developer to define version type field to application, due to this defined
field Hibernate updates version field of database table every time relational tuple is updated in form of Java class
object to that table. So if two users retrieve same tuple and then modify it and one user save this modified tuple to

194/ADTU OLE
database, version is automatically updated for this tuple by Hibernate. When other user tries to save updated tuple
to database then it does not allow saving it because this user does not has updated data. In JDBC there is no check
that always every user has updated data. This check has to be added by the developer.
• Open-Source, Zero-Cost Product License: Hibernate is an open source and free to use for both development
and production deployments.
• Enterprise-Class Reliability and Scalability: Hibernate scales well in any environment, no matter if use it in-
house Intranet that serves hundreds of users or for mission-critical applications that serve hundreds of thousands.
JDBC can not be scaled easily.

8.8 Disadvantages of Hibernate


The disadvantages of Hibernate are given below
• Steep learning curve.
• Use of Hibernate is an overhead for the applications which are:
‚‚ simple and use one database that never change
‚‚ need to put data to database tables, no further SQL queries
‚‚ there are no objects which are mapped to two different tables
• Hibernate increases extra layers and complexity. So for these types of applications JDBC is the best choice.
• Support for Hibernate on Internet is not sufficient.
• Anybody wanting to maintain application using Hibernate will need to know Hibernate.
• For complex data, mapping from Object-to-tables and vice versa reduces performance and increases time of
conversion.
• Hibernate does not allow some type of queries which are supported by JDBC. For example it does not allow to
insert multiple objects (persistent data) to same table using single query. Developer has to write separate query
to insert each object

8.9 The Model-View-Controller Architecture


“Model-View-Controller” is a way to build applications that promotes complete separation between business logic
and presentation. It is not specific to web applications, or Java, or J2EE (it predates all of these by many years), but
it can be applied to building J2EE web applications.

The “view” is the user interface, the screens that the end user of the application actually sees and interacts with. In
a J2EE web application, views are JSP files. For collecting user input, we have a JSP that generates an HTML page
that contains one or more HTML forms. For displaying output (like a report), we have a JSP generates an HTML
page that probably contains one or more HTML tables. Each of these is a view that is a way for the end user to
interact with the system, putting data in, and getting data out.

When the user clicks ‘Submit’ in an HTML form, the request (complete with all the form information) is sent to a
“controller”. In a J2EE web application, controllers are JavaBeans. The controller’s job is to take the data entered
by the user in the HTML form that the JSP generated and pass it to the “model”, which is a separate Java class that
contains actual business logic. The model does whatever it does for instance; store the user’s data in a database,
then returns some result back to the controller perhaps a new ID value from the database, or perhaps just a result
code saying “OK, I’m done”. The controller takes this value and figures out what the user needs to see next, and
presents the user with a new view for instance, a new JSP file that displays a confirmation that the data they entered
was successfully saved.

195/ADTU OLE
Advanced Java

This all sounds like a lot of work, and it is. But there is a point to architecting applications this way: flexibility. The
beauty of model-view-controller separation is that new views and controllers can be created independently of the
model. The model is a pure business logic which knows nothing of HTML forms or JSP pages. The model defines a
set of business functions that only ever get called by controllers, and the controllers act as proxies between the end
user (interacting with the view) and the business logic (encapsulated in the model). This means that we can add a
new view and its associated controller, and our model doesn’t know or care that there are now two different ways
for human beings to interact with the application.

For instance, in an application with complicated data entry screens, we could add a JSP that generated a quick-edit
form with default values instead of a longer, standard form. Both JSPs (the short form and the long form) could
use the same controller; default values could simply be stored in the HTML <form> as hidden input values, and
the controller would never know the difference. Or we could create a completely new interface that is a desktop
application in addition to a web application. The desktop application would have views implemented in some
interface-building tool, and have associated controllers for each screen. But these controllers would call the business
functions in the model, just like the controllers in the web application. This is called “code reuse”, specifically
“business logic reuse”, and it’s not just a myth: it really can happen, and the Model-View-Controller architecture
is one way to make it happen.

8.10 What is Struts?


Struts are a framework that promotes the use of the Model-View-Controller architecture for designing large scale
applications. The framework includes a set of custom tag libraries and their associated Java classes, along with
various utility classes. The most powerful aspect of the Struts framework is its support for creating and processing
web-based forms.

8.11 Struts Tags


Struts tags include the tags explained below:

8.11.1 Common Attributes


Almost all tags provided by the Struts framework use the following attributes:

Attribute Used for


id the name of a bean for temporary use by the tag

name the name of a pre-existing bean for use with the tag

property the property of the bean named in the name attribute for use with the tag

scope the scope to search for the bean named in the name attribute

8.11.2 Referencing Properties


Bean properties can be referenced in three different ways: simple, nested, or indexed. Shown here are examples for
referencing the properties each way:

Reference Method Example

<!-- uses [Link]() -->


simple
<bean:write name=”tutorial” property=”anAttribute”/>

<!-- uses [Link]().getAnotherAttribute() -->


nested
<bean:write name=”tutorial” property=”[Link]”/>

196/ADTU OLE
<!-- uses [Link](3) to access the -->
indexed <!-- fourth element of the someAttributes property array -->
<bean:write name=”tutorial” property=”someAttributes[3]”/>
<!-- uses [Link](2).getSomeMoreAttributes(1) -->
flavorful mix of methods
<bean:write name=”foo” property=”goo[2].someAttributes[1]”/>

8.11.3 Creating Beans


Beans are created by Java code or tags. Here, is an example of bean creation with Java code:

// Creating a Plumber bean in the request scope


Plumber aPlumber = new Plumber();
[Link](“plumber”, aPlumber);

Beans can be created with the <jsp:useBean></jsp:useBean> tag:

<!-- If we want to do <jsp:setProperty ...></jsp:setProperty> or -->


<!-- <jsp:getProperty ... ></jsp:getProperty> -->
<!-- we first need to do a <jsp:useBean ... ></jsp:useBean> -->
<jsp:useBean id=”aBean” scope=”session” class=”[Link]”>
creating/using a bean in session scope of type [Link]
</jsp:useBean>

Most useful is the creation of beans with Struts tags:

<!-- Constant string bean -->


<bean:define id=”greenBean” value=”Here is a new constant string bean; pun intended.”/>
<!-- Copying an already existent bean, frijole, to a new bean, lima -->
<bean:define id=”lima” name=”frijole”/>
<!-- Copying an already existent bean, while specifying the class -->
<bean:define id=”lima” name=”frijole” class=”[Link]”/>
<!-- Copying a bean property to a different scope -->
<bean:define id=”goo” name=”foo” property=”geeWhiz” scope=”request” toScope=”application”/>

8.11.4 Other Bean Tags


The Struts framework provides other tags for dealing with issues concerning copying cookies, request headers, JSP
implicitly defined objects, request parameters, web application resources, Struts configuration objects, and including
the dynamic response data from an action. These tags are not discussed here, but it is important to be aware of their
existence.

<bean:cookie ... >

<bean:header ... >

<bean:page ... >

197/ADTU OLE
Advanced Java

<bean:parameter ... >

<bean:header ... >

<bean:resource ... >

<bean:struts ... >

Bean Output
The <bean:message> and <bean:write> tags from the Struts framework will write bean and aplication resources
properties into the current HttpResponse object.

This tag allows locale specific messages to be displayed by looking up the message
in the application resources .properties file.

<!-- looks up the [Link] resource -->


<!-- and writes it to the HttpResponse object -->
<bean:message key=”[Link]”/>
<bean:message ... >
<!-- looks up the [Link] resource -->
<!-- and writes it to the HttpResponse object; -->
<!-- failing that, it writes the string -->
<!-- contained in the attribute arg0-->
<bean:message key=”[Link]” arg0=’Enter a name:’/>

This tag writes the string equivalent of the specified bean or bean property to the
current HttpResponse object.
<bean:write ... >
<!-- writes the value of [Link]().toString() -->
<!-- to the HttpResponse object -->
<bean:write name=”customer” property=”streetAddress”/>

8.11.5 Creating HTML Forms


Quite often information needs to be collected from a user and processed. Without the ability to collect user input,
a web application would be useless. In order to get the users information, an html form is used. User input can
come from several widgets, such as text fields, text boxes, check boxes, pop-up menus, and radio buttons. The data
corresponding to the user input is stored in an ActionForm class. A configuration file called [Link] is
used to define exactly how the user inputs are processed. The following diagram roughly depicts the use of Struts
for using forms.

198/ADTU OLE
Action Form Action

[Link]

JSP Page user-input data


JSP Page
with a Form

Fig. 8.3 Use of Struts for using forms


(Source: [Link]

The Struts html tags are used to generate the widgets in the html that will be used in gathering the user’s data. There
are also tags to create a form element, html body elements, links, images, and other common html elements as well
as displaying errors. Below are the tags provided by html section of the Struts framework and a short description
of each.

<html:base> Generates a <base> tag. This tag should be used inside of a <head> tag.

<html:button> Generates an <input type=”button”> tag. This tag should be used inside
a <form> element.

<html:cancel> Generates an <input type=”submit”> tag and causes the Action servlet not
to invoke its validate() method. This tag should be used inside a <form> element.

Wheat Wood Clay


<html:checkbox> Stone Ship
<html:checkbox> Generates an <input type=”checkbox”>. <html:multibox> Generates
<html:multibox> an <input type=”checkbox”>. “Checkedness” depends upon whether the property array
specified contains a corresponding value as the one specified for the multibox.

Generates html to display any errors that may have occurred during invocation of
<html:errors>
the validate() method.

<html:file>

<html:form> Generates <form>.

There is a hidden element here which is invisible. :-)


<html:hidden>
Generates <input type=”hidden”>.

<html:html> Generates <html>.

<html:image>

199/ADTU OLE
Advanced Java

Are you above

<html:img>

or below the cube?

A link to an external site


<html:link>
Generates an html link.

<html:password>
Generates <input type=”password”> for use in collecting information that should not
be shown on-screen.

<html:radio> Credit Debit


Generates a radio button (<input type=”radio”>).

<html:reset>
Generates <input type=”reset”>.
<html:rewrite>

<html:select>

<html:options>

<html:option>
<html:select> Generates <select>. <html:options> Generates html for an entire list
of <option> tags. <html:option> Generates a single <option>.

<html:submit>
Generates <input type=”submit”> to submit form data entered by the user.

Name
<html:text>
Email id:
Generates <input type=”text”>.

<html:textarea>

Generates <textarea>.

200/ADTU OLE
8.12 Generics
Generics have ability to write general or generic code which is independent of a particular type it is similar to the
template in C++ in concept, there are a number of differences. For one, unlike C++ where different classes are
generated for each parameterised type, in Java, there is only one class for each generic type, irrespective of how
many different types we instantiated it with. There are of course certain problems as well in Java Generics.

The work of Generics in Java originated from a project called GJ1 (Generic Java) which started out as a language
extension. This idea then went though the Java Community Process (JCP) as Java Specification Request (JSR)
142.

8.13 Generic Type-safety


Let’s start with the non-generic example we looked at to see how we can benefit from Generics. Let’s convert the
code above to use Generics. The modified code is shown below:

package [Link];
import [Link];
import [Link];
public class Test
{
public static void main(String[] args)
{
ArrayList<Integer> list = new ArrayList<Integer>();
populateNumbers(list);
int total = 0;
for(Integer val : list)
{
total = total + val;
}
[Link](total);
}
private static void populateNumbers(ArrayList<Integer> list)
{
[Link](new Integer(1));
[Link](new Integer(2));
[Link](“hello”);
}
}

We will use ArrayList<Integer> instead of the ArrayList. Now, if we compile the code, we will get a compilation
error:

[Link]: cannot find symbol


symbol : method add([Link])
location: class [Link]<[Link]>
[Link](“hello”);
^

1 error: The parameterised type of ArrayList provides the type-safety. “Making Java easier to type and easier to
type,” was the slogan of the generics contributors in Java.

201/ADTU OLE
Advanced Java

8.14 Naming Conventions


In order to avoid confusion between the generic parameters and real types in our code, we must follow a good naming
convention. If we are following good Java convention and software development practices, we would probably not
be naming our classes with single letters. We would also be using mixed case with class names starting with upper
case. Here are some conventions to use for generics:
• Use the letter E for collection elements, like in the definition public class PriorityQueue<E> {…}
• Use letters T, U, S, and so on for general types

8.15 Writing Generic Classes


The syntax for writing a generic class is pretty simple. Here is an example of a generic class:

package [Link];
public class Pair<E>
{
private E obj1;
private E obj2;
public Pair(E element1, E element2)
{
obj1 = element1;
obj2 = element2;
}
public E getFirstObject() { return obj1; }
public E getSecondObject() { return obj2; }
}
This class represents a pair of values of some generic type E. Let’s look at some examples
of usage of this class:
// Good usage
Pair<Double> aPair
= new Pair<Double>(new Double(1), new Double(2.2));

If we try to create an object with types that mismatch we will get a compilation error. For instance, consider the
following example:

// Wrong usage
Pair<Double> anotherPair = new Pair<Double>(new Integer(1), new Double(2.2));

Here, we are trying to send an instance of Integer and an instance of Double to the instance of Pair. However, this
will result in a compilation error.

202/ADTU OLE
8.16 Generics and Substitutability
Generics honour the Liskov’s Substitutability Principle4. Consider an example to understand it. Say I have a Basket
of Fruits. To it I can add Oranges, Bananas, Grapes, etc. Now, let’s create a Basket of Banana. To this, I should only
be able to add Bananas. It should disallow adding other types of fruits. Banana is a Fruit that is Banana inherits from
Fruit. Should Basket of Banana inherit from Basket for Fruits as shown in Figure below?

Fruit Basket-Of-Fruit

Banana Basket-Of-Banana

Fig. 8.4 Figure for given example


(Source: [Link]

If Basket of Banana were to inherit from Basket of Fruit, then we may get a reference of type Basket of Fruit to
refer to an instance of Basket of Banana. Then, using this reference, we may add a Banana to the basket, but we
may also add an Orange. While adding a Banana to a Basket of Banana is OK, adding an Orange is not. At best,
this will result in a runtime exception. However, the code that uses Basket of Fruits may not know how to handle
this. The Basket of Banana is not substitutable where a Basket of Fruits is used. Generics honour this principle.
Consider the example below:

Pair<Object> objectPair = new Pair<Integer>(new Integer(1), new Integer(2));

This code will produce a compile time error:

Error: line (9) incompatible types found :


[Link]<[Link]>
required: [Link]<[Link]>

Now, what if we want to treat different type of Pair commonly as one type? Another thing can happen is:

While
Pair<Object> objectPair = new Pair<Integer>(new Integer(1), new Integer(2));

is not allowed, the following is allowed, however:

Pair objectPair = new Pair<Integer>(new Integer(1), new Integer(2));

The Pair without any parameterised type is the non-generic form of the Pair class. Each generic class also has a non-
generic form so it can be accessed from a non-generic code. This allows for backward compatibility with existing
code or code that has not been ported to use generics. While this compatibility has a certain advantage, this feature
can lead to some confusion and also type-safety issues.

203/ADTU OLE
Advanced Java

8.17 Generic Methods


In addition to classes, methods may also be parameterised. Consider the following example:

public static <T> void filter(Collection<T> in, Collection<T> out)


{
boolean flag = true;
for(T obj : in)
{
if(flag)
{
[Link](obj);
}
flag = !flag;
}
}

The filter() method copies alternate elements from the in Collection to the out Collection. The <T> in front of the
void indicates that the method is a generic method with <T> being the parameterised type. Let’s look at a usage of
this generic method:

ArrayList<Integer> lst1 = new ArrayList<Integer>();


[Link](1);
[Link](2);
[Link](3);
ArrayList<Integer> lst2 = new ArrayList<Integer>();
filter(lst1, lst2);
[Link]([Link]());

We populate an ArrayList lst1 with three values and then filter (copy) its contents into another ArrayList lst2. The
size of the lst2 after the call to filter() method is 2. Now, let’s look at a slightly different call:

ArrayList<Double> dblLst = new ArrayList<Double>();


filter(lst1, dblLst);

Here we will get a compilation error:

Error:
line (34) <T>filter([Link]<T>,[Link]<T>)
in [Link] cannot be applied to
([Link]<[Link]>,
[Link]<[Link]>)
The error says that it can’t send ArrayList of different types to this method. This is
good. However, let’s try the following:
ArrayList<Integer> lst3 = new ArrayList<Integer>();
ArrayList lst = new ArrayList();
[Link](“hello”);
filter(lst, lst3);
[Link]([Link]());

204/ADTU OLE
Like it or not, this code compiles with no error and the call to [Link]() returns a 1. First, why did this compile
and what’s going on here? The compiler bends over its back to accommodate calls to generic methods, if possible.
In this case, by treating lst3 as a simple ArrayList, without any parameterised type that is, it is able to call the filter
method. Now, this can lead to some problems. Let’s add another statement to the example above. As we start typing,
the IDE (I am using IntelliJ IDEA) is helping me with code prompt as shown below:

It says that the call to the get() method takes an index and returns an Integer. Here is the completed code:

ArrayList<Integer> lst3 = new ArrayList<Integer>();


ArrayList lst = new ArrayList();
[Link](“hello”);
filter(lst, lst3);
[Link]([Link]());
[Link]([Link](0));

When we run this code it should give runtime exception but the fact is we get the following output for this code
segment:

1
hello

Why this is so? The answer is in what actually gets compiled. Even though code completion suggested that an
Integer is being returned, in reality the return type is Object. So, the String “hello” managed to get through without
any error. Now, what happens if we add the following code:

for(Integer val: lst3)


{
[Link](val);
}

Here, we are clearly asking for an Integer from the collection. This code will raise a ClassCastException. While
Generics are supposed to make our code type-safe, this example shows how we can easily, with intent or by mistake,
bypass that, and at best, end up with runtime exception, or at worst, have the code silently misbehave.

Upper Bounds
Let’s say we want to write a simple generic method to determine the max of two parameters. The method prototype
would look like this:

205/ADTU OLE
Advanced Java

public static <T> T max(T obj1, T obj2)

Use it as shown below:

[Link](max(new Integer(1), new Integer(2)));

Now, the question is how to complete the implementation of the max() method? Let’s
take a stab at this:

public static <T> T max(T obj1, T obj2)


{
if (obj1 > obj2) // ERROR
{
return obj1;
}
return obj2;
}

This will not work. The > operator is not defined on references. Now, how to compare the two objects? The Comparable
interface comes to mind. So, why not use the comparable interface to get our work done:

public static <T> T max(T obj1, T obj2)


{
// Not elegant code
Comparable c1 = (Comparable) obj1;
Comparable c2 = (Comparable) obj2;
if ([Link](c2) > 0)
{
return obj1;
}
return obj2;
}

While this code may work, there are two problems. First, it is ugly. Second, we have to consider the case where the
cast to Comparable fails. Since we are so heavily dependent on the type implementing this interface, why not ask
the compiler to enforce this. That is exactly what upper bounds do for us. Here is the code:

public static <T extends Comparable> T max(T obj1, T obj2)


{
if ([Link](obj2) > 0)
{
return obj1;
}
return obj2;
}

The compiler will check to make sure that the parameterised type given when calling this method implements the
Comparable interface. If we try to call max() with instances of some type that does not implement the Comparable
interface, we will get a stern compilation error.

206/ADTU OLE
Lets see few more interesting concepts with Generics. Let’s consider this example:

public abstract class Animal


{
public void playWith(Collection<Animal> playGroup)
{
}
}
public class Dog extends Animal
{
public void playWith(Collection<Animal> playGroup)
{
}
}

The Animal class has a playWith() method that accepts a Collection of Animals. The Dog, which extends Animal,
overrides this method. Let’s try to use the Dog class in an example:

Collection<Dog> dogs = new ArrayList<Dog>();


Dog aDog = new Dog();
[Link](dogs); //ERROR

Now create an instance of Dog and send a Collection of Dog to its playWith() method. We get a compilation
error:

Error: line (29) cannot find symbol method playWith([Link]<[Link]>)

This is because a Collection of Dogs can’t be treated as a Collection of Animals which the playWith() method
expects (see the section “Generics and Substitutability” above). However, it would make sense to be able to send a
Collection of Dogs to this method, isn’t it? How can we do that? This is where the wildcard or unknown type comes
in. We modify both the playMethod() methods (in Animal and Dog) as follows:

public void playWith(Collection<?> playGroup)

The Collection is not of type Animal. Instead it is of unknown type (?). Unknown type is not Object, it is just
unknown or unspecified. Now, the code

[Link](dogs);
compiles with no error.
There is a problem however. We can also write:
ArrayList<Integer> numbers = new ArrayList<Integer>();
[Link](numbers);

Make a change to allow a Collection of Dogs to be sent to the playWith() methodnow permits a Collection of Integers
to be sent as well. If we allow that it will become one weird dog. How can we say that the compiler should allow
Collections of Animal or Collections of any type that extends Animal, but not any Collections of other types? This
is made possible by the use of upper bounds as shown below:

207/ADTU OLE
Advanced Java

public void playWith(Collection<? extends Animal> playGroup)

One restriction of using wildcards is that we are allowed to get elements from a Collection<?>, but we can’t add
elements to such a collection the compiler has no idea what type it is dealing with.

Lower bounds
Let’s consider one final example. Assume we want to copy elements from one collection to another. Here is my
first attempt for a code to do that:

public static <T> void copy(Collection<T> from, Collection<T> to) {…}

Let’s try using this method:

ArrayList<Dog> dogList1 = new ArrayList<Dog>();


ArrayList<Dog> dogList2 = new ArrayList<Dog>();
//…
copy(dogList1, dogList2);

In this code we are copying Dogs from one Dog ArrayList to another. Since Dogs are Animals a Dog may be in
both a Dog’s ArrayList and an Animal’s ArrayList, isn’t it? So, here is the code to copy from a Dog’s ArrayList to
an Animal’s ArrayList.

ArrayList<Animal> animalList = new ArrayList<Animal>();


copy(dogList1, animalList);

This code, however, fails compilation with error:

Error:
line (36) <T>copy([Link]<T>,[Link]<T>)
in [Link] cannot be applied
to ([Link]<[Link]>,
[Link]<[Link]>)

How can we make this work? This is where the lower bounds come in. Our intent for the second argument of Copy
is for it to be of either type T or any type that is a base type of T. Here is the code:

public static <T> void copy(Collection<T> from,


Collection<? super T> to)

Here we are saying that the type accepted by the second collection is the same type as T is, or its super type.

208/ADTU OLE
Summary
• Hibernate is an Object-Relational Mapping (ORM) solution for JAVA. It is a powerful, high performance object/
relational persistence and query service.
• Hibernate uses the database specification from Hibernate Properties file.
• Hibernate is an open source (released under LPGL) product for providing seamless persistence for Java
objects.
• A mapping property or configuration file is used to generate database schema and provide persistence.
• The Session acts as an agent between the application and the data store.
• A Query class allows us to manage our queries and allows for parameterised queries as well.
• Hibernate provides highly efficient transparent persistence for Java objects. It leaves behind a very small
footprint; has low resource requirements.
• Hibernate is flexible and powerful ORM solution to map Java classes to database tables.
• The automatic mapping of Java objects with database tables and vice versa is called Transparent Persistence.
• JDBC supports only native Structured Query Language (SQL).
• With JDBC, it is developer’s responsibility to handle JDBC result set and convert it to
• Caching is retention of data, usually in application to reduce disk access.
• “Model-View-Controller” is a way to build applications that promotes complete separation between business
logic and presentation.
• Struts are a framework that promotes the use of the Model-View-Controller architecture for designing large
scale applications.
• User input can come from several widgets, such as text fields, text boxes, check boxes, pop-up menus, and
radio buttons.
• The Struts html tags are used to generate the widgets in the html that will be used in gathering the user’s data.
• Generics have ability to write general or generic code which is independent of a particular type it is similar to
the template in C++.
• The work of Generics in Java originated from a project called GJ1 (Generic Java) which started out as a language
extension.

References
• Minter, D. & Linwood, J., Beginning Hibernate, 2nd ed. Apress Publication.
• Holmes, 2007. Struts: The Complete Reference, Tata McGraw-Hill Education Publication.
• masslight, Introduction to Struts, [Online] Available at: <[Link] [Accessed
12 April 2012].
• Suez, E., Hibernate by Example, [Online] Available at: <[Link]
[Link]> [Accessed 12 April 2012].
• 2010. Java Hibernate Tutorial Part 1 – setup, [Video Online] Available at: <[Link]
watch?v=GINvxAaXDbY> [Accessed 12 April 2012].
• 2011. Learn Java Struts from the Introduction to Struts course from [Link], [Video Online] Available
at: <[Link] [Accessed 12 April 2012].

Recommended Reading
• Iverson, W., 2005. Hibernate: A J2ee Developer’s Guide, Addison-Wesley Publication.
• Elliott, J., 2008. Getting Started with Hibernate 3, O’Reilly Media, Inc. Publication.
• Siggelkow, B., 2005. Jakarta Struts cookbook, O’Reilly Media Publication.

209/ADTU OLE
Advanced Java

Self Assessment
1. __________ is an open source product for providing seamless persistence for Java objects.
a. Hibernate
b. Struts
c. Javabeans
d. Hibernate Query Language

2. __________is a way to build applications that promotes complete separation between business logic and
presentation.
a. Model-View-Controller
b. Hibernate Query Language
c. Structured Query Language
d. Hibernate

3. Which of the following does not refer the bean property?


a. Simple
b. Nested
c. Indexed
d. Compound

4. _________have ability to write general or generic code which is independent of a particular type.
a. JSP
b. JSR
c. Generics
d. Delegates

5. A configuration file called ____________is used to define exactly how the user inputs are processed.
a. <bean:struts ... >
b. [Link]
c. [Link]-xml
d. [Link]

6. __________are a framework that promotes the use of the Model-View-Controller architecture for designing
large scale applications.
a. Hibernate
b. J2EE
c. JDBC
d. Struts

7. Mapping between tables and application objects is done in _______files.


a. HTML
b. XML
c. SHTML
d. JDBC

210/ADTU OLE
8. The ________ acts as an agent between the application and the data store.
a. Transaction
b. Session
c. Session Factory
d. Session form

9. ______ uses byte code enhancement while _____ uses runtime reflection to determine persistent properties of
classes.
a. JDBC, Hibernate
b. Struts, JDO
c. JDO, Hibernate
d. Hibernate, Struts

10. _________ provides a rich query language to access objects, provide caching and JMX support.
a. JDO
b. Struts
c. ODBC
d. Hibernate

211/ADTU OLE
Advanced Java

Application I
Login Application Using Action Form (Struts)

In this example we will see how to create a login application using ActionForm. The following files are required
for the login application.
• [Link]
• [Link]
• [Link]
• [Link]
• [Link]
• [Link]
• [Link]
• [Link]

[Link]
The first page that will be called in the login application is the [Link] page. This configuration should be done in
[Link] as shown below.

[Link]
We use Struts HTML Tags to create login page. The form has one text field to get the user name and one password
field to get the password. The form also has one submit button, which when clicked calls the login action. <html:errors
/> tag is used to display the error messages to the user.

The user enters the user name and password and clicks the login button. The login action is invoked.

[Link]
The validate method in the LoginForm class is called when the Form is submitted. If any errors are found then the
control is returned back to the input page where the errors are displayed to the user. The input page is configured in
the action tag of strut-config file. <html:errors /> tag is used to display the errors in the jsp page.

212/ADTU OLE
Here, the action is “/Login”, the input page is “[Link]” and the corresponding action class is [Link].
Now the validate method in the LoginForm class will be invoked.
[Link]

Inside the validate method, we check whether the user name and password is entered. If not the corresponding error
message is displayed to the user. The error messages are configured in the [Link] file.

[Link]
The [Link] file contains the error messages. The key “[Link]” is used in
the validate function to add a new error. Since the error messages are configured in a separate properties file they
can be changed anytime without making any changes to the java files or the jsp pages.

If either user name or password is not entered then the corresponding error message will be added to the ActionErrors.
If any errors are found then the control is returned back to the input jsp page, where the error messages are displayed
using the <html:errors /> tag. The validate method is used to perform the client-side validations. Once when the
input data is valid the execute method in the LoginAction class is called.

[Link]
The execute method contains the business logic of the application. Here first we typecast the ActionForm object
to LoginForm, so that we can access the form variables using the getter and setter methods. If the user name and
password is same then we forward the user to the success page else we forward to the failure page.

213/ADTU OLE
Advanced Java

Let’s enter the user names and password as “Eswar”. Since the user name and password is same the execute method
will return an ActionForward “success”. The corresponding result associated with the name “success” will be shown
to the user. This configuration is done in [Link] file.

So according to the configuration in [Link] the user will be forwarded to [Link] page.

214/ADTU OLE
If the user name and password did not match the user will be forwarded to the failure page. Lets try entering “Joe”
as the user name and “Eswar” as the password, the following page will be displayed to the user.

(Source: Login Application Using Action Form, [Online] Available at: <[Link]
example/[Link]> [Accessed 12 April 2012]).

Questions
1. Which are the files used in this application?
Answer
Following files are being used in this application
‚‚ [Link]
‚‚ [Link]
‚‚ [Link]
‚‚ [Link]
‚‚ [Link]

215/ADTU OLE
Advanced Java

‚‚ [Link]
‚‚ [Link]
‚‚ [Link]

2. Which are the two methods with which we can access the form variables?
Answer
The two methods to access the form variables are getter and setter method.

3. Which tags are used in this application to create login page?


Answer
Struts HTML Tags are used here to create login application form

216/ADTU OLE
Application II
Example Using Struts

We are building an application using struts with the following conditions.


1. Define and create all of the Views, in relation to their purpose, that will represent the user interface of our
application. Add all ActionForms used by the created Views to the [Link] file.
2. Create the components of the application’s Controller.
3. Define the relationships that exist between the Views and the Controllers ([Link]).
4. Make the appropriate modifications to the [Link] file, describe the Struts components to the Web
application.

Lets Start with step one. we will create the view file named [Link] [Link]

<%@ page language=”java” %>


<%@ taglib uri=”/WEB-INF/[Link]” prefix=”html” %>
<html>
<head>
<title>Sample Struts Application</title>
</head>
<body>
<html:form action=”Name” name=”nameForm” type=”[Link]”>
<table width=”80%” border=”0”>
<tr>
<td>Name:</td>
<td><html:text property=”name” /></td>
</tr>
<tr>
<td><html:submit /></td>
</tr>
</table>
</html:form>
</body>
</html>

We have used some Struts-specific Form tag like <html:form /> instead of HTML tags.

In the Form tags the attributes we can find some attributes defined in we will go through it.

action: Represents the URL to which this form will be submitted. This attribute is also used to find the appropriate
ActionMapping in the Struts configuration file, which we will describe later in this section. The value used in our
example is Name, which will map to an ActionMapping with a path attribute equal to Name.

name: Identifies the key that the ActionForm will be referenced by. We use the value NameForm. An ActionForm
is an object that is used by Struts to represent the form data as a JavaBean. It main purpose is to pass form data
between View and Controller components. We will discuss NameForm later in this section.

type:Names the fully qualified class name of the form bean to use in this request. For this example, we use thevalue
[Link], which is an ActionForm object containing data members matching the inputs of this form.

217/ADTU OLE
Advanced Java

To use the HTML tags, you must first add a taglib entry in the application’s [Link] file that references the URI /
WEB-INF/[Link]. This TLD describes all of the tags in the HTML tag library. The following snippet shows
the <taglib> element that must be added to the [Link] file:

<taglib>
<taglib-uri>/WEB-INF/[Link]</taglib-uri>
<taglib-location>/WEB-INF/[Link]</taglib-location>
</taglib>

The [Link] is placed in the /WEB_INF directory.

Next Step is to create the action form

The ActionForm used in this example contains a single data member that maps directly to the name input parameter
of the form defined in the [Link] View. When an <html:form/> is submitted, the Struts framework populates the
matching data members of the ActionForm with the values entered into the <html:input/> tags. The Struts framework
does this by using JavaBean reflection. The accessors of the ActionForm must follow the JavaBean standard naming
convention for example

private String name;


public void setName(String name);
public String getName();

The [Link] file is shown below

[Link]

package example;
//import statements
import [Link];
import [Link];
import [Link];
public class NameForm extends ActionForm {
private String name = null;
public String getName() {
return (name);
}
public void setName(String name) {
[Link] = name;
}
public void reset(ActionMapping mapping, HttpServletRequest request) {
[Link] = null;
}
}

To deploy the NameForm to our Struts application, we need to compile this class, move it to the /WEB-INF/classes/
example directory, and add the following line to the <form-beans> section of the /WEB-INF/[Link]
file:

<form-bean name=”nameForm” type=”[Link]”/>

218/ADTU OLE
This makes the Struts application aware of the NameForm and how it should be referenced.

Now we create the out page for the sample application.


Lets name it [Link]

[Link]
<html>
<head>
<title>Sample Struts Display Name</title>
</head>
<body>
<table width=”80%” border=”0”>
<tr>
<td>Hello <%= [Link](“NAME”) %> !!</td>
</tr>
</table>
</body>
</html>

Now, we move to the step two of creating the application’s controller

In a Struts application, two components make up the Controller. These two components are the [Link].
[Link] and the [Link]. [Link] classes. In most Struts applications, there is
one org. [Link] implementation and can have many [Link]. [Link]
implementations.

The [Link] is the Controller component that handles client requests and determines
which [Link] will process the received request. When assembling simple applications, such
as the one we are building, the default ActionServlet will satisfy your application needs, and therefore, you do not
need to create a specialized [Link] implementation.

The second component of a Struts Controller is the [Link]. [Link] class. As opposed to the
ActionServlet, the Action class must be extended for each specialized function in your application. This class is
where your application’s specific logic begins.
[Link]

219/ADTU OLE
Advanced Java

package example;
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
public class NameAction extends Action {
public ActionForward execute(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException {
String target = new String(“success”);
if ( form != null ) {
// Use the NameForm to get the request parameters
NameForm nameForm = (NameForm)form;
String name = [Link]();
}
// if no mane supplied Set the target to failure
if ( name == null ) {
target = new String(“failure”);
}
else {
[Link](“NAME”, name);
}
return ([Link](target));
}
}

Moving to step three, to deploy the NameAction to our Struts application, we need to compile the NameAction
class and move the class file to /WEB-INF/classes/example directory, and add the following entry to the <action-
mappings> section of the /WEB-INF/[Link] file:
<action path=”/Name” type=”[Link]” name=”nameForm” input=”/[Link]”>
<forward name=”success” path=”/[Link]”/>
<forward name=”failure” path=”/[Link]”/>
</action>

For step four we modify the [Link] file. We have to to tell the Web application about our ActionServlet. This is
accomplished by adding the following servlet definition to the /WEB-INF/[Link] file:

<servlet>
<servlet-name>action</servlet-name>
<servlet-class> [Link] </servlet-class>
<init-param>
<param-name>config</param-name>
<param-value>/WEB-INF/[Link]</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>

220/ADTU OLE
Once we have told the container about the ActionServlet, we need to tell it when the action should be executed. To
do this, we have to add a <servlet-mapping> element to the /WEB-INF/ [Link] file:
<servlet-mapping>
<servlet-name>action</servlet-name>
<url-pattern>*.do</url-pattern>
</servlet-mapping>

You will notice in the previously listed [Link] that our action does not include a .do at the end of the URL. We
do not have to append the .do because it is automatically appended if we use the <html:form /> tag. If you do
not use the <html:form /> tag, then you will need to append .do to the action’s URL. This mapping tells the Web
application that whenever a request is received with .do appended to the URL, the servlet named action should
service the request.

Now the application is ready to run, to begin using this application, we need to open our Web browser to the following
URL: [Link]

(Source: Struts Example, [Online] Available at: <[Link] [Accessed


12 April 2012]).

Questions
1. Write the actions the above program performs?
2. Write a note on name tag.
3. Which are the components of Struts Controller?

221/ADTU OLE
Advanced Java

Application III
Mulitthreaded Chat Application in Java

This is the server and the client program thatI wrote basically it gives u a good understanding of how sockets work
in java Author:

Code:
/*************Start program
Server************************************************/
/*This is the server for the MultiThreadedChatClient program thatI
wrote
basically it
gives u a good understanding of how sockets work in java
Author: Mohammed Alfaaz
email:alfaaz@[Link]
*/
import [Link].*;
import [Link].*;

public class MultiThreadChatServer{

// Declaration section:
// declare a server socket and a client socket for the server
// declare an input and an output stream

static Socket clientSocket = null;


static ServerSocket serverSocket = null;

// This chat server can accept up to 10 clients’ connections

static clientThread t[] = new clientThread[10];

public static void main(String args[]) {

// The default port

int port_number=8888;

if ([Link] < 1)
{
[Link](“Usage: java MultiThreadChatServer <BR>+
“Now using port number=”+port_number);
} else {
port_number=[Link](args[0]).intValue();
}

// Initialization section:
// Try to open a server socket on port port_number (default 8888)
// Note that we can’t choose a port less than 1023 if we are not
// privileged users (root)

try {

222/ADTU OLE
serverSocket = new ServerSocket(port_number);
}//try
catch (IOException e)
{[Link](e);}

// Create a socket object from the ServerSocket to listen and accept


// connections.
// Open input and output streams for this socket will be created in
// client’s thread since every client is served by the server in
// an individual thread

//can use a for loop to control the number of clients


//I have used the while so that we can have unlimited number of clients
while(true){
try {
clientSocket = [Link]();
new clientThread(clientSocket,t).start();
break;
}//try

catch (IOException e){


[Link](e);}
}
}
} //class

// This client thread opens the input and the output streams for a
particular client,
// ask the client’s name, informs all the clients currently connected
to
the
// server about the fact that a new client has joined the chat room,
// and as long as it receive data, echos that data back to all other
clients.
// When the client leaves the chat room this thread informs also all
the
// clients about that and terminates.

class clientThread extends Thread{

DataInputStream is = null;
PrintStream os = null;
Socket clientSocket = null;
clientThread t[];

public clientThread(Socket clientSocket, clientThread[] t){


[Link]=clientSocket;
this.t=t;
}

public void run()


{
String line;

223/ADTU OLE
Advanced Java

String name;
try{
is = new DataInputStream([Link]());
os = new PrintStream([Link]());
[Link](“Enter your name.”);
name = [Link]();
[Link](“Hello “+name+” to our chat room.
To leave enter /quit
in
a new line”);
for(int i=0; i<=9; i++)
if (t[i]!=null && t[i]!=this)
t[i].[Link](“*** A new user “+name+” entered the chat room
!!!
***” );
while (true) {
line = [Link]();
if([Link](“/quit”)) break;
for(int i=0; i<=9; i++)
if (t[i]!=null) t[i].[Link](“<”+name+”> “+line);
}
for(int i=0; i<=9; i++)
if (t[i]!=null && t[i]!=this)
t[i].[Link](“*** The user “+name+” is leaving the chat room
!!!
***” );

[Link](“*** Bye “+name+” ***”);

// Clean up:
// Set to null the current thread variable such that other client
could
// be accepted by the server

for(int i=0; i<=9; i++)


if (t[i]==this) t[i]=null;

// close the output stream


// close the input stream
// close the socket

[Link]();
[Link]();
[Link]();
}
catch(IOException e){};
}
}

/*************End program
Server************************************************/

224/ADTU OLE
/***********************Start Client
program************************************/

/*This is the client for the MultiThreadedChatServer program thatI


wrote
basically it
gives u a good understanding of how sockets work in java
Author: Mohammed Alfaaz
email:alfaaz@[Link]

*/

import [Link].*;
import [Link].*;

public class MultiThreadChatClient implements Runnable{

// Declaration section
// clientClient: the client socket
// os: the output stream
// is: the input stream

static Socket clientSocket = null;


static PrintStream os = null;
static DataInputStream is = null;
static BufferedReader inputLine = null;
static boolean closed = false;

public static void main(String[] args) {

// The default port

int port_number=8888;
String host=”localhost”;

if ([Link] < 2)
{
[Link](“Usage: java MultiThreadChatClient <BR>+
“Now using host=”+host+”, port_number=”+port_number);
} else {
host=args[0];
port_number=[Link](args[1]).intValue();
}
// Initialization section:
// Try to open a socket on a given host and port
// Try to open input and output streams
try {
clientSocket = new Socket(host, port_number);
inputLine = new BufferedReader(new
InputStreamReader([Link]));
os = new PrintStream([Link]());
is = new DataInputStream([Link]());
} catch (UnknownHostException e) {

225/ADTU OLE
Advanced Java

[Link](“Don’t know about host “+host);


} catch (IOException e) {
[Link](“Couldn’t get I/O for the connection to
the
host “+host);
}

// If everything has been initialized then we want to write some data


// to the socket we have opened a connection to on port port_number

if (clientSocket != null && os != null && is != null) {


try {

// Create a thread to read from the server

new Thread(new MultiThreadChatClient()).start();

while (!closed) {
[Link]([Link]());
}

// Clean up:
// close the output stream
// close the input stream
// close the socket

[Link]();
[Link]();
[Link]();
} catch (IOException e) {
[Link](“IOException: “ + e);
}
}
}

public void run() {


String responseLine;

// Keep on reading from the socket till we receive the “Bye” from the
server,
// once we received that then we want to break.
try{
while ((responseLine = [Link]()) != null) {
[Link](responseLine);
if ([Link](“*** Bye”) != -1) break;
}
closed=true;
} catch (IOException e) {
[Link](“IOException: “ + e);
}
}
}

226/ADTU OLE
/***********************End Client
program************************************/

(Source: Mulitthreaded chat application in java, [Online] Available at: <[Link]


multithreading/[Link]> [Accessed 12 April 2012]).

Questions
1. Write a program for online bus booking.
2. Write a code for an application form of college.
3. Create a simple web browser.

227/ADTU OLE
Advanced Java

Bibliography
References
• 2007. Java 6 Programming Black Book, New Ed, Dreamtech Press.
• 2009. Java Servlet Definition, [Video Online] Available at: <[Link]
[Accessed 12 April 2012].
• 2009. JSP (Java Server pages) video tutorial [Video Online] Available at: <[Link]
watch?v=6MV6dfLZ0Ts> [Accessed 12 April 2012].
• 2010. Enterprise Java Beans - Introduction [Video Online] Available at: <[Link]
wSY8joz20&feature=results_main&playnext=1&list=PLEFB2BACD4935A80F> [Accessed 12 April 2012].
• 2010. Java beans, [Video Online] Available at: <[Link] [Accessed
12 April 2012].
• 2010. Java Hibernate Tutorial Part 1 – setup, [Video Online] Available at: <[Link]
watch?v=GINvxAaXDbY> [Accessed 12 April 2012].
• 2010. Java server pages (JSP) [Video Online] Available at: <[Link]
Y&feature=related> [Accessed 12 April 2012].
• 2010. Java Servlets, [Video Online] Available at: <[Link] [Accessed
12 April 2012].
• 2011. Learn Java Struts from the Introduction to Struts course from [Link], [Video Online] Available
at: <[Link] [Accessed 12 April 2012].
• 2012. Java - JDBC Databases - GUI and SQL Statements - 3 of 3, [Video Online] Available at: < [Link]
[Link]/watch?v=Of4LRHOZoII> [Accessed 10 April 2012].
• A Servlet and JSP Tutorial, [Online] Available at: < [Link] >
[Accessed 12 April 2012].
• Abernethy, M., 2005. Introduction to Swing, [Online] Available at: <[Link]
[Link]> [Accessed 10 April 2012].
• Advanced Java Programming with Database Application, Manonaniam Sundaranar University [Online] Available
at: <[Link] [Accessed 10 April
2012].
• Advanced Java Programming with Database Application,[Online] Available at: <[Link]
[Link]> [Accessed 11 April 2012].
• Bai, Y., 2011. Practical Database Programming with Java, John Wiley & Sons Publication.
• Bollinger, G. & Natarajan, B., 2001. JSP: A beginner’s guide, Osborne/McGraw-Hill Publication.
• Cornell, G. and Horstman S. C., 2011. Core Java 2: Fundamentals, 5th ed. Prentice Hall Professional.
• Crawford, W. and Hunter, J., 2001. Java servlet programming, 2nd ed. O’Reilly Media, Inc. Publication.
• Database Connectivity ODBC, JDBC and SQLJ, [Online] Available at: <[Link]
Teaching/cs2312/Lectures/Handouts/[Link]> [Accessed 11 April 2012].
• Eckstein, R. and Loy, M., 2002. Java Swing, 2nd ed. O’Reilly Media, Inc. Publication.
• Eisenberg, A. and Melton, J., 2000. Understanding SQL and Java Together: A Guide to Sqlj, Jdbc, and Related
Technologies, Morgan Kaufmann Publication.
• Englander, R., 1997. Developing Java Beans, O’Reilly Media, Inc. Publication.
• Fletcher, J., AWT vs SWING, [Online] Available at: <[Link]
EMBARCADERO DEVELOPER NETWORK [Accessed 10 April 2012].
• Geary, M., D. & Microsystems, S., 2001. Advanced JavaServer pages, Prentice Hall PTR Publication.
• Goetz, B., 2002. Introduction to Java threads, [Online] Available at: <[Link]
java/tutorials/j-threads/[Link]> [Accessed 10 April 2012].

228/ADTU OLE
• Gupta, G., 2006. Advanced Java, Laxmi Publications.
• Haefel, M., E. & Burke, B., 2006. Enterprise JavaBeans 3.0, 5th ed. O’Reilly Media, Inc. Publication.
• Holmes, 2007. Struts: The Complete Reference, Tata McGraw-Hill Education Publication.
• Introduction to Struts, [Online] Available at: <[Link] [Accessed 12 April
2012].
• java9s, 2010. Introduction to OOP and Java Programming for Beginners Part 1 [Video Online] Available at:
<[Link] [Accessed 10 April 2012].
• JavaBeans, JavaBean as a Software Component Model, [Online] Available at: <[Link]
javase/[Link]> [Accessed 12 April 2012].
• jldavis007, 2009. A Brief History of Java and JDBC, [Video Online] Available at: <[Link]
watch?v=WAy9mgEYb6o&feature=related> [Accessed 10 April 2012].
• John, 2012. Advanced Java: Swing (GUI) Programming Part 2 -- Adding Components, [Video Online] Available
at: <[Link] > [Accessed 10 April 2012].
• John, 2012. Advanced Java: Swing (GUI) Programming Part 4 – GridBagLayout, [Video Online] Available at:
<[Link]
257751F> [Accessed 10 April 2012].
• JSP Tutorial, [Online] Available at: < [Link] > [Accessed 12 April 2012].
• Liang D. Y., 2012. Introduction to Java Programming, Brief Version, 9th ed. Pearson Education, Limited.
• Minter, D. & Linwood, J., Beginning Hibernate, 2nd ed. Apress Publication.
• ORACLE’ Sun Developer Network (SDN), Chapter 4 Continued: Servlets, [Online] Available at: <[Link]
[Link]/developer/onlineTraining/Programming/JDCBook/[Link]> [Accessed 11 April 2012].
• Perry, W., B., 2004. Java servlet and JSP cookbook, O’Reilly Media, Inc Publication.
• Suez, E., Hibernate by Example [Online] Available at: <[Link]
[Link] > [Accessed 12 April 2012].
• superboysales, 2010. Java swings and awt, [Video Online] Available at: <[Link]
M47Ggc4&feature=results_main&playnext=1&list=PL91DBCBD1A8242D8A> [Accessed 10 April 2012].
• TheSynergetics, Java database connectivity - JDBC Module 20, [video Online] Available at: < [Link]
[Link]/watch?v=-hz8TGEQULc> [Accessed 10 April 2012].
• Thomas, M. T., 2002. Java data access: JDBC, JNDI, and JAXP, M&T Books Publication.
• Tutorial 12 – Advanced Swing, [Online] Available at: <[Link] [Accessed
10 April 2012].
• Voss, G., Java Beans: Introducing Java Beans, [Online] Available at: <[Link]
onlineTraining/Beans/Beans1/> [Accessed 12 April 2012].
• Wahli, U., Fielding, M., Mackown, G., Shaddon D. and Hekkenberg, G., Servlet and JSP Programming, [pdf]
Available at: <[Link] [Accessed 11 April 2012].
• Wong, H. and Oaks, S., 2004. Java threads, 3rd ed. O’Reilly Media, Inc Publication.
• XsysIEEE, 2011. JDBC with SQL Server, [Video Online] Available at: <[Link]
wU86ucczUY&feature=related> [Accessed 10 April 2012].

Recommended Reading
• Anderson, P. & Anderson, G., 2002. Enterprise JavaBeans Component Architecture: Designing and Coding
Enterprise Applications, Prentice Hall Professional Publication.
• Bates, B. and Sierra, K., 2005. Head First Java, 2nd ed. O’Reilly Media, Inc. Publication.
• Berge, J. C., 2000. Advanced Java 2: Development for Enterprise Applications, 2nd ed. Sun Microsystems
Press Publication.
• Bharat, V. and Wehling, J., 1996. Late night advanced Java, Ziff-Davis Press Publication.

229/ADTU OLE
Advanced Java

• Brunner, J. R., 2003. Jsp: Practical Guide for Java Programmers, Elsevier Publication.
• Buyya, 2009. Object Oriented Prog With Java, Tata McGraw-Hill Education Publication.
• Callaway, Inside Servlets, Pearson Education India Publication.
• Elliott, J., 2008. Getting Started with Hibernate 3, O’Reilly Media, Inc. Publication.
• Farley, J., Crawford, W., Malani, P., Norman, J. & Gehtland, J., 2005. Java Enterprise in a Nutshell, 3rd ed.
O’Reilly Media, Inc. Publication.
• Haecke, V. B., 2002. Jdbc 3.0: Java Database Connectivity, John Wiley & Sons Publication.
• Hall, 2008. Core Servlets And Javaserver Pages,Vol 2: Advanced Technologies, 2/E, Pearson Education India
Publication.
• Horstmann, 2008. Core Java, Volume 2-Advanced Features, 8/E, Pearson Education India Publication.
• Horton, I., 2005. Ivor Horton’s Beginning Java 2: JDK, 5th ed, John Wiley & Sons Publication.
• Iverson, W., 2005. Hibernate: A J2ee Developer’s Guide, Addison-Wesley Publication.
• Matena, V., Krishnan, S. & Strearns, B., 2003. Applying Enterprise JavaBeans: Component-Based Development
for the J2EE Platform, 2nd ed. Addison-Wesley Professional Publication.
• McManus, A. & Hunt, J., 1998. Key Java: Advanced Tips and Techniques, Springer Publication.
• Ruvalcaba, Z. & Pizzi, M., 2003. Macromedia Dreamweaver Mx Unleashed, Sams Publication.
• Shaw, P., Java threads FAQ, One Percent Better Publication.
• Siggelkow, B., 2005. Jakarta Struts cookbook, O’Reilly Media Publication.
• Speegle, D. G., 2001. Jdbc: Practical Guide for Java Programmers, Morgan Kaufmann publication.
• Steflik, D. & Sridharan, P., 2000. Advanced Java Networking, 2nd ed. Prentice Hall Professional Publication.
• Topley, K., 2000. Core Swing: Advanced Programming, Prentice Hall Professional Publication.
• Valesky, Enterprise Java Beans, Pearson Education India Publication.
• Zukowski, J., 2005. The Definitive Guide To Java Swing, 3rd ed. Apress Publication.

230/ADTU OLE
Self Assessment Answers
Chapter I
1. b
2. a
3. c
4. d
5. a
6. b
7. a
8. c
9. b
10. c

Chapter II
1. a
2. b
3. d
4. c
5. d
6. a
7. b
8. c
9. b
10. a

Chapter III
1. a
2. b
3. c
4. b
5. a
6. d
7. b
8. c
9. d
10. a

Chapter IV
1. d
2. a
3. b
4. c
5. a
6. d
7. a
8. b
9. c
10. d

231/ADTU OLE
Advanced Java

Chapter V
1. a
2. a
3. d
4. b
5. c
6. b
7. d
8. a
9. b
10. b

Chapter VI
1. c
2. a
3. c
4. b
5. d
6. a
7. b
8. a
9. d
10. c

Chapter VII
1. a
2. b
3. c
4. d
5. a
6. b
7. c
8. a
9. a
10. b

Chapter VIII
1. a
2. a
3. d
4. c
5. d
6. d
7. b
8. b
9. c
10. d

232/ADTU OLE

You might also like