KEMBAR78
Web design and development cs506 handouts | PDF
Web Design & Development – CS506 VU 
© Copyright Virtual University of Pakistan 1 
Table of Contents 
Chapter No.1 Java Fratures 12 
1.1 Designing Goals of Java 12 
1.2 Right Language, Right Time 12 
1.3 Java Buzzwords 12 
1.4 Java Language + Libraries 12 
1.5 Simple 12 
1.6 Object Oriented 13 
1.7 Distributed/Network Oriented 13 
1.8 Robust/Secure/Safe 13 
1.9 Portable 14 
1.10 Support for Web & Enterprise Web Applications 14 
1.11 High Performance 14 
1.12 Multi Threaded 14 
1.13 Dynamic 14 
1.14 Java Compiler Structure 14 
1.15 Java Programmer Efficiency 15 
1.16 OOP 15 
1.17 Libraries 15 
1.18 Microsoft vs. Java 15 
Chapter No.2 Java Virtual Machine & Runtime Enviornment 16 
2.1 Basic Concepts 16 
2.2 Byte Code 17 
2.3 Java Virtual Machine (JVM) 17 
2.4 Java Runtime Environment (JRE) 18 
2.5 2.5.1 Edit 20 
Java Program Development and Execution Steps 19 
2.5.2 Compile 20 
2.5.3 Loading 20 
2.5.4 Verify 21 
2.2.5 Execute 21 
2.6 Installation & Environment Setting 22 
2.6.1 Installation 22 
2.6.2 Environment Setting 22 
2.7 First Program in Java 26 
2.8 HelloWorldApp 26 
2.9 HelloWorldApp Description 27 
2.10 Compiling & Running HelloWorldApp 28 2.11 Points to Remember 28 
2.12 An Idiom Explained 29 
Chapter No.3 Learning Basics 30 
3.1 Strings 30 
3.1.1 String Concatenation 30 
3.1.2 Comparing Strings 30 
3.2 Command Line Arguments 32 
3.3 Primitives vs. Objects 34 
3.4 Stack vs. Heap 34
Web Design & Development – CS506 VU 
© Copyright Virtual University of Pakistan 2 
3.5 Wrapper Classes 35 
3.6 Wrapper Use 35 
3.7 Converting String to Numeric Primitive Data Types 35 
3.8 Input/Output Example 37 
3.9 Selection & Control Structure 38 
Chapter No.4 Object Oriented Programming 40 
4.1 OOP Vocabulary Review 40 
4.1.1 Class 40 
4.1.2 Object 40 
4.1.3 Constructor 40 
4.1.4 Attributes 40 
4.1.5 Methods 40 
4.2 Defining a Class 41 
4.3 Comparison with C++ 41 
4.4 Defining a Student Class 43 
4.5 Getters/Setters 43 
4.6 Using a Class 45 
4.7 Static 47 
4.8 Garbage Collection & Finalize 47 
Chapter No.5 Inheritance 52 
5.1 Comparison with C++ 52 
5.2 Object (Root Class) 56 
5.3 Polymorphism 57 
5.4 Type Casting 59 
5.4.1 Up-Casting 59 
5.4.2 Down-Casting 59 
Chapter No.6 Collections 60 
6.1 Collection Design 60 
6.2 Collection Messages 60 
6.3 ArrayList 61 
6.3.1 Useful Methods 61 
6.4 HashMap 62 
6.4.1 Useful Methods 62 
6.5 Address Book 65 
6.5.1 Problem 65 
6.5.2 Approach for Solving Problem 65 
Chapter No.7 Intro to Exceptions 70 
7.1 Types of Errors 70 
7.1.1 Syntax Errors 70 
7.1.2 Logical Errors 70 
7.3.1 Runtime Errors 70 
7.2 What is an Exception? 70 
7.3 Why Handle Exceptions? 70 
7.4 Exceptions in Java 71 
7.5 Exceptions Hierarchy 71 
7.5 Types of Exceptions 72
Web Design & Development – CS506 VU 
© Copyright Virtual University of Pakistan 3 
7.5.1 Unchecked Exceptions 72 
7.5.2 Checked Exceptions 72 
7.6 How Java Handles exceptions 72 
7.6.1 try Block 72 
7.6.2 catch block 72 
7.6.3 finally block 72 
7.6.4 throw 74 
7.6.5 throws 74 
7.7 Examples of Unchecked Exceptions 75 
7.8 Examples of Checked Exceptions 77 
7.9 The finally Block 79 
7.10 Multiple catch blocks 80 
7.11 The throws clause 82 
7.12 printStackTrace Method 83 
Chapter No.8 Streams 85 
8.1 The Concept of Streams 85 
8.2 Types of Systems 86 
8.3 Stream Classification Based on Functionality 86 
8.4 Example of Reading from File 88 
8.5 Example of Writing to File 89 
Chapter No.9 Modification of Address Book Code 90 
9.1 Adding Persistence Functionality 90 
9.1.1 Scenario 1- Startup 90 
9.1.2 Scenario 2- End/Finish up 93 
9.2 Abstract Classes & Interfaces 96 
9.3 Problems & Requirements 96 
9.4 Abstract Classes 96 
9.4.1 Example of Abstract Classes 97 
9.5 Interfaces 98 
9.5.1 Defining an Interface 98 
9.5.2 Implementing Interface 98 
9.5.3 Example of Interface 98 
9.5.4 Interface Characteristics 99 
9.5.5 Example: Interface Based Polymorphism 100 
Chapter No.10 Graphical User Interfaces 102 
10.1 Support for GUI in Java 102 
10.2 GUI Classes vs. Non GUI Support Classes 102 
10.3 java.awt package 102 
10.4 javax.swing package 102 
10.5 A Part of the framework 103 
10.6 GUI Creation Steps 104 
10.6.1 import required package 104 
10.6.2 Setup the Top Level Containers 104 
10.6.3 Get the Component Area of Top Level Container 105 
10.6.4 Apply Layout to Component Area 105 
10.6.5 Create & Add Components 106 
10.6.6 Set Size of Frame & Make it Visible 106
Web Design & Development – CS506 VU 
© Copyright Virtual University of Pakistan 4 
10.7 Making a Simple GUI 106 
10.8 Important Points to Consider 108 
10.9 Layout Managers 109 
10.9.1 Flow Layout 109 
10.9.2 Grid Layout 111 
10.9.3 Border Layout 113 
10.10 Making Complex GUIs 115 
10.11 JPanel 115 
10.12 Calculator GUI 116 
Chapter No.11 Event Handling 119 
11.1 Event Handling Model 120 
11.2 Event Handling Steps 120 
11.3 Event Handling Process 120 
11.3.1 Event Generators 120 
11.3.2 Event Handlers/Listeners 121 
11.3.3 Registering Handler with Generator 123 
11.4 How Event Handling Participants Interact Behind the Scene 125 
11.4.1 Event Generator/Source 125 
11.4.2 Event Object 125 
11.4.3 Event Listener/Handler 125 
11.4.4 JVM 125 
11.5 Making a Small Calculator 127 
Chapter No.12 More Examples of Handling Events 130 
12.1 Handling Mouse Events 130 
12.1.1 MouseMotionListener Interface 130 
12.3 MouseListener Interface 130 
12.4 Example: Handling Mouse Events 131 
12.5 Handling Window Events 133 
Chapter No.13 Problem in Last Code Example 136 
13.1 Problem 136 
13.2 Solution 136 
13.3 Adapter Classes 136 
13.4 Available Adapter Classes 137 
13.5 How to Use Adapter Classes 137 
13.6 Example 138 
13.7 Problem in Example 139 
13.8 Inner Classes 139 
13.9 Handling Window Events with Inner Classes 140 
13.10 Handling Window & Mouse Events with Inner Classes 141 
13.11 Small Calculator Making Inner Classes 143 
13.12 Anonymous Inner Classes 146 
13.13 Named vs. Anonymous Objects 146 
13.14 Handling Window Events with Anonymous Inner Class 147 
13.15 Summary of Approaches for Handling Events 148 
Chapter No.14 Java Data Base Connectivity 149 
14.1 Introduction 149
Web Design & Development – CS506 VU 
© Copyright Virtual University of Pakistan 5 
14.2 The java.sql package 149 
14.3 Connecting with Microsoft Access 149 
14.3.1 Create Database 149 
14.3.2 Setup System DSN 150 
14.4 Basic Steps in Using JDBC 151 
14.4.1 Import Required Package 151 
14.4.2 Load Driver 152 
14.4.3 Define Connection URL 152 
14.4.4 Establish Connection with Database 152 
14.4.5 Create Statement 152 
14.4.6 Execute Query 152 
14.4.7 DELETE 153 
14.4.8 Close the Connection 153 
14.5 Retrieving Data from Resultset 153 
Chapter No.15 More on JDBC 156 
15.1 Useful Statement Methods 156 
15.1.1 executeUpdate( ) 156 
15.1.2 getMaxRows( )/setMaxRows(int) 158 
15.1.3 getQueryTimeOut( )/setQueryTimeOut(int) 158 
15.2 Different Type of Statements 158 
15.2.1 Statement 159 
15.2.2 PreparedStatement 159 
15.2.3 CallableStatement 159 
15.3 PreparedStatement 159 
Chapter No.16 Result Set 162 
16.1 ResultSet 162 
16.2 Default ResultSet 162 
16.3 Useful ResultSet’s Methods 162 
16.3.1 next( ) 163 
16.3.2 getters 163 
16.3.3 close( ) 163 
16.4 Updatable &/or Scrollable ResultSet 163 
16.5 Getting Updatable & Scrollable ResultSet 163 
16.5.1 previous( ) 164 
16.5.2 absolute(int) 165 16.5.3 updaters 166 
16.5.4 updateRow( ) 166 
16.5.5 moveToInsertRow(int) 168 
16.5.6 insertRow( ) 168 
16.5.7 last( ) & first( ) 171 
16.5.8 getRow( ) 171 
16.5.9 deleteRow( ) 171 
Chapter No.17 Meta Data 174 
17.1 ResultSet Meta data 174 
17.2 Getting ResultSet Meta Data Object 174 
17.3 Useful ResultSetMetaData Methods 175 
17.4 DataBaseMetaData 177
Web Design & Development – CS506 VU 
© Copyright Virtual University of Pakistan 6 
17.4.1 Creating DataBaseMetaData Object 177 
17.5 JDBC Driver Types 179 
Chapter No.18 Java Graphics 183 
18.1 Painting 183 
18.2 How Painting Works 183 
18.3 Painting a Swing Component 186 
18.4 Your Painting Strategy 187 
Chapter No.19 How to Animate? 191 
19.1 Problem & Solution 191 
19.2 Coding Example 191 
19.3 Ball Animation 195 
Chapter No.20 Applets 199 
20.1 Applets Support 199 
20.2 What an Applet is? 199 
20.3 The Genealogy of Applet 201 
20.4 Applet Life Cycle Methods 202 
20.5 Design Process 204 
20.6 Generating Random Numbers 204 
20.7 Program’s Modules 205 
20.8 Merging Pieces 208 
Chapter No.21 Socket Programming 211 
21.1 Socket 211 
21.2 Socket Dynamics 211 
21.3 What is Port? 211 
21.4 How Client Server Communicate 211 
21.5 Steps to make a Simple Client 212 
21.6 Steps to make a Simple Server 214 
Chapter No.22 Serialization 219 
22.1 What? 219 
22.2 Motivation 219 
22.3 Revisiting AddressBook 219 
22.4 Serialization in Java 220 
22.5 Serializable Interface 220 
22.6 Automatic Writing 220 
22.7 Automatic Reading 220 
22.8 Serialization- How it Works? 220 
22.9 Object Serialization & Network 222 
22.10 Reading Objects over Network 223 
22.11 Preventing Serialization 225 
Chapter No.23 Multithreading 226 
23.1 Introduction 226 
23.2 Sequential Execution vs. Multithreading 226 
23.3 Creating Threads in Java 228 
23.4 Thread Creating Steps using Inheritance 228
Web Design & Development – CS506 VU 
© Copyright Virtual University of Pakistan 7 
23.5 Thread priority Scheduling 230 
23.6 Problems with Thread Priorities 232 
Chapter No.24 More on Multithreading 233 
24.1 Reading Two Files Simultaneously 233 
24.2 Threads’ Joining 240 
Chapter No.25 Web Application Development 242 
25.1 Introduction 242 
25.2 Web Applications 242 
25.3 HTTP Basics 242 
25.3.1 Parts of HTTP Request 243 
25.3.2 Parts of HTTP Response 243 
25.4 HTTP Response Codes 244 
25.5 Server Side Programming 245 
25.6 Why Build Pages Dynamically? 247 
25.7 Dynamic Web Content Technologies Evolution 248 
25.8 Layers & Web Applications 249 
Chapter No.26 Java Servlets 250 
26.1 What Servlets can do? 250 
26.2 Servlets vs. other SSP Technologies 250 
26.3 Software Requirements 251 
26.4 Jakarta Servlet Engine (Tomcat) 251 
26.5 Environment Setup 251 
26.6 Environment Setup using .zip File 251 
26.7 Environment Setup using .exe File 252 
Chapter No.27 Creating a Simple Web Application in Tomcat 260 
27.1 Slandered Directory Structure of a J2EE Web Application 260 
27.2 Writing Servlets 262 
27.3 Servlet Types 262 
27.4 Servlet Class Hierarchy 263 
27.5 Types of HTTP Requests 263 
27.6 GET & POST HTTP Request Types 264 
27.7 Steps for Making Hello World Servlet 264 
27.8 Compiling & Invoking Servlets 266 
Chapter No.28 Servlets Lifecycle 267 
28.1 Stages of Servlet Lifecycle 267 
28.2 Reading HTML Form Data Using Servlets 269 
28.3 HTML & Servlets 270 
28.4 Types of Data Send to Web Server 270 
28.5 Reading HTML Form Data from Servlets 270 
Chapter No.29 More on Servlets 275 
29.1 Initialization Parameters 275 
29.2 ServletConfig 275 
29.3 Reading Initialization Parameters 276 
29.4 Response Redirection 278
Web Design & Development – CS506 VU 
© Copyright Virtual University of Pakistan 8 
29.5 Sending a Standered Redirect 278 
29.6 Sending a Redirect to an Error Page 278 
29.7 ServletContext 281 
29.8 Request Dispatcher 281 
Chapter No.30 Dispatching Requests 284 
30.1 Recap 284 
30.2 Example Code- Request Dispatching- Include 284 
30.3 Example Code- Request Dispatcher- Forward 289 
30.4 HttpServletRequest Methods 293 
30.5 HttpServletResponse Methods 294 
30.6 Session Tracking 295 
Chapter No.31 Session Tracking 297 
31.1 Store State Somewhere 297 
31.2 Post Notes 297 
31.3 Three Typical Solutions 297 
31.4 Cookies 298 
31.4.1 What a Cookie is? 298 
31.4.2 Cookie’s Voyage 298 
31.4.3 Potential Uses of Cookies 298 
31.4.4 Sending Cookies to Browser 299 
31.4.5 Reading cookies from Client 299 
Chapter No.32 Session Tracking 2 308 
32.1 URL Rewriting 308 
32.2 Disadvantages of URL Rewriting 308 
32.3 How to Make a QueryString 308 
32.4 Hidden Form Fields 312 
32.5 Java Solution for Session Tracking 312 
32.6 Working with HttpSession 313 
32.7 HttpSession- Behind the Scenes 316 
32.8 Encoding URLs sent to Client 317 
32.9 Difference between encodURL( ) & encodeRedirectURL( ) 317 
32.10 Some Methods of HttpSession 317 
Chapter No.33 Case Study Using Servlets 321 
33.1Design Process 321 
33.2 Layers and Web Application 321 
33.3 Package 328 
33.4 What is a Package? 328 
33.5 How to Create a Package? 328 
33.6 How to use Package? 329 
33.7 JavaServer Pages (JSP) 330 
33.8 The Need for JSP 330 
33.9 JSP Framework 330 
33.10 Advantages of JSP over Competing Technologies 330 
33.11Setting Up Your Environment 331 
Chapter No.34 Java Server Pages 1 332
Web Design & Development – CS506 VU 
© Copyright Virtual University of Pakistan 9 
34.1 First run of a JSP 332 
34.2 Benifits of JSP 332 
34.3 JSP vs. Servlet 333 
34.4 Scripting Elements 335 
34.5 Comments 335 
34.6 Expressions 335 
34.7 Scriplets 335 
34.8 Declarations 336 
34.9 Writing JSP Scripting Elements in XML 337 
Chapter No.35 Java Server Pages 2 339 
35.1 Implicit Objects 339 
35.2 JSP Directives 344 
35.3 JSP Page Directive 344 
35.4 JSP Include Directive 345 
35.5 JSP LifeCycle Methods 348 
Chapter No.36 Java Server Pages 3 349 
36.1 Displaying Course Outline 349 
36.2 Java Beans 356 
36.3 Java Beans Design Conventions 356 
36.4 A Sample Java Bean 356 
Chapter No.37 JSP Action Elements & Scope 367 
37.1 JSP Action Elements 367 
37.2 Working with JavaBeans using JSP Action Elements 368 
37.3 JSP useBean Action Element 368 
37.4 JSP setProperty Action Element 368 
37.5 JSP getProperty Action Element 369 
37.6 Sharing Beans & Object Scopes 372 
37.7 Summary of Object’s Scopes 375 
37.8 More JSP Action Elements 377 
37.9 JSP include action Element 377 
37.10 JSP forward action Element 377 
Chapter No.38 JSP Custom Tags 378 
38.1 Motivation 378 
38.2 What is a Custom Tag? 378 
38.3 Why Build Custom Tag? 379 
38.4 Advantages of Using Custom Tags 379 
38.5 Types of Tags 379 
38.6Building Custom Tags 381 
38.7 Building Tags with Attributes 384 
Chapter No.39 MVC + Case Study 393 
39.1 Error Page 393 
39.2 Defining & Using Error Pages 393 
39.3 Case Study- Address Book 394 
39.4 Ingredients of Address Book 394 
39.5 Program Flow 395
Web Design & Development – CS506 VU 
© Copyright Virtual University of Pakistan 10 
39.6 Model View Controller 408 
39.7 Participants & Responsibilities 409 
39.8 Evolution of MVC Architecture 409 
39.9 MVC Model 1 409 
Chapter No.40 MVC Model 2 Architecture 410 
40.1 Page-Centric Approach 410 
40.2Page-with-Bean Approach 410 
40.3 MVC Model 2 Architecture 410 
40.4 Case Study: Address Book Using MVC Model2 412 
40.5Introducing a JSP as Controller 413 
40.6 How Controller Differentiate between Requests? 413 
40.7 JSP is the Right Choice as a Controller? 428 
40.8 Introducing a Servlet as Controller 428 
Chapter No.41 Layers & Tiers 435 
41.1 Layers vs. Tiers 435 
41.2 Layers 435 
41.3 Presentation Layer 436 
41.4 Business Layer 436 
41.5 Data Layer 437 
41.6 Tiers 437 
41.7 Layers Support in Java 438 
41.8 J2EE Multi-Tiered Applications 439 
41.9 Case Study: Matrix Multiplication Using Layers 440 
41.10 Layer by Layer View 440 
41.11 ControllerServlet 443 
41.12 Matrix Multiplier 445 
41.13 Matrix DAO 447 
Chapter No.42 Expression Language 451 
42.1Overview 451 
42.2JSP before & after EL 451 
42.3 Expression Language Nuggets 452 
42.4 EL Syntax 452 
42.5 EL Literals 453 
42.6 EL Operators 453 
42.7 EL Identifiers 454 
42.8 EL Implicit Objects 454 
42.9 Storing Scoped Variables 456 
42.10 Retrieving Scoped Variables 457 
42.11EL Accessors 458 
42.12 EL – Robust Features 459 
42.13 Using Expression Language 459 
Chapter No.43 JSTL 468 
43.1 Introduction 468 
43.2 JSTL and EL 468 
43.3 Functional Overview 468 
43.4 Twin Tag Libraries 469
Web Design & Development – CS506 VU 
© Copyright Virtual University of Pakistan 11 
43.5 Using JSTL 469 
43.6 Working with Core Actions (Tags) 470 
43.7 c:set 470 
43.8Using with JavaBeans & Map 471 
43.9c:out 471 
43.10 c:remove 472 
43.11 c:forEach 472 
43.12 Iteration over an Integer range 473 
43.13 Iteration over a Collection 473 
43.14 c:if 475 
43.15 c:choose 475 
43.16 netBeans 4.1 & JSTL 476 
Chapter No.44 Client Side Validation & JSF 480 
44.1 Client side Validation 480 
44.2 Why is client side Validation Good? 480 
44.3 Form Validation using JavaScript 480 
44.4 JavaServer Faces 483 
44.5 Different Existing Frameworks 483 
44.6 javaServer Faces 483 
44.7 JSF UI Components 483 
44.8 JSF - Managed Bean-Intro 486 
44.9 JSF – Value Binding 487 
44.10 JSF – Method Binding 487 
44.11 JSF Navigation 487 
Chapter No.45 JavaServer Faces 488 
45.1 Example Code 488 
45.2 Web Services 488 
45.3 Introduction 488 
45.4 Web Services, Definition by W3C 488 
45.5 Distributed Computing Evolution 488 
45.6 Characteristics of Web Services 489 
45.7 Types of Web Service 489 
45.8 Comparison between Web Page & Web Service 490 
45.9 Web Service Architectural Components 490
Web Design & Development – CS506 VU 
© Copyright Virtual University of Pakistan 12 
Lesson 1 
JAVA FEATURES 
This handout is a traditional introduction to any language features. You might not be able to comprehend some of the features fully at this stage but don’t worry, you’ll get to know about these as we move on with the course 
Design Goals of Java 
The massive growth of the Internet and the World-Wide Web leads us to a completely new way of looking at development of software that can run on different platforms like Windows, Linux and Solaris etc. 
Right Language, Right Time 
Java came on the scene in 1995 to immediate popularity. 
Before that, C and C++ dominated the software development 
1. compiled, no robust memory model, no garbage collector causes memory leakages, not great support of built in libraries 
Java brings together a great set of "programmer efficient" features 
2. Putting more work on the CPU to make things easier for the programmer. 
Java – Buzzwords (Vocabulary) 
From the original Sun Java whitepaper: "Java is a simple, object-oriented, distributed, interpreted, robust, secure, architecture-neutral, portable, high- performance, multi-threaded, and dynamic language." 
Here are some original java buzzwords... 
Java -- Language + Libraries 
Java has two parts... 
1. The core language -- variables, arrays, objects 
o The Java Virtual Machine (JVM) runs the core language 
o The core language is simple enough to run on small devices -- phones, smart cards, PDAs. 
2. The libraries 
o Java includes a large collection of standard library classes to provide "off the shelf" code. (Useful built-in classes that comes with the language to perform basic tasks) 
o Example of these classes is String, ArrayList, HashMap, StringTokenizer (to break string into substrings), Date ... 
o Java programmers are more productive in part because they have access to a large set of standard, well documented library classes. 
Simple 
Very similar C/C++ syntax, operators, etc. 
The core language is simpler than C++ -- no operator overloading, no pointers, and no multiple inheritance
Web Design & Development – CS506 VU 
© Copyright Virtual University of Pakistan 13 
The way a java program deals with memory is much simpler than C or C++. 
Object-Oriented 
Java is fundamentally based on the OOP notions of classes and objects. 
Java uses a formal OOP type system that must be obeyed at compile-time and run-time. 
This is helpful for larger projects, where the structure helps keep the various parts consistent. Contrast to Perl, which has a more anything-goes feel. 
D 
istributed / Network Oriented 
Java is network friendly -- both in its portable, threaded nature, and because common networking operations are built-in to the Java libraries. 
R 
obust / Secure / Safe 
• Java is very robust 
o Both, vs. unintentional errors and vs. malicious code such as viruses. 
o Java has slightly worse performance since it does all this checking. (Or put the other way, C can be faster since it doesn't check anything.) 
• The JVM "verifier" checks the code when it is loaded to verify that it has the correct structure -- that it does not use an uninitialized pointer, or mix int and pointer types. This is one-time "static" analysis -- checking that the code has the correct structure without running it. 
• The JVM also does "dynamic" checking at runtime for certain operations, such as pointer and array access, to make sure they are touching only the memory they should. You will write code that runs into 
• As a result, many common bugs and security problems (e.g. "buffer overflow") are not possible in java. The checks also make it easier to find many common bugs easy, since they are caught by the runtime checker. 
• You will generally never write code that fails the verifier, since your compiler is smart enough to only generate correct code. You will write code that runs into the runtime checks all the time as you debug -- array out of bounds, null pointer. 
• Java also has a runtime Security Manager can check which operations a particular piece of code is allowed to do. As a result, java can run un-trusted code in a "sandbox" where, for example, it can draw to the screen but cannot access the local file system.
Web Design & Development – CS506 VU 
© Copyright Virtual University of Pakistan 14 
Portable 
"Write Once Run Anywhere", and for the most part this works. 
Not even a recompile is required -- a Java executable can work, without change, on any Java enabled platform. 
Support for Web and Enterprise Web Applications 
Java provides an extensive support for the development of web and enterprise applications 
Servlets, JSP, Applets, JDBC, RMI, EJBs and JSF etc. are some of the Java technologies that can be used for the above mentioned purposes. 
High-performance 
The first versions of java were pretty slow. 
Java performance has gotten a lot better with aggressive just-in-time-compiler (JIT) techniques. 
Java performance is now similar to C -- a little slower in some cases, faster in a few cases. However memory use and startup time are both worse than C. 
Java performance gets better each year as the JVM gets smarter. This works, because making the JVM smarter does not require any great change to the java language, source code, etc. 
Multi-Threaded 
Java has a notion of concurrency wired right in to the language itself. 
This works out more cleanly than languages where concurrency is bolted on after the fact. 
Dynamic 
Class and type information is kept around at runtime. This enables runtime loading and inspection of code in a very flexible way. 
J 
ava Compiler Structure 
The source code for each class is in a .java file. Compile each class to produce 
“.class” file. 
Sometimes, multiple .class files are packaged together into a .zip or .jar "archive" 
file. 
On unix or windows, the java compiler is called "javac". To compile all the .java files in a directory use "javac *.java".
Web Design & Development – CS506 VU 
© Copyright Virtual University of Pakistan 15 
Java: Programmer Efficiency 
Faster Development 
Building an application in Java takes about 50% less time than in C or C++. So, faster time to market 
Java is said to be “Programmer Efficient”. 
OOP 
Java is thoroughly OOP language with robust memory system 
Memory errors largely disappear because of the safe pointers and garbage collector. The lack of memory errors accounts for much of the increased programmer productivity. 
Libraries 
Code re-use at last -- String, ArrayList, Date, ... available and documented in a standard way 
Microsoft vs. Java 
Microsoft hates Java, since a Java program (portable) is not tied to any particular operating system. If Java is popular, then programs written in Java might promote non-Microsoft operating systems. For basically the same reason, all the non- Microsoft vendors think Java is a great idea. 
Microsoft's C# is very similar to Java, but with some improvements, and some questionable features added in, and it is not portable in the way Java is. Generally it is considered that C# will be successful in the way that Visual Basic is: a nice tool to build Microsoft only software. 
Microsoft has used its power to try to derail Java somewhat, but Java remains very popular on its merits. 
J 
ava Is For Real 
Java has a lot of hype, but much of it is deserved. Java is very well matched for many modern problems 
Using more memory and CPU time but less programmer time is an increasingly appealing tradeoff. 
Robustness and portability can be very useful features 
A general belief is that Java is going to stay here for the next 10-20 years 
References 
Majority of the material in this handout is taken from the first handout of course cs193j at Stanford. 
The Java™ Language Environment, White Paper, by James Gosling & Henry McGilton 
Java’s Sun site: http://java.sun.com 
Java World: www.javaworld.com
Web Design & Development – CS506 VU 
© Copyright Virtual University of Pakistan 16 
Lesson 2 
Java Virtual Machine & Runtime Environment 
Basic Concept 
When you write a program in C++ it is known as source code. The C++ compiler converts this source code into the machine code of underlying system (e.g. Windows) If you want to run that code on Linux you need to recompile it with a Linux based compiler. Due to the difference in compilers, sometimes you need to modify your code. 
Java has introduced the concept of WORA (write once run anywhere). When you write a java program it is known as the source code of java. The java compiler does not compile this source code for any underlying hardware system; rather it compiles it for a software system known as JVM (This compiled code is known as byte code). We have different JVMs for different systems (such as JVM for Windows, JVM for Linux etc). When we run our program the JVM interprets (translates) the compiled program into the language understood by the underlying system. So we write our code once and the JVM runs it everywhere according to the underlying system. 
This concept is discussed in detail below 
JAVA 
Source 
Code 
Java Compiler javac 
Java Byte 
Code 
Java Interpreter 
Machin 
Code 
e
Web Design & Development – CS506 VU 
© Copyright Virtual University of Pakistan 17 
B 
ytecode 
Java programs (Source code) are compiled into a form called Java bytecodes. 
The Java compiler reads Java language source (.java) files, translates the source into 
Java bytecodes, and places the bytecodes into class (.class) files. 
The compiler generates one class file for each class contained in java source file. 
Java Virtual Machine (JVM) 
The central part of java platform is java virtual machine 
Java bytecode executes by special software known as a "virtual machine". 
Most programming languages compile source code directly into machine code, suitable for execution he differenc 
T e with Java is that it uses bytecode - a special type of machine code. 
he JVM executes Java bytecodes, so Java bytecodes can be thought of as the machine language 
App1 
s 
• JVM are available for almost all operating systems. 
• Java bytecode is executed by using any operating system’s JVM. Thus achieve portability. 
T 
of the JVM. 
A 
pp2 App3 
App4 App5 
Java Virtual Machine 
WindowOS X Solaris Linux 
Linux 
Intel PowerPC 
SPARC
Web Design & Development – CS506 VU 
© Copyright Virtual University of Pakistan 18 
J 
ava Runtime Environment (JRE) 
The Java Virtual Machine is a part of a large system i.e. Java Runtime Environment (JRE). 
Each operating system and CPU architecture requires different JRE. 
The JRE consists of set of built-in classes, as well as a JVM. 
Without an available JRE for a given environment, it is impossible to run Java software. 
References 
Java World: http://www.javaworld.com 
Inside Java: http://www.javacoffeebreak.com/articles/inside_java
Web Design & Development – CS506 VU 
© Copyright Virtual University of Pakistan 
19 
Java Program Development and Execution Steps 
Java program normally go through five phases. These are 
1. Edit, 
2. Compile, 
3. Load, 
4. Verify and 
5. Execute 
We look over all the above mentioned phases in a bit detail. First consider the following figure that summarizes the all phases of a java program. 
Phase 1 
Phase 3 
Phase 4 
Phase 5 
Editor 
Compiler 
Class Loader 
Disk 
Bytecode Verifier 
Interpreter 
Disk 
Disk 
Primary 
Memory 
Primary 
Memory 
Primary 
Memory 
Program is created in the editor and stored on disk. 
Compiler creates bytecodes and stores them on disk. 
Class loader puts bytecodes in memory. 
Bytecode verifier confirms that all bytecodes are valid and do not violate Java’s security restrictions. 
Interpreter reads bytecodes and translates them into a language that the computer can understand, possibly storing data values as the program executes.
Web Design & Development – CS506 VU 
© Copyright Virtual University of Pakistan 
20 
Phase 1: Edit 
Phase 1 consists of editing a file. This is accomplished with an editor program. The programmer types a java program using the editor like notepad, and make corrections if necessary. 
When the programmer specifies that the file in the editor should be saved, the program is stored on a secondary storage device such as a disk. Java program file name ends with a 
.java extension. 
On Windows platform, notepad is a simple and commonly used editor for the beginners. However java integrated development environments (IDEs) such as NetBeans, Borland JBuilder, JCreator and IBM’s Ecllipse have built-in editors that are smoothly integrated into the programming environment. 
Phase 2: Compile 
In Phase 2, the programmer gives the command javac to compile the program. The java compiler translates the java program into bytecodes, which is the language understood by the java interpreter. 
To compile a program called Welcome.java, type 
javac Welcome.java 
at the command window of your system. If the program compiles correctly, a file called Welcome.class is produced. This is the file containing the bytecodes that will be interpreted during the execution phase. 
Phase 3: Loading 
In phase 3, the program must first be placed in memory before it can be executed. This is done by the class loader, which takes the .class file (or files) containing the bytecodes and transfers it to memory. The .class file can be loaded from a disk on your system or over a network (such as your local university or company network or even the internet). 
Applications (Programs) are loaded into memory and executed using the java interpreter 
via the command java. When executing a Java application called Welcome, the command 
Java Welcome 
Invokes the interpreter for the Welcome application and causes the class loader to load information used in the Welcome program.
Web Design & Development – CS506 VU 
© Copyright Virtual University of Pakistan 
21 
Phase 4: Verify 
Before the bytecodes in an application are executed by the java interpreter, they are verified by the bytecode verifier in Phase 4. This ensures that the bytecodes for class that are loaded form the internet (referred to as downloaded classes) are valid and that they do not violate Java’s security restrictions. 
Java enforces strong security because java programs arriving over the network should not be able to cause damage to your files and your system (as computer viruses might). 
Phase 5: Execute 
Finally in phase 5, the computer, under the control of its CPU, interprets the program one bytecode at a time. Thus performing the actions specified by the program. 
Programs may not work on the first try. Each of the preceding phases can fail because of various errors. This would cause the java program to print an error message. The programmer would return to the edit phase, make the necessary corrections and proceed through the remaining phases again to determine id the corrections work properly. 
----------------------------------------------- 
References: 
Java™ How to Program 5th edition by Deitel & Deitel 
Sun Java online tutorial: http://java.sun.com/docs/books/tutorial/java/index.html
Web Design & Development – CS506 VU 
© Copyright Virtual University of Pakistan 
22 
Installation and Environment Setting 
Installation 
• Download the latest version j2se5.0 (java 2 standard edition) from http://java.sun.com 
or get it from any other source like CD. 
Note: j2se also called jdk (java development kit). You can also use the previous versions like jdk 1.4 or 1.3 etc. but it is recommended that you use either jdk1.4 or jdk5.0 
• Install j2se5.0 on your system 
Note: For the rest of this handout, assume that j2se is installed in C:Program 
FilesJavajdk1.5.0 
Environment Setting 
Once you successfully installed the j2se, the next step is environment or path setting. You can accomplish this in either of two ways. 
• Temporary Path Setting 
Open the command prompt from Start Æ Programs Æ Accessories Æ Comman 
Prompt. The command prompt screen would be opened in front of you. 
Write the command on the command prompt according to the following format 
path = < java installation directorybin > 
So, according to handout, the command will look like this 
path = C:Program FilesJavajdk1.5.0bin 
To Test whether path has been set or not, write javac and press ENTER. If the list ofn b 
options displayed as shown in the below figure means that you have successfully 
completed the steps of path setting. 
The above procedure is illustrates in the given below picture.
Web Design & Development – CS506 VU 
© Copyright Virtual University of Pakistan 
23 
Note: The issue with the temporary path setting is you have to repeat the above explained procedure 
again and again each time you open a new command prompt window. To avoid this overhead, it is better 
to set your path permanently 
• Permanent Path Setting 
In Windows NT (XP, 2000), you can set the permanent environment variable. 
Right click on my computer icon click on properties as shown below
Web Design & Development – CS506 VU 
© Copyright Virtual University of Pakistan 
24 
A System Properties frame would appeared as shown in the picture 
Select the advanced tab followed by clicking the Environment Variable button. The 
g box would be appeared. 
Environment variables frame would be displayed in front of you Locate the Path variable in the System or user variables, if it is present there, select it by single click. Press Edit button. The following dialo 
• Write; C:Program FilesJavajdk1.5.0bin at the end of the value field. Press OK button. 
Remember to write semicolon (;) before writing the path for java installation directory as illustrate in 
the above figure 
• If Path variable does not exist, click the New button. Write variable name 
“PATH”, variable value C:Program FilesJavajdk1.5.0bin and press OK button.
Web Design & Development – CS506 VU 
© Copyright Virtual University of Pakistan 
25 
• Now open the command prompt and write javac, press enter button. You see the list of options 
would be displayed. 
• After setting the path permanently, you have no need to set the path for each new opened 
command prompt. 
References 
Entire material for this handout is taken from the book JAVA A Lab Course by Umair Javed. This material is 
available just for the use of VU students of the course Web Design and Development and not for any other 
commercial purpose without the consent of author.
Web Design & Development – CS506 VU 
© Copyright Virtual University of Pakistan 
26 
First Program in Java 
Like any other programming language, the java programming language is used to create applications. So, we start from building a classical “Hello World” application, which is generally used as the first program for learning any new language. 
HelloWorldApp 
1. Open notepad editor from Start Æ ProgarmFiles Æ AccessoriesÆ Notepad. 
2. Write the following code into it. 
Note: Don’t copy paste the given below code. Probably it gives errors and you can’t able to remove them at the beginning stage. 
1. /* The HelloWorldApp class implements an application that 
2. simply displays "Hello World!" to the standard output. 
3. */ 
4. public class HelloWorldApp { 
5. public static void main(String[] args) { 
6. //Display the string. No global main 
7. System.out.println(“Hello World”); 
8. } 
9. } 
3. To save your program, move to File menu and choose save as option. 
4. Save your program as “HelloWorldApp.java” in some directory. Make sure to add double quotes around class name while saving your program. For this example create a folder known as “examples” in D: drive 
Note: Name of file must match the name of the public class in the file (at line 4). Moreover, it is case sensitive. For example, if your class name is MyClass, than file name must be MyClass. Otherwise the Java compiler will refuse to compile the program. 
For the rest of this handout, we assume that program is saved in D:examples directory.
Web Design & Development – CS506 VU 
© Copyright Virtual University of Pakistan 
27 
HelloWorldApp Described 
Lines 1-3 
Like in C++, You can add multiple line comments that are ignored by the compiler. 
Lines 4 
Line 4 declares the class name as HelloWorldApp. In java, every line of code must reside inside class. This is also the name of our program (HelloWorldApp.java). The compiler creates the HelloWorldApp.class if this program successfully gets compiled. 
Lines 5 
Line 5 is where the program execution starts. The java interpreter must find this defined exactly as given or it will refuse to run the program. (However you can change the name of parameter that is passed to main. i.e. you can write String[] argv or String[] some Param instead of String[] args) 
Other programming languages, notably C++ also use the main( ) declaration as the starting point for execution. However the main function in C++ is global and reside outside of all classes where as in Java the main function must reside inside a class. In java there are no global variables or functions. The various parts of this main function declaration will be covered at the end of this handout. 
Lines 6 
Again like C++, you can also add single line comment 
Lines 7 
Line 7 illustrates the method call. The println( ) method is used to print something on the console. In this example println( ) method takes a string argument and writes it to the standard output i.e. console. 
Lines 8-9 
Line 8-9 of the program, the two braces, close the method main( ) and the class 
HelloWorldApp respectively.
Web Design & Development – CS506 VU 
© Copyright Virtual University of Pakistan 
28 
Compiling and Running HelloWorldApp 
1. Open the command prompt from Start Æ Program Files Æ Accessories. OR 
alternatively you can write cmd in the run command window. 
2. Write cd.. to came out from any folder, and cd [folder name] to move inside the specified directory. To move from one drive to another, use [Drive Letter]: See figure given below 
3. After reaching to the folder or directory that contains your source code, in our case 
HelloWorldApp.java. 
4. Use “javac” on the command line to compile the source file (“.java” file). 
D:examples> javac HelloWorld.java 
5. If program gets successfully compiled, it will create a new file in the same directory named HelloWorldApp.class that contains the byte-code. 
6. Use “java” on the command line to run the compiled .class file. Note “.class” would be added with the file name. 
D:examples> java HelloWorld 
7. You can see the Hello World would be printed on the console. Hurrah! You are successful in writing, compiling and executing your first program in java ☺ 
Points to Remember 
ƒ Recompile the class after making any changes 
ƒ Save your program before compilation 
ƒ Only run that class using java command that contains the main method, because program executions 
always starts form main
Web Design & Development – CS506 VU 
© Copyright Virtual University of Pakistan 
29 
An Idiom Explained 
You will see the following line of code often: 
– public static void main(String args[]) { …} 
• About main() 
“main” is the function from which your program starts 
Why public? 
Since main method is called by the JVM that is why it is kept public so that it is accessible from outside. Remember private methods are only accessible from within the class 
Why static? 
Every Java program starts when the JRE (Java Run Time Environment) calls the main method of that program. If main is not static then the JRE have to create an object of the class in which main method is present and call the main method on that object (In OOP based languages method are called using the name of object if they are not static). It is made static so that the JRE can call it without creating an object. 
Also to ensure that there is only one copy of the main method per class 
Why void? 
• Indicates that main ( ) does not return anything. 
What is String args[] ? 
Way of specifying input (often called command-line arguments) at startup of application. More on it latter 
References 
Entire material for this handout is taken from the book JAVA A Lab Course by Umair Javed. This material is available just for the use of VU students of the course Web Design and Development and not for any other commercial purpose with out the consent of author.
Web Design & Development – CS506 VU 
© Copyright Virtual University of Pakistan 
30 
Lesson 3 
Learning Basics 
Strings 
A string is commonly considered to be a sequence of characters stored in memory and accessible as a unit. Strings in java are represented as objects. 
String Concatenation 
“+” operator is used to concatenate strings 
– System.out.pritln(“Hello” + “World”) will print Hello World on console 
String concatenated with any other data type such as int will also convert that datatype to String and the result will be a concatenated String displayed on console. For example, 
– int i = 4; 
– int j = 5; 
System.out.println (“Hello” + i) 
will print Hello 4 on screen 
– However 
System,.out..println( i+j) ; 
will print 9 on the console because both i and j are of type int. 
Comparing Strings 
For comparing Strings never use == operator, use equals method of String class. 
– == operator compares addresses (shallow comparison) while equals compares values (deep comparison) 
E.g string1.equals(string2)
Web Design & Development – CS506 VU 
© Copyright Virtual University of Pakistan 
31 
Example Code: String concatenation and comparison 
public class StringTest { 
public static void main(String[] args) { 
int i = 4; 
int j = 5; 
System.out.println("Hello" + i); // will print Hello4 
System.out.println(i + j); // will print 9 
String s1 = new String (“pakistan”); 
String s2 = “pakistan”; 
if (s1 == s2) { 
System.out.println(“comparing string using == operator”); 
} 
if (s1.equals( s2) ) { 
System.out.println(“comparing string using equal method”); 
} 
} 
} 
On execution of the above program, following output will produce
Web Design & Development – CS506 VU 
© Copyright Virtual University of Pakistan 
32 
Taking in Command Line Arguments 
In Java, the program can be written to accept command-line-arguments. 
Example Code: command-line arguments 
/* This Java application illustrates the use of Java command-line arguments. */ 
public class CmdLineArgsApp { 
public static void main(String[] args){ //main method 
System.out.println(”First argument ” + args[0]); 
System.out.println(”Second argument ” + args[1]); 
}//end main 
}//End class. 
To execute this program, we pass two arguments as shown below: 
public void someMethod( ) { 
int x; //local variable 
System.out.println(x); // compile time error 
• These parameters should be separated by space. . 
• The parameters that we pass from the command line are stored as Strings inside the “args” array. You can see that the type of “args” array is String. 
Example Code: Passing any number of arguments 
In java, array knows their size by using the length property. By using, length property we can determine how many arguments were passed. The following code example can accept any number of arguments 
/* This Java application illustrates the use of Java 
command-line arguments. */ 
public class AnyArgsApp { 
public static void main(String[] args){ //main method 
for(int i=0; i < args.length; i++) 
System.out.println(“Argument:” + i + “value” +args[i]); 
}//end main 
}//End class.
Web Design & Development – CS506 VU 
© Copyright Virtual University of Pakistan 
33 
Output 
C:java AnyArgsApp i can pass any number of arguments 
Argument:0 value i Argument:1 value can Argument:2 value pass Argument:3 value any Argument:4 value number Argument:5 value of Argument:6 value arguments
Web Design & Development – CS506 VU 
© Copyright Virtual University of Pakistan 
34 
Primitives vs Objects 
• Everything in Java is an “Object”, as every class by default inherits from class 
“Object” , except a few primitive data types, which are there for efficiency reasons. 
• Primitive Data Types 
Primitive Data types of java 
boolean, byte 1 byte 
char, short 2 bytes 
int, float 4 bytes 
long, double 8 bytes 
• Primitive data types are generally used for local variables, parameters and instance variables (properties of an object) 
• Primitive datatypes are located on the stack and we can only access their value, while objects are located on heap and we have a reference to these objects 
• Also primitive data types are always passed by value while objects are always passed by reference in java. There is no C++ like methods 
– void someMethod(int &a, int & b ) // not available in java 
Stack vs. Heap 
Stack and heap are two important memory areas. Primitives are created on the stack while objects are created on heap. This will be further clarified by looking at the following diagram that is taken from Java Lab Course. 
int num = 5; 
Student s = new Student(); 
Stack Heap 
num 
5 
0F59 
name ali 
0F59
Web Design & Development – CS506 VU 
© Copyright Virtual University of Pakistan 
35 
Wrapper Classes 
Each primitive data type has a corresponding object (wrapper class). These wrapper classes provides additional functionality (conversion, size checking etc.), which a primitive data type cannot provide. 
Wrapper Use 
You can create an object of Wrapper class using a String or a primitive data type 
• Integer num = new Integer(4); or 
• Integer num = new Integer(“4”); 
Note: num is an object over here not a primitive data type 
You can get a primitive data type from a Wrapper using the corresponding value function 
• int primNum = num.intValue(); 
Converting Strings to Numeric Primitive Data Types 
To convert a string containing digits to a primitive data type, wrapper classes can help. parseXxx method can be used to convert a String to the corresponding primitive data type. 
String value = “532”; 
int d = Integer.parseInt(value); 
String value = “3.14e6”; 
double d = Double.parseDouble(value);
Web Design & Development – CS506 VU 
© Copyright Virtual University of Pakistan 
36 
The following table summarizes the parser methods available to a java programmer. 
Data Type Convert String using either … 
byte Byte.parseByte(string ) 
new Byte(string ).byteValue() 
short Short.parseShort(string ) 
new Short(string ).shortValue() 
int Integer.parseInteger(string ) 
new Integer(string ).intValue() 
long Long.parseLong(string ) 
new Long(string ).longValue() 
float Float.parseFloat(string ) 
new Float(string ).floatValue() 
double Double.parseDouble(string ) 
new Double(string ).doubleValue()
Web Design & Development – CS506 VU 
© Copyright Virtual University of Pakistan 
37 
Example Code: Taking Input / Output 
So far, we learned how to print something on console. Now the time has come to learn how to print on the GUI. Taking input from console is not as straightforward as in C++. Initially we’ll study how to take input through GUI (by using JOPtionPane class). 
The following program will take input (a number) through GUI and prints its square on the console as well on GUI. 
1. import javax.swing.*; 
2. public class InputOutputTest { 
3. public static void main(String[] args) { 
4. //takes input through GUI 
5. String input = JOptionPane.showInputDialog("Enter number"); 
6. int number = Integer.parseInt(input); 
7. int square = number * number; 
8. //Display square on console 
9. System.out.println("square:" + square); 
10. //Display square on GUI 
11. JOptionPane.showMessageDialog(null, "square:"+ square); 
12. System.exit(0); 
13. } 
14. } 
On line 1, swing package was imported because it contains the JOptionPane class that will be used for taking input from GUI and displaying output to GUI. It is similar to header classes of C++. 
On line 5, showInputDialog method is called of JOptionPane class by passing string argument that will be displayed on GUI (dialog box). This method always returns back a String regardless of whatever you entered (int, float, double, char) in the input filed. 
Our task is to print square of a number on console, so we first convert a string into a number by calling parseInt method of Integer wrapper class. This is what we done on line number 6. 
Line 11 will display square on GUI (dialog box) by using showMessageDialog method of JOptionPane class. The first argument passed to this method is null and the second argument must be a String. Here we use string concatenation. 
Line 12 is needed to return the control back to command prompt whenever we use 
JoptionPane class.
Web Design & Development – CS506 VU 
© Copyright Virtual University of Pakistan 
38 
Compile & Execute
Web Design & Development – CS506 VU 
© Copyright Virtual University of Pakistan 
39 
erators that 
we use in C++ to perform comparisons are also available in java with same behavior. Likewise for, while and do-while 
control structures are alike to C++. 
Reference: 
Selection & Control Structure The if-else and switch selection structures are exactly similar to we have in C++. All relational op 
1- Java tutorial: http://www.dickbaldwin.com/java 
2- Example code, their explanations and corresponding figures for this handout are taken from the book JAVA 
A Lab Course by Umair Javed. This material is available just for the use of VU students of the course Web 
Design and Development and not for any other commercial purpose without the consent of author.
Web Design & Development – CS506 VU 
© Copyright Virtual University of Pakistan 
40 
Lesson 4 
Object Oriented Programming 
Java is fundamentally object oriented. Every line of code you write in java must be inside a class (not counting import directives). OOP fundamental stones Encapsulation, Inheritance and Polymorphism etc. are all fully supported by java. 
OOP Vocabulary Review 
• Classes 
– Definition or a blueprint of a user-defined datatype 
– Prototypes for objects 
– Think of it as a map of the building on a paper 
• Objects 
– Nouns, things in the world 
– Anything we can put a thumb on 
– Objects are instantiated or created from class 
• Constructor 
– A special method that is implicitly invoked. Used to create an Object (that is, an Instance of the Class) and to initialize it. 
• Attributes 
– Properties an object has. 
• Methods 
– Actions that an object can do
Web Design & Development – CS506 VU 
© Copyright Virtual University of Pakistan 
41 
Defining a Class 
class Poin { 
t 
private int xCord; 
private int yCord; 
public Point (……) {……} 
public void display (……) 
{ 
………. 
} 
} //end of class 
in 
astance variables and symbolic constants 
constructor – how to create and initialize objects 
methods – how to manipulate those objects 
(may or may not include its own “driver”, e., main( )) 
i. 
Comparison with C++ 
Some important points to consider when defining a class in java as you probably noticed from the above given skeleton are 
– There are no global variables or functions. Everything resides inside a class. Remember we wrote our main method inside a class. (For example, in HelloWorldApp program) 
– Specify access modifiers (public, private or protected) for each member method or data members at every line. 
– public: accessible anywhere by anyone 
– private: Only accessible within this class 
– protect: accessible only to the class itself and to it’s subclasses or other classes in the same package. 
– default: default access if no access modifier is provided. Accessible to all classes in the same package. 
– There is no semicolon (;) at the end of class. 
– All methods (functions) are written inline. There are no separate header and implementation files. 
– Automatic initialization of class level data members if you do not initialize them 
Primitives 
o Numeric (int, float etc) with zero
Web Design & Development – CS506 VU 
© Copyright Virtual University of Pakistan 
42 
o Char with null 
o Boolean with false 
Object References 
– With null 
Note: Remember, the same rule is not applied to local variables (defined inside method body). Using a local variable without initialization is a compile time error 
Public void someMethod( ) { 
int x; //local variable 
System.out.println(x); // compile time error 
} 
– Constructor 
– Same name as class name 
– Does not have a return type 
– No initialization list 
– JVM provides a zero argument (default) constructor only if a class doesn’t define it’s own constructor 
– Destructors 
– Are not required in java class because memory management is the responsibility of JVM.
Web Design & Development – CS506 VU 
© Copyright Virtual University of Pakistan 
43 
Task – Defining a Student class 
The following example will illustrate how to write a class. We want to write a 
“Student” class that 
– should be able to store the following characteristics of student 
– Roll No 
– Name 
– Provide default, parameterized and copy constructors 
– Provide standard getters/setters (discuss shortly) for instance variables 
– Make sure, roll no has never assigned a negative value i.e. ensuring the correct state of the object 
– Provide print method capable of printing student object on console 
Getters / Setters 
The attributes of a class are generally taken as private or protected. So to access them outside of a class, a convention is followed knows as getters & setters. These are generally public methods. The words set and get are used prior to the name of an attribute. Another important purpose for writing getter & setters to control the values assigned to an attribute. 
Student Class Code 
// File Student.java 
public class Student { 
private String name; 
private int rollNo; 
// Standard Setters 
public void setName (String name) { 
this.name = name; 
} 
// Note the masking of class level variable rollNo 
public void setRollNo (int rollNo) { 
if (rollNo > 0) { 
this.rollNo = rollNo; 
}else { 
this.rollNo = 100; 
} 
} 
// Standard Getters 
public String getName ( ) { 
return name; 
}
Web Design & Development – CS506 VU 
© Copyright Virtual University of Pakistan 
44 
public int getRollNo ( ) { 
return rollNo; 
} 
// Default Constructor public Student() { 
name = “not set”; 
rollNo = 100; 
} 
// parameterized Constructor for a new student 
public Student(String name, int rollNo) { 
setName(name); //call to setter of name 
setRollNo(rollNo); //call to setter of rollNo 
} 
// Copy Constructor for a new student 
public Student(Student s) { 
name = s.name; 
rollNo = s.rollNo; 
} 
// method used to display method on console 
public void print () { 
System.out.print("Student name: " +name); 
System.out.println(", roll no: " +rollNo); 
} 
} // end of class
Web Design & Development – CS506 VU 
© Copyright Virtual University of Pakistan 
45 
Using a Class 
Objects of a class are always created on heap using the “new” operator followed by constructor 
• Student s = new Student ( ); // no pointer operator “*” between Student and s 
• Only String constant is an exception 
String greet = “Hello” ; // No new operator 
• However you can also use 
String greet2 = new String(“Hello”); 
Members of a class ( member variables and methods also known as instance variables/methods ) are accessed using “.” operator. There is no “Æ” operator in java 
s.setName(“Ali”); 
sÆsetName(“Ali”) is incorrect and will not compile in java 
Note: Objects are always passed by reference and primitives are always passed by value in java. 
Task - Using Student Class 
Create objects of student class by calling default, parameterize and copy constructor 
Call student class various methods on these objects 
Student client code 
// File Test.java 
/* This class create Student class objects and demonstrates 
how to call various methods on objects 
*/ 
public class Test{ 
public static void main (String args[]){ 
// Make two student obejcts 
Student s1 = new Student("ali", 15); 
Student s2 = new Student(); //call to default costructor 
s1.print(); // display ali and 15 
s2.print(); // display not set and 100 
s2.setName("usman"); 
s2.setRollNo(20); 
System.out.print("Student name:" + s2.getName()); 
System.out.println(" rollNo:" + s2.getRollNo());
Web Design & Development – CS506 VU 
© Copyright Virtual University of Pakistan 
46 
System.out.println("calling copy constructor"); 
Student s3 = new Student(s2); //call to copy constructor 
s2.print(); 
s3.print(); 
s3.setRollNo(-10); //Roll No of s3 would be set to 100 
s3.print(); 
/*NOTE: public vs. private 
A statement like "b.rollNo = 10;" will not compile in a 
client of the Student class when rollNo is declared 
protected or private 
*/ 
} //end of main 
} //end of class 
Compile & Execute 
Compile both classes using javac commad. Run Test class using java command.
Web Design & Development – CS506 VU 
© Copyright Virtual University of Pakistan 
47 
More on Classes 
Static 
A class can have static variables and methods. Static variables and methods are associated with the class itself and are not tied to any particular object. Therefore statics can be accessed without instantiating an object. Static methods and variables are generally accessed by class name. 
The most important aspect of statics is that they occur as a single copy in the class regardless of the number of objects. Statics are shared by all objects of a class. Non static methods and instance variables are not accessible inside a static method because no this reference is available inside a static method. 
We have already used some static variables and methods. Examples are 
System.out.println(“some text”); -- out is a static variable 
JOptionPane.showMessageDialog(null, “some text”); -- showMessageDialog is a static method 
Garbage Collection & Finalize 
Java performs garbage collection and eliminates the need to free objects explicitly. When an object has no references to it anywhere except in other objects that are also unreferenced, its space can be reclaimed. 
Before an object is destroyed, it might be necessary for the object to perform some action. For example: to close an opened file. In such a case, define a finalize() method with the actions to be performed before the object is destroyed. 
finalize 
When a finalize method is defined in a class, Java run time calls finalize() whenever it is about to recycle an object of that class. It is noteworthy that a garbage collector reclaims objects in any order or never reclaims them. We cannot predict and assure when garbage collector will get back the memory of unreferenced objects. 
The garbage collector can be requested to run by calling System.gc() method. It is not necessary that it accepts the request and run.
Web Design & Development – CS506 VU 
© Copyright Virtual University of Pakistan 
48 
Example Code: using static & finalize () 
We want to count exact number of objects in memory of a Student class the one defined earlier. For this purpose, we’ll modify Student class. 
Add a static variable countStudents that helps in maintaining the count of student objects. 
Write a getter for this static variable. (Remember, the getter also must be static one. Hoping so, you know the grounds). 
In all constructors, write a code that will increment the countStudents by one. 
Override finalize() method and decrement the countStudents variable by one. 
Override toString() method. 
Class Object is a superclass (base or parent) class of all the classes in java by default. This class has already finalize() and toString() method (used to convert an object state into string). Therefore we are actually overriding these methods over here. (We’ll talk more about these in the handout on inheritance). 
By making all above modifications, student class will look like 
// File Student.java 
public class Student { 
private String name; 
private int rollNo; 
private static int countStudents = 0; 
// Standard Setters 
public void setName (String name) { 
this.name = name; 
} 
// Note the masking of class level variable rollNo 
public void setRollNo (int rollNo) { 
if (rollNo > 0) { 
this.rollNo = rollNo; 
}else { 
this.rollNo = 100; 
} 
} 
// Standard Getters 
public String getName ( ) { 
return name; 
} 
public int getRollNo ( ) { 
return rollNo; 
}
Web Design & Development – CS506 VU 
© Copyright Virtual University of Pakistan 
49 
// gettter of static countStudents variable 
public static int getCountStudents(){ 
return countStudents; 
} 
// Default Constructor public Student() { 
name = “not set”; 
rollNo = 100; 
countStudents += 1; 
} 
// parameterized Constructor for a new student 
public Student(String name, int rollNo) { 
setName(name); //call to setter of name 
setRollNo(rollNo); //call to setter of rollNo 
countStudents += 1; 
} 
// Copy Constructor for a new student 
public Student(Student s) { 
name = s.name; 
rollNo = s.rollNo; 
countStudents += 1; 
} 
// method used to display method on console 
public void print () { 
System.out.print("Student name: " +name); 
System.out.println(", roll no: " +rollNo); 
} 
// overriding toString method of java.lang.Object class 
public String toString(){ 
return “name: ” + name + “ RollNo: ” + rollNo; 
} 
// overriding finalize method of Object class 
public void finalize(){ 
countStudents -= 1; 
} 
} // end of class 
Next, we’ll write driver class. After creating two objects of student class, we deliberately loose object’s reference and requests the JVM to run garbage collector to reclaim the memory. By printing countStudents value, we can confirm that. Coming up code is of the Test class.
Web Design & Development – CS506 VU 
© Copyright Virtual University of Pakistan 
50 
// File Test.java 
public class Test{ 
public static void main (String args[]){ 
int numObjects; 
// printing current number of objects i.e 0 
numObjs = Student.getCountStudents(); 
System.out.println(“Students Objects” + numObjects); 
// Creating first student object & printing its values 
Student s1 = new Student("ali", 15); 
System.out.println(“Student: ” + s1.toString()); 
// printing current number of objects i.e. 1 
numObjs = Student.getCountStudents(); 
System.out.println(“Students Objects” + numObjects); 
// Creating second student object & printing its values 
Student s2 = new Student("usman", 49); 
// implicit call to toString() method 
System.out.println(“Student: ” + s2); 
// printing current number of objects i.e. 2 
numObjs = Student.getCountStudents(); 
System.out.println(“Students Objects” + numObjects); 
// loosing object reference 
s1 = null 
// requesting JVM to run Garbage collector but there is 
// no guarantee that it will run 
System.gc(); 
// printing current number of objects i.e. unpredictable 
numObjs = Student.getCountStudents(); 
System.out.println(“Students Objects” + numObjects); 
} //end of main 
} //end of class
Web Design & Development – CS506 VU 
© Copyright Virtual University of Pakistan 
51 
The compilation and execution of the above program is given below. Note that output may be different one given here because it all depends whether garbage collector reclaims the memory or not. Luckily, in my case it does. 
Reference: 
Sun java tutorial: http://java.sun.com/docs/books/tutorial/java 
Thinking in java by Bruce Eckle 
Beginning Java2 by Ivor Hortan 
Example code, their explanations and corresponding execution figures for this handout are taken from the book JAVA A Lab Course by Umair Javed. This material is available just for the use of VU students of the course Web Design and Development and not for any other commercial purpose without the consent of author.
Web Design & Development – CS506 VU 
© Copyright Virtual University of Pakistan 
52 
Lesson 5 
Inheritance 
In general, inheritance is used to implement a “is-a” relationship. Inheritance saves code rewriting for a client thus promotes reusability. 
In java parent or base class is referred as super class while child or derived class is known as sub class. 
Comparison with C++ 
ƒJava only supports single inheritance. As a result a class can only inherit from one class at one time. 
ƒKeyword extends is used instead of “:” for inheritance. 
ƒAll functions are virtual by default 
ƒAll java classes inherit from Object class (more on it later). 
ƒTo explicitly call the super class constructor, use super keyword. It’s important to remember that call to super class constructor must be first line. 
ƒKeyword super is also used to call overridden methods.
Web Design & Development – CS506 VU 
© Copyright Virtual University of Pakistan 
53 
Example Code: using inheritance 
We’ll use three classes to get familiar you with inheritance. First one is Employee class. This will act as super class. Teacher class will inherit from Employee class and Test class is driver class that contains main method. Let’s look at them one by one 
class Employee{ 
protected int id; 
protected String name; 
//parameterized constructor 
public Employee(int id, String name){ 
this.id = id; 
this.name = name; 
} 
//default constructor 
public Employee(){ 
// calling parameterized constructor of same (Employee) 
// class by using keyword this 
this (10, “not set”); 
} 
//setters 
public void setId (int id) { 
this.id = id; 
} 
public void setName (String name) { 
this.name = name; 
} 
//getters 
public int getId () { 
return id; 
} 
public String getName () { 
return name; 
} 
// displaying employee object on console 
public void display(){ 
System.out.println(“in employee display method”); 
System.out.println("Employee id:" + id + " name:" + name); 
} 
//overriding object’s class toString method 
public String toString() { 
System.out.println(“in employee toString method”); 
return "id:" + id + "name:" + name; 
} 
}//end class
Web Design & Development – CS506 VU 
© Copyright Virtual University of Pakistan 
54 
The Teacher class extends from Employee class. Therefore Teacher class is a subclass of 
Employee. The teacher class has an additional attribute i.e. qualification. 
class Teacher extends Employee{ 
private String qual; 
//default constructor 
public Teacher () { 
//implicit call to superclass default construct 
qual = ""; 
} 
//parameterized constructor 
public Teacher(int i, String n, String q){ 
//call to superclass param const must be first line 
super(i,n); 
qual = q; 
} 
//setter 
public void setQual (String qual){ 
this.qual = qual; 
} 
//getter 
public String getQual(){ 
return qual; 
} 
//overriding display method of Employee class 
public void display(){ 
System.out.println("in teacher's display method"); 
super.display(); //call to superclass display method 
System.out.println("Teacher qualification:" + qual); 
} 
//overriding toString method of Employee class 
public String toString() { 
System.out.println("in teacher's toString method"); 
String emp = super.toString(); 
return emp +" qualification:" + qual; 
} 
}//end class
Web Design & Development – CS506 VU 
© Copyright Virtual University of Pakistan 
55 
Objects of Employee & Teacher class are created inside main method in Test class. Later calls are made to display and toString method using these objects. 
class Test{ 
public static void main (String args[]){ 
System.out.println("making object of employee"); 
Employee e = new Employee(89, "khurram ahmad"); 
System.out.println("making object of teacher"); 
Teacher t = new Teacher (91, "ali raza", "phd"); 
e.display(); //call to Employee class display method 
t.display(); //call to Teacher class display method 
// calling employee class toString method explicitly 
System.out.println("Employee: " +e.toString()); 
// calling teacher class toString implicitly 
System.out.println("Teacher: " + t); 
} //end of main 
}//end class 
Output
Web Design & Development – CS506 VU 
© Copyright Virtual University of Pakistan 
56 
Teacher 
Object – The Root Class 
The Od Java classes. For user defined classes, its not necessary to mention the Object class as a super class, java doesbject class in Java is a superclass for all other classes defined in Java's class libraries, as well as for user-define it automatically for you. 
The class Hierarchy of Employee class is shown below. Object is the super class of Employee class and Teacher is a subclass of Employee class. We can make another class Manager that can also extends from Employee class. 
Object 
Employe 
Manager
Web Design & Development – CS506 VU 
© Copyright Virtual University of Pakistan 
57 
Polymorphism 
“Polymorphic” literally means “of multiple shapes” and in the context of OOP, polymorphic means “having multiple behavior”. 
A parent class reference can point to the subclass objects because of is-a relationship. For example a Employee reference can point to: 
o Employee Object 
o Teacher Object 
o Manager Object 
A polymorphic method results in different actions depending on the object being referenced 
o Also known as late binding or run-time binding 
Example Code: using polymorphism 
This Test class is the modification of last example code. Same Employee & Teacher classes are used. Objects of Employee & Teacher class are created inside main methods and calls are made to display and toString method using these objects. 
class Test{ 
public static void main (String args[]){ 
// Make employee references 
Employee ref1, ref2; 
// assign employee object to first employee reference 
ref1 = new Employee(89, "khurram ahmad"); 
// is-a relationship, polymorphism 
ref2 = new Teacher (91, "ali raza", "phd"); 
//call to Employee class display method 
ref1.display(); 
//call to Teacher class display method 
ref2.display(); 
// call to Employee class toString method 
System.out.println("Employee: " +ref1.toString()); 
// call to Teacher class toString method 
System.out.println("Teacher: " + ref2.toString()); 
} //end of main 
}//end class
Web Design & Development – CS506 VU 
© Copyright Virtual University of Pakistan 
58 
Output
Web Design & Development – CS506 VU 
© Copyright Virtual University of Pakistan 
59 
Type Casting 
In computer science, type conversion or typecasting refers to changing an entity of one datatype into another. Type casting can be categorized into two types 
1. Up-casting 
Converting a smaller data type into bigger one 
Implicit – we don’t have to do something special 
No loss of information 
Examples of 
— Primitives 
int a = 10; 
double b = a; 
— Classes 
Employee e = new Teacher( ); 
2. Down-casting 
Converting a bigger data type into smaller one 
Explicit – need to mention 
Possible loss of information 
Examples of 
— Primitives 
double a = 7.65; 
int b = (int) a; 
— Classes 
Employee e = new Teacher( ); // up-casting 
Teacher t = (Teacher) e; // down-casting 
References: 
Java tutorial: http://java.sun.com/docs/books/tutorial/java/javaOO/ 
Stanford University 
Example code, their explanations and corresponding figures for handout 5-1,5-2 are taken from the book JAVA A Lab Course by Umair Javed. This material is available just for the use of VU students of the course Web Design and Development and not for any other commercial purpose without the consent of author.
Web Design & Development – CS506 VU 
© Copyright Virtual University of Pakistan 
60 
Lesson 6 
Collections 
A collection represents group of objects know as its elements. Java has a built-in support for collections. Collection classes are similar to STL in C++. An advantage of a collection over an array is that you don’t need to know the eventual size of the collection in order to add objects to it. The java.util package provides a set of collection classes that helps a programmer in number of ways. 
Collections Design 
All classes almost provides same methods like get(), size(), isEmpty() etc. These methods will return the object stored in it, number of objects stored and whether collection contains an object or not respectively. 
Java collections are capable of storing any kind of objects. Collections store references to objects. This is similar to using a void* in C. therefore down casting is required to get the actual type. For example, if string in stored in a collection then to get it back, we write 
String element = (String)arraylist.get(i); 
Collection messages 
Some basic messages (methods) are: 
Constructor 
— creates a collection with no elements 
int size() 
— returns the number of elements in a collection 
boolean add(Object) 
— adds a new element in the collection 
— returns true if the element is added successfully false otherwise 
boolean isEmpty() 
— returns true if this collection contains no element false otherwise 
boolean contains(Object) 
— returns true if this collection contains the specified element by using iterative search 
boolean remove(Object) 
— removes a single instance of the specified element from this collection, if it is present
Web Design & Development – CS506 VU 
© Copyright Virtual University of Pakistan 
61 
ArrayList 
It’s like a resizable array. ArrayList actually comes as a replacement the old “Vector” collection. As we add or remove elements into or from it, it grows or shrinks over time. 
Useful Methods 
add (Object) 
— With the help of this method, any object can be added into ArrayList because 
Object is the super class of all classes. 
— Objects going to add will implicitly up-cast. 
Object get(int index) 
— Returns the element at the specified position in the list 
— index ranges from 0 to size()-1 
— must cast to appropriate type 
remove (int index) 
— Removes the element at the specified position in this list. 
— Shifts any subsequent elements to the left (subtracts one from their indices). 
int size( ) 
Example Code: Using ArrayList class 
We’ll store Student objects in the ArrayList. We are using the same student class which we built in previous lectures/handouts. 
We’ll add three student objects and later prints all the student objects after retrieving them from ArrayList. Let’s look at the code 
iport java.util.*; 
public class ArrayListTest { 
public static void main(String[] args) { 
// creating arrayList object by calling constructor 
ArrayList al= new ArrayList(); 
// creating three Student objects 
Student s1 = new Student (“ali” , 1); 
Student s2 = new Student (“saad” , 2); 
Student s3 = new Student (“raza” , 3); 
// adding elements (Student objects) into arralylist al.add(s1); 
al.add(s2); 
al.add(s3);
Web Design & Development – CS506 VU 
© Copyright Virtual University of Pakistan 
62 
// checking whether arraylist is empty or not boolean b = al.isEmpty (); 
if (b = = true) { 
System.out.println(“arraylist is empty”); 
} else { 
int size = al.size(); 
System.out.println(“arraylist size: ” + size); 
} 
// using loop to iterate. Loops starts from 0 to one 
// less than size 
for (int i=0; i<al.size(); i++ ){ 
// retrieving object from arraylist 
Student s = (Student) al.get(i); 
// calling student class print method 
s.print(); 
} // end for loop 
} // end main 
} // end class 
Output 
HashM 
ap 
Store el ue pair form. A key is associated with each object that is stored. This 
al 
Useful M 
put(Object key, Object Value) 
Values are stored in the form of objects (implicit upcasting is performed). 
— Associates the specified value with the specified key in this map. 
ements in the form of key- vallows fast retrieval of that object. 
Keys are unique. hods 
et 
— Keys &
Web Design & Development – CS506 VU 
© Copyright Virtual University of Pakistan 
63 
— If the map previously contained a mapping for this key, the old value is replaced. 
Object get(Object key) 
ing for this key. 
owncast to appropriate type when used 
int 
Example Code: usin 
In of strings as keys. Same 
Student cla 
iport java.util.*; 
public g[] args) { 
p object 
HashMap(); 
// creating Student objects 
= new Student (“ali” , 1); Student s2 = new Student (“saad” , 
dding elements (Student objects) where roll nos 
// are stored as keys and student objects as values 
h.put(“six”, s3); 
// checking whether hashmap is empty or not boolean b = h.isEmpty (); 
ty”); 
} else { 
int size = h.size(); 
.out.println(“hashmap size: ” + size); 
// retrieving student object against rollno two and 
performing downcasting 
Student s = (Student) h.get(“two”); 
// calling student’s class print method s.print(); 
— Returns the value to which the specified key is mapped in this identity hash map, or null if the map contains no mapp 
— Must d 
size( ) 
g HashMap class 
this example code, we’ll store St 
udent objects as values and their rollnos in the form ss is used. The code is; 
public c 
lass HashMapTest { 
static void main(Strin 
// creating HashMa 
HashMap h= new 
Student s1 
2); Student s3 = new Student (“raza” , 6); 
// a 
h.put(“one” , s1); 
h.put(“two” , s2); 
if (b = = true) { 
System.out.println(“hashmap is emp 
System 
} 
//
Web Design & Development – CS506 VU 
© Copyright Virtual University of Pakistan 
64 
} // end main 
} // end class 
Output 
Ref 
erences: 
J2SE 5.0 new features: http://java.sun.com/j2se/1.5.0/docs/relnotes/features.html 
Technical Article: http://java.sun.com/developer/technicalArticles/releases/j2se15/ 
Beginning Java2 by Ivor Horton 
Example code, their explanations and corresponding figures for this handout are taken from the book JAVA 
A Lab Course by Umair Javed. This material is available just for the use of VU students of the course 
Web Design and Development and not for any other commercial purpose without the consent of author.
Web Design & Development – CS506 VU 
© Copyright Virtual University of Pakistan 
65 
Address Book 
Warning: It is strongly advised that you type the code given in this example yourself. Do not copy/paste it; most probably you will get unexpected errors that you have never seen. Some bugs are deliberately introduced as well to avoid copy- pasting. TAs will not cooperate with you in debugging such errors☺. 
Problem 
We want to build an address book that is capable of storing name, address & phone number of a person. 
Address book provides functionality in the form of a JOptionPane based menu. The feature list includes 
ƒ Add – to add a new person record 
ƒ Delete – to delete an existing person record by name 
ƒ Search – to search a person record by name 
ƒ Exit – to exit from application 
The Address book should also support persistence for person records 
Approach for Solving Problem 
Building a small address book generally involves 3 steps. Let us briefly discuss each step and write a solution code for each step 
Step1 – Make PersonInfo class 
First of all you need to store your desired information for each person. For this you can create a user- defined data type (i.e. a class). Make a class PersonInfo with name, address and phone number as its attributes. 
Write a parameterized constructor for this class. 
Write print method in Person class that displays one person record on a message dialog box.
Web Design & Development – CS506 VU 
© Copyright Virtual University of Pakistan 
66 
The code for PersonInfo class is given below. 
import javax.swing.*; 
class PersonInfo { 
String name; 
String address; 
String phoneNum; 
//parameterized constructor 
public PersonInfo(String n, String a, String p) { 
name = n; 
address = a; 
phoneNum = p; 
} 
//method for displaying person record on GUI 
public void print( ) { 
JOptionPane.showMessageDialog(null, “name: ” + name + 
“address:” +address + “phone no:” + phoneNum); 
} 
} 
Note: Not declaring attributes as private is a bad approach but we have done it to keep things simple here. 
Step2 – Make AddressBook class 
Take the example of daily life; generally address book is used to store more than one person records and we don’t know in advance how many records are going to be added into it. 
So, we need some data structure that can help us in storing more than one 
PersonInfo objects without concerning about its size. 
ArrayList can be used to achieve the above functionality 
Create a class Address Book with an ArrayList as its attribute. This arraylist will be used to store the information of different persons in the form of PersonInfo Objects. This class will also provide addPerson, deletePerson & searchPerson methods. These methods are used for adding new person records, deleting an existing person record by name and searching among existing person records by name respectively. 
Input/Output will be performed through JOptionPane.
Web Design & Development – CS506 VU 
Copyright Virtual University of Pakistan 67 
The code for AddressBook class is 
import javax.swing.*; 
import java.util.*; 
class AddressBook { 
ArrayList persons; 
//constructor 
public AddressBook ( ) { 
persons = new ArrayList(); 
} 
//add new person record to arraylist after taking input 
public void addPerson( ) { 
String name =JOptionPane.showInputDialog(“Enter name”); 
String add = JOptionPane.showInputDialog(“Enter address”); 
String pNum = JOptionPane.showInputDialog(“Enter phone no”); 
//construt new person object 
PersonInfo p = new PersonInfo(name, add, pNum); 
//add the above PersonInfo object to arraylist 
persons.add(p); 
} 
//search person record by name by iterating over arraylist 
public void searchPerson (String n) { 
for (int i=0; i< persons.size(); i++) { 
PersonInfo p = (PersonInfo)persons.get(i); 
if ( n.equals(p.name) ) { 
p.print(); 
} 
} // end for 
} // end searchPerson 
//delete person record by name by iterating over arraylist 
public void deletePerson (String n) { 
for (int i=0; i< persons.size(); i++) { 
PersonInfo p = (PersonInfo)persons.get(i); 
if ( n.equals(p.name) ) { 
persons.remove(i); 
}
Web Design & Development – CS506 VU 
Copyright Virtual University of Pakistan 68 
} 
} 
} // end class 
The addperson method first takes input for name, address and phone number and than construct a PersonInfo object by using the recently taken input values. Then the newly constructed object is added to the arraylist – persons. 
The searchPerson & deletePerson methods are using the same methodology i.e. first they search the required record by name and than prints his/her detail or delete the record permanently from the ArrayList. 
Both the methods are taking string argument, by using this they can perform their search or delete operation. We used for loop for iterating the whole ArrayList. By using the size method of ArrayList, we can control our loop as ArrayList indexes range starts from 0 to one less than size. 
Notice that, inside loop we retrieve each PersonInfo object by using down casting operation. After that we compare each PersonInfo object’s name by the one passed to these methods using equal method since Strings are always being compared using equal method. 
Inside if block of searchPerson, print method is called using PersonInfo object that will display person information on GUI. On the other hand, inside if block of deletePerson method, remove method of ArrayList class is called that is used to delete record from persons i.e. ArrayList. 
Step3 – Make Test class (driver program) 
This class will contain a main method and an object of AddressBook class. 
Build GUI based menu by using switch selection structure 
Call appropriate methods of AddressBook class 
The code for Test class is 
import javax.swing.*; 
class Test { 
Public static void main (String args[]) { 
AddressBook ab = new AddressBook(); 
String input, s; 
int ch; 
while (true) { 
input = JOptionPane.showInputDialog(“Enter 1 to add ” + 
“n Enter 2 to Search n Enter 3 to Delete“ + 
“n Enter 4 to Exit”);
Web Design & Development – CS506 VU 
Copyright Virtual University of Pakistan 69 
ch = Integer.parseInt(input); 
switch (ch) { 
case 1: 
ab.addPerson(); 
break; 
case 2: 
s = JOptionPane.showInputDialog( 
“Enter name to search ”); 
ab.searchPerson(s); 
break; 
case 3: 
s = JOptionPane.showInputDialog( 
“Enter name to delete ”); 
ab.deletePerson(s); 
break; 
case 4: 
System.exit(0); 
} 
}//end while 
}//end main 
} 
Note that we use infinite while loop that would never end or stop given that our program should only exit when user enters 4 i.e. exit option. 
Compile & Execute 
Compile all three classes and run Test class. Bravo, you successfully completed the all basic three steps. Enjoy! ☺. 
Reference 
Entire content for this handout are taken from the book JAVA A Lab Course by Umair Javed. This material is available just for the use of VU students of the course Web Design and Development and not for any other commercial purpose.
Web Design & Development – CS506 VU 
Copyright Virtual University of Pakistan 70 
Lesson 7 
Intro to Exceptions 
Types of Errors 
Generally, you can come across three types of errors while developing software. These are Syntax, Logic & Runtime errors. 
1. Syntax Errors 
Arise because the rules of the language are not followed. 
2. Logic Errors 
Indicates that logic used for coding doesn’t produce expected output. 
3. Runtime Errors 
Occur because the program tries to perform an operation that is impossible to complete. 
Cause exceptions and may be handled at runtime (while you are running the program) 
For example divide by zero 
What is an Exception? 
An exception is an event that usually signals an erroneous situation at run time 
Exceptions are wrapped up as objects 
A program can deal with an exception in one of three ways: 
o ignore it 
o handle it where it occurs 
o handle it an another place in the program 
Why handle Exceptions? 
Helps to separate error handling code from main logic (the normal code you write) of the program. 
As different sort/type of exceptions can arise, by handling exceptions we can distinguish between them and write appropriate handling code for each type for example we can differently handle exceptions that occur due to division by Zero and exceptions that occur due to non-availability of a file. 
If not handled properly, program might terminate.
Web Design & Development – CS506 VU 
Copyright Virtual University of Pakistan 71 
Exceptions in Java 
An exception in java is represented as an object that’s created when an abnormal situation arises in the program. Note that an error is also represented as an object in Java, but usually represents an unrecoverable situation and should not be caught 
The exception object stores information about the nature of the problem. For example, due to network problem or class not found etc. 
All exceptions in java are inherited from a class know as Throwable. 
Exception Hierarchy 
Following diagram is an abridged version of Exception class hierarchy
Web Design & Development – CS506 VU 
Copyright Virtual University of Pakistan 72 
Types of Exceptions 
Exceptions can be broadly categorized into two types, Unchecked & Checked Exceptions. 
Unchecked Exceptions 
• Subclasses of RuntimeException and Error. 
• Does not require explicit handling 
• Run-time errors are internal to your program, so you can get rid of them by debugging your code 
• For example, null pointer exception; index out of bounds exception; division by zero exception; ... 
Checked Exceptions 
• Must be caught or declared in a throws clause 
• Compile will issue an error if not handled appropriately 
• Subclasses of Exception other than subclasses of RuntimeException. 
• Other arrive from external factors, and cannot be solved by debugging 
• Communication from an external resource – e.g. a file server or database 
How Java handles Exceptions 
Java handles exceptions via 5 keywords. try, catch, finally, throw & throws. 
ƒ try block 
• Write code inside this block which could generate errors 
ƒ catch block 
• Code inside this block is used for exception handling 
• When the exception is raised from try block, only than catch block would execute. 
ƒ finally block 
• This block always executes whether exception occurs or not. 
• Write clean up code here, like resources (connection with file or database) that are opened may need to be closed.
Web Design & Development – CS506 VU 
Copyright Virtual University of Pakistan 73 
The basic structure of using try – catch – finally block is shown in the picture below: 
try //try block 
{ 
// write code that could generate exceptions 
} catch (<exception to be caught>) //catch block 
{ 
} 
…… 
....... 
//write code for exception handling 
catch (<exception to be caught>) //catch block 
{ 
//code for exception handling 
} finally //finally block 
{ 
//any clean-up code, release the acquired resources 
}
Web Design & Development – CS506 VU 
Copyright Virtual University of Pakistan 74 
ƒ throw 
• To manually throw an exception, keyword throw is used. 
Note: we are not covering throw clause in this handout 
ƒ throws 
• If method is not interested in handling the exception than it can throw back the exception to the caller method using throws keyword. 
• Any exception that is thrown out of a method must be specified as such by a 
throws clause. 
References: 
ƒ Java tutorial by Sun: http://java.sun.com/docs/books/turorial 
ƒ Beginning Java2 by Ivor Hortan 
ƒ Thinking in Java by Bruce Eckle 
ƒ CS193j Stanford University
Web Design & Development – CS506 VU 
Copyright Virtual University of Pakistan 75 
Code Examples of Exception Handling 
Unchecked Exceptions 
Example Code: UcException.java 
The following program takes one command line argument and prints it on the console 
// File UcException.java 
public class UcException { 
public static void main (String args[ ]) { 
System.out.println(args[0]); 
} 
} 
Compile & Execute 
If we compile & execute the above program without passing any command line argument, an ArrayIndexOutOfBoundsException would be thrown. This is shown in the following picture 
Since we have passed size of String args[ ] is zero, and we have tried to access the first 
element (first element has index zero) of this array. 
From the output window, you can find out, which code line causes the exception to be raised. In the above 
example, it is 
System.out.println(args[0]); 
Why? 
no argument, therefore the
Web Design & Development – CS506 VU 
Copyright Virtual University of Pakistan 76 
Modify UcException.java 
Though it is not mandatory to handle unchecked exceptions we can still handle 
Unchecked Exceptions if we want to. These modifications are shown in bold. 
// File UcException.java 
public class UcException { 
public static void main (String args[ ]) { 
try { 
System.out.println(args[0]); 
catch (IndexOutOfBoundsExceptoin ex) { 
System.out.println(“You forget to pass command line argument”); 
} 
} 
The possible exception that can be thrown is IndexOutOfBoundsException, so we handle it in the catch block. 
When an exception occurs, such as IndexOutOfBoundsException in this case, then an object of type IndexOutOfBoundesException is created and it is passed to the corresponding catch block (i.e. the catch block which is capable of handling this exception). The catch block receives the exception object inside a variable which is ex in this case. It can be any name; it is similar to the parameter declared in the method signature. It receives the object of exception type (IndexOutOfBoundsExceptoin) it is declared. 
Compile & Execute 
If we execute the modified program by passing command line argument, the program would display on console the provided argument. After that if we execute this program again without passing command line argument, this time information message would be displayed which is written inside catch block.
Web Design & Development – CS506 VU 
Copyright Virtual University of Pakistan 77 
Checked Exceptions 
Example Code: CException.java 
The following program reads a line (hello world) from a file and prints it on the console. The File reading code is probably new for you. We’ll explain it in the coming handouts 
(Streams). For now, assumed that the code written inside the main read one line from a file and prints that to console. 
// File CException.java 
import java.io.* ; 
public class CException { 
public static void main (String args[ ]) { 
FileReader fr = new FileReader (“input.txt”); 
BufferedReader br = new BufferedReader (fr); 
//read the line form file 
String line = br.readLine(); 
System.out.println(line); 
} 
} 
Compile & Execute 
If you try to compile this program, the program will not compile successfully and displays the message of unreported exception. This happens when there is code that can generate a checked exception but you have not handled that exception. Remember checked exceptions are detected by compiler. As we early discussed, without handling Checked exception, out program won’t compile.
Web Design & Development – CS506 VU 
Copyright Virtual University of Pakistan 78 
Modify CException.java 
As we have discussed earlier, it is mandatory to handle checked exceptions. In order to compile the code above, we modify the above program so that file reading code is placed inside a try block. The expected exception (IOException) that can be raised is caught in catch block. 
// File CException.java 
import java.io.* ; 
public class CException { 
public static void main (String args[ ]) { 
try{ 
FileReader fr = new FileReader (“input.txt”); 
BufferedReader br = new BufferedReader (fr); 
//read the line form file 
String line = br.readLine(); 
System.out.println(line); 
catch( IOExceptoin ex) { 
System.out.println(ex); 
} 
} 
} 
The code line written inside the catch block will print the exception name on the console if exception occurs 
Compile & Execute 
After making changes to your program, it would compile successfully. On executing this program, hello world would be displayed on the console 
Note: Before executing, make sure that a text file named input.txt must be placed in the same directory where the program is saved. Also write hello world in that file before saving it.
Web Design & Development – CS506 VU 
Copyright Virtual University of Pakistan 79 
The finally block 
The finally block always executes regardless of exception is raised or not while as you remembered the catch block only executes when an exception is raised. 
Exampel Code : FBlockDemo.java 
// File FBlockDemo.java 
import java.io.* ; 
public class FBlockDemo { 
public static void main (String args[ ]) { 
try{ 
FileReader fr = new FileReader (“strings.txt”); 
BufferedReader br = new BufferedReader (fr); 
//read the line form file 
String line = br.readLine(); 
System.out.println(line); 
catch( IOExceptoin ex) { 
System.out.println(ex); 
} 
finally { 
System.out.println(“finally block always execute”); 
} 
} 
} 
Compile & Execute 
The program above, will read one line from string.txt file. If string.tx is not present in the same directory the FileNotFoundException would be raised and catch block would execute as well as the finally block. 
If string.txt is present there, no such exception would be raised but still finally block executes. This is shown 
in the following output diagram
Web Design & Development – CS506 VU 
Copyright Virtual University of Pakistan 80 
Mul 
tiple catch blocks 
• 
Possible to have multiple catch clau ses for a single try statement 
• Evaluated in the order of the code 
– tion hierarchy when writing multiple catch clauses! 
– t and then IOException, the IOException will never be caught! 
Exam 
The f ing program would read a number form a file numbers.txt and than prints its square on the console 
g args[ ]) { 
try{ 
tion 
ers.txt”); 
BufferedReader br = new BufferedReader (fr); 
String s = br.readLine(); 
//may throws NumberFormatException, if s is not a no. 
number); 
toin nfEx) { 
catch( FileNotFoundExceptoin fnfEx) { 
– Essentially checking for different types of exceptions that may happen 
Bear in mind the Excep 
If you catch Exception firs 
ple code: MCatchDemo.java 
ollow 
// File MCatchDemo.java 
import java.io.* ; 
public class MCatchDemo { 
public static void main (Strin 
// can throw FileNotFound or IOExcep 
FileReader fr = new FileReader (“numb 
//read the number form file 
int number = Integer.parseInt(s); 
System.out.println(number * 
catch( NumberFormatExcep 
System.out.println(nfEx); 
}
Web Design & Development – CS506 VU 
Copyright Virtual University of Pakistan 81 
System.out.println(fnfEx); 
} 
} 
We read everything from a file (numbers, floating values or text) as a String. That’s why we first convert it to 
numb and than print its square on console. 
If file numbers.txt is not present in the same directory, the FileNotFoundException 
would be thrown during execution. 
catch( IOExceptoin ioEx) { System.out.println(ioEx); 
} 
} 
er 
Compile & Execute 
If numbers.txt present in the same directory and contains a number, than hopefully no exception would be 
thrown.
Web Design & Development – CS506 VU 
© Copyright Virtual University of Pakistan 
82 
The throws clause 
The following code examples will introduce you with writing & using throws clause. 
Example Code: ThrowsDemo.java 
The ThrowsDemo.java contains two methods namely method1 & method2 and one main method. The main method will make call to method1 and than method1 will call method2. The method2 contains the file reading code. The program looks like one given below 
// File ThrowsDemo.java 
import java.io.* ; 
public class ThrowsDemo { 
// contains file reading code 
public static void method2( ) { 
try{ 
FileReader fr = new FileReader (“strings.txt”); 
BufferedReader br = new BufferedReader (fr); 
//read the line form file 
String s = br.readLine(); 
System.out.println(s); 
catch( IOExceptoin ioEx) { 
ioEx.printStackTrace(); 
} 
}// end method 2 
//only calling method2 
public static void method1( ) { 
method2(); 
} 
public static void main (String args[ ]) { 
ThrowsDemo.method1(); 
} 
}
Web Design & Development – CS506 VU 
© Copyright Virtual University of Pakistan 
83 
printStackTrace method 
Defined in the Throwable class – superclass of Exception & Error classes 
Shows you the full method calling history with line numbers. 
Extremely useful in debugging 
Modify: ThrowsDemo.java 
Let method2 doesn’t want to handle exception by itself, so it throws the exception to the caller of method2 i.e. method1 
So method1 either have to handle the incoming exception or it can re-throw it to its caller i.e. main. 
Let method1 is handling the exception, so method1& method2 would be modified as: 
// File ThrowsDemo.java 
import java.io.* ; 
public class ThrowsDemo { 
// contains file reading code 
public static void method2( ) throws IOEception{ 
FileReader fr = new FileReader (“strings.txt”); 
BufferedReader br = new BufferedReader (fr); 
//read the line form file 
String s = br.readLine(); 
System.out.println(s); 
}// end method 2 
// calling method2 & handling incoming exception 
public static void method1( ) { 
try { 
method2(); 
catch (IOException ioEx) { 
ioEx.printStackTrace(); 
} 
} 
public static void main (String args[ ]) { 
ThrowsDemo.method1(); 
} 
}
Web Design & Development – CS506 VU 
© Copyright Virtual University of Pakistan 
84 
Compile & Execute 
If file strings.txt is not present in the same directory, method2 will throw an exception that would be caught by method1 and the printStackTrace method will print the full calling history on console. The above scenario is shown in the output below: 
If file strings.txt exist there, than hopefully line would be displayed on the console. 
Reference 
Example code, their explanations and corresponding figures for this handout are taken from the book JAVA 
A Lab Course by Umair Javed. This material is available just for the use of VU students of the course Web 
Design and Development and not for any other commercial purpose without the consent of author.
Web Design & Development – CS506 VU 
© Copyright Virtual University of Pakistan 
85 
Lesson 8 
Streams 
I/O libraries often use the abstraction of a stream, which represents any data source or sink as an object capable of producing or receiving pieces of data. 
The Java library classes for I/O are divided by input and output. You need to import java.io package to use streams. There is no need to learn all the streams just do it on the need basis. 
The concept of "streams" 
• It is an abstraction of a data source/sink 
• We need abstraction because there are lots of different devices (files, consoles, network, memory, etc.). We need to talk to the devices in different ways 
(sequential, random access, by lines, etc.) Streams make the task easy by acting in the same way for every device. Though inside handling of devices may be quite different, yet on the surface everything is similar. You might read from a file, the keyboard, memory or network connection, different devices may require specialization of the basic stream, but you can treat them all as just "streams". When you read from a network, you do nothing different than when you read from a local file or from user's typing 
//Reading from console 
BufferedReader stdin = new BufferedReader(new InputStreamReader( 
System.in )); 
-------- ( your console) 
// Reading from file 
BufferedReader br=new BufferedReader(new FileReader(“input.txt”)); 
//Reading from network 
BufferedReader br = new BufferedReader(new InputStreamReader 
(s.getInputStream())); 
---- “s” is the socket 
• So you can consider stream as a data path. Data can flow through this path in one direction between specified terminal points (your program and file, console, socket etc.)
Web Design & Development – CS506 VU 
© Copyright Virtual University of Pakistan 
86 
Stream classification based on Functionality 
Based on functionality streams can be categorized as Node Stream and Filter Stream. Node Streams are those which connect directly with the data source/sick and provide basic functionality to read/write data from that source/sink 
FileReader fr = new FileReader(“input.txt”); 
You can see that FileReader is taking a data/source “input.txt” as its argument and hence it is a node stream. 
FilterStreams sit on top of a node stream or chain with other filter stream and provide some additional functionality e.g. compression, security etc. FilterStreams take other stream as their input. 
BufferedReader bt = new BufferedReader(fr); 
BufferedReader makes the IO efficient (enhances the functionality) by buffering the input before delivering. And as you can see that BufferedReader is sitting on top of a node stream which is FileReader. 
Stream classification based on data
Web Design & Development – CS506 VU 
© Copyright Virtual University of Pakistan 
87 
Two type of classes exists. 
Classes which contain the word stream in their name are byte oriented and are here since JDK1.0. These streams can be used to read/write data in the form of bytes. Hence classes with the word stream in their name are byte- oriented in nature. Examples of byte oriented streams are FileInputStream, ObjectOutputStream etc. 
Classes which contain the word Reader/Writer are character oriented and read and write data in the form of characters. Readers and Writers came with JDK1.1. Examples of Reader/Writers are FileReader, PrintWriter etc
Web Design & Development – CS506 VU 
© Copyright Virtual University of Pakistan 
88 
Example Code 8.1: Reading from File 
The ReadFileEx.java reads text file line by line and prints them on console. Before we move on to the code, first create a text file (input.txt) using notepad and write following text lines inside it. 
Hello World 
Text File: input.txt 
Pakistan is our homeland 
Web Design and Development 
// File ReadFileEx.java 
import java.io.*; 
public class ReadFileEx { 
public static void main (String args[ ]) { 
FileReader fr = null; 
BufferedReader br = null; 
try { 
// attaching node stream with data source 
fr = new FileReader(“input.txt”); 
// attatching filter stream over node stream 
br = new BufferedReader(fr); 
// reading first line from file 
String line = br.readLine(); 
// printing and reading remaining lines 
while (line != null){ 
System.out.println(line); 
line = br.readLine(); 
} 
// closing streams 
br.close(); 
fr.close(); 
}catch(IOException ioex){ 
System.out.println(ioex); 
} 
} // end main 
} // end class
Web Design & Development – CS506 VU 
© Copyright Virtual University of Pakistan 
89 
Example Code 8.2: Writing to File 
The WriteFileEx.java writes the strings into the text file named “output.txt”. If 
“output.txt” file does not exist, the java will create it for you. 
// File WriteFileEx.java 
import java.io.*; 
public class WriteFileEx { 
public static void main (String args[ ]) { 
FileWriter fw = null; 
PrintWriter pw = null; 
try { 
// attaching node stream with data source 
// if file does not exist, it automatically creates it 
fw = new FileWriter (“output.txt”); 
// attatching filter stream over node stream 
pw = new PrintWriter(fw); 
String s1 = “Hello World”; 
String s2 = “Web Design and Development”; 
// writing first string to file 
pw.println(s1); 
// writing second string to file 
pw.println(s2); 
// flushing stream 
pw.flush(); 
// closing streams 
pw.close(); 
fw.close(); 
}catch(IOException ioex){ 
System.out.println(ioex); 
} 
} // end main 
} // end class 
After executing the program, check the output.txt file. Two lines will be written there. 
Reference 
Example code, their explanations and corresponding figures for this handout are taken from the book JAVA A Lab Course by Umair Javed. This material is available just for the use of VU students of the course Web Design and Development and not for any other commercial purpose without the consent of author.
Web Design & Development – CS506 VU 
© Copyright Virtual University of Pakistan 
90 
Lesson 9 
Modification of Address Book Code 
Adding Persistence Functionality 
Hopefully, your address book you built previously is giving you the required results except one i.e. persistence. You might have noticed that after adding some person records in the address book; if you exit form the program next time on re-executing address book all the previous records are no more available. 
To overcome the above problem, we will modify our program so that on exiting/starting of address book, all the previously added records are available each time. To achieve this, we have to provide the persistence functionality. Currently, we will accomplish this task by saving person records in some text file. 
Supporting simple persistence by any application requires handling of two scenarios. These are 
On start up of application – data (person records ) must be read from file 
On end/finish up of application – data (person records) must be saved in file 
To support persistence, we have to handle the above mentioned scenarios 
Scenario 1 – Start Up 
Establish a data channel with a file by using streams 
Start reading data (person records) from file line by line 
Construct PersonInfo objects from each line you have read 
Add those PersonInfo objects in arraylist persons. 
Close the stream with the file 
Perform these steps while application is loading up 
We will read records from a text file named persons.txt. The person records will be present in the file in the following format. 
Ali,defence,9201211 
Usman,gulberg,5173940 
Salman,LUMS,5272670 
persons.txt 
As you have seen, each person record is on a separate line. Person’s name, address & 
phone number is separated using comma (,). 
We will modify our AddressBook.java by adding a new method loadPersons into it. This method will provide the implementation of all the steps. The method is shown below:
Web Design & Development – CS506 VU 
© Copyright Virtual University of Pakistan 
91 
public void loadPersons ( ){ 
String tokens[] = null; 
String name, add, ph; 
try { 
FileReader fr = new FileReader("persons.txt"); 
BufferedReader br = new BufferedReader(fr); 
String line = br.readLine(); 
while ( line != null ) { 
tokens = line.split(","); 
name = tokens[0]; 
add = tokens[1]; 
ph = tokens[2]; 
PersonInfo p = new PersonInfo(name, add, ph); 
persons.add(p); 
line = br.readLine(); 
} 
br.close(); 
fr.close(); 
}catch(IOException ioEx){ 
System.out.println(ioEx); 
} 
} 
First, we have to connect with the text file in order to read line by line person records from it. This task is accomplished with the following lines of code 
FileReader fr = new FileReader(“persons.txt”); BufferedReader br = new BufferedReader(fr); 
FileReader is a character based (node) stream that helps us in reading data in the form of characters. As we are using streams, so we have to import the java.io package in the AddressBook class. 
We passed the file name persons.txt to the constructor of the FileReader. 
Next we add BufferedReader (filter stream) on top of the FileReader because BufferedReader facilitates reading data line by line. (As you can recall from the lecture that filter streams are attached on top of node streams). That’s why the constructor of BufferedReader is receiving the fr – the FileReader object. 
The next line of code will read line from file by using readLine( ) method of 
BufferedReader and save it in a string variable called line. 
String line = br.readLine( );
Web Design & Development – CS506 VU 
© Copyright Virtual University of Pakistan 
92 
After that while loop starts. The condition of while loop is used to check whether the file is reached to end (returns null) or not. This loop is used to read whole file till the end. When end comes (null), this loop will finish. 
while (line != null) 
Inside loop, the first step we performed is tokenizing the string. For this purpose, we have used split method of String class. This method returns substrings (tokens) according to the regular expression or delimiter passed to it. 
tokens = line.split(“,”); 
The return type of this method is array of strings that’s why we have declared tokens as a String array in the beginning of this method as 
String tokens[]; 
For example, the line contains the following string 
Ali,defence,9201211 
Now by calling split(“,”) method on this string, this method will return back three substrings ali defence and 9201211 because the delimiter we have passed to it is comma. The delimiter itself is not included in the substrings or tokens. 
The next three lines of code are simple assignments statements. The tokens[0] contains the name of the person because the name is always in the beginning of the line, tokens[1] contains address of the person and tokens[2] contains the phone number of the person. 
name = tokens[0]; 
add = tokens[1]; 
ph = tokens[2]; 
The name, add and ph are of type String and are declared in the beginning of this method. 
After that we have constructed the object of PersonInfo class by using parameterized constructor and passed all these strings to it. 
PersonInfo p = new PersonInfo(name, add, ph); 
Afterward the PersonInfo object’s p is added to the arraylist i.e. persons. persons.add(p); 
The last step we have done inside loop is that we have again read a line form the file by using the readLine() method.
Web Design & Development – CS506 VU 
© Copyright Virtual University of Pakistan 
93 
By summarizing the task of while loop we can conclude that it reads the line from a file, 
Tokenize that line into three substrings followed by constructing the PersonInfo object by 
using these tokens. And adding these objects to the arraylist. This process continues till the file 
reaches its end. 
The last step for reading information from the file is ordinary one – closing the streams, 
because files are external resources, so it’s better to close them as soon as possible. 
Also observe that we used try/catch block because using streams can result in raising exceptions 
that falls under the checked exceptions category – that needs mandatory handling. 
The last important step you have to perform is to call this method while loading up. The most 
appropriate place to call this method is from inside the constructor of AddressBook.java. So 
the constructor will now look like similar to the one given below: 
……………… 
public AddressBook () { 
Persons = new ArrayList(); 
loadPersons(); 
} 
……………… 
AddressBook.java 
Scenario 2 – End/Finish Up 
Establish a datachanel(stream) with a file by using streams 
Take out PersonInfo objects from ArrayList (persons) 
Build a string for each PersonInfo object by inserting commas (,) between name 
& address and address & phone number. 
Write the constructed string to the file 
Close the connection with file 
Perform these steps while exiting from address book. 
Add another method savePersons into AddressBook.java. This method will provide the implementation of all the above mentioned steps. The method is shown below:
Web Design & Development – CS506 VU 
© Copyright Virtual University of Pakistan 
94 
Public void savePersons ( ){ 
try { 
PersonInfo p; 
String line; 
FileWriter fw = new FileWriter("persons.txt"); 
PrintWriter pw = new PrintWriter(fw); 
for(int i=0; i<persons.size(); i++) 
{ 
p = (PersonInfo)persons.get(i); 
line = p.name +","+ p.address +","+ p.phoneNum; 
// writes line to file (persons.txt) 
pw.println(line); 
} 
pw.flush(); 
pw.close(); 
fw.close(); 
}catch(IOException ioEx){ 
System.out.println(ioEx); 
} 
} 
As you can see, that we have opened the same file (persons.txt) again by using a set of streams. 
After that we have started for loop to iterate over arraylist as we did in 
searchPerson and deletePerson methods. 
Inside for loop body, we have taken out PersonInfo object and after type casting it we have assigned its reference to a PersonInfo type local variable p. This is achieved by the help of following line of code 
p = (PersonInfo)persons.get(i); 
Next we build a string and insert commas between the PersonInfo attributes and assign the newly constructed string to string’s local variable line as shown in the following line of code. 
line = p.name +","+ p.address +","+ p.phoneNum; 
Note: Since, we haven’t declare PersonInfo attributes private, therefore we are able to directly access them inside AddressBook.java. 
The next step is to write the line representing one PersonInfo object’s information, to the file. This 
is done by using println method of PrintWriter as shown below 
pw.println(line);
Web Design & Development – CS506 VU 
© Copyright Virtual University of Pakistan 
95 
After writing line to the file, the println method will move the cursor/control to the next line. That’s why each line is going to be written on separate line. 
The last step for saving information to the file is ordinary one – closing the streams but before that notice the code line that you have not seen/performed while loading persons records from file. That is 
pw.flush( ); 
The above line immediately flushes data by writing any buffered output/data to file. This step is necessary to perform or otherwise you will most probably lose some data for the reason that PrintWriter is a Buffered Stream and they have their own internal memory/storage capacity for efficiency reasons. Buffered Streams do not send the data until their memory is full. 
Also we have written this code inside try-catch block. 
The last important step you have to perform is to call this method before exiting from the address book. The most appropriate place to call this method is under case 4 
(exit scenario) in Test.java. So the case 4 will now look like similar to the one given below: 
case 4: 
ab.savePersons(); 
System.exit(0); 
Test.java 
Compile & Execute 
Now again after compiling all the classes, run the Test class. Initially we are assuming that out persons.txt file is empty, so our arraylist persons will be empty on the first start up of address book. Now add some records into it, perform search or delete operations. Exit from the address book by choosing option 4. Check out the persons.txt file. Don’t get surprised by seeing that it contains all the person records in the format exactly we have seen above. 
Next time you will run the address book; all the records will be available to you. Perform the search or delete operation to verify that. 
Finally You have done it !!! 
References 
Example code, their explanations and corresponding figures for this handout are taken from the book JAVA A Lab Course by Umair Javed. This material is available just for the use of VU students of the course Web Design and Development and not for any other commercial purpose without the consent of author.
Web Design & Development – CS506 VU 
© Copyright Virtual University of Pakistan 
96 
Abstract Classes and Interfaces 
Problem and Requirements 
Before moving on to abstract classes, first examine the following class hierarchy shown below: 
Circle Square 
• Suppose that in order to exploit polymorphism, we specify that 2-D objects must be able to compute their area. 
– All 2-D classes must respond to area() message. 
• How do we ensure that? 
– Define area method in class Shape 
– Force the subclasses of Shape to respond area() message 
• Java’s provides us two solutions to handle such problem 
– Abstract Classes 
– Interfaces 
Abstract Classes 
Abstract classes are used to define only part of an implementation. Because, information is not complete therefore an abstract class cannot be instantiate. However, like regular classes, they can also contain instance variables and methods that are full implemented. The class that inherits from abstract class is responsible to provide details. 
Any class with an abstract method (a method has no implementation similar to pure virtual function in C++) must be declared abstract, yet you can declare a class abstract that has no abstract method. 
If subclass overrides all abstract methods of the super class, than it becomes a concrete (a class whose object can be instantiate) class otherwise we have to declare it as abstract or we can not compile it.
Web Design & Development – CS506 VU 
© Copyright Virtual University of Pakistan 97 
The most important aspect of abstract class is that reference of an abstract class can point to the object of concrete classes. 
Code Example of Abstract Classes 
The Shape class contains an abstract method calculateArea() with no definition. 
public abstract class Shape{ 
public abstract void calculateArea(); 
} 
Class Circle extends from abstract Shape class, therefore to become concrete class it must provides the definition of calculateArea() method. 
public class Circle extends Shape { 
private int x, y; 
private int radius; 
public Circle() { 
x = 5; 
y = 5; 
radius = 10; 
} 
// providing definition of abstract method 
public void calculateArea () { 
double area = 3.14 * (radius * radius); 
System.out.println(“Area: ” + area); 
} 
}//end of class 
The Test class contains main method. Inside main, a reference s of abstract Shape class is created. This reference can point to Circle (subclass of abstract class Shape) class object as it is a concrete class. With the help of reference, method calculateArea() can be invoked of Circle class. This is all shown in the form of code below 
public class Test { 
public static void main(String args[]){ 
//can only create references of A.C. 
Shape s = null; 
//Shape s1 = new Shape(); //cannot instantiate 
//abstract class reference can point to concrete subclass 
s = new Circle(); 
s.calculateArea(); 
} 
}//end of class 
The compilation and execution of the above program is shown below:
Web Design & Development – CS506 VU 
© Copyright Virtual University of Pakistan 98 
Interfaces 
As we seen ne possible java’s solution to problem discussed in start of the tutorial. The second possible java’s 
solution 
Interfac are special java type which contains only a set of method prototypes, but doest not provide the 
implementation for these prototypes. All the methods inside an interface are abstract by default thus an 
abstract class – a class with zero implementation. Interface can also contains 
} 
Classes implement interfaces. Implementing an interface is like signing a contract. A class that implements an 
interfac definition of all the methods that are present inside an interface. If the 
class d tions of all methods, the class would not compile. We have to declare it as an 
abstract class in order to get it compiled. 
Code Example of Defining & Implementing an Interface 
The interface Printable contains print() method. 
o 
is Interfaces. 
es 
interface is tantamount to a pure static final constants 
Defining an Interface Keyword interface is used instead of class as shown below: 
public interface Speaker{ 
public void speak(); 
Implementing (using) Interface 
e will have to provide the 
oes not provide defini 
Relationship between a class and interface is equivalent to “responds to” while “is a” relationship exists in inheritance.
Web Design & Development – CS506 VU 
© Copyright Virtual University of Pakistan 99 
public interface Printable{ 
public void print(); 
Class . Note the use of keyword implements after the class 
name. Student class has to provide the definition of print method or we are unable to compile. 
The cod s is given below: 
ent implements Printable { 
private String name; 
ess; 
//providing definition of interface’s print method 
ress"+address); 
Interface Characteristics 
ct class, interfaces imposes a design structure on any class that uses the interface. Contrary to 
inheritance, a class can implement more than one interfaces. To do this separate the interface names with 
comma. This is java’s way of multiple inheritance. 
class Circle implements Drawable , Printable { ………. } 
Objects o f interfaces also cannot be instantiated. 
Speaker s = new Speaker(); // not compile 
However, a reference of interface can be created to point any of its implementation class. This is interface based 
polymorphism. 
} 
Student is implementing the interface Printable 
e snippet of student clas 
public class Stud 
private String addr 
public String toString () { return "name:"+name +" address:"+address; } 
public void print() { System.out.println("Name:" +name+" add 
} }//end of class 
Similar to abstra
Web Design & Development – CS506 VU 
© Copyright Virtual University of Pakistan 100 
Code Example: Interface based polymorphism 
Interface Speaker is implemented by three classes Politician, Coach and Lecturer. Code snippets of all these three classes are show below: 
public class Politician implements Speaker{ 
public void speak(){ 
System.out.println(“Politics Talks”); 
} 
} 
public class Coach implements Speaker{ 
public void speak(){ 
System.out.println(“Sports Talks”); 
} 
} 
public class Lecturer implements Speaker{ 
public void speak(){ 
System.out.println(“Web Design and Development Talks”); 
} 
} 
As usual, Test class contains main method. Inside main, a reference sp is created of Speaker class. Later, this reference is used to point to the objects of Politician, Coach and Lecturer class. On calling speak method with the help of sp, will invoke the method of a class to which sp is pointing. 
public class Test{ 
public static void main (String args[ ]) { 
Speaker sp = null; 
System.out.println("sp pointing to Politician"); 
sp = new Politician(); 
sp.speak(); 
System.out.println("sp pointing to Coach"); 
sp = new Coach(); 
sp.speak(); 
System.out.println("sp pointing to Lecturer"); 
sp = new Lecturer(); 
sp.speak(); 
} 
}
Web Design & Development – CS506 VU 
© Copyright Virtual University of Pakistan 101 
The compilation and execution of the above program is shown below: 
References 
Example code, their explanations and corresponding figures for this handout are taken from the book JAVA A Lab Course by Umair Javed. This material is available just for the use of VU students of the course Web Design and Development and not for any other commercial purpose without the consent of author.
Web Design & Development – CS506 VU 
© Copyright Virtual University of Pakistan 102 
Lesson 10 
Graphical User Interfaces 
A graphical user interface is a visual interface to a program. GUIs are built from GUI components (buttons, menus, labels etc). A GUI component is an object with which the user interacts via the mouse or keyboard. 
Together, the appearance and how user interacts with the program are known as the program look and feel. 
Support for GUI in Java 
The classes that are used to create GUI components are part of the “java.awt” or 
“javax.swing” package. Both these packages provide rich set of user interface components. 
GUI classes vs. Non-GUI Support Classes 
The classes present in the awt and swing packages can be classified into two broad categories. GUI classes & Non-GUI Support classes. 
The GUI classes as the name indicates are visible and user can interact with them. Examples of these are JButton, JFrame & JRadioButton etc 
The Non-GUI support classes provide services and perform necessary functions for GUI classes. They do not produce any visual output. Examples of these classes are Layout managers (discussed latter) & Event handling (see handout on it) classes etc. 
java.awt package 
AWT stands for “Abstract Windowing Toolkit “contains original GUI components that came with the first release of JDK. These components are tied directly to the local platform’s (Windows, Linux, MAC etc) graphical user interface capabilities. Thus results in a java program executing on different java platforms (windows, Linux, Solaris etc) has a different appearance and sometimes even different user interaction on each platform. 
AWT components are often called Heavy Weight Components (HWC) as they rely on the local platform’s windowing system to determine their functionality and their look and feel. Every time you create an AWT component it creates a corresponding process on the operating system. As compared to this SWING components are managed through threads and are known as Light Weight Components. 
This package also provides the classes for robust event handling (see handout on it) and layout managers. 
javax.swing package 
These are the newest GUI components. Swing components are written, manipulated and displayed completely in java, therefore also called pure java components. The swing components allow the programmer to specify a uniform look and feel across all platforms.
Web Design & Development – CS506 VU 
© Copyright Virtual University of Pakistan 103 
Swing components are often referred to as Light Weight Components as they are completely written in java. Several swing components are still HWC. e.g. JFrame etc. 
A part of the FrameWork 
Object 
Component 
Container 
JComponent 
Window 
AbstractButton 
JPanel 
F 
rame 
JButton 
J 
Frame
Web Design & Development – CS506 VU 
© Copyright Virtual University of Pakistan 104 
GUI Creation Steps 
1. import required packages 
import java.awt.* and/or javax.swing.* package. 
2. Setup the top level containers 
A container is a collection of related components, which allows other components to be nested inside it. In application with JFrame, we attatch components to the content pane – a container. 
Two important methods the container class has add and setLayout. 
The add method is used for adding components to the content pane while setLayout method is used to specify the layout manager. 
Container are classified into two broad categories that are Top Level containers and General Purpose Containers 
Top level containers can contain (add) other containers as well as basic components (buttons, labels etc) while general purpose containers are typically used to collect basic components and are added to top level containers. 
General purpose containers cannot exist alone they must be added to top level containers 
Examples of top level container are JFrame, Dialog and Applet etc. Our application uses one of these. 
Examples of general purpose container are JPanel, Toolbar and ScrollPane etc. 
So, take a top level container and create its instance. Consider the following code of line if JFrame is selected as a top level container 
JFrame frame = new JFrame();
Web Design & Development – CS506 VU 
© Copyright Virtual University of Pakistan 105 
3. Get the component area of the top level container 
Review the hierarchy given above, and observe that JFrame is a frame is a 
window. So, it can be interpreted as JFrame is a window. 
Every window has two areas. System Area & Component Area 
The programmer cannot add/remove components to the System Area. 
The Component Area often known as Client area is a workable place for the programmer. Components can be added/removed in this area. 
So, to add components, as you guessed right component area of the JFrame is required. It can be accomplished by the following code of line 
Conntainer con = frame.getContentPane(); 
frame is an instance of JFrame and by calling getContentPane() method on it, it returns the component area. This component area is of type container and that is why it is stored in a variable of a Container class. As already discussed, container allows other components to be added / removed. 
4. Apply layout to component area 
The layout (size & position etc. How they appear) of components in a container is usually governed by Layout Managers. 
The layout manager is responsible for deciding the layout policy and size of its components added to the container. 
Layout managers are represented in java as classes. (Layout Managers are going to be discussed in detail later in this handout) 
To set the layout, as already discussed use setLayout method and pass object of layout manager as an argument. 
con.setLayout( new FlowLayout( ) ); 
We passed an object of FlowLayout to the setLayout method here. 
We can also use the following lines of code instead of above. FlowLayout layout = new FlowLayout(); con.setLayout(layout);
Web Design & Development – CS506 VU 
© Copyright Virtual University of Pakistan 106 
5. Create and Add components 
Create required components by calling their constructor. 
JButton button = new JButton ( ); 
After creating all components your are interested in, the next task is to add these components into the component area of your JFrame (i.e ContentPane, the reference to which is in variable con of type Container) 
Use add method of the Container to accomplish this and pass it the component to be added. 
con.add(button); 
6. Set size of frame and make it visible 
A frame must be made visible via a call to setVisible(true) and its size defined via a call setSize(rows in pixel, columns in pixel) to be displayed on the screen. 
frame.setSize(200, 300) ; 
frame.setVisible(true) ; 
Note: By default, all JFrame’s are invisible. To make visible frame visible we have passed true to the setVisible method. 
frame.setVisible(false) ; 
Making a Simple GUI 
The above figured GUI contains one text field and a button. Let’s code it by following the six GUI creation steps we discussed.
Web Design & Development – CS506 VU 
© Copyright Virtual University of Pakistan 107 
Code for Simple GUI 
// File GUITest.java 
//Step 1: import packages import java.awt.*; 
import javax.swing.*; 
public class GUITest { 
JFrame myFrame ; 
JTextField tf; 
JButton b; 
//method used for setting layout of GUI 
public void initGUI ( ) { 
//Step 2: setup the top level container 
myFrame = new JFrame(); 
//Step 3: Get the component area of top-level container 
Container c = myFrame.getContentPane(); 
//Step 4: Apply layouts 
c.setLayout( new FlowLayout( ) ); 
//Step 5: create & add components 
JTextField tf = new JTextField(10); 
JButton b1 = new JButton("My Button"); 
c.add(tf); 
c.add(b1); 
//Step 6: set size of frame and make it visible 
myFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
myFrame.setSize(200,150); 
myFrame.setVisible(true); 
} //end initGUI method 
public GUITest () { // default constructor 
initGUI (); 
} 
public static void main (String args[ ]) { 
GUITest gui = new GUITest(); 
} 
} // end of class
Web Design & Development – CS506 VU 
© Copyright Virtual University of Pakistan 108 
Important Points to Consider 
main method (from where program execution starts) is written in the same class. The main method can be in a separate class instead of writing in the same class its your choice. 
Inside main, an object of GUI test class is created that results in calling of constructor of the class and from the constructor, initGUI method is called that is responsible for setting up the GUI. 
The following line of code is used to exit the program when you close the window 
myFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
If you delete this line and run your program, the desired GUI would be displayed. However if you close the window by using (X) button on top left corner of your window, you’ll notice that the control doesn’t return back to command prompt. The reason for this is that the java process is still running. How ever if you put this line in your code, when you exit your prompt will return. 
R 
eferences: 
Sun java tutorial: http://java.sun.com/docs/books/tutorial/java 
Thinking in java by Bruce Eckle 
Beginning Java2 by Ivor Hortan 
GUI creation steps are taken from the book Java A Lab Course by Umair Javed
Web Design & Development – CS506 VU 
© Copyright Virtual University of Pakistan 109 
Graphical User Interfaces - 2 
Layout Managers 
Layout Managers are used to form the appearance of your GUI. They are concerned with the arrangement of components of GUI. A general question is “why we can not place components at our desired location (may be using the x,y coordinate position?” 
The answer is that you can create your GUI without using Layout Managers and you can also do VB style positioning of components at some x,y co-ordinate in Java, but that is generally not advisable if you desire to run the same program on different platforms 
The appearance of the GUI also depends on the underlying platform and to keep that same the responsibility of arranging layout is given to the LayoutManagers so they can provide the same look and feel across different platforms 
Commonly used layout managers are 
1. Flow Layout 
2. Grid Layout 
3. Border Layout 
4. Box Layout 
5. Card Layout 
6. GridBag Layout and so on 
Let us discuss the top three in detail one by one with code examples. These top three will meet most of your basic needs 
1. Flow Layout 
Position components on line by line basis. Each time a line is filled, a new line is started. 
The size of the line depends upon the size of your frame. If you stretch your frame while your program is running, your GUI will be disturbed. 
Example Code 
// File FlowLayoutTest.java 
import java.awt.*; 
import javax.swing.*; 
public class FlowLayoutTest { 
JFrame myFrame ; 
JButton b1, b2, b3, b4, b5; 
//method used for setting layout of GUI 
public void initGUI ( ) {
Web Design & Development – CS506 VU 
© Copyright Virtual University of Pakistan 110 
myFrame = new JFrame(“Flow Layout”); 
Container c = myFrame.getContentPane(); 
c.setLayout( new FlowLayout( ) ); 
b1 = new JButton(“Next Slide”); 
b2 = new JButton(“Previous Slide”); 
b3 = new JButton(“Back to Start”); 
b4 = new JButton(“Last Slide”); 
b5 = new JButton(“Exit”); 
c.add(b1); 
c.add(b2); 
c.add(b3); 
c.add(b4); 
c.add(b5); 
myFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
myFrame.setSize(300,150); 
myFrame.setVisible(true); 
} //end initGUI method 
public FlowLayoutTest () { // default constructor 
initGUI (); 
} 
public static void main (String args[ ]) { 
FlowLayoutTest flTest = new FlowLayoutTest(); 
} 
} // end of class 
Output
Web Design & Development – CS506 VU 
© Copyright Virtual University of Pakistan 111 
2. Grid Layout 
Splits the panel/window into a grid (cells) with given number of rows and columns. 
Forces the size of each component to occupy the whole cell. Size of each component is same 
Components are added row wise. When all the columns of the first row are get filled the components are then added to the next row. 
Only one component can be added into each cell. 
Example Code 
// File GridLayoutTest.java 
import java.awt.*; 
import javax.swing.*; 
public class GridLayoutTest { 
JFrame myFrame ; 
JButton b1, b2, b3, b4, b5; 
//method used for setting layout of GUI 
public void initGUI ( ) { 
myFrame = new JFrame(“Grid Layout”); 
Container c = myFrame.getContentPane(); 
// rows , cols 
c.setLayout( new GridLayout( 3 , 2 ) ); 
b1 = new JButton(“Next Slide”); 
b2 = new JButton(“Previous Slide”); 
b3 = new JButton(“Back to Start”); 
b4 = new JButton(“Last Slide”); 
b5 = new JButton(“Exit”); 
c.add(b1); 
c.add(b2); 
c.add(b3); 
c.add(b4); 
c.add(b5); 
myFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
myFrame.setSize(300,150); 
myFrame.setVisible(true); 
} //end initGUI method
Web Design & Development – CS506 VU 
© Copyright Virtual University of Pakistan 112 
public GridLayoutTest () { // default constructor 
initGUI (); 
} 
public static void main (String args[ ]) { 
GridLayoutTest glTest = new GridLayoutTest(); 
} 
} // end of class 
output 
Modification 
The grid layout also allows the spacing between cells. To achieve spacing between cells, modify the above program. 
Pass additional parameters to the constructor of GridLayout, spaces between rows & 
spaces between columns as shown below 
c.setLayout( new GridLayout( 3 , 2 , 10 , 20) ); 
The output is look similar to one given below.
Web Design & Development – CS506 VU 
© Copyright Virtual University of Pakistan 
113 
3. Border Layout 
Divides the area into five regions. North, South, East, West and Center 
Components are added to the specified region 
If any region not filled, the filled regions will occupy the space but the center region will still appear as background if it contains no component. 
Only one component can be added into each region. 
NORTH 
WEST CENTER EAST 
SOUTH 
Example Code 
// File BorderLayoutTest.java 
import java.awt.*; 
import javax.swing.*; 
public class BorderLayoutTest { 
JFrame myFrame ; 
JButton b1, b2, b3, b4, b5; 
//method used for setting layout of GUI 
public void initGUI ( ) { 
myFrame = new JFrame(“Border Layout”); 
Container c = myFrame.getContentPane(); 
c.setLayout( new BorderLayout( ); 
b1 = new JButton(“Next Slide”); 
b2 = new JButton(“Previous Slide”); 
b3 = new JButton(“Back to Start”); 
b4 = new JButton(“Last Slide”); 
b5 = new JButton(“Exit”); 
c.add( b1 , BorderLayout.NORTH ); 
c.add( b2 , BorderLayout.SOUTH );
Web Design & Development – CS506 VU 
© Copyright Virtual University of Pakistan 
114 
c.add( b3 , BorderLayout.EAST ); 
c.add( b4 , BorderLayout.WEST ); 
c.add( b5 , BorderLayout.CENTER); 
myFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
myFrame.setSize(300,150); 
myFrame.setVisible(true); 
} //end initGUI method 
public BorderLayoutTest () { // default constructor 
initGUI (); 
} 
public static void main (String args[ ]) { 
BorderLayoutTest glTest = new BorderLayoutTest(); 
} 
} // end of class 
Points to Remember 
Revisit the code of adding components, we specify the region in which we want to add component or otherwise they will not be visible. 
Consider the following segment of code: BorderLayout.NORTH, as you guessed correctly NORTH is a constant (final) defined in BorderLayout class public access modifier. Similarly the other ones are defined. Now you understand, 
why so much emphasis has been made on following the naming conventions. 
Output
Web Design & Development – CS506 VU 
© Copyright Virtual University of Pakistan 
115 
Making Complex GUIs 
From the discussion above it seems that the basic Layout Managers may not help us in constructing complex GUIs, but generally a combination of these basic layouts can do the job. So lets try to create the calculator GUI given below 
This GUI has 16 different buttons each of same size and text field on the top and a label 
lator’ on the bottom. 
So, h w 
most on 
compon om has different size. 
Flow shape. 
Can we ma a bit tricky business but 
General Purpose Containers are there to provide the solution. 
JPanel 
‘my calcu 
o we can make this GUI? If Border Layout is selected, it has five regions (each region can have at e component) but here we have more than five components to add. Lets try Grid Layout, but all the ents in a Grid have same size and the text field at the top and label at the bott 
Layout cannot be selected because if we stretch our GUI it will destroy its 
ke this GUI? Yes, we can. Making of such GUI is 
onents (JButton , JTextField etc even other JPanels) 
anel has its own layout that can be set while creating JPanel instance 
Add components by using add method like shown below. 
e JFrame etc) in order to be visible as they (general purpose 
It is general purpose container (can’t exist alone, it has to be in some toplevel container) in whichwe can put in different comp 
JP 
JPanel myPanel = new JPanel ( new FlowLayout( ) ); 
myPanel.add (button ); Must be added to a top level container (likcontainers) can’t exist alone.
Web Design & Development – CS506 VU 
© Copyright Virtual University of Pakistan 
116 
Solution 
To own above, take JFrame (top level container) and set its layout to border. Than 
take JPa tainer) and set its layout to Grid with 4 rows and 4 columns. 
Add s they all have equal size and JPanel layout has been set to GridLayout. Afterthat, 
add n, label to the south region and panel to the center region of the JFrame’s 
container. The east and west regions are left blank and the center region will be stretched to cover up these. 
So, n build our calculator GUI. 
Cod 
make the calculator GUI shnel (general purpose con 
buttons to JPanel a 
text field to the north regio 
that’s how we ca 
e for Calculator GUI 
// Fi 
import javax.swing.*; 
public class CalculatorGUI { 
JButton b1, b2, b3, b4, b5, b6, b7, b8, b9, b0; 
oint, bEqual, bClear; 
ut of GUI 
= new JButton("0"); 
b1 = new JButton("1"); 
b2 = new JButton("2"); 
b3 = new JButton("3"); 
b4 = new JButton("4"); 
b5 = new JButton("5"); 
b6 = new JButton("6"); 
b7 = new JButton("7"); 
b8 = new JButton("8"); 
b9 = new JButton("9"); 
le CalculatorGUI.java 
import java.awt.*; 
JFrame fCalc; 
JButton bPlus, bMinus, bMul, bP 
JPanel pButtons; 
JTextField tfAnswer; 
JLabel lMyCalc; 
//method used for setting layo 
public void initGUI ( ) { 
fCalc = new JFrame(); 
b0
Web Design & Development – CS506 VU 
© Copyright Virtual University of Pakistan 
117 
bPlus = new JButton("+"); 
bMinus = new JButton("-"); 
bMul = new JButton("*"); 
bPoint = new JButton("."); 
bEqual = new JButton("="); 
bClear = new JButton("C"); 
tfAnswer = new JTextField(); 
lMyCalc = new JLabel("My Clacualator"); 
//creating panel object and setting its layout pButtons = new JPanel (new GridLayout(4,4)); 
//adding components (buttons) to panel 
pButtons.add(b1); 
pButtons.add(b2); 
pButtons.add(b3); 
pButtons.add(bClear); 
pButtons.add(b4); 
pButtons.add(b5); 
pButtons.add(b6); 
pButtons.add(bMul); 
pButtons.add(b7); 
pButtons.add(b8); 
pButtons.add(b9); 
pButtons.add(bMinus); 
pButtons.add(b0); 
pButtons.add(bPoint); 
pButtons.add(bPlus); 
pButtons.add(bEqual); 
// getting componenet area of JFrame 
Container con = fCalc.getContentPane(); 
con.setLayout(new BorderLayout()); 
//adding components to container 
con.add(tfAnswer, BorderLayout.NORTH); 
con.add(lMyCalc, BorderLayout.SOUTH); 
con.add(pButtons, BorderLayout.CENTER); 
fcalc.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
fCalc.setSize(300, 300); 
fCalc.setVisible(true); 
} //end initGUI method 
public CalculatorGUI () { // default constructor 
initGUI (); 
}
Web Design & Development – CS506 VU 
© Copyright Virtual University of Pakistan 
118 
public static void main (String args[ ]) { 
CalculatorGUI calGUI = new CalculatorGUI (); 
} 
} // end of class 
Reference: 
Sun java tutorial: http://java.sun.com/docs/books/tutorial/java 
Thinking in java by Bruce Eckle 
Beginning Java2 by Ivor Hortan 
Java A Lab Course by Umair Javed
Web Design & Development – CS506 VU 
© Copyright Virtual University of Pakistan 
119 
Lesson 11 
Event Handling 
One of the most important aspects of most non-trivial applications (especially UI type- apps) is the ability to respond to events that are generated by the various components of the application, both in response to user interactions and other system components such as client-server processing. In this handout we will look at how Java supports event generation and handling and how to create (and process) custom events. 
GUIs generate events when the user interacts with GUI. For example, 
— Clicking a button 
— Moving the mouse 
— Closing Window etc 
Both AWT and swing components (not all) generate events 
— java.awt.event.*; 
— javax.swing.event.*; 
In java, events are represented by Objects 
These objects tells us about event and its source. Examples are: 
— ActionEvent (Clicking a button) 
— WindowEvent (Doing something with window e.g. closing , minimizing) 
Some event classes of java.awt.event are shown in diagram below
Web Design & Development – CS506 VU 
© Copyright Virtual University of Pakistan 
120 
Event Handling Model 
In Java both AWT and Swing components use Event Delegation Model. 
– In this model processing of an event is delegated to a particular object (handlers ) 
in the program 
– It’s a Publish-Subscribe model. That is, event generating component publish an event and event handling components subscribe for that event. The publisher sends these events to subscribers. Similar to the way that you subscribe for newspaper and you get the newspaper at your home from the publisher. 
– This model separates UI code from program logic, it means that we can create separate classes for UI components and event handlers and hence business/program logic is separated from GUI components. 
Event Handling Steps 
For a programmer the event Handling is a three step process in terms of code 
– Step 1: Create components which can generate events (Event Generators) 
– Step 2: Build component (objects) that can handle events (Event Handlers) 
– Step 3: Register handlers with generators 
Event Handling Process 
Step 1: Event Generators 
The first step is that you create an event generator. You have already seen a lot of event generators like: 
– Buttons 
– Mouse 
– Key 
– Window etc 
Most of GUI components can be created by calling their constructors. For example 
JButton b1 = new JButton(“Hello”); 
Now b1 can generate events 
Note: We do not create Mouse/Keys etc as they are system components
Web Design & Development – CS506 VU 
© Copyright Virtual University of Pakistan 
121 
Step 2: Event Handlers/ Event Listener 
The second step is that you build components that can handle events 
First Technique - By Implementing Listener Interfaces 
– Java defines interfaces for every event type 
– If a class needs to handle an event. It needs to implement the corresponding listener interface 
– To handle “ActionEvent” a class needs to implement “ActionListener” 
– To handle “KeyEvent” a class needs to implement “KeyListener” 
– To handle “MouseEvent” a class needs to implement “MouseListener” and so on 
– Package java.awt.event contains different event Listener Interfaces which are shown in the following figure
Web Design & Development – CS506 VU 
© Copyright Virtual University of Pakistan 
122 
– Some Example Listeners, the way they are defined in JDK by Sun 
public interface ActionListener { 
public void actionPerformed(ActionEvent e); 
} 
public interface ItemListener { 
public void itemStateChanged(ItemEvent e); 
} 
public interface ComponentListener { 
public void componentHidden(ComponentEvent e); 
public void componentMoved(ComponentEvent e); 
public void componentResized(ComponentEvent e); 
public void componentShown(ComponentEvent e); 
} 
– By implementing an interface the class agrees to implement all the methods that are present in that interface. Implementing an interface is like signing a contract. 
– Inside the method the class can do what ever it wants to do with that event 
– Event Generator and Event Handler can be the same or different classes 
– To handle events generated by Button. A class needs to implement ActionListener interface and thus needs to provide the definition of actionPerformed() method which is present in this interface. 
public class Test implements ActionListener{ 
public void actionPerformed(ActionEvent ae) { 
// do something 
} 
}
Web Design & Development – CS506 VU 
© Copyright Virtual University of Pakistan 
123 
Step 3: Registering Handler with Generator 
The event generator is told about the object which can handle its events 
Event Generators have a method 
— addXXXListener(_reference to the object of Handler class_) 
For example, if b1 is JButton then 
— b1.addActionListener(this); // if listener and generator are same class 
Event Handling Example 
Clicking the “Hello” button will open up a message dialog shown below. 
We will take the simplest approach of creating handler and generator in a single class. Button is our event generator and to handle that event our class needs to implement ActionListener Interface and to override its actionPerformed method and in last to do the registration 
1. import java.awt.*; 
2. import javax.swing.*; 
3. import java.awt.event.*; 
/* Implementing the interface according to the type of the event, i.e. creating event handler (first part of step 2 of our process) */ 
4. public class ActionEventTest implements ActionListner{ 
5. JFrame frame; 
6. JButton hello; 
// setting layout components 
7. public void initGUI ( ) { 
8. frame = new JFrame(); 
9. Container cont = frame.getContentPane(); 
10. cont.setLayout(new FlowLayout()); 
//Creating event generator step-1 of our process 
11. hello = new JButton("Hello");
Web Design & Development – CS506 VU 
© Copyright Virtual University of Pakistan 
124 
/* Registering event handler with event generator. 
Since event handler is in same object that contains 
button, we have used this to pass the reference.(step 
3 of the process) */ 
12. hello.addActionListener(this); 
13. cont.add(hello); 
14. frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
15. frame.setSize(150, 150); 
16. frame.setVisible(true); 
17. } 
//constructor 
18. public ActionEventTest ( ) { 
19. initGUI(); 
20. } 
/* Override actionPerformed method of ActionListener’s 
interfacemethod of which will be called when event 
takes place (second part of step 2 of our process) */ 
21. public void actionPerformed(ActionEvent event) { 
22. JOptionPane.showMessageDialog(null,"Hello is pressed"); 
23. } 
24. public static void main(String args[]) { 
25. ActionEventTest aeTest = new ActionEventTest(); 
26. } 
27.} // end class
Web Design & Development – CS506 VU 
© Copyright Virtual University of Pakistan 
125 
How Event Handling Participants interact Behind the Scenes? 
We have already seen that what a programmer needs to do handle events. Let’s see what takes place behind the scenes, i.e How JVM handles event. Before doing that lets revisit different participants of Event Handling Process and briefly what they do. 
1. Event Generator / Source 
– Swing and awt components 
– For example, JButton, JTextField, JFrame etc 
– Generates an event object 
– Registers listeners with itself 
2. Event Object 
– Encapsulate information about event that occurred and the source of that event 
– For example, if you click a button, ActionEvent object is created 
3. Event Listener/handler 
– Receives event objects when notified, then responds 
– Each event source can have multiple listeners registered on it 
– Conversely, a single listener can register with multiple event sources 
4. JVM 
– Receives an event whenever one is generated 
– Looks for the listener/handler of that event 
– If exist, delegate it for processing 
– If not, discard it (event).
Web Design & Development – CS506 VU 
© Copyright Virtual University of Pakistan 
126 
When button generates an ActionEvent it is sent to JVM which puts it in an event queue. After that when JVM find it appropriate it de-queue the event object and send it to all the listeners that are registered with that button. This is all what we shown in the pictorial form below: 
(figure from JAVA A Lab Course)
Web Design & Development – CS506 VU 
© Copyright Virtual University of Pakistan 
127 
Making Small Calculator 
User enters numbers in the provided fields 
On pressing “+” button, sum would be displayed in the answer field 
On pressing “*” button, product would be displayed in the answer field
Web Design & Development – CS506 VU 
© Copyright Virtual University of Pakistan 
128 
17. ans = new JTextField (15); 
18. plus = new JButton("+"); 
19. plus.setPreferredSize(new Dimension(70,25)); 
20. mul = new JButton("*"); 
21. mul.setPreferredSize(new Dimension(70,25)); 
22. Container cont = frame.getContentPane(); 
23. cont.setLayout(new FlowLayout()); 
24. cont.add(firstOperand); 
25. cont.add(op1); 
26. cont.add(secondOperand); 
27. cont.add(op2); 
28. cont.add(plus); 
29. cont.add(mul); 
30. cont.add(answer); 
31. cont.add(ans); 
32. plus.addActionListener(this); 
33. mul.addActionListener(this); 
34. frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
35. frame.setSize(200, 220); 
36. frame.setVisible(true); 
37. } 
38. //constructor 
39. public SmallCalcApp ( ) { 
40. initGUI(); 
Example Code: Making Small Calculator 
1. import java.awt.*; 
2. import javax.swing.*; 
3. import java.awt.event.*; 
4. public class SmallCalcApp implements ActionListener{ 
5. JFrame frame; 
6. JLabel firstOperand, secondOperand, answer; 
7. JTextField op1, op2, ans; 
8. JButton plus, mul; 
9. // setting layout 
10. public void initGUI ( ) { 
11. frame = new JFrame(); 
12. firstOperand = new JLabel("First Operand"); 
13. secondOperand = new JLabel("Second Operand"); 
14. answer = new JLabel("Answer"); 
15. op1 = new JTextField (15); 
16. op2 = new JTextField (15);
Web Design & Development – CS506 VU 
© Copyright Virtual University of Pakistan 
129 
41. } 
42. public void actionPerformed(ActionEvent event) { 
43. String oper, result; 
44. int num1, num2, res; 
/* All the information regarding an event is contained 
inside the event object. Here we are calling the 
getSource() method on the event object to figure out 
the button that has generated that event. */ 
45. if (event.getSource() == plus) { 
46. oper = op1.getText(); 
47. num1 = Integer.parseInt(oper); 
48. oper = op2.getText(); 
49. num2 = Integer.parseInt (oper); 
50. res = num1+num2; 
51. result = res+""; 
52. ans.setText(result); 
53. } 
54. else if (event.getSource() == mul) { 
55. oper = op1.getText(); 
56. num1 = Integer.parseInt(oper); 
57. oper = op2.getText(); 
58. num2 = Integer.parseInt (oper); 
59. res = num1*num2; 
60. result = res+""; 
61. ans.setText(result); 
62. } 
63. public static void main(String args[]) { 
64. SmallCalcApp scApp = new SmallCalcApp(); 
65. } 
66. }// end class
Web Design & Development – CS506 VU 
© Copyright Virtual University of Pakistan 
130 
Lesson 12 
More Examples of Handling Events 
Handling Mouse Event 
Mouse events can be trapped for any GUI component that inherits from Component class. For example, JPanel, 
JFrame & JButton etc. 
To handle Mouse events, two types of listener interfaces are available. 
– MouseMotionListener 
– MouseListener 
The class that wants to handle mouse event needs to implement the corresponding interface and needs to 
provide the definition of all the methods in that interface. 
MouseMotionListener interface 
– Used for processing mouse motion events 
– Mouse motion event is generated when mouse is moved or dragged 
MouseMotionListener interfaces is defined in JDK as follows 
public interface MouseMotionListener { 
public void mouseDragged (MouseEvent me); 
public void mouseMoved (MouseEvent me); 
} 
MouseListener interface 
– Used for processing “interesting” mouse events like when mouse is: 
ƒ Pressed 
ƒ Released 
ƒ Clicked (pressed & released without moving the cursor) 
ƒ Enter (mouse cursor enters the bounds of component) 
ƒ Exit (mouse cursor leaves the bounds of component)
Web Design & Development – CS506 VU 
© Copyright Virtual University of Pakistan 
131 
MouseListener interfaces is defined in JDK as follows 
public interface MouseListener { 
public void mousePressed (MouseEvent me); 
public void mouseClicked (MouseEvent me); 
public void mouseReleased (MouseEvent me); 
public void mouseEntered (MouseEvent me); 
public void mouseExited (MouseEvent me); 
} 
Example Code: Handling Mouse Events 
Example to show Mouse Event Handling .Every time mouse is moved, the coordinates for a new place is 
shown in a label. 
1. import java.awt.*; 
2. import javax.swing.*; 
3. import java.awt.event.*; 
4. public class EventsEx implements MouseMotionListener{ 
5. JFrame frame; 
6. JLabel coordinates; 
7. // setting layout 
8. public void initGUI ( ) { 
9. // creating event generator 
10. frame = new JFrame(); 
11. Container cont = frame.getContentPane(); 
13. coordinates = new JLabel (); 
16. frame.addMouseMotionListener(this); 
17. frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
19. frame.setVisible(true); 
21. //default constructor 
12. cont.setLayout(new BorderLayout( ) ); 
14. cont.add(coordinates, BorderLayout.NORTH); 
15. // registring mouse event handler with generator 
18. frame.setSize(350, 350); 
20. } // end initGUI method 
22. public EventsEx ( ) { 
23. initGUI(); 
24. }
Web Design & Development – CS506 VU 
© Copyright Virtual University of Pakistan 
132 
// MouseMotionListener event hadler handling dragging 
26. int x = me.getX(); 
30. public void mouseMoved (MouseEvent me) { 
31. int x = me.getX(); 
36. EventsEx ex = new EventsEx(); 
25. public void mouseDragged (MouseEvent me) { 
27. int y = me.getY(); 
28. coordinates.setText("Dragged at [" + x + "," + y + "]"); 
29. } 
// MouseMotionListener event handler handling motion 
32. int y = me.getY(); 
33. coordinates.setText("Moved at [" + x + "," + y + "]"); 
34. } 
35. public static void main(String args[]) { 
37. } 
38. } // end class
Web Design & Development – CS506 VU 
© Copyright Virtual University of Pakistan 
133 
Another Example: Handling Window Events 
Task 
We want to handle Window Exit event only 
Why? 
When window is closed, control should return back to command prompt. 
But we have already achieved this functionality through following line of code 
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
But, what if we want to display some message (Good Bye) befoe exiting? 
r 
How? 
When user closes 
the window, Message would be displayed 
After pressing Ok button program will exit 
“WindowListner” interface contains 7 methods We require only one i.e. 
WindowListener interface is defined in the JDK as follows 
public interface WindowListener { 
public void windowClosed(WindowEvent we); 
public void windowDeactivated(WindowEvent we); 
public void windowDeiconified(WindowEvent we); 
public void windowOpened(WindowEvent we); 
To handle window events, we need to implement “WindowListner” interface. 
windowClosing 
But, We have to provide definitions of all methods to make our class a concrete class 
public void windowActivated(WindowEvent we); 
public void windowClosing(WindowEvent we); 
public void windowIconified(WindowEvent we); 
} 
public void windowClosing(WindowEvent we is our required method
Web Design & Development – CS506 VU 
© Copyright Virtual University of Pakistan 
134 
2. import javax.swing.*; 
7. public void initGUI ( ) { 
13. frame.addMouseMotionListener(this); 
// registering window handler with generator 
15. frame.setSize(350, 350); 
17. } // end initGUI method 
19. initGUI(); 
// MouseMotionListener event hadler handling dragging 
21. public void mouseDragged (MouseEvent me) { 
22. int x = me.getX(); 
Example Code: WindowExitHandler 
This example code is modification of the last code example i.e. EventsEx.java 
1. import java.awt.*; 
3. import java.awt.event.*; 
4. public class EventsEx implements MouseMotionListener , 
WindowListener { 
5. JFrame frame; 
6. JLabel coordinates; 
// setting layout 
// creating event generator 
8. frame = new JFrame(); 
9. Container cont = frame.getContentPane(); 
10. cont.setLayout(new BorderLayout( ) ); 
11. coordinates = new JLabel (); 
12. cont.add(coordinates, BorderLayout.NORTH); 
// registring mouse event handler with generator 
14. frame.addWindowListener(this); 
16. frame.setVisible(true); 
//default constructor 
18. public EventsEx ( ) { 
20. } 
23. int y = me.getY(); 
24. coordinates.setText("Dragged at [" + x + "," + y + "]"); 
25. }
Web Design & Development – CS506 VU 
© Copyright Virtual University of Pakistan 
135 
26. public void mouseMoved (MouseEvent me) { 
27. int x = me.getX(); 
29. 
31. } 
// window listener event handler 
37. } 
38. public void windowDeactivated (WindowEvent we) { } 
42. public static void main(String args[]) { 
45. } // end class 
// MouseMotionListener event handler handling motion 
28. int y = me.getY(); 
30. coordinates.setText("Moved at [" + x + "," + y + "]"); 
32. public void windowActivated (WindowEvent we) { } 
33. public void windowClosed (WindowEvent we) { } 
34. public void windowClosing (WindowEvent we) { 
35. JOptionPane.showMessageDialog(null, “Good Bye”); 
36. System.exit(0); 
39. public void windowDeiconified (WindowEvent we) { } 
40. public void windowIconified (WindowEvent we) { } 
41. public void windowOpened (WindowEvent we) { } 
43. EventsEx ex = new EventsEx(); 
44. }
Web Design & Development – CS506 VU 
© Copyright Virtual University of Pakistan 
136 
Lesson 13 
Problem in Last Code Example 
Problem 
– We were interested in windowClosing() method only 
– But have to provide definitions of all the methods, Why? 
– Because a class implementing an interface has to provide definitions of all methods present in that interface. 
Solution 
– To avoid giving implementations of all methods of an interface when we are not using these methods we use Event Adapter classes 
Adapter Classes – For WindowListener Æ WindowAdapter 
– and many more 
• Adapter classes provide definitions for all the methods (empty bodies) of their corresponding 
Listener interface 
• It means that WindowAdapter class implements WindowListener interface and provide the definition 
of all methods inside that Listener interface 
• Consider the following example of MouseMotionAdapter and its corresponding 
public void mouseDragged (MouseEvent me) { } 
• For listener interfaces containing more than one event handling methods, jdk defines adapter classes. Examples are 
– For MouseMotionListener Æ MouseMotionAdapter 
MouseMotionListener interface 
public interface MouseMotionListener { 
public void mouseDragged (MouseEvent me); 
public void mouseMoved (MouseEvent me); 
} 
public class MouseMotionAdapter implements MouseMotionListener{ 
public void mouseMoved (MouseEvent me) { } 
}
Web Design & Development – CS506 VU 
© Copyright Virtual University of Pakistan 
137 
Available Adapter classes 
How to use Adapter Classes 
public class EventsEx implements MouseMotionListener{...} 
Now our handler class will inherit from adapter class 
Due to inheritance, all the methods of the adapter class will be available inside our handler class 
Since adapter classes has already provided definitions with empty bodies. 
Previously handler class need to implement interface 
Therefore it has to provide definitions of all the methods inside that interface 
public class EventsEx extends MouseMotionAdapter{...} 
We do not have to provide implementations of all the methods again 
We only need to override our method of interest.
Web Design & Development – CS506 VU 
© Copyright Virtual University of Pakistan 
138 
Example Code 13.1: Handling Window Events using Adapter Classes 1. import java.awt.*; 
3. import java.awt.event.*; 
5. JFrame frame; 
12. cont.add(coordinates, BorderLayout.NORTH); 
// registering window handler with generator 
13. frame.addWindowListener(this); 
14. frame.setSize(350, 350); 
16. } // end initGUI method 
//default constructor 
17. public EventsEx ( ) { 
18. initGUI(); 
19. } 
// As you can see that we have only implemented 
// our required method 
21. JOptionPane.showMessageDialog(null, “Good Bye”); 
24. public static void main(String args[]) { 
25. EventsEx ex = new EventsEx(); 
27. } // end class 
Here we are modifying the window event code in the last example to show the use of WindowAdapter instead of WindowListener. Code related to MouseMotionListener is deleted to avoid cluttering of code. 
2. import javax.swing.*; 
4. public class EventsEx extends WindowAdapter { 
6. JLabel coordinates; 
// setting layout 
7. public void initGUI ( ) { 
// creating event generator 
8. frame = new JFrame(); 
9. Container cont = frame.getContentPane(); 
10. cont.setLayout(new BorderLayout( ) ); 
11. coordinates = new JLabel (); 
15. frame.setVisible(true); 
20. public void windowClosing (WindowEvent we) { 
22. System.exit(0); 
23. } 
26. }
Web Design & Development – CS506 VU 
© Copyright Virtual University of Pakistan 
139 
Problem in Last Code Example We have inherited from WindowAdapter 
What if we want to use MouseMotionAdpater as well ? or what if our class already inherited form some 
other class ? 
Problem 
— Java allows single inheritance 
Solution 
— Use Inner classes 
Inner Classes 
Generally used as a private utility class which does not need to be seen by others classes 
GUI class (contains GUI creation code) 
Outer 
A class defined inside another class 
Inner class can access the instance variables and members of outer class 
It can have constructors, instance variables and methods, just like a regular class 
• tf is a JTextField 
Class 
Inner class 
Handler class 
• contains event 
handling code 
•tf is accessible here
Web Design & Development – CS506 VU 
© Copyright Virtual University of Pakistan 
140 
Example Code13.2: Handling Window Event with Inner Class 
Here we are modifying the window event code in the last example to show the use of 
3. import java.awt.event.*; 
5. JFrame frame; 
9. frame = new JFrame(); 
window events and registering it with generator */ 
14. WindowHandler handler = new Window Handler (); 
//default constructor 
27. } // end of WindowHandler class 
WindowAdapter as an inner class. 
1. import java.awt.*; 
2. import javax.swing.*; 
4. public class EventEx { 
6. JLabel coordinates; 
7. // setting layout 
8. public void initGUI ( ) { 
10. Container cont = frame.getContentPane(); 
11. cont.setLayout(new BorderLayout( )); 
12. coordinates = new JLabel (); 
13. cont.add(coordinates, BorderLayout.NORTH); 
/* Creating an object of the class which is handling our 
15. frame.addWindowListener(handler); 
16. frame.setSize(350, 350); 
17. frame.setVisible(true); 
18. } // end initGUI 
19. public EventEx ( ) { 
20. initGUI(); 
21. } 
/* Inner class implementation of window adapter. Outer 
class is free to inherit from any other class. */ 
22. private class WindowHandler extends WindowAdapter { 
// Event Handler for WindowListener 
23. public void windowClosing (WindowEvent we) { 
24. JOptionPane.showMessageDialog(null, “Good Bye”); 
25. System.exit(0) 
26. } 
28. public static void main(String args[]) { 
29. EventEx e = new EventEx(); 
30. } 
31. } // end class
Web Design & Development – CS506 VU 
© Copyright Virtual University of Pakistan 
141 
Example Code 13.3: Handling Window and Mouse Events with Inner Class 
Here we are modifying the window event code of the last example to handle window and mouse events using inner classes. The diagram given below summarizes the approach. 
1. import java.awt.*; 
3. import java.awt.event.*; 
4. public class EventEx { 
5. JFrame frame; 
8. public void initGUI ( ) { 
9. frame = new JFrame(); 
11. cont.setLayout(new BorderLayout( ) ); 
16. MouseHandler mhandler = new MouseHandler (); 
Inner class Handling Mouse Events 
Outer class for GUI and other code 
Inner class 
Handling 
Window 
2. import javax.swing.*; 
6. JLabel coordinates; 
7. // setting layout 
10. Container cont = frame.getContentPane(); 
12. coordinates = new JLabel (); 
13. cont.add(coordinates, BorderLayout.NORTH); 
/* Creating an object of the class which is handling our 
window events and registering it with generator */ 
14. WindowHandler whandler = new WindowHandler (); 
15. frame.addWindowListener(whandler); 
/* Creating an object of the class which is handling our 
MouseMotion events & registering it with generator */ 
17. frame.addMouseMotionListener(mhandler); 
18. frame.setSize(350, 350); 
19. frame.setVisible(true); 
20. }
Web Design & Development – CS506 VU 
© Copyright Virtual University of Pakistan 
142 
//default constructor 
21. public EventEx ( ) { 
22. initGUI(); 
23. } 
/* Inner class implementation of WindowAdapter. Outer class 
26. JOptionPane.showMessageDialog(null, “Good Bye”); 
35. } 
36. } // end of MouseHandler 
37. public static void main(String args[]) { 
39. } 
40. } // end class 
is free to inherit from any other class. */ 
24. private class WindowHandler extends WindowAdapter { 
// Event Handler for WindowListener 
25. public void windowClosing (WindowEvent we) { 
27. System.exit(0) 
28. } 
29. } // end of WindowHandler 
//Inner class implementation of MouseMotionAdapter 
30. private class MouseHandler extends MouseMotionAdapter { 
// Event Handler for mouse motion events 
31. public void mouseMoved (MouseEvent me) { 
32. int x = me.getX(); 
33. int y = me.getY(); 
34. coord.setText(“Moved at [" + x + "," + y + "]” ); 
38. EventEx e = new EventEx();
Web Design & Development – CS506 VU 
© Copyright Virtual University of Pakistan 
143 
Example Code: Making Small Calculator using Inner classes 
User enters numbers in the provided fields 
On pressing “*” button, product would be displayed in the answer field 
On pressing “+” button, sum would be displayed in the answer field
Web Design & Development – CS506 VU 
© Copyright Virtual University of Pakistan 
144 
1. import java.awt.*; 
2. import javax.swing.*; 
3. import java.awt.event.*; 
4. public class SmallCalcApp implements ActionListener{ 
5. JFrame frame; 
6. JLabel firstOperand, secondOperand, answer; 
7. JTextField op1, op2, ans; 
8. JButton plus, mul; 
13. secondOperand = new JLabel("Second Operand"); 
18. plus = new JButton("+"); 
21. mul.setPreferredSize(new Dimension(70,25)); 
23. cont.setLayout(new FlowLayout()); 
26. cont.add(secondOperand); 
29. cont.add(mul); 
31. cont.add(ans); 
/* Creating an object of the class which is handling 
9. // setting layout 
10. public void initGUI ( ) { 
11. frame = new JFrame(); 
12. firstOperand = new JLabel("First Operand"); 
14. answer = new JLabel("Answer"); 
15. op1 = new JTextField (15); 
16. op2 = new JTextField (15); 
17. ans = new JTextField (15); 
19. plus.setPreferredSize(new Dimension(70,25)); 
20. mul = new JButton("*"); 
22. Container cont = frame.getContentPane(); 
24. cont.add(firstOperand); 
25. cont.add(op1); 
27. cont.add(op2); 
28. cont.add(plus); 
30. cont.add(answer); 
button events & registering it with generators */ 
32. ButtonHandler bHandler = new ButtonHandler(); 
33. plus.addActionListener(bHandler); 
34. mul.addActionListener(bHandler); 
35. frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
36. frame.setSize(200, 220); 
37. frame.setVisible(true); 
38. }
Web Design & Development – CS506 VU 
© Copyright Virtual University of Pakistan 
145 
39. //constructor 
40. public SmallCalcApp ( ) { 
41. initGUI(); 
//Inner class implementation of ActionListener 
54. ans.setText(result); 
56. else if (event.getSource() == mul) { 
57. oper = op1.getText(); 
65. } // end actionPerformed method 
69. } 
42. } 
43. private class ButtonHandler implements ActionListener{ 
44. public void actionPerformed(ActionEvent event) { 
45. String oper, result; 
46. int num1, num2, res; 
47. if (event.getSource() == plus) { 
48. oper = op1.getText(); 
49. num1 = Integer.parseInt(oper); 
50. oper = op2.getText(); 
51. num2 = Integer.parseInt (oper); 
52. res = num1+num2; 
53. result = res+""; 
55 } 
58. num1 = Integer.parseInt(oper); 
59. oper = op2.getText(); 
60. num2 = Integer.parseInt (oper); 
61. res = num1*num2; 
62. result = res+""; 
63. ans.setText(result); 
64 } 
66. } // end inner class ButtonHandler 
67. public static void main(String args[]) { 
68. SmallCalcApp scApp = new SmallCalcApp(); 
70. }// end class
Web Design & Development – CS506 VU 
© Copyright Virtual University of Pakistan 
146 
Anonymous Inner Classes 
Same as inner class in capabilities 
Named 
– String s = “hello”; System.out.println(s); 
We generally use anonymous object when there is just a one time use of a particular object but in case of a 
repeated use we generally used named objects and use that named reference to use that objects again and again. 
Has no name 
much shorter 
difficult to understand 
Named vs. Anonymous Objects 
– “hello” has a named reference s. 
Anonymous 
– System.out.println(“hello”);
Web Design & Development – CS506 VU 
© Copyright Virtual University of Pakistan 
147 
Example Code 13.4 Handling Window Event with Anonymous Inner Class 
Here we are modifying the window event code of 13.3 to show the use of anonymous inner class. 
28. import java.awt.*; 
29. import javax.swing.*; 
30. import java.awt.event.*; 
31. public class EventsEx extends WindowAdapter { 
32. JFrame frame; 
33. JLabel coordinates; 
// setting layout 
34. public void initGUI ( ) { 
// creating event generator 
35. frame = new JFrame(); 
36. Container cont = frame.getContentPane(); 
37. cont.setLayout(new BorderLayout( ) ); 
38. coordinates = new JLabel (); 
// registering event handler (anonymous inner class) 
52. initGUI(); 
39. cont.add(coordinates, BorderLayout.NORTH); 
// with generator by using 
40. frame.addWindowListener ( 
41. new WindowAdapter ( ) { 
42. public void windowClosing (WindowEvent we) { 
43. JOptionPane.showMessageDialog(null, “Good Bye”); 
44. System.exit(0); 
45. } // end window closing 
46. } // end WindowAdapter 
47. ); // end of addWindowListener 
48. frame.setSize(350, 350); 
49. frame.setVisible(true); 
50. } // end initGUI method 
//default constructor 
51. public EventsEx ( ) { 
53. } 
54. public static void main(String args[]) { 
55. EventsEx ex = new EventsEx(); 
56. } 
57. } // end class
Web Design & Development – CS506 VU 
© Copyright Virtual University of Pakistan 
148 
Summary of Approaches for Handling Events To implement the above two techniques we can use 
Same class 
• putting event handler & generator in one class 
1. Outer class 
• Putting event handlers & generator in two different classes 
3. Anonymous Inner classes 
1. By implementing Interfaces 
2. By extending from Adapter classes 
Separate class 
3. Inner classes 
R 
eferences 
Java A Lab Course by Umair Javed
Web Design & Development – CS506 VU 
© Copyright Virtual University of Pakistan 
149 
Lesson 14 
Java Database Connectivity 
Introduction 
Java Database Connectivity (JDBC) provides a standard library for accessing databases. The JDBC API 
contains number of interfaces and classes that are extensively helpful while communicating with a database. 
The java.sql package 
The java.sql package contains basic & most of the interfaces and classes. You automatically get this package when you download the J2SE™. You have to import this package whenever you want to interact with a relational database. 
Connecting With Microsoft Access In this handout, we will learn how to connect & communicate with Microsoft Access Database. We 
chooses Access because most of you are familiar with it and if not than it is very easy to learn. 
Create Database 
In start create a database “PersonInfo” using Microsoft Access. Create one table named “Person”. The schema of the table is shown in the picture. 
Add the following records into Person table as shown below.
Web Design & Development – CS506 VU 
© Copyright Virtual University of Pakistan 
150 
Save the 
etup System DSN 
data base in some folder. (Your database will be saved as an .mdb file) 
S 
ƒ After creating database, you have to setup a system Data Source Name (DSN). DSN is a name 
through which your system recognizes the underlying data source. 
ƒ Select Start Settings Control Panel Administrative Tools Data Sources (ODBC). 
ƒ The ODBC Data Source Administrator window would be opened as shown below. Select System 
DSN tab. (If you are unable to use System DSN tab due to security restrictions on your machine, 
you can use the User DSN tab) 
ƒ Press Add… button and choose Microsoft Access Driver (*.mdb) from Create New Data Source 
window and press Finish button as shown in diagram. 
ƒ After that, ODBC Microsoft Access Setup window would be opened as shown in following 
diagram 
ƒ Enter the Data Source Name personDSN and select the database by pressing Select button. The 
browsing window would be opened, select the desired folder that contains the database (The 
database .mdb file you have created in the first step) Press Ok button.
Web Design & Development – CS506 VU 
© Copyright Virtual University of Pakistan 
151 
Basic Steps in U 
sing JDBC There are eight (8) basic steps that must be followed in order to successfully communicate with a database. 
Let’s take a detail overview of all these one by one. 
1. Imp t 
ƒ I p 
data 
import java.sql.*; 
or Required Package 
mort the package java.sql.* that contains useful classes and interfaces to access & work withbase.
Web Design & Development – CS506 VU 
© Copyright Virtual University of Pakistan 
152 
2. Load Driver 
ƒ Need to load suitable driver for underlying database. 
ƒ Different drivers & types for different databases are available. 
); 
ƒ ollowing driver. You have to download it explicitly. 
oracle.jdbc.driver.OracleDriver”); 
URL 
atabase (Actually we need to specify the 
address of the database which is in the form of URL) 
ƒ and we have loaded a JDBC-ODBC driver. Using 
d it personDSN. 
String conURL = “jdbc:odbc:personDSN”; 
. t 
ƒ on object. 
to the getConnection method. Connection con = 
n below: 
String u 
String p 
Connection con = null;con = DriverManager.getConnection(conURL, usr, pwd); 
5. Create Statement 
Stateme 
Once yo arious kinds of SQL queries. 
6. Execute a Query 
ƒ The next step is to pass the SQL statements & to execute them. 
ƒ Two methods are generally used for executing SQL queries. These are: 
es. 
the 
ƒ For MS Access, load following driver available with j2se. Class.forName(“sun.jdbc.odbc.JdbcOdbcDriver” 
For Oracle, load the f 
Class.forName(“ 
3. Define Connection 
ƒ To get a connection, we need to specify the URL of a d 
As we are using Microsoft Access database 
JDBC-ODBC driver requires a DSN which we have created earlier and nameSo the URL of the database will be 
4 
Esablish Connection With DataBase 
Use DriverManagerto get the connecti 
ƒ The URL of the database is passed 
DriverManager.getConnection(conURL); ƒ If DataBase requires username & password, you can use the overloaded version of getConnection method as show 
sr = “umair”; wd = “vu”; 
ƒ A Statement object is obtained from a Connection object. 
nt stmt = con.createStatement( ); 
u have a statement, you can use it for v 
executeQuery(sql) method 
ƒ Used for SQL SELECT queri 
ƒ Returns the ResultSET object that contains the results of the query and can be used to accessquery results.
Web Design & Development – CS506 VU 
© Copyright Virtual University of Pakistan 
153 
ecuteQuery(sql); 
executeUpdate(sql)method 
. This method is used for executing an update statement like INSERT, UPDATE or 
7. DELETE 
ƒ Returns an the number of rows updated 
String sql = “INSERT INTO tablename ” + “(columnNames) Values (values)” ; 
int count = stmt.executeUpdate(sql); 
Process Results of the Query 
ƒ et maintains the data in the form tables (rows & columns) 
ƒ First row has index 1, not 0. 
ƒ The next method of ResultSet returns true or false depending upon whether the next row is 
available (exist) or not and moves the cursor 
ƒ Always remember to call next() method at-least once 
ƒ To retrieve the data of the column of the current row you need to use the various getters provided 
by the ResultSet. 
ƒ For example, the following code snippet will iterate over the whole ResultSet and illustrates the 
usage of getters methods 
while ( rs.next() ){ 
/by using column name 
String name = rs.getString(“columnName”); 
// or by using column indexString name = 
tString(1); } 
8. Close the Connection 
ƒ An opening connection is expensive, postpone this step if additional database operations are 
e 
Example ResultSet 
String sql = “SELECT * from sometable”;ResultSet rs = stmt.ex 
Integer value representing 
ƒ The ResultSet provides various getXXX methods that takes a column index or name and returns the data The ResultS 
/ 
rs.ge 
xpected 
con.close(); 
Code 14.1: Retrieving Data from 
The JdbcEx.java demonstrates the usage of all above explained steps. In this code example, we connect 
with the e we have created earlier, and then execute the simple SQL SELECT 
query on results. 
PersonInfo database, the onPerson table, and then process the query
Web Design & Development – CS506 VU 
© Copyright Virtual University of Pakistan 
154 
// File Jd 
//step 1: import packageimport java.sql.*; 
public cla 
publi ng args[ ]) { 
try { 
//S driverClass.forName(“sun.jdbc.odbc.JdbcOdbcDriver”); 
//Step 3: define the connection URL 
String url = “jdbc:odbc:personDSN”; 
on 
ger.getConnection(url); 
//Step 5: create Statement 
ement(); 
//Step 6: preapare & execute the query 
FROM Person”; 
ResultSet rs = st.executeQuery(sql); 
//Step 7: process the results 
while(rs.next()){ 
// The row name is “name” in database “PersonInfo,// hence specified in the getString() 
method. 
String name = rs.getString(“name”);String add = rs.getString(“address”);String 
pNum = rs.getString(“phoneNum”); 
System.out.println(name + “ ” + add + ” ” + pNum);} 
//Step 8: close the connection 
con.close(); 
(Exception sqlEx){ 
System.out.println(sqlEx); 
} 
} // 
e important thing you must notice that we have put all code inside try block and then handle (in the 
above example, only printing the name of the exception raised) exception inside catch block. 
bcEx.java 
ss JdbcEx { 
c static void main (Stri 
tep 2: load 
//Step 4: establish the connectiConnection con = DriverMana 
Statement st = con.createStat 
String sql = “SELECT * 
}catch 
end main} // end class 
Th
Web Design & Development – CS506 VU 
© Copyright Virtual University of Pakistan 
155 
Why? Because we are dealing with an external resource (database). If you can recall all IO related 
involving external resources in java throw exceptions. These exceptions are checked exceptions and we 
must need to handle these exceptions. 
operations 
Compile & Execute 
Since the Person table contains only three records, so the following output would be produced on executing 
the above program. 
References: . Java – 
. Java tutori 
A Lab Course by Umair Javed al by Sun: http://java.sun.com/docs/books/turorial 
. Beginning Java2 by Ivor Hortan
Web Design & Development – CS506 VU 
© Copyright Virtual University of Pakistan 
156 
Lesson 15 
More on JDBC 
In the pr w to execute SQL statements. In this handout, we’ll learn 
how to ex ods provided by the JDBC 
API. 
Before ju ets take a brief overview of executeUpdate()method that is used for 
executing DML statements. 
Useful S 
evious handout, we have discussed hoecute DML (insert, update, delete) statements as well some useful meth 
mping on to example, l 
tatement Methods: 
o executeUpdate( ) 
. Us ATE, or DELETE SQL statements. 
. Th he number of rows that were affected in the database. 
. . efinition Language) statements CREATE TABLE, DROP 
TA tc. For example, 
int num = stmt.executeUpdate(“DELETE from Person WHERE id = 2” ); 
Example Code 15.1: Executing SQL DML Statements 
This program will take two command line arguments that are used to update records in the database. 
executeUpdate( ) method will be used to achieve the purpose stated above. 
//step 1: import packageimport java.sql.*; public class 
JdbcDmlEx {public static void main (String args[ ]) { try { 
//Step 2: load driverClass.forName(“sun.jdbc.odbc.JdbcOdbcDriver”); 
//Step 3: define the connection URL 
String url = “jdbc:odbc:personDSN”; 
//Step 4: establish the connection 
Connection con = DriverManager.getConnection(url); 
// assigning first command line argument value 
String addVar = args[0]; 
// assigning second command line argument value 
ed to execute for INSERT, UPDis method returns t 
Also supports DDL (Data DBLE, and ALERT TABLE e 
// File JdbcDmlEx.java 
//Step 5: create Statement Statement st = con.createStatement();
Web Design & Development – CS506 VU 
© Copyright Virtual University of Pakistan 
157 
String nameVar = args[1]; // preparing query – nameVar & addVar strings are embedded 
// into query within ‘” + string + “’ 
String sql = “UPDATE Person SET address = ‘”+addVar+”’” + 
“ WHERE name = ‘”+nameVar+”’ ”; 
// executing query 
int num = st.executeUpdate(sql); 
// Step 7: process the results of the query 
// printing number of records affected 
System.out.println(num + “ records updated”); 
//Step 8: close the connection 
con.close(); 
}catch(Exception sqlEx){ 
System.out.println(sqlEx); 
} 
} // end main} // end class 
ompil Exe 
Ce &cute 
The Person table is shown in the following diagram before execution of the program. We want to update 
first row i.e address of the person ali. 
The next diagram shows how we have executed our program. We passed it two arguments. The first one is 
the address (defence) and later one is the name (ali) of the person against whom we want to update the 
address value.
Web Design & Development – CS506 VU 
© Copyright Virtual University of Pakistan 
158 
The Per n after the execution of the program. Notice that address 
of the ali is now ch 
sotable is shown in the following diagramanged to defence. 
No 
When w tabase explicitly to 
mak 
But in the above code, you have never seen such act that java will implicitly 
commit the changes. However, we can change this java behavior to manual commit. We will cover these in 
some la 
Useful t.): 
te e execute DML statements (insert, update, delete) we have to commit it in the da 
e the changes permanent or otherwise we can rollback the previously executed statements. a statement. This is due to the f 
ter handout. Statement Methods (con 
. Used for determines the number of rows a ResultSet may contain 
. are unlimited (return value is 0), or by using 
setMaxRows(int), the number of rows can be specified. 
o tQueryTimeOut (int) 
. Retrieves the number of seconds the driver will wait for a Statement object to execute. 
seconds, zero means there is no limit 
. If the limit is exceeded, a SQLException is thrown 
if 
o getMaxRows / setMaxRows(int) 
By default, the number of rows 
getQueryTimeOut / se 
. The current query time out limit in 
Dferent Types of Statements 
. n the previous handout that through Statement objects, SQL queries 
are sent to the databases. 
. Three types of Statement objects are available. These are; 
As we have discussed i
Web Design & Development – CS506 VU 
© Copyright Virtual University of Pakistan 
159 
1. Statement 
-The Statement objects are used for executing simple SQL statements. -We have already seen its usage in the code examples. 
ent 
for executing precompiled SQL statements and passing in 
different parameters to it. 
about it in detail shortly. 
3. C 
- procedures. 
- ava tutorial on it if you are interested in learning it. 
Prepared 
2. PreparedStatem 
-The PrepaeredStatement are used 
- We will talk 
allableStatement 
Theses are used for executing storedWe are not covering this topic; See the J 
Statements 
ƒ What if we want to execute same query multiple times by only changing parameters. 
ƒ PreparedStatement object differs from Statement object as that it is used to create a statement in 
standard form that is sent to database for compilation, before actually being used. 
ƒ Each time you use it, you simply replace some of the marked parameters (?) using some setter 
methods. 
ƒ W nnection class. 
T is pa 
Prepa 
” ); 
ƒ Notices that we used marked parameters (?) in query. We will replace them later on by using 
various setter methods. 
ƒ If we want to replace first ? with String value, we use setString method and to replace second ? with 
i his is shown in the following code snippet. 
pStmt.setString (1 , stringValue); 
pStmt.setInt (2 , intValue) 
Note 
. Next, call executeUpdate (for INSERT, UPDATE or ETE queries) or executeQuery (for 
simp 
pStmt.executeUpdate(); 
e can create PreparedStatement object by using prepareStatementmethod of the cohe SQL query ssed to this method as an argument as shown below. 
redStatement pStmt = con.prepareStatement (“UPDATE tableName SET columnName = ? ” + 
“WHERE columnName = ? 
nt value, we use setInt method. T 
: The first market parameter has index 1. we can DELle SELECT query) method.
Web Design & Development – CS506 VU 
© Copyright Virtual University of Pakistan 
160 
Modify E 
This exam the last example code (JdbcDmlEx.java).The modifications are 
highlighte 
// File JdbcDmlEx.java 
//step 1 l.*; 
public s JdbcDmlEx {public static void main (String 
args[ ]) { try { 
//Step 2: load driverClass.forName(“sun.jdbc.odbc.JdbcOdbcDriver”); 
//Step 3: define the connection URL 
String url = “jdbc:odbc:personDSN”; 
l, ””, ””); 
// make query and place ? where values are to 
//be inserted later 
String sql = “UPDATE Person SET address = ? “ + “ WHERE name 
// assigning first command line argument valueString addVar = args[0]; 
// assigning second command line argument valueString nameVar = args[1]; // 
setting first marked parameter (?) by using setString()// method to address. 
pStmt.setString(1 , addVar); 
// setting second marked parameter(?) by using setString()// method to name 
pStmt.setString(2 , nameVar); 
// suppose address is “defence” & name is “ali” 
// by setting both marked parameters, the query will look 
// like: 
// sql = “UPDATE Person SET address = “defence” 
// WHERE name = “ali” ” 
// executing update statemnt 
int num = pStmt.executeUpdate(); 
xample Code 15.1: Executing SQL DML using Prepared Statements 
ple code is modification to d as bold face. 
: import packageimport java.sqclas 
//Step 4: establish the connection Connection con = DriverManager.getConnection(ur 
= ? ”; // creating statement using Connection object and passing // sql statement as parameter PreparedStatement pStmt = con.prepareStatement(sql);
Web Design & Development – CS506 VU 
© Copyright Virtual University of Pakistan 
161 
// Step 7: process the results of the query// printing number of records 
affectedSystem.out.println(num + “ re ”); 
//Step 8: close the connection 
con.close(); 
}catch(Exception sqlEx){ 
System.out.println(sqlEx); 
} 
} // 
ompile & Execute 
cords updated 
end main} // end class 
C 
Execute this code in a similar way as we showed you in execution of the last program. Don’t forget to pass 
the address & name values as the command line arguments. 
References: 
Entire material for this handout is taken from the book JAVA A Lab Course by Umair Javed. This 
mat Web Design and Development and not 
for any other commercial purpose without the consent of author. 
eri 
al is available just for the use of VU students of the course
Web Design & Development – CS506 VU 
© Copyright Virtual University of Pakistan 
162 
Lesson 16 
Result Set 
This handout will familiarize you with another technique of inserting, updating & deleting rows. Before 
moving on, first we look at ResultSet. 
ResultSet 
– A 
Represented by a table with rows and columns 
First row has index 1 
ResultSet contains the results of the SQL query 
Maintains a cursor pointing to its current row of data. Initially the cursor positioned before the row (0). Default ResultSet 
. A default ResultSet object is not updatable and has a cursor that moves forward only. 
. You can iterate over through it only once and only from the first row to last row. 
U 
. For a quick overview, here how we create a default ResultSet object. 
; PreparedStatement pStmt = 
con.prepareStatement(sql); ResultSet rs = pStmt.executeQuery( ); 
Useful ResultSet’s Methods 
. ntil now, we have worked & used it in various examples. 
String sql = “SELECT * FROM Person” 
Following methods are used often to wor et object. We already seen and used some of 
them in code examples. 
k with default ResultS
Web Design & Development – CS506 VU 
© Copyright Virtual University of Pakistan 
163 
ƒ next( ) 
-Attempts to move to the next row in the ResultSet, if available 
-The next() method returns true or false depending upon whether the next row is available (exist) or 
not. 
initially 
tioned before first row. 
ƒ getters 
-To retrieve the data of the column of the current row you need to use the various getters provided by 
the 
ResultSet 
-These getters return the value from the column by specifying column name or column index. 
-For example, if the column name is “Name” and this column has index 3 in the ResultSet object, then 
we can retrieve the values by using one of the following methods: 
e = rs.getString(“Name”);String name = 
); 
-These gett her types like getInt( ),getDouble( ) etc. Consult the Java 
API documentation for more references. 
No dex 1, NOT zero (0). 
ƒ 
-Used to release the JDBC and database resources 
-The ResultSet is implicitly closed when the associated Statement object executes a new query or closed 
Updatable and/or Scrollable ResultSet 
-Before retrieving any data from ResultSet, always remember to call next()at least once because 
cursor is posi 
String namrs.getString(3 
er methods are also available for ot 
te: Remember that first column has an in 
close( ) 
by method call. 
ƒ It is possible to produce ResultSet objects that are scrollable and/or updatable (since JDK 1.2) 
ƒ p of such ResultSet, it is possible to move forward as well as backward with in 
ƒ Another advantage is, rows can be inserted, updated or deleted by using updatable ResultSet object. 
esultSet 
The following code fragment, illustrates how to make a ResultSet object that is scrollable and updatable. 
With the hel 
RestultSetobject. 
Creating Updatable & Scrollable R
Web Design & Development – CS506 VU 
© Copyright Virtual University of Pakistan 
164 
String sql = “SELECT * FROM Person”; 
tSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR 
_UPDATABLE); 
eQuery( ); 
constants have been used of ResultSet class for producing a ResultSet rs that is scrollable, will not 
show changes made by others and will be updatable 
Useful ResultSet’s Methods (cont.) 
PreparedStatement pStmt = 
con.prepareStatement(sql,Resul 
ResultSet rs = pStmt.execut 
Two 
The methods discussed in this section can only be used with updatable/scrollable ResultSet object. 
. previous( ) 
-Moves the cursor to the previous row in the ResultSet object, if available -Returns true if 
cursor is on a valid row, false it is off the result set. -Throws exception if result type is 
TYPE_FORWARD_ONLY. 
Example Code 16.1: Use of previous( ), next( ) & various getters methods 
The ResultSetEx.java shows the use of previous, next and getters methods. We are using the same Person 
table of PersonInfo database, the one we had created earlier in this example and later on. 
1 // File ResultSetEx.java 
2 import java.sql.*; 
3 public class ResultSetEx { 
4 public static void main (String args[ ]) { 
5 try { 
6 
7 
8 
9 
10 //Step 4: establish the connection 
11 Connection con = DriverManager.getConnection(url); 
12 //Step 5: creating PrepareStatement by passing sql and 
13 //ResultSet’s constants so that the ResultSet that will 
14 
15 //scrollable & updatable 
16 ”; 
17 PreparedStatement pStmt = con.prepareStatement(sql, 
18 ResultSet.TYPE_SCROLL_INSENSITIVE, 
19 ResultSet.CONCUR_UPDATABLE); 
20 
21 
//Step 2: load driver Class.forName(“sun.jdbc.odbc.JdbcOdbcDriver”); 
//Step 3: define the connection URL String url = “jdbc:odbc:personDSN”; 
//produce as a result of executing query will be String sql = “SELECT * FROM Person 
//Step 6: execute the query ResultSet rs = pStmt.executeQuery();
Web Design & Development – CS506 VU 
© Copyright Virtual University of Pakistan 
165 
22 
23 rs.next( ); 
24 current row (first) 
25 rward”); 
26 String name = rs.getString(“Name”); 
27 System.out.println(name); 
28 // moving cursor forward i.e. on to second row 
29 rs.next( ); 
30 // moving cursor ba 
31 rs.previous( ); 
32 // printing column “name” value of current row (first) 
33 System.out.println(“moving cursor forward”); 
34 name = rs.getString(“Name”); 
35 System.out.println(name); 
36 //Step 8: close the connection 
37 con.close(); 
38 }catch(Exception sqlEx){ 
39 System.out.println(sqlEx); 
40 } 
41 } // end main 
42 
43 } // end class 
Compile & Execute: 
: 
// moving cursor forward i.e. first row 
// printing column “name” value of System.out.println(“moving cursor fo 
ckward i.e to first row 
The sample output is given below 
Useful ResultSet’s Methods (cont.) ƒ 
-Moves the cursor to the given row number in the ResultSetobject. 
-If g ves the cursor forward with respect to beginning of the result set. 
-If t , the cursor moves to the absolute row position with respect to the 
absolute(int) 
iven row number is positive, mo 
he given row number is negative 
end of the result set.
Web Design & Development – CS506 VU 
© Copyright Virtual University of Pakistan 
166 
-For example, calling absolute(-1) positions the cursor on the last row; calling absolute(-2) moves the 
-last row, and so on. 
-Throws Exception if ResultSet type is TYPE_FORWARD_ONLY 
ƒ updaters (for primitives, String and Object) 
-Used to update the column values in the current row or in insert row (discuss later) 
-Do not update the underlying database 
-Each update method is overloaded; one that takes column name while other takes column index. For 
example String updater are available as: 
updateString(String columnName, String value) 
updateString(String columnIndex, String value) 
ƒ updateRow( ) 
-Updates the underlying database with new contents of the current row of this ResultSetobject 
Example Code 16.2: Updating values in existing rows 
cursor to next-t 
o 
The following code example updates the Name column in the second row of the ResultSet object rs and 
then uses the method updateRow to update the Person table in database. 
This code is the modification of the last one. Changes made are shown in bold face. 
1 // File ResultSetEx.java 
2 import java.sql.*; 
3 public class ResultSetEx { 
4 public static void main (String args[ ]) { 
5 try { 
6 //Step 2: load driver 
7 Class.forName(“sun.jdbc.odbc.JdbcOdbcDriver”); 
8 //Step 3: define the connection URL 
9 String url = “jdbc:odbc:personDSN”; 
10 //Step 4: establish the connection 
11 Connection con = DriverManager.getConnection(url); 
12 //Step 5: create PrepareStatement by passing sql and 
13 // ResultSet appropriate fields 
14 String sql = “SELECT * FROM Person”; 
15 PreparedStatement pStmt = con.prepareStatement(sql, 
16 ResultSet.TYPE_SCROLL_INSENSITIVE, 
17 ResultSet.CONCUR_UPDATABLE); 
18 //Step 6: execute the query 
19 ResultSet rs = pStmt.executeQuery();
Web Design & Development – CS506 VU 
© Copyright Virtual University of Pakistan 
167 
20 // moving cursor to second row 
21 rs.absolute(2); 
22 lumn of 2nd row in rs 
23 
24 
25 
26 
27 
28 tion sqlEx){ 
29 System.out.println(sqlEx); 
30 
31 } // end main 
32 } // end class 
Compile & Execute 
Given below are two states of Person table. Notice that address of 2nd row is updated. Person table: 
Before execution 
// update address co 
rs.updateString(“Address”, “model town”); // update the row in database rs.updateRow( ); //Step 8: close the connection con.close(); }catch(Excep 
} Person table: After execution
Web Design & Development – CS506 VU 
© Copyright Virtual University of Pakistan 
168 
Useful ResultSet’s Methods (cont.) 
. moveToInsertRow(int) 
-An updatable resultset object has a special row associate with it i.e. 
insert row -Insert row – a buffer, where a new row may be constructed 
by calling updater methods. -Doesn’t insert the row into a result set or 
into a databse. 
-For example, initially cursor is positioned on the first row as shown in the diagram. 
-Bng moveToInsertRow( ), the cursor is m y calli oved to insert row as shown below. 
Now by calling various updates, we can insert values into the columns of insert row as shown 
nser the current row into this ResultSet object and into the database too. 
belo 
w. 
. insertRow 
( ) 
-Its the contents of
Web Design & Development – CS506 VU 
© Copyright Virtual University of Pakistan 
169 
-Moves the cursor back to the position where it was before calling moveToInsertRow() 
given below diagram 
Note: The cursor must be on the insert row before calling this method or exception would be raised. 
Example Code 16.3: Inserting new row 
-This is shown in the 
The following code example illustrates how to add/insert new row into the ResultSet as well into the 
database. 
This code is the modification of the last one. Changes made are shown in bold face. 
1 // File ResultSetEx.java 
2 import java.sql.*; 
3 public class ResultSetEx { 
4 public static void main (String args[ ]) { 
5 try { 
6 d driver 
7 Class.forName(“sun.jdbc.odbc.JdbcOdbcDriver”); 
8 
9 String url = “jdbc:odbc:personDSN”; 
10 
11 nection(url); 
12 //Step 5: create PrepareStatement by passing sql and 
13 ultSet appropriate fields 
14 String sql = “SELECT * FROM Person”; 
15 PreparedStatement pStmt = con.prepateStatement(sql, 
16 ResultSet.TYPE_SCROLL_INSENSITIVE, 
17 ResultSet.CONCUR_UPDATABLE); 
18 //Step 6: execute the query 
19 ResultSet rs = pStmt.executeQuery(); 
20 // moving cursor to insert row 
21 
22 
23 rs.updateString( “Name” , “imitiaz” ); 
24 rs.updateString( “Address” , “cantt” ); 
25 rs.updateString( “phoneNum” , “9201211” ); 
//Step 2: loa 
//Step 3: define the connection URL //Step 4: establish the connection Connection con = DriverManager.getCon 
// Res 
rs.moveToInsertRow(); // updating values in insert row
Web Design & Development – CS506 VU 
© Copyright Virtual University of Pakistan 
170 
26 // inserting row in resultset & into database 
27 rs.insertRow( ); 
29 con.close(); 
32 } 
ven b er executing program, a newly added row is 
sent. 
tion 
28 //Step 8: close the connection 
30 }catch(Exception sqlEx){ 31 System.out.println(sqlEx); 
33} // end main 
34 } // end class 
Compile & Execute 
Gielow are two states o 
f Person table. Note that aft 
pre 
Person table: Before execu 
Person table: After execution
Web Design & Development – CS506 VU 
© Copyright Virtual University of Pakistan 
171 
Useful ResultSet’s Methods (cont.) 
. last( ) & first( ) 
-Moves the cursor to the last & first row of the ResultSetobject respectively. -Throws exception if 
the ResultSet is TYPE_FORWARD_ONLY 
. getRow( ) 
-Returns the current row number 
-As mentioned earlier, the first row has index 1 and so on. 
. deleteRow( ) 
row from this ResultSet object and from the underlying database. 
-Throws exception if the cursor is on the insert row. 
Example Code 16.4: Deleting existing row 
-Deletes the current 
The given below example code shows the usage of last( ), getRow( ) and deleteRow( ) method. 
This code is also the modification of the last one. Changes made are shown in bold face. 
1 // File ResultSetEx.java 
2 import java.sql.*; 
3 public class ResultSetEx { 
4 public static void main (String args[ ]) { 
5 try { 
6 //Step 2: load driver 
7 Class.forName(“sun.jdbc.odbc.JdbcOdbcDriver”); 
8 //Step 3: define the connection URL 
9 String url = “jdbc:odbc:personDSN”; 
10 //Step 4: establish the connection 
11 Connection con = DriverManager.getConnection(url); 
12 //Step 5: create PrepareStatement by passing sql and 
13 // ResultSet appropriate fields 
14 String sql = “SELECT * FROM Person”; 
15 PreparedStatement pStmt = con.prepateStatement(sql, 
16 ResultSet.TYPE_SCROLL_INSENSITIVE, 
17 ResultSet.CONCUR_UPDATABLE); 
18 //Step 6: execute the query 
19 ResultSet rs = pStmt.executeQuery(); 
20 // moves to last row of the resultset 
21 rs.last(); 
22 // retrieving the current row number 
23 int rNo = rs.getRow();
Web Design & Development – CS506 VU 
© Copyright Virtual University of Pakistan 
172 
24 System.out.println(“current 
25 // delete current row from rs & db i.e. 4 because 
26 // previously we have called last() method 
27 rs.deleteRow( ); 
28 //Step 8: close the connection 
29 con.close(); 
30 }catch(Exception sqlEx){ 
31 System.out.println(sqlEx); 
32 } 
33 } // end main 
34 } // end class 
ompile & Execute 
he first diagram shows the Person table before execution. Person table: Before execution 
row number” + rNo); 
C 
T Execution program from command prompt will result in displaying current row number on console. This 
can be confirmed from following diagram. 
After execution, the last row (4) is deleted from ResultSet as well as from database. The Person table is 
shown after execution
Web Design & Development – CS506 VU 
© Copyright Virtual University of Pakistan 
173 
Person table: After execution 
References: 
Entire material for this handout is taken from the book JAVA A Lab Course by Umair Javed. This 
material is available just for the use of VU students of the course Web Design and Development and not 
. 
for any other commercial purpose without the consent of author
Web Design & Development – CS506 VU 
© Copyright Virtual University of Pakistan 
174 
Lesson 17 
Meta Data 
rmation) about data. The actual data has no meaning without 
tenc are listed some numeric values 
In simple terms, Meta Data is data (info 
exise of Meta data. To clarify this, let’s look at an example. Given below What this information about? We cannot state accurately. These values might be representing some one’s 
salaries, price, tax payable & utility bill etc. But if we specify Meta data about this data like shown below: 
Now, just casting a glance on these values, you can conclude that it’s all about some ones salaries. 
ResultSet Meta data 
ResultSet Meta Data will help you in answering such questions 
-Ho columns are in the ResultSet? 
-Wh 
-Ar 
-Wh n? 
-Wh 
-Ca 
m a ry() ), derive a ResultSetMetaData object by calling 
eta pet (here rsis a valid ResultSetobject): 
etaData(); 
w many 
at is the name of given column? 
e the column name case sensitive? 
at is the data type of a specific colum 
at is the maximum character size of a column? 
n you search on a given column? 
Creating ResultSetMetaData object 
FroResultSet (the return type of executeQue 
getMData() method as shown in the given code snip 
ResultSetMetaData rsmd = rs.getM 
Now, rsmd can be used to look up number, names & types of columns
Web Design & Development – CS506 VU 
© Copyright Virtual University of Pakistan 
175 
Useful ResultSetMetaData methods 
. getColumnCount ( ) 
– Returns the number of columns in the result set 
ColumnDisplaySize (int) 
olumn in characters 
getColumnLabel (int) 
ame of the column 
– The getColumnLabel() method returns the suggested column label for printouts 
(int) 
Ret he column to compare against types in java.sql.Types 
mp ultSetMetaData 
. get 
– Returns the maximum width of the specified c 
. getColumnName(int) / 
– The getColumnName() method returns the database n 
. getColumnType 
– urns the SQL type for t 
Exale Code 17.1: Using R 
es 
The MetaDataEx.java will print the am 
column names by using ResultSetMetaData object and column values 
ons ple of the scenario where we have no idea about the column names in 
ance 
te: F for the coming ones, we are using the same database (PersonInfo) the one 
created e anges are shown in bold face 
//Step 2: load driver 
“sun.jdbc.odbc.JdbcOdbcDriver”); 
the connection 
11 Connection con = null; 
12 con = DriverManager.getConnection(url, “”, “”); 
13 //Step 5: create PrepareStatement by passing sql and 
14 // ResultSet appropriate fields 
15 String sql = “SELECT * FROM Person”; 
16 PreparedStatement pStmt = con.prepateStatement(sql, 
17 ResultSet.TYPE_SCROLL_INSENSITIVE, 
18 ResultSet.CONCUR_UPDATABLE); 
19 //Step 6: execute the query 
20 ResultSet rs = pStmt.executeQuery(); 
21 // get ResultSetMetaData object from rs 
22 ResultSetMetaData rsmd = rs.getMetaData( ); 
23 // printing no. of column contained by rs 
24 int numColumns = rsmd.getColumnCount(); 
25 System.out.println(“Number of Columns:” + numColumns); 
26 // printing all column names by using for loop 
27 String cName; 
on cole. This is an excellent ex 
adv 
Noor this example code andarlier and repeatedly used. Ch 
we 
1 // File MetaD 
ataEx.java 2 import java.sql.*; 
3 public class MetaDataEx { 
4 pub 
lic static void main (String args[ ]) { 5 try { 
6 
7 Class.forName( 
8 //Step 3: define the connection URL 9 String url = “jdbc:odbc:personDSN”; 10 //Step 4: establish
Web Design & Development – CS506 VU 
© Copyright Virtual University of Pakistan 
176 
28 for(int i=1; i<= numColumns; i++) { 
29 cName = rsmd.getColumnName(i); 
30 System.out.println(cName); 
31 System.out.println(“t”); 
32 } 
33 // changing line or printing an empty string 
34 System.out.println(“ ”); 
35 // printing all values of ResultSet by iterating over it 
36 String id, name, add, ph; 
37 while( rs.next() ) 
38 { 
39 id = rs.getString(1); 
40 name = rs.getString(2); 
41 add = rs.getString(3); 
42 ph = rs.getString(4); 
43 System.out.println(id); 
44 System.out.println(“t”); 
47 System.out.println(add); 
48 
49 
50 
51 
52 
3 con.close(); 
55 System.out.println(sqlEx); 
C 
T on of this program. The database and the 
output are shown below: 
45 System.out.println(name); 46 System.out.println(“t”); 
System.out.println(“t”); 
System.out.println(ph); 
System.out.println(“ ”); 
} 
//Step 8: close the connection 
5 
54 }catch(Exception sqlEx){ 
56 } 57 } // end main101.} // end class 
ompile & Execute: 
he database contains the following values at the time of executi
Web Design & Development – CS506 VU 
© Copyright Virtual University of Pakistan 
177 
DataB 
aseMetaData 
DataBa ng such questions 
ƒ uct? 
i 
be derived. The following code snippet 
n ataBaseMetaDataobject. 
n , usr, pwd); 
ta ata(); 
y the database. 
u f the database’s product name 
u is database product 
u he name of the JDBC driver used to established the connection 
a 
– Retri s database is in read-only mode 
u s true if so, false otherwise 
se Meta Data will help you in answeri 
ƒ 
What SQL types are supported by DBMS to create table? 
What is the name of a database prod 
ƒ 
What is the version number of this database product? 
ƒ 
What is the name of the JDBC driver that is used? 
ƒ 
Is the database in a read-only mode? 
Creat 
ng DataBaseMetaData object 
From 
a Connection object, a DataBaseMetaData object can 
demo 
strates how to get D 
Con 
ection con= DriverManager.getConnection(url 
Da 
BaseMetaData dbMetaData = con.getMeataD 
Now, 
ou can use the dbMetaData to gain information about 
Usefu 
l ResultSetMetaData methods 
. getD 
atabaseProductName( ) 
– Ret 
rns the name o 
. getD 
atabaseProductVersion( ) 
– Ret 
rns the version number of thrName( ) 
. getD– Ret 
riverns t 
. isRe 
dOnly( ) 
eves whether thi 
– Ret 
rn
Web Design & Development – CS506 VU 
© Copyright Virtual University of Pakistan 
178 
Example Code 17.2: using DataBaseMetaData 
This code is modification of the example code 17.1. Changes made are shown in bold face. 
102.// File MetaDataEx.java 103.import java.sql.*; 104.public class MetaDataEx { 
105. public static void main (String args[ ]) { 
106. try { 
107. //Step 2: load driver 
108. Class.forName(“sun.jdbc.odbc.JdbcOdbcDriver”); 
109 
110. 
11. e connection 
12. Connection con = null; 
113. n(url, “”, “”); 
114. 
115. DataBaseMetaData dbMetaData = con.getMetaData(); 
116. // printing database product name 
117. eProductName(); 
118. System.out.println(“DataBase: ” + pName); 
119. // printing database product version 
abaseProductVersion(); 
122. // printing driver name used to establish connection & 
123. // to retrieve data 
ta.getDriverName(); 
125. System.out.println(“Driver: ” + dName); 
126. 
127. b 
128. S 
129. // you can create & execute statements and can 
130. // process results over here if needed 
131. //Step 8: close the connection 
132. con.close(); 
133. }catch(Exception sqlEx){ 
134. System.out.println(sqlEx); 
135. } 
136. } // end main 
137. 
} // end class 
. //Step 3: define the connection URL String url = “jdbc:odbc:personDSN”; 
11 
//Step 4: establish th 
con = DriverManager.getConnectio// getting DataBaseMetaDat object Sring pName = dbMetaData.getDatabas 
120. Sring pVer = dbMetaData.getDat121. System.out.println(“Version: ” + pVer); 
124. Sring dName = dbMetaDa 
// printing whether database is read-only or not oolean rOnly = dbMetaData.isReadOnly(); ystem.out.println(“Read-Only: ” + rOnly);
Web Design & Development – CS506 VU 
© Copyright Virtual University of Pakistan 
179 
Compile & Execute 
On executing the above program, the following output will produce: 
JDBC Driver Types 
ƒ JDBC Driver Types are divided into four types or levels. 
ƒ Each type defines a JDBC driver implementation with increasingly higher level of platform 
Type – 1: JDBC – ODBC Bridge 
Type 2: Native – API/partly Java driver 
Type 3: Net – protocol/all–Java driver 
Type 4: Native – protocol/all–Java driver 
Now, let’s look at each type in more detail 
them to the ODBC Driver - 
independence, performance, deployment and administration. The four types are: 
Type – 1: JDBC – ODBC Bridge 
-Translates all JDBC calls into ODBC (Open Database Connectivity) calls and send 
Generally used for Microsoft database. -Performance is degraded
Web Design & Development – CS506 VU 
© Copyright Virtual University of Pakistan 
180 
4. Type – 2: Native – API/partly Java driver 
-Converts JDBC calls into database-specific calls such as SQL Server, Informix, Oracle or Sybase. 
-Partly-Java drivers communicate with database-specific API (which may be in C/C++) using the Java 
Native Interface. 
-Significantly better Performance than the JDBC-ODBC bridge 
4. Type – 3: Net – protocol/all–Java driver 
-Follows a three-tiered approach whereby the JDBC database requests ()are passed through the network to 
the middle-tier server 
-Pure Java client to server drivers which send requests that are not database-specific 
to a server that translates them into a database-specific protocol. . -If the middle-tier server is 
written in java, it can use a type 1or type 2JDBC driver 
to do this
Web Design & Development – CS506 VU 
© Copyright Virtual University of Pakistan 
181 
4. Type – 4: Native – protocol / all – java driver 
-Converts JDBC calls into the vendor-specific DBMS protocol so that client application can communicate 
directly with the database server 
plemented in Java to achieve platform independence and eliminate deployment issues. 
-Per m 
-Completely im 
forance is typically very good
Web Design & Development – CS506 VU 
© Copyright Virtual University of Pakistan 
182 
On – Line Resources 
• Sun’s JDBC Site 
http://java.sun.com/products/jdbc/ 
• JDBC Tutorial 
tp://java.sun.com/docs/books/tutorial/jdbc/ ht 
• List of available JDBC Drivers http://industry.java.sun.com/products/jdbc/drivers/ • RowSet Tutorial 
http://java.sun.com/developer/Books/JDBCTutorial/chapter5.html • JDBC RowSets Implementation Tutorial http://java.sun.com/developer/onlineTraining/ Database/jdbcrowsets.pdf 
References: 
• Java API documentation 5.0 
• Java – A Lab Course by Umair Javed 
• JDBC drivers in the wild 
http://www.javaworld.com/javaworld/jw-07-2000/jw-0707-jdbc_p.html
Web Design & Development – CS506 VU 
© Copyright Virtual University of Pakistan 
183 
Lesson 18 
Java Graphics 
Painting 
Window is like a painter’s canvas. All window paints on the same surface. More importantly, windows don’t 
remember what is under them. There is a need to repaint when portions are newly exposed. 
Java components are also able to paint themselves. Most of time, painting is done automatically. However 
sometimes you need to do drawing by yourself. Anything else is programmer responsibility 
How painting works? 
Let’s take windows example. Consider the following diagram in which the blue area is representing the 
desktop. The one frame (myApp) is opened in front of desktop with some custom painting as shown 
below. 
myApp consist of a JPanel. The JPanel contains a JButton. Two rectangles, a circle & a lines are also drawn 
on the JPanel.
Web Design & Development – CS506 VU 
© Copyright Virtual University of Pakistan 
184 
After opening notepad and windows explorer window, diagram will look like this: Lets shuts off the windows explorer, the repaint event is sent to desktop first and then to myApp. The 
figure shown below describes the situation after desktop repaint event get executed. Here you can clearly 
see that only desktop repaints itself and window explorer remaining part is still opened in front of myApp.
Web Design & Development – CS506 VU 
© Copyright Virtual University of Pakistan 
185 
The following figure shows the situation when myApp’s JPanel calls its repaint method. Notice that some 
t repaint event is sent to it. 
Next, JPanel forwards repaint event to JButton that causes the button to be displayed in its original form. 
portion of window explorer is still remains in front of JButton because yet no
Web Design & Development – CS506 VU 
© Copyright Virtual University of Pakistan 
186 
This is all done automatically and we cannot feel this process cause of stunning speed of modern compthat performs all these steps in flash of eye. 
uters 
Painting a Swing Component Three methods are at the heart of painting a swing component like JPanel etc. For instance, paint() gets 
called when it's time to render -- then Swing further factors the paint() call into three separate methods, 
which are invoked in the following order: 
— protected void paintComponent(Graphics g) 
— protected void paintBorder(Graphics g) 
— protected void paintChildren(Graphics g) 
) to paint. 
Lets look at these methods in order in which they get executed 
paomponet( ) 
intC 
— it is a main method for painting 
— By default, it first paints the background 
— After that, it performs custom painting (drawing circle, rectangles etc.) 
paintBorder( ) Tells the components border (if any 
— 
— It is suggested that you do not override or invoke this method paintChildern( ) 
— Tells any components contained by this component to paint themselves — It is suggested that you do not override or invoke this method too.
Web Design & Development – CS506 VU 
© Copyright Virtual University of Pakistan 
187 
ing methods calls 
Example: Understand 
Consider the following figure The figure above illustrates ich each component that inherits from 
JC e background and performing custom painting is 
perfor 
In Figure 3 – paintBorder is get called And finally in figure 4 – paintChildern is called that causes the 
JButto important thing to note here is for JButton (since it is a JComponent), 
all thes 
metho 
Yo 
the order in wh 
omponent paint itself. Figure 1 to 2 --painting th 
med by the paintComponent method 
n to render itself. Note: The 
e 
ds are also called in the same order. 
ur Painting Strategy 
You must follow the three steps in order to perform painting. 
Subclass JPanel 
– class MyPanel extends JPanel 
– Doing so MyPanel also becomes a JPanle due to inheritance 
Override the paintComponent(Graphics g) method 
– Inside method using graphics object, do whatever drawing you want to do 
Install that JPanel inside a JFrame 
– When frame becomes visible through the paintChildren() method your panel become visible 
– To become visible your panel will call paintComponent() method which will do your custom 
drawing
Web Design & Development – CS506 VU 
© Copyright Virtual University of Pakistan 
188 
Example Code 18.1: Suppose, we want to draw one circle & rectangle and a string “Hello World”. 
The first step is building a cl anel. The following class MyPanel is fulfilling this 
requirement. p o override in this class. The sample code is given below 
// importing requ port java.awt.*; 
// extending class from JPanelpu { 
// overriding p 
public void pa g){ 
// erasing r all the// previous painting super.paintComponent(g); 
// Down cas DGraphics2D g2 = (Graphics2D)g; 
// drawing rectanle 
g2.drawRe 0); 
// changin 
g2.setColo 
// drawing filled oval with 
// draw 
}// end pain 
} // end MyPan 
ass that inherits from JPaintComponent( ) method is als 
ired packagesimport javax.swing.*;im 
blic class MyPanel extends JPanelaintComponent method intComponent(Graphicsbehaviour – this will clea 
ting Graphics object to Graphics2 
ct(20,20,20,2 
g the color to blue r(Color.blue); color i.e. blueg2.fillOval(50,50,20,20); 
ing stringg2.drawString("Hello World", 120, 50); tComponent el class
Web Design & Development – CS506 VU 
© Copyright Virtual University of Pakistan 
189 
The Test class that contains the main method as well uses MyPainel (previously built) class is given below 
// importing required packages 
import javax.swing.*; 
import java.awt.*; 
public class Test { 
JFrame f; 
// declaring Reference of MyPanel class 
MyPanel p; 
// parameter less constructor 
public Test(){ 
f = new JFrame(); 
Container c = f.getContentPane(); 
c.setLayout(new BorderLayout()); 
// instantiating reference 
p = new MyPanel(); 
// adding MyPanel into container 
c.add(p); 
f.setSize(400,400); 
f.setVisible(true); 
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
} // end constructor 
// main method 
public static void main(String args[ ]){ 
Test t = new Test(); 
}
Web Design & Development – CS506 VU 
© Copyright Virtual University of Pakistan 
190 
Note: Here we have used only some methods (drawRect( ) & fillOval( ) etc. ) of Graphics class. F 
complete list, see the Java API documentation 
or a
Web Design & Development – CS506 VU 
© Copyright Virtual University of Pakistan 
191 
Lesson 19 
How to Animate? 
If we want to animate something like ball, moving from one place to another, we constantly need to call 
paintComponent( ) method and to draw the shape (ball etc.) at new place means at new coordinates. 
Painting is managed by system, so calling paintComponent() directly is not recommended at all. Similarly 
calling paint( ) method is also not recommended. Why? Because such code may be invoked at times when it 
is not appropriate to paint -- for instance, before the component is visible or has access to a valid Graphics 
object. 
Java gives us a solution in the from of repaint( ) method. Whenever we need to repaint, we call this method 
that in fact makes a call to paint( ) method at appropriate time. 
Problem & Solution 
present in example code 18.1 (last example) when a mouse is 
dragged 
ƒ When a mouse is clicked find the co-ordinates of that place and paint Rectangle at that place by 
ead of Hard-coding the position of co-ordinates uses some variables. For example mx, my 
tangle by passing hard-coded values like 20 
0); 
at a new 
ƒ nis game (during lecture). Now, what to do code the paddle 
ƒ le. We are doing it using mouse, try it using mouse. 
Exam 
Th oduced when mouse is dragged from one location to anther 
ƒ What to do to move the shapes 
ƒ First time painting is what we already have done 
requesting, using repaint() call 
ƒ Here inst 
– In the last example code, we draw a recg.drawRect(20,20,20,2 
– Now, we’ll use variables so that change in a variable value causes to display a rectangle location 
g.drawRect(mx,my,20,20; 
Similarly, you have seen a tenmovement. 
In the coming up examp 
ple Code 19.1 
e following outputs were pr
Web Design & Development – CS506 VU 
© Copyright Virtual University of Pakistan 
192 
First we examine the MyPanel.java class that is drawing a filled rectangle. 
import jav t.*; 
// exten 
// variables used to draw rectangles at different//locations 
int m 
int m 
// overriding paintComponent method 
public void paintComponent(Graphics g){ 
// erasing behaviour – this the// previous painting super.paintComponent(g); 
// Down casting Graphics object to Graphics2D 
// changing the color to blue 
stance variablesg2.fillRect(mX,mY,20,20); 
}// en 
The Test 
// importing required packagesimport javax.swing.*;import java.awt.*; 
public cla 
ax.swing.*;import java.awding class from JPanelpublic class MyPanel extends JPanel { 
X = 20; Y = 20; 
will clear all 
Graphics2D g2 = (Graphics2D)g; 
g2.setColor(Color.blue); 
// drawing filled oval with color i.e. blue// using in 
d paintComponent 
class is given below. Additionally this class also contains the code for handling mouse events. 
ss Test {
Web Design & Development – CS506 VU 
© Copyright Virtual University of Pakistan 
193 
JFra 
MyPanel class 
MyPanel p; 
// parameter less constructor 
C ntPane(); 
c.setLayout(new BorderLayout()); 
// instantiating reference 
// adding MyPanel into container 
f.setSize 
f.setVisi 
// creating inner class object 
Handler h = new Handler(); 
// registering MyPanel to handle events 
p.addMouseMotionListner(h); 
} // end constructor 
// inner class used for handling events 
public class Handler extends MouseMotionAdapter{ 
// capturing mouse dagged events 
public void mouseDragged(MouseEvent me){ 
// getting the X-Position of mouse and assigning// value to instance variable mX of MyPanel 
class 
p.mX = me.getX(); 
// getting the Y-Position of mouse and assigning// value to instance variable mX of MyPanel 
class 
p.mY = me.getY(); 
// call to repaint causes rectangle to be drawn on// new location 
me f; 
// declaring Reference of 
public Test(){ 
f = new JFrame(); ontainer c = f.getConte 
p = new MyPanel(); 
c.add(p); 
(400,400); ble(true); 
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Web Design & Development – CS506 VU 
© Copyright Virtual University of Pakistan 
194 
p.repaint() ; 
} // end mouseDragged } // end Handler class 
// main method 
public static void main(String args[ ]){ 
Test t = new Test(); 
} 
} // end MyPanel class 
On executing this program, when you drag mouse from one location to another, rectangle is also in sink 
with the movement of mouse. Notice that previously drawn rectangle is erased first. 
If we exclude or comment out the following line from MyPanel class 
sup 
Dragging a mouse will produce a similar kind of output shown next 
er.paintComponent(g);
Web Design & Development – CS506 VU 
© Copyright Virtual University of Pakistan 
195 
Example Code 19.2: Ball Animation 
The ball is continuously moving freely inside the corner of the frames. The sample outputs are shown 
below: First we examine the MyPanel.java class that is drawing a filled oval. 
import j va.awt.*; 
// extending blic class MyPanel extends JPanel { 
// va oval at different locations 
int m 
int m 
// overriding paintComponent method 
publ 
/ s painting super.paintComponent(g); 
/ 
G Graphics2D)g; 
// changing the color to blue 
g2.setColor(Color.blue); 
// drawing filled oval with blue color 
// using instance variables 
g2.fillOval(mX,mY,20,20); 
} 
} end of MyP 
avax.swing.*;import jaclass from JPanelpu 
riables used to drawX = 200; Y = 0; 
ic void paintComponent(Graphics g){ / erasing behaviour – this will clear all the// previou/ Down casting Graphics object to Graphics2D raphics2D g2 = ( 
// end paintComponent 
anel class
Web Design & Development – CS506 VU 
© Copyright Virtual University of Pakistan 
196 
The T nts. 
// importing required packagesimport javax.swing.*;import 
java.awt.*;Import java.awt.event.*; 
pu { 
JFrame f; 
MyPa 
public AnimTest(){ 
f = new JFrame(); 
x = 5; 
ultCloseOperation(JFrame.EXIT_ON_CLOSE); 
Timer class object, used for firing 
er a specified delay 
ires time in 
// milliseconds and object of class that handles 
Timer t = new Timer (5, this); 
// starts the timer, causing it to start sending// action events to listeners 
t.start(); 
} // end constructor 
// event handler method 
public void actionPerformed(ActionEvent ae){ 
est class is given below. Additionally this class also contains the code for handling mouse eve 
blic class AnimTest implements ActionListener 
nel p; 
// used to control the direction of ball int x, y; 
Container c = f.getContentPane(); c.setLayout(new BorderLayout()); 
y = 3; 
p = new MyPanel(); c.add(p); 
f.setSize(400,400); f.setVisible(true); 
f.setDefa 
// creating a // one or more action events aft// Timer class constructor requ 
// action events
Web Design & Development – CS506 VU 
© Copyright Virtual University of Pakistan 
197 
// if ball reached to maximum width of frame minus// 40 since diameter of ball is 40 then 
change the// X-direction of ball 
i 
x = -5; 
// if ball reached to maximum height of frame 
// minus 40 then change the Y-direction of ball 
if (f.getHeight()-40 == p.mY) 
y = -3; 
// if ball reached to min. of width of frame, 
// change the X-direction of ball 
if (p.mX == 0 ) 
x = 5; 
// if ball reached to min. of height of frame, 
// change the Y-direction of ball 
if (p.mY == 0 ) 
y = 3; 
// Assign x,y direction to MyPanel’s mX & mY 
p.mX += x; 
p.mY += y; 
// call to repaint() method so that ball is drawn on// new locations 
p.repaint(); 
} // end actionPerformed() method 
// main method 
public static void main(String args[ ]){ 
AnimTest at = new AnimTest(); 
} 
} // end of AnimTest class 
f (f.getWidth()-40 == p.mX)
Web Design & Development – CS506 VU 
© Copyright Virtual University of Pakistan 
198 
References: 
ƒ Java, A Lab Course by Umair Javed 
ƒ Painting in AWT & Swing 
http://java.sun.com/products/jfc/tsc/ar ting/index.html 
ticles/pain 
ƒ Performing Custom Painting 
g/index.html 
http://java.sun.com/docs/books/tutorial/uiswing/14paintin
Web Design & Development – CS506 VU 
© Copyright Virtual University of Pakistan 
199 
Lesson 20 
Applets 
d included in a HTML page. 
ating system on which it runs 
ƒ An applet is a Panel that allows interaction with a Java program 
ƒ A 
ƒ Y 
ƒ For security reasons, applets run in a sandbox: they have no access to the client’s file system 
Applets Support 
ƒ Most modern browsers support Java 1.4 if they have the appropriate plugin 
ƒ Sun provides an application appletviewerto view applets without using browser. 
ƒ In general you should try to write applets that can be run with any browser 
What an App 
ƒ You w extending the class Appletor JApplet 
ƒ Applet is just a class like any other; you can even use it in applications if you want 
ƒ When ou write an applet, you are only writing part of a program 
ƒ The browser supplies the main method 
The genealogy o 
The following figure shows the inheritance hierarchy of the JApplet class. This hierarchy determines much 
of what an applet can do and how, as you'll see on the next few pages. 
bject 
| 
+----java.awt.Component 
| 
+----java.awt.Container|+----java.awt.Panel 
| 
+----java.applet.Applet|+----javax.swing.JApplet 
ƒ A small program written in Java an ƒ It is independent of the oper 
applet is typically embedded in a Web page and can be run from a browser ou need special HTML in the Web page to tell the browser about the applet 
let is? rite an applet by y 
f Applet 
java.lang.O 
Example Code 20.1: Writing a Simple Applet 
Below is the source code for an applet called HelloApplet. This displays a “Hello World” string. Note that 
no main method has been provided. 
// File HelloApplet.java
Web Design & Development – CS506 VU 
© Copyright Virtual University of Pakistan 
200 
//step 1 kagesimport java.awt.*;import 
javax.swing.*; 
ss also becomes an//appletpublic class HelloApplet extends 
JApplet { 
// overriding paint method 
public void paint(Graphics g) { 
// write code here u want to display & draw by using// Graphics objectg.drawString(“Hello 
World”, 30 , 30); 
After defining the HelloApplet.java, the next step is to write .html file. Below is the source code of 
Tes m tains the ordinary html code except one. 
<title> Simple 
<body> 
<!-- providing the class name of applet with 
width &height--!> 
<applet code="HelloApplet.class” 
width=150 height=100> 
</applet> 
</body> 
</html> 
Compile & Execute 
By simply double clicking on Test.html file, you can view the applet in your browser. However, you can 
also use the appletviewer java program for executing or running applets. 
The applet viewer is invoked from the command line by the command 
appletviewer htmlfile 
where htmlfile is the name of the file that contains the html document. For our example, the command 
e this: 
: importing required pac 
// extending class from JApplet so that our cla 
} } // end class 
t.htl file. The Test.html con 
<html> 
<head> 
Applet </title> </head> 
looks lik
Web Design & Development – CS506 VU 
© Copyright Virtual University of Pakistan 
201 
appletviewer Test.html 
As a s 
reult, you will see the following output Applet Life Cycle Methods 
When an applet is loaded, an instance of the applet's controlling class (an Applet subclass) is created. After that an applet passes through some stages or methods, each of them are build for specific purpose 
An applet can react to major events in the following ways: 
ƒ It can initialize itself. 
op running. 
ƒ It can perform a final cleanup, in preparation for being unloaded 
lled in the specific order shown below. Not every applet needs to 
ƒ It can start running. ƒ It can st 
The applet’s life cycle methods are caoverride every one of these methods.
Web Design & Development – CS506 VU 
© Copyright Virtual University of Pakistan 
202 
Let’s t each method in detail and find out what they do 
init( ) 
ƒ Is ca 
ƒ The t each time it's loaded (or reloaded). 
ƒ You can 
on 
ƒ For example, n the applet's loaded or when the user revisits a page that contains the applet 
alled whenever the browser is maximized 
paint( ) 
ƒ paint( ) is called for the first time when the applet becomes visible 
ƒ Whenever applet needs to be repainted, paint( ) is called again 
ƒ Do all your painting in paint( ), or in a method that is called from paint( ) 
the user leaves the applet's page or quits the browser. 
ƒ stop( ) is also called whenever the browser is minimized 
estroy( ) 
ƒ Is called only once. 
ƒ To perform a final cleanup in preparation for unloading 
xample Code 20.2: Understanding Applet Life Cycle Methods 
ake a look on 
lled only once. purpose of init( ) is to initialize the apple 
think of it as a constructor 
start( ) ƒ To start the applet's executi 
whe ƒ start( ) is also c 
stop( ) ƒ To stop the applet's execution, such as when 
d 
E 
The following code example helps you in understanding the calling sequence of applet’s life cycle methods.
Web Design & Development – CS506 VU 
© Copyright Virtual University of Pakistan 
203 
These methods are only displaying debugging statements on the console. 
/ File AppletDemo.java 
//step 1: importing required packagesimport java.awt.*;import 
javax.swing.*; 
ss also becomes an//appletpublic 
clas p 
alled"); 
} 
// overriding start method 
p li 
} 
// overriding paint method 
public void paint(Graphics g){ 
System.out.println("paint() called"); 
// overriding stop method 
public void stop(){ 
println("stop() called"); 
} 
// overriding destroy method 
public void destroy(){ 
tln("destroy() called"); 
// end class 
The DemoTest.html file is using this applet. The code snippet of it given below: 
<html> <head> <title> Applet Life Cycle Methods 
</ 
/ 
// extending class from JApplet so that our cla 
s ApletDemo extends JApplet { 
// overriding init method 
public void init ( ) { 
System.out.println("init() c 
ubc void start ( ){ 
System.out.println("start() called"); 
} 
System.out. 
System.out.prin} } 
title></head> <body>
Web Design & Development – CS506 VU 
© Copyright Virtual University of Pakistan 
204 
<!-- providing the class name of applet with width &height--!> 
<applet code="AppletDemo.class” 
width=150 height=100> 
</applet></body></html> 
Compile & Execute 
To u cycle methods, you have to execute it by using 
appletvi zing, minimizing the applet, bringing another window 
in fro utput. 
Example Code 20.3: Animated Java Word Sample Output 
nderstand the calling sequence of applet life 
ewer command. Do experiments like maximint of applet and keep an eye on console o 
The b elow: 
Design Process 
The Progr method 
ƒ Draws string “java” on 40 random locations 
ƒ F ndom font out of 4 different fonts 
ƒ For every drawing, it selects random color out of 256 * 256 * 256 RGB colors 
Repaint is called after every 1000 ms. 
After 10 calls to repaint, screen is cleared 
Generating Random Numbers 
ƒ Use static method random of Math class 
Mat 
ƒ less than 1.0. 
ƒ Multiply the number with appropriate scaling factor to increase the range and type cast it, if needed. 
int i = (int)( Math.random() * 5 );// will generate random numbers between 0 & 4. 
rowser output of the program is given b 
am in a single call of paint 
or every drawing, it selects ra 
h.random() ; 
Returns positive double value greater than or equal to 0.0 or
Web Design & Development – CS506 VU 
© Copyright Virtual University of Pakistan 
205 
Progra 
The pr ny custom methods. Let’s discuss each of them one by one that will help in 
unders overall logic of the program. 
. drawJava( ) 
As name indicates, this method will be used to write String “java” on random locations. The code is 
given below: 
// m 
public void drawJava(Graphics2D g2) { 
// generate first number randomly. The panel width is 1000int x = (int) (Math.random() * 1000); // 
generate second number randomly. The panel height is 700 
int y = (int) (Math.random() * 700); // draw String on these randomly 
select 
. chooseC 
This method will choose color randomly out of 256 * 256 * 256 possible colors. The code snippet is given 
below: 
// method c 
public Color 
// choosing red color value randomly 
int r = (int) (Math.random() * 255); 
// choosing green color value randomly 
int g = (int) (Math.random() * 255); 
// choosing blue color value randomly 
r by providing R-G-B valuesColor c = new Color(r, g, b); 
// returning color 
return c; 
m’s Modules 
ogram is build using matanding the 
ethod drawJava 
ed numebrsg2.drawString("java", x, y); } olor( ) 
hooseColor 
chooseColor() { 
int b = (int) (Math.random() * 255); // constructing a colo
Web Design & Development – CS506 VU 
© Copyright Virtual University of Pakistan 
206 
} . chooseFont( ) 
This method will choose a Font for text (java) to be displayed out of 4 available fonts. The code snippet is 
given below: 
dom value that helps in choosing a fontint fontChoice = (int) 
) + 1; 
for selecting font 
Font("Serif", Font.BOLD + Font.ITALIC, 20);break; 
case 2: f = new Font("SansSerif", Font.PLAIN, 17);break; 
ca , Font.ITALIC, 23);break; 
case 4: f = new Font("Dialog", Font.ITALIC, 30);break; 
} // end switch 
// returns Font object 
return f; 
. p 
The last method to be discussed here is paint( ). By overriding this method, we will print string “java” 
on 40 random locations. For every drawing, it selects random font out of 4 different fonts & random 
color out of 256 * 256 * 256 RGB colors. 
Let’s see, how it happens: 
/ overriding method paint 
public void paint(Graphics g) { 
counter variable. 
clearCounter++; 
// method chooseFont 
public Font chooseFont() { // generating a ran(Math.random() * 4// declaring font reference 
Font f = null; // using switch based logicswitch (fontChoice) { 
case 1: f = new 
se 3: f = new Font("Monospaced" 
} //end chooseFont 
aint( ) 
/ 
// incrementing clear
Web Design & Development – CS506 VU 
© Copyright Virtual University of Pakistan 
207 
// printing 40 “java” strings on different locations by// selcting random font & colorfor (int i = 
1; i <= 40; i++) { 
// choosing random color by calling chooseColor() method 
Color c = chooseColor(); 
// setting color 
g2.setColor(c); 
// choosing random Font by calling chooseColor() method 
Font f = chooseFont(); 
g2.setFont(f); 
va” by calling drawJava() method 
drawJava(g2); 
g2 = (Graphics2D) g; 
paint is called 10 times then clears the// screen and set counter again to zero if 
, 0, 1000, 700);clearCounter = 0; } } 
// end paint method 
// drawing string “ja 
} // end for loop Graphics2D// checking if 
(clearCounter == 10) { 
g2.clearRect(0
Web Design & Development – CS506 VU 
© Copyright Virtual University of Pakistan 
208 
Merging Pieces 
By ins the program will look like one given below. Notice that 
it con me extra code with which you are already familiar. 
/ 
/step 1: importing required packages 
import java.awt.*; 
import java.awt.event.*; 
x.swing.*; 
public class JavaAnim extends JApplet implements ActionListener { 
// used to count how many times paint is called 
clearCounter; 
Timer reference 
publ ) { 
setBackground(Color.black); 
clearCounter = 0; 
Timer t = new Timer(1000, this); 
} 
// overriding paint method – discussed above 
phics g) { 
if (clearCounter == 10) { 
g2 
cle 
} 
for (int i = 1; i <= 40; i++) { 
Color c = chooseColor(); 
g2.setColor(c); 
Font f = chooseFont(); 
erting all method inside JavaAnim.java class, tains methods discussed above with so 
/ File JavaAnim.java 
/ 
import java 
int// declaring 
Timer t; // overriding init method, used to initialize variables ic void init( 
t.start(); 
public void paint(Gra 
clearCounter++; Graphics2D g2 = (Graphics2D) g; 
.clearRect(0, 0, 1000, 700); 
arCounter = 0;
Web Design & Development – CS506 VU 
© Copyright Virtual University of Pakistan 
209 
g2.setFont(f); 
drawJava(g2); 
} 
} 
// o r 
pub v 
repaint(); 
} 
// chooseColor method – discussed above 
public Color chooseColor() { 
in 
i 
int b ndom() * 255); 
Cr 
r 
} 
// ch 
public Font chooseFont() { 
int fontChoice = (int) (Math.random() * 4) + 1; 
Font f = null; 
switch (fontChoice) { 
case 1: f = new Font("Serif", Font.BOLD + Font.ITALIC, 20);break; 
case 2: f = new Font("SansSerif", Font.PLAIN, 17);break; 
case 3: f = new Font("Monospaced", Font.ITALIC, 23);break; 
case 4: f = new Font("Dialog", Font.ITALIC, 30);break; 
} 
return f; 
} 
veriding actionPerformed()of ActionListener interface// called by Timer object licoid actionPerformed(ActionEvent ae) { 
t r= (int) (Math.random() * 255); nt g= (int) (Math.random() * 255); = (int) (Math.ra 
olor c = new Color(r, g, b); 
etun c; 
ooseFont method – discussed above
Web Design & Development – CS506 VU 
© Copyright Virtual University of Pakistan 
210 
// drawJava() method – discussed above 
public void drawJava(Graphics2D g2) { 
int x = (int) (Math.random() * 1000); 
int y = (int) (Math.random() * 700); 
g2.drawString("java", x, y); 
} 
} / 
: 
<html> 
<head> 
<title> Animated Java Word </title> 
</head> 
<applet code="JavaAnim.class" width=1000 height=700> </applet> 
</b l> 
Compile & Execute 
You can cute it directly us you can use 
“your name” instead of “java” 
References: 
 . Java, A Lab Course by Umair Javed 
 . W s 
. http://java.sun.com/docs/books/tutorial/applet/ 
/ end class The AnimTest.html file is using this applet. The code snippet of it given below 
body 
ody /htm 
exe 
ing browser or by using appletviewer application. For having fun, and watch it in different colors ☺ 
riting Applet
Web Design  Development – CS506 VU 
© Copyright Virtual University of Pakistan 
211 
Lesson 21 
Socket Programming 
Socket 
ƒ A socket is one endpoint of a two-way communication link between two programs running 
generally on a network. 
ƒ A socket is a bi-directional communication channel between hosts. A computer on a network often 
termed as host. 
Socket 
ƒ at file is an abstraction of your hard drive. 
Similarly you can think of a socket as an abstraction of the network. 
ƒ wired up to the other 
ƒ cs of 
receive data to and from network through socket, without 
actually going into underlying mechanics. 
ƒ You read and write data from/to a file using streams. To read and write data to socket, you will also 
What is 
protocols available to communicate such as TCP and UDP. We will use TCP 
for programming in this handout. 
ƒ There are 64k ports available for available for UDP, so at least 
n 128k simultaneous connections. 
ƒ There are well-known ports w 
o below 1024 
o provides standard services 
o Some well-known ports are: 
-FTP works on port 21 
-HTTP works on port 80 -TELNET works on port 23 etc. 
How Client – Server Communicate 
Dynamics As you have already worked with files, you know th 
Each end has input stream (to send data) and output stream (to receive data) 
host. You store and retrieve data through files from hard drive, without knowing the actual dynamithe hard drive. Similarly you send and 
use streams. 
Port? ƒ It is a transport address to which processes can listen for connections request. ƒ There are different 
TCP sockets and 64k ports 
theoretically we can ope 
hich are 
ƒ Normally, a server runs on a specific computer and has a socket that is bound to a specific port 
number. 
ƒ The server just waits, listening to the socket for a client to make a connection request. 
ƒ On the client side: The client knows the hostname of the machine on which the server is running 
and the port number to which the server is connected. 
ƒ On the server side, if the connection is accepted, a socket is successfully created and the client can 
use the socket to communicate with the server. 
ƒ Note that the socket on the client side is not bound to the port number used to make contact with 
the server. Rather, the client is assigned a port number local to the machine on which the client is 
running. 
ƒ The client and server can now communicate by writing to or reading from their sockets
Web Design  Development – CS506 VU 
© Copyright Virtual University of Pakistan 
212 
. As soon as client creates a socket that socket attempts to connect to the specified server. 
. The server listens through a special kind of socket, which is named as server socket. 
. The sole purpose of the server socket is to listen for incoming request; it is not used for 
communication. 
. 
I 
n 
. The (and consequently a different port number) so that it can 
continue to listen through the original server socket for connection requests while tending to 
the 
c 
f every thing goes well, the server accepts the connection. Upon acceptance, the server gets a ew socket, a communication socket, bound to a different port number. 
server needs a new socket 
needs of the connected client. This scheme is helpful when two or more clients try to onnect to a server simultaneously (a very common scenario). Steps – To Make a Simple Client 
To make a client, process can be split into 5 steps. These are: 
1. Import required package 
You have to import two packages 
. java.net.*; 
. java.io.*; 
Server 
serverName : Name or address of the server you wanted to connect such as 
e.com or 172.2.4.98 etc. For testing if you are 
running client and server on the same machine then you can specify 
“localhost” as the name of server 
. serverPort : Port number you want to connect to 
2. Connect / Open a Socket with 
Create a client socket (communication socket) Socket s = new Socket(“serverName”, serverPort) ; 
http://www.googl
Web Design  Development – CS506 VU 
© Copyright Virtual University of Pakistan 
213 
The scheme is very similar to our home address and then phone number. 
3. Get I/O Streams of Socket 
Get input  output streams connected to your socket 
. For reading data from socket As stated above, a socket has input stream attached to it. InputStream is = s.getInputStream(); 
// now to convert byte oriented sstream that helps in achieving abo 
tream into character oriented buffered reader // we use intermediary 
ve stated purpose 
InputStreamReader isr= new InputStreamReader(is); BufferedReader br = new BufferedReader(isr); 
. For writing data to socket A socket has also output stream attached to it. Therefore, 
OutputStream os = s.getOutputStream(); 
// now to convert byte oriented stream into character oriented print writer 
// here we will not use any intermediary stream because PrintWriter constructor // directly 
accepts an object of OutputStream 
PrintWriter pw = new PrintWriter(os, true); 
Here notice that true is also passed to so that output buffer will flush. 
4. Send / Receive Message 
Once you have the streams, sending or receiving messages isn’t a big task. It’s very much similar to the 
way you did with files 
. To send messages 
pw.println(“hello world”); 
. To read messages 
ne(); 
5. Close Socket 
Don’t forget to close the socket, when you finished your work 
s.c 
String recMsg = br.readLi 
lose();
Web Design  Development – CS506 VU 
© Copyright Virtual University of Pakistan 
214 
Steps – To M 
ake a Simple Server 
To make a server, process can be split into 7 steps. Most of these are similar to steps used in making a 
client. These are: 
1. Import req 
You need the similar set of packages you have used in making of client 
. java.net.*; 
. java.io.*; 
2. Create a Server Socket 
In order t 
for client requests. 
ServerSocket ss = new ServerSocket(serverPort) ; 
. serv 
uired package 
o create a server socket, you will need to specify port no eventually on which server will listen 
erPort: port local to the server i.e. a free port on the server machine. This 
is the same port number that is given in the client socket constructor 
3. Wait f nnections 
The job of the server socket is to listen for the incoming connections. This listening part is done 
th d. 
Socket s = ss.accept(); 
The server program blocks ( stops ) at the accept method and waits for the incoming client connection 
for connection comes it opens a new communication socket (s) and use this socket to 
4. Get I/O Streams of Socket 
Once you have the communication socket, getting I/O streams from communication socket is similar 
or Incoming Co 
rough the accept metho 
when a request 
communicate with the client. 
to the way did in making a client 
1. For reading data from socket InputStream is = s.getInputStream(); InputStreamReader isr= new 
ader br = new BufferedReader(isr); 
2. For writi 
InputStreamReader(is); BufferedRe 
ng data to socket OutputStream os = s.getOutputStream(); 
Pr 
5. Send / Receive Message 
Sending and receivi nt 
T 
pw.println(“hello world”); 
. T 
intWriter pw = new PrintWriter(os, true); 
ng messages is very similar as discussed in making of clieo send messages: 
o read messages 
String recMsg = br.readLine();
Web Design  Development – CS506 VU 
© Copyright Virtual University of Pakistan 
215 
6. Close Socket 
s.close 
Example Code 21.1: Echo Server  Echo Client 
(); 
The c append “hello” with the name send by the client. 
After that, server will send back the name with appended “hello”. 
EchoServ 
Let’s first see the code for the server 
import java.net.*; 
import java.io.*; 
import javax.swing.*; 
public class EchoServer 
{ 
public static void main(String args[]) 
{ 
try 
{ 
//step 2: create a server socket 
ServerSocket ss = new ServerSocket(2222); 
System.out.println(Server 
/* Loop back to the accept method of the serversocket and wait for a new connection request. 
Soserver will continuously listen for requests 
*/ 
while(true) { 
// step 3: wait for incoming connection 
Socket s = ss.accept(); 
System.out.println(connection request recieved); 
// step 4: Get I/O streams 
InputStream is = s.getInputStream();InputStreamReader isr= new 
InputStreamReader(is);BufferedReader br = new BufferedReader(isr); 
OutputStream os = s.getO 
lient will send its name to the server and server will er.java 
// step 1: importing required package 
started...); 
utputStream();
Web Design  Development – CS506 VU 
© Copyright Virtual University of Pakistan 
216 
PrintWriter pw = new PrintWriter(os,true); 
// reading name sent by clientString name = br.readLine(); // appending “hello” with the 
received name 
String msg = Hello  + name +  from Server; // sending back to client 
pw.println(msg); 
// closing communication sockeys.close(); 
} // end while 
}catch(Exception ex){ 
System.out.println(ex); } } } // end class 
EchoClient.java 
The code of the client is given below 
// step 1: importing required package 
import java.net.*;import java.io.*;import 
javax.swing.*; 
public class EchoClient{ 
public static void main(String args[]){ 
try { 
//step 2: create a communication socket 
// if your server will run on the same machine thenyou can pass “localhost” as server address 
*/ 
/* Notice that port no is similar to one passedwhile creating server socket */server 
Socket s = new Socket(“localhost”, 2222); 
// step 3: Get I/O streams 
InputStream is = s.getInputStream();InputStreamReader isr= new 
InputStreamReader(is);BufferedReader br = new BufferedReader(isr); 
OutputStream os = s.getOutputStream();PrintWriter pw = new 
PrintWriter(os,true); 
// step 4: Send / Receive message 
// asking use to enter his/her name 
String msg = JOptionPane.showInputDialog(Enter your name); 
// sending name to server 
pw.println(msg); 
// step 5: Send / Receive message
Web Design  Development – CS506 VU 
© Copyright Virtual University of Pakistan 
217 
// reading message (name appended with hello) from// servermsg = br.readLine(); 
// displaying received messageJOptionPane.showMessageDialog(null , msg); 
// closing communication sockets.close(); 
}catch(Exception ex){ System.out.println(ex); } } } 
Com il 
After compiling both files, run EchoServer.java first, from the command prompt window. You’ll see a 
as shown in the figure below. Also notice that cursor is continuously blinking 
since server is waiting for client request 
// end class 
pe  Execute 
message of “server started” Now, open another command prompt window and run EchoClient.java from it. Look at EchoServer 
window; you’ll see ask you to enter 
name in input dial me press ok button, with in no time, a message dialog box will 
pop up containing your name with appended “hello” from server. This whole process is illustrated below in 
pictorial form: 
the message of “request received”. Sooner, the EchoClient program willog box. After entering na
Web Design  Development – CS506 VU 
© Copyright Virtual University of Pakistan 
218 
sending name to server 
response from server 
Notice that server is still running, you can run again EchoClient.java as many times untill server is running. 
r on a different computer and client on a different. But before doing that 
find the IP of the computer machine on which your EchoServer will eventually run. Replace “localhost” 
with the new IP and start conversion over network ☺ 
References 
To have more fun, run the serve 
Entire material for this handout is taken from the book JAVA A Lab Course by Umair Javed. This 
material is available just for the use of VU students of the course Web Design and Development and not 
for any other co the consent of author. 
mmercial purpose without
Web Design  Development – CS506 VU 
© Copyright Virtual University of Pakistan 
219 
Lesson 22 
Serialization 
. You want to send an object to a stream. 
Motivati 
ƒ A boring conversion from a file to memory 
ƒ As you might recall that AddressBook program reads data from file and then parses it 
ƒ This is a common problem 
Revisiting A 
We read rec amed persons.txt. The person record was present in the file in the 
following format. 
T s used to construct Person objects after reading information from the file is given below. 
Here only the part of code is shown, for complete listing, see AddressBook code in your earlier handout. 
FileReader fr = new FileReader(persons.txt);BufferedReader br = 
while ( line != null ) { 
tokens = line.split(,); 
add = tokens[1]; 
ph = tokens[2]; 
/ you can add p into arraylist, if 
} 
As you have rsing code is required for converting a line into PersonInfo objects. Serialization 
mechanism ving all above in a very simple way. 
What? 
on lot of code involves 
ddressBook ord from a text file n 
persons.txt 
he code that wa 
new BufferedReader(fr); String line = br.readLine(); 
name = tokens[0]; 
PersonInfo p = new PersonInfo(name, add, ph); / 
needed line = br.readLine(); 
seen a lot of paeases developer’s life by achie
Web Design  Development – CS506 VU 
© Copyright Virtual University of Pakistan 
220 
Serialization in Java 
ƒ Java provides an extensive support for serialization 
ƒ Object knows how to read or write themselves to streams 
: 
ƒ Problem 
bjects have some state 
ƒ You need to save and restore that state. 
ƒ The good news is that java serialization takes care of it automatically 
Serializable Interface 
ƒ By implementing this interface a class declares that it is willing to be read/written by automatic 
serialization machinery 
ƒ Found in java.iopackage 
ƒ Tagging interface – has no methods and serves only to identify the semantics of being serializable 
Automa 
ƒ System knows how to recursively write out the state of an object to stream 
ƒ If an object has the reference of another object, the java serialization mechanism takes care of it 
a 
Automa 
ƒ System knows object in memory 
ƒ T nto 
a 
Serializ 
ƒ of PersonInfo, ObejctOutputStream and its method writeObject( ) will be used 
PersonInfo p = new PersonInfo( ); 
ObejctOutputStream out; 
// writing PersonInfo’s object p 
out.writeObject(p); 
ƒ To read that object back, ObejctInputStream and its method readObject()will be used 
ObejctInputStream in; 
// reading PersonInfo’s object. Remember type casting// is required 
PersonInfo obj = (PersonInfo)in.readObject( ); 
Example Code 22.1: Reading / Writing PersonInfo objects 
ƒ As you know, objects get created on heap and have some values therefore Oin memory 
tic Writing 
nd writes it too. tic Reading 
how to read the data from Stream and re-create 
he recreated object is of type “Object” therefore Down-casting is required to convert it ictual type. 
ation: How it worTo write an object 
ks? 
We wato send PersonInfo object to stream. You have alr nt eady seen this class number of times before. 
Here it will also implement serializable interface.
Web Design  Development – CS506 VU 
© Copyright Virtual University of Pakistan 
221 
PersonInfo.java 
import javax.swing.*; 
String name; 
String address; 
String phoneNum; 
(String n, String a, String p) { 
phoneNm = p; 
g person record on GUIpublic void printPersonInfo( ) { 
JOptionPane.showMessageDialog(null , 
“name: ” + name + “address:” +address + 
phone no:” + phoneNum); 
} 
} // end class 
WriteEx.java 
The fo sonInfo object to a file 
impor 
public 
public static void main(String args[ ]){ 
ew PersonInfo(ali, defence, 9201211); 
tput stream with “ali.dat” 
FileOutputStream fos =new FileOutputStream(ali.dat); 
// attaching ObjectOutput stream over FileOutput// stream 
tputStream out =new ObjectOutputStream(fos); 
//serialization 
// writing object to ‘ali.dat’ 
out.writeObject(pWrite); 
out.close(); 
fos.close(); 
} catch (Exception ex){ 
System.out.println(ex) 
import java.io.* 
class PersonInfo implements Serializable{ 
//parameterized constructorpublic PresonInfoname = n; address = a; } //method for displayin 
“ 
llowing class will serialize Per 
t java.io*; 
class WriteEx{ 
PersonInfo pWrite =ntry { // attaching FileOuObjectOu 
// closing streams
Web Design  Development – CS506 VU 
© Copyright Virtual University of Pakistan 
222 
} 
} // end class 
ReadEx.java 
The following class will read serialized object of PersonInfo from file i.e “ali.data” 
import java.io*; public class ReadEx{ public 
static void main(String args[ ]){ try { // 
attaching FileInput stream with “ali.dat” 
FileInputStream fin = new FileInputStream(ali.dat); 
tStream in = new ObjectInputStream(fis); 
li.dat’ 
adObject( ); 
intPersonInfo method to confirm that// object contains same set of values 
before// serializatoion 
// closing streams 
} 
} // en 
Compile  Execute 
After compilation, first run the WriteEx.java file and visit the “ali.dat” file. Then run ReadEx.java from 
different command or same command prompt. 
Object Serialization  Network 
// attaching FileInput stream over ObjectInput stream 
ObjectInpu//de-serializa 
tion // reading object from ‘a 
PersonInfo pRead = (PersoInfo)in.Re 
// calling pr 
pRead.printPersonInfo(); 
in.close(); fis.close(); 
catch (Exception ex){ System.out.println(ex) } d class 
. You can read / write to a network using sockets 
. All you need to do is attach your stream with socket rather than file 
. The class version should be same on both sides (client  network) of the network
Web Design  Development – CS506 VU 
© Copyright Virtual University of Pakistan 
223 
Example Code 22.2: Sending/Reading Objects to/from Network 
We are going to use same PersonInfo class listed in example code 22.1. An object of PersonInfo class will be sent by client on network using sockets and then be read by server from network. 
Sending Objects over Network 
The following class ClientWriteNetEx.java will send an object on network 
imp j 
java w 
in(Str 
sonIn ”); // create a 
communication socket 
Socket s = new Socket(“localhost”, 2222); 
treams 
OutputStream is = s.getOutputStream(); 
tOutput stream over Input stream 
ObjectOutputStream oos= new ObjectOutputStream(is); 
// writing object to network 
oo 
// closing communication socket 
s.close(); 
}cat 
System.out.println( 
} 
} }// end class 
Reading Objects over Network 
The following class ServerReadNetEx.java will read an object of PersonInfo sent by client. 
import java.net.*;import java.io.*;import 
javax.swing.*; 
ortava.net.*;import java.io.*;import x.sing.*; 
public class ClientWriteNetEx 
{ public static void 
maing args[]){ try { Pers 
onInfo p = new 
Perfo(“ali”, “defence”, “9201211 
// Get I/O s 
// attaching Objec 
s.write(p); 
ch(Exception ex){ 
ex);
Web Design  Development – CS506 VU 
© Copyright Virtual University of Pakistan 
224 
public class ServerReadNetEx{ 
public static void main(String rgs[]) 
// create a server socket 
ServerSocket ss = new ServerSocket(2222); 
{ 
ing connection 
Socket s = ss.accept(); 
request recieved); 
// Get I/O streams 
InputStr tInputStream(); 
// attaching ObjectOutput stream over Input stream 
ObjectIn new ObjectInputStream(is); 
// read PersonInfo object from network 
Pers 
p.printPersonInfo(); 
// closing communication socket 
s.close(); 
} // end while 
}catch(Exception ex){ System.out.println(ex); } } } // end class 
{ try 
{ 
System.out.println(Server started...); /* Loop back to the accept method of the serversocket and wait for a new connection request. Soserver will continuously listen for requests */ while(true) / wait for incom 
/ 
System.out.println(connection 
eam is = s.ge 
putStream ois = 
onInfo p = (PersonInfo)ois.read( );
Web Design  Development – CS506 VU 
© Copyright Virtual University of Pakistan 
225 
Compile  Execute 
After compiling both files, run ServerReadNetEx.java first, from the command prompt window. Open 
.java will send an Object of PersonInfo to ServerReadNetEx.java that displays that 
object values in dialog box after reading it from network. 
Preventing Serialization 
another command prompt window and run ClientWriteNetEx.javafrom it. The ClientWriteNetEx 
ƒ Often there is no need to serialize sockets, streams  DB connections etc because they do no 
represent the state of object, rather connections to external resources 
ƒ To do so, transient keyword is used to mark a field that should not be serialized 
o transient OutputStream os; 
o transient Connecction con; 
ƒ Transient fields are returned as nullon reading 
Example Code 22 . 3: transient 
ƒ So we can mark them as, o transient Socket s; 
Assume that we do not want to serialize phoneNum attribute of PersonInfo class, this can be done as 
shown below 
PersonInfo.java 
import javax.swing.*; 
import java.io.* 
class PersonInfo implements Serializable{ 
String name; 
String address; 
transient String phoneNum; 
public PresonInfo(String n, String a, String p) { name = n;address = a;phoneNm = p; 
} 
public void printPersonInfo( ) { 
JOptionPane.showMessageDialog(null , “name: ” + name + “address:” +address + 
“phone no:” + phoneNum); 
} 
} // end class 
References 
Entire material for this handout is taken from the book JAVA A Lab Course by Umair Javed. This 
material is available just for the use of VU students of the course Web Design and Development and not 
for any other commercial purpose without the consent of author.
Web Design  Development – CS506 VU 
© Copyright Virtual University of Pakistan 
226 
Lesson 23 
Multithreading 
odu 
Intrction 
Multithreading is the ability to do multiple things at once wnular 
ith in the same application. It provides finer 
reads ess. A 
. mul require more complex 
chro arvation. 
graity of concurrency. A thread — sometimes called an execution context or a lightweight process — is a single sequential flow of control within a program. 
Th are light weight as compared to processes because they take fewer resources then a procthread is easy to create and destroy. Threads share the same address space 
i.etiple threads can share the memory variables directly, and therefore may 
synnization logic to avoid deadlocks and st 
Sequential Execution vs Multithreading 
Every program has atleast one thread. Programs without multithreading executes sequentially. That is, after 
executing one instruction the next instruction in sequence is executed. If a function is called then until the 
mplet executed. Similarly if there is a loop then instructions 
er loo ets completed. Consider the following java program having 
ree loops in it. 
// F T 
public class ThreeLoopTest { 
//first loop 
// sec 
for (in rintln(“second ” + j); 
d ” + k); 
} // end main} // end class 
coion of the function the next instruction is not 
aftp only gets executed when the loop g 
th 
ilehreeLoopTest.java 
public static void main (String args[ ]) { 
for (int i=1; i= 5; i++)System.out.println(“first ” +i); 
ond loop t j=1; j= 5; j++)System.out.p 
// third loop for (int k=1; k= 5; k++)System.out.println(“thir Note: Each loop has 5 iterations in the ThreeLoopTest program.
Web Design  Development – CS506 VU 
© Copyright Virtual University of Pakistan 
227 
Note: Each loop has 10 iterations in the ThreadTest program. Your output can be different from 
the one given above. 
Notice th e between the outputs of the two programs. In ThreeLoopTest each loop generated a 
sequentia ile in ThreadTest the output of the loops got intermingled i.e. concurrency took place 
and ly 
Let us code our first multithreaded program and try to learn how Java supports multithreading. 
support for threading. While other languages have threads bolted-on to an existing 
f the original language but latter came into existence as the need 
aros 
All w e days support multithreading. JVM transparently maps Java Threads 
to the ating system i.e. OS Threads. JVM allows threads in Java to take advantage 
of ha d operating system level advancements. It keeps track of threads and schedules them to get 
CPU . Scheduling may be pre-emptive or cooperative. So it is the job of JVM to manage different tasks 
of thread. Let’s see how we can create threads? 
e differencl output wh 
loops executed simultaneous 
Java includes built-in 
structure. i.e. threads were not the part o 
e. 
ell known operating systems thesir counter-parts in the operrdware antime
Web Design  Development – CS506 VU 
© Copyright Virtual University of Pakistan 
228 
Creating Threads in Java 
There are two approaches to create threads in Java. 
Using Interface 
Using Inheritance 
Foll sing Interface: 
1 Create a class where you want to put some code that can run in parallel with some other code and 
ethod therefore provide the implementation for the run() 
in parallel here 
Runnable object in constructor 
are the steps to create threads by using Intheritance: 
herit a class from java.lang.Thread class 
ethod in the subclass 
t of the subclass 
ments Runnable 
• Step 2 - Provide an Implementation of run() method 
public void run( ){// write thread behavior// code that will be executed by the thread 
• Step 3 - Instant nnable object in the constructor 
Worker 
Thread 
• Step 4 – Start thread by calling start() method 
owing are the steps to create threads by u 
let that class implement the Runnable interface 2 Runnable interface has the run() mmethod and put your code that you want to run3 Instantiate Thread class object by passing4 Start thread by calling start() method Following1 In2 Override the run() m3 Instantiate the objec 
4 Start thread by calling start() method To write a multithreaded program using Runnable interface, follow these steps: • Step 1 - Implement the Runnable Interface class Worker imple 
iate Thread class object by passing Ruw = new Worker(“first”); t = new Thread (w); 
t.start(); Threads Creation Steps Using Inheritance 
To write a multithreaded program using inheritance from Thread class, follow these steps: 
Step 1 – Inherit from T 
class Wo 
Step 2 - Override run() method 
public void run( ){ 
// write thread behavior 
// code that will execute by thread 
Step 3 - Instantiate subclass object 
Step 4 – Start thread by calling start() method 
ƒ Two ways to write multithreaded Java programs 
hread Class rker extends Thread 
Worker w = new Worker(“first”); t.start(); So far we have explored: 
ƒ What is multithreading? 
ƒ What are Java Threads?
Web Design  Development – CS506 VU 
© Copyright Virtual University of Pakistan 
229 
Now we will re-write the ThreeLoopTest program by using Java Threads. At first we will use the Iapproach and then we will use Inheritance. Code Example using Interface // File Worker.java public class Worker implements Runnable { 
nterface 
private String job ; 
//Constructor of Worker class 
public Worker (String j ){ 
job = j; 
} 
//Implement run() method of Runnable interface 
public void run ( ) { 
for(int i=1; i= 10; i++)System.out.println(job +  =  + i); 
} 
} // end class 
// File ThreadTest.java 
public class ThreadTest{ 
public static void main (String args[ ]){ 
//instantiate three objects 
Worker first = new Worker (“first job”); 
Worker second = new Worker (“second job”); 
Worker third = new Worker (“third job”); 
//create three objects of Thread class  passing worker 
//(runnable) to them 
Thread t1 = new Thread (first ); 
Thread t2 = new Thread (second); 
Thread t3 = new Thread (third); 
//start threads to execute 
}//end main} // end class 
Following code is similar to the code given above, but uses Inheritance instead of interface 
// File Worker.java 
public cla ead{ 
priva 
//C 
public Worker (String j ){ 
job 
} 
//Override run() method of Thread class 
public void run ( ) {for(int i=1; i= 10; i++)System.out.println(job +  =  + i); 
} 
t1.start(); 
t2.start(); 
t3.start(); 
ss Worker extends Thrte String job ; onstructor of Worker class 
= j;
Web Design  Development – CS506 VU 
© Copyright Virtual University of Pakistan 
230 
} // end class 
/ File ThreadTest.java 
public class ThreadTest{ 
public static void main (String args[ ]) { 
//instantiate three objects of Worker (Worker class is now 
//becomes a Thread because it is inheriting from it)class 
Worker third = new Worker (“third job”); 
//start threads to execute 
t1.st 
.s 
hreads provide a way to write concurrent programs. But on a single CPU, all the threads do not run 
eously. JVM assigns threads to the CPU based on thread priorities. Threads with higher priority are 
executed in preference to threads with lower priority. A thread’s default priority is same as that of the 
creating 
A Thre and 10. We can also use the following predefined 
constants to assign priorities. 
Thread.MAX_PRIORITY (typically 10) 
Thread.NORM_PRIORITY (typically 5) 
Thread.MIN_PRIORITY (typically 1) 
To change the priority of a thread, we can use the following method 
setPriority(int priority) 
It changes the priority of this thread to integer value that is passed. It throws an IllegalArgumentException 
if the priority is not in the range MIN_PRIORITY to MAX_PRIORITY i.e. (1–10). 
For example, we can write the following code to change a thread’s priority. 
Thread t = new Thread (RunnableObject); 
// by using predefined constantt.setPriority 
(Thread.MAX_PRIORITY); 
// by using integer constantt.setPriority (7); 
Thread Priority Scheduling 
/ 
Worker first = new Worker (“first job”); Worker second = new Worker (“second job”); 
art(); tart(); 
t2 
t3.start(); }//end main} // end class 
Tsimultan 
thread i.e. parent thread. 
ad’s priority can be any integer between 1 
The Java runtime environment supports a very simple, deterministic scheduling algorithm called fixed-priority 
scheduling. This algorithm schedules threads on the basis of their priority relative to other Runnable 
threads. 
At any given time, when multiple threads are ready to be executed, the runtime system chooses for 
execution the Runnable thread that has the highest priority. Only when that thread stops, yields (will be 
explained later), or becomes Not Runnable will a lower-priority thread start executing. If two threads of the 
same priority are waiting for the CPU, the scheduler arbitrarily chooses one of them to run. The chosen 
thread runs until one of the following conditions becomes true: 
ƒ A higher priority thread becomes Runnable. 
ƒ It yields, or its run() method exits. 
ƒ On systems that support time-slicing, its time allotment has expired.
Web Design  Development – CS506 VU 
© Copyright Virtual University of Pakistan 
231 
Then the second thread is given a chance to run, and so on, until the interpreter exits. Consider t 
following figure in which threads of various priorities are represented by capital alphabets A, B, …, K. A 
and B have same priority (highest in this iority (lowest in this case). JVM start 
executing with A and B, and divides CPU time between these two threads arbitrarily. When both A and B 
comes to an end, it chooses the next thread C to execute. 
he 
case). J and K have same pr Code Example: Thread Properties 
Try following example to understand how JVM executes threads based on their priorities. 
// File PriorityEx.java 
public class PriorityEx{ public static void main (String args[ ]){ 
//instantiate two objects 
Worker first = new Worker (“first job”); 
Worker second = new Worker (“second job”); 
//create two objects 
Thread t1 = new Thread (first ); 
Thread t2 = new Thread (second); 
IN_PRIORITY); 
t2.setPriority (Thread.MAX_PRIORITY); 
hreads to execute 
//set thread priorities t1.setPriority (Thread.M 
//start tstart(); 
t1. t2.start();
Web Design  Development – CS506 VU 
© Copyright Virtual University of Pakistan 
232 
}//end main} // end class 
Ou 
tput rities 
Problems with Thr 
ead Prio 
Ho hreads, remember the following two issues: 
First ities of the underlying OS. It is because 
of dif lying OS. For example 
ƒ 
ƒ Windows NT has only 7 user priority levels 
Second, starvation can occur for lower-priority threads if the higher-priority threads never terminate, sleep, 
or wait for I/O indefinitely. 
Refe 
ƒ ractical Guide by Umair Javed 
ƒ Java How to Program by Deitel and Deitel 
ƒ CS193j handouts on Stanford 
wever, when using priorities with Java T 
a Java thread priority may map differently to the thread priorference in priority levels of JVM and under Solaris has 232–1 priority levels 
rences: Java, A P
Web Design  Development – CS506 VU 
© Copyright Virtual University of Pakistan 
233 
Lesson 24 
More on Multithreading 
In this handout, we’ll cover different aspects of multithreading. Some examples are given to make you 
understand the topic of multithreading. First we will start with an example that reads data from two text 
files simultaneously. 
Example Code: Reading Two Files Simultaneously 
The task is to read data from file “first.txt”  “second.txt” simultaneously. Suppose that files contains the 
following data as shown below 
first.txt 
second.txt 
Follo is the code for ReadFile.java that implements Runable interface. The file reading code will be 
writte inside the run( ) method. 
// File ReadFile.java 
import java.io.*; 
public class ReadFile implements Runnable{ 
wingn
Web Design  Development – CS506 VU 
© Copyright Virtual University of Pakistan 
234 
//attribute used for name of file 
String fileName; 
public ReadFile(String fn){ 
// o ains the code for file reading 
pub 
try 
{ // connecting FileReader with attribute fileNameFileReader fr = new 
FileReader(fileName);BufferedReader br = new BufferedReader(fr); 
String line = ; 
// reading line by line data from file// and displaying it on console 
line = br.readLine(); 
while(line != null) { 
System.out.println(line); 
line = br.readLine(); 
} 
ose(); 
lose(); 
}catch (Exception e){ 
System.out.println(e); 
} 
} // end run() method 
} // File Test.java 
ublic class Test { 
public static void main (String args[]){ 
// creating ReadFile objects by passing file names to them 
ReadFile first = new ReadFile(first.txt); 
ReadFile second = new ReadFile(second.txt); 
// Instantiating thread objects and passing 
// runnable (ReadFile) objects to them 
Thread t1 = new Thread(first); 
Thread t2 = new Thread(second); 
// starting threads that cause threads to read data from 
// two different files simultaneously 
t1.start(); 
t2.start(); 
} 
} 
// param constructor 
fileName = fn; } 
verriding run method// this method contlic void run ( ){ 
fr.clbr.c 
p
Web Design  Development – CS506 VU 
© Copyright Virtual University of Pakistan 
235 
Output 
On executing Test class, following kind output would be generated: 
Now let’s discuss some useful thread class methods. 
. sle 
ep(int time) method -Causes the currently executing thread to wait for the time (milliseconds) specified 
-Waiting is efficient equivalent to non-busy. The waiting thread will not occupy the processor 
-T hen the specified time interval expires or when interrupted by some 
-T ming out of sleep may go to the running or ready state depending upon the availability of the 
The different states of threads will be discussed later 
-High priority threads should execute sleep method after some time to give low priority threads a 
-sl sed for delay purpose i.e. anyone cal call Thread.sleep()method 
-N hrow InterruptedException. So, you need try-catch block 
Example Code: Demonstrating sleep ( ) usage 
t we used in the previous handout. 
// File Worker.javapublic class Worker implements Runnable { 
; 
public Worker (String j ){ 
job = j; 
} 
Runnable interface 
try { Thread.sleep(100); // go to sleep for 100 
hreads come out of the sleep wother thread hread coprocessor. 
chance to run otherwise starvation may occur eep() method can be uote that sleep() method can t 
Below the modified code of Worker.java is given tha 
private String job 
//Constructor of Worker class 
() method of 
//Implement runpublic void run ( 
) { for(int i=1; i= 10; i++) {
Web Design  Development – CS506 VU 
© Copyright Virtual University of Pakistan 
236 
ms}catch (Exception 
ex){System.out.println(ex);} 
} // end for} // 
en 
// File 
public class SleepEx { 
public static void main (String args[ ]){ 
// Creating Worker objects 
Worker first = new Worker (“first job”); 
Worker second = new Worker (“second job”); 
tiating thread class objects 
Thread t1 = new Thread (first ); 
Thread t2 = new Thread (second); 
// starting thread 
t1.start(); 
t2.start(); 
} 
} // end class 
Output 
On executing SleepEx.java, the output will be produced with exact alternations between first thread  
second thread. On starting threads, first thread will go to sleep for 100 ms. It gives a chance to second 
thread to execute. Later this thread will also go to sleep for 100 ms. In the mean time the first thread will 
come out of sleep and got a chance on processor. It will print job on console and again enters into sleep 
state and this cycle goes on until both threads finished the run() method 
System.out.println(job +  =  + i); d run } // end class SleepEx.java 
// Instan Before jumping on to example code, lets reveal another aspect about main() method. When you run a Java 
program, the VM creates a new thread and then sends the main(String[] args) message to the class to be run! 
Therefore, there is always at least one running thread in existence. However, we can create more threads
Web Design  Development – CS506 VU 
© Copyright Virtual University of Pakistan 
237 
which can run concurrently with the existing default thread. 
void main (String args[ ]){ System.out.println(“main thread 
going to sleep”); 
try { 
// the main thread will go to sleep causing delay 
Thread.sleep(100); 
}catch (Exception ex){ 
System.out.println(ex); 
} 
System.out.println(“main thread coming out of sleep”); } // end main() 
} // end class 
Output 
On executing DelayEx class, you will experience a delay after the first statement displayed. The second 
statement will print when the time interval expired. This has been show below in the following two 
diagrams: 
sleep() method can be used for delay purpose. This is demonstrated in the DelayEx.java given below // File DelayEx.java public class DelayEx { public static . yield( ) method 
-Allows any other threads of the same priority to execute (moves itself to the end of the priority queue) 
-If all waiting threads have a lower priority, then the yielding thread resumes execution on the CPU 
-Generally used in cooperative scheduling schemes 
Example Code: Demonstrating yield ( ) usage 
Below the modified code of Worker.javais given 
// File Worker.javapublic class Worker implements 
Runnable { private String job ; 
//Constructor of Worker class
Web Design  Development – CS506 VU 
© Copyright Virtual University of Pakistan 
238 
public Worker (String j ){ 
1; i= 10; i++) { 
// g 
Thread.yield( ); 
System.out.println(job +  =  + i); 
} // end for 
} // end run 
} // end class // File YieldEx.java 
Worker second = new Worker (“second job”); 
g thread class objects 
t2.start(); 
job = j; 
} 
//Implem 
ent run() method of Runnable interface public void run ( ) { for(int i= 
iving chance to a thread to execute of same priority 
public class YieldEx { 
public static void main (String args[ ]){ // Creating Worker objects 
Worker first = new Worker (“first job”); 
// Instantiatin 
Thread t1 = new Thread (first ); Thre 
ad t2 = new Thread (second); // starting thread t1.start(); 
} 
} // end class
Web Design  Development – CS506 VU 
© Copyright Virtual University of Pakistan 
239 
Output 
Since both threads have the same priority (until we change the priority of some thread explicitly). Therefore both threads will execute on alternate basis. This can be confirmed from the output given below: A thread can be in different states during its lifecycle as shown in the figure.
Web Design  Development – CS506 VU 
© Copyright Virtual University of Pakistan 
240 
Some Important states are 
. New state 
-When a thread is just created 
. Ready state 
-Thread’s start() method invoked -Thread can now execute -Put it into the Ready Queue of the 
scheduler 
. Running state 
-Thread is assigned a processor and now is running 
. Dead state 
-Thread has completed or exited 
-Eventually disposed off by system 
Thread’s Joining 
-Used when a thread wants to wait fo ethod 
-For example, if thread2 sent the thread2.join() message, it causes the currently executing thread to block 
efficiently until thread2 finishes its run() method 
public class Worker implements Runnable { private String job ; public Worker (String j ){ 
job = j;} public void run ( ) {for(int i=1; i= 10; i++) { 
System.out.println(job +  =  + i); } // end for} // end run} // 
end class 
The class JoinEx will demonstrate how current running (main) blocks until the remaining threads finished 
their run( ) 
// File JoinEx.java 
public class JoinEx { public static void main (String args[ ]){ 
Worker first = new Worker (first job);Worker second = new Worker (second 
job); 
System.out.println(Starting...); 
// starting threads 
t1.start(); 
t2.start(); 
}catch (Exception ex) {System.out.println(ex);} 
System.out.println 
} // end main} 
r another thread to complete its run( ) m 
-Calling join method can throw InterruptedException, so you must use try-catch block to handle it Example Code: Demonstrating join( ) usage Below the modified code of Worker.java is given. It only prints the job of the worker // File Worker.java 
Thread t1 = new Thread (first ); Thread t2 = new Thread (second); 
// The current running thread (main) blocks until both //workers have finished 
try { t1.join(); 
t2.join(); 
(All done );
Web Design  Development – CS506 VU 
© Copyright Virtual University of Pakistan 
241 
Ou 
On exec . Since main 
thread do not finish until both threads have finished their run( ). Therefore “All done” will be print on last. 
tput uting JoinEx, notice that “Starting” is printed first followed by printing workers jobs References: 
ed 
ƒ Java, A Practical Guide by Umair Jav ƒ Java tutorial by Sun 
: http://java.sun.com/docs/books/tutorial/ ƒ CS193j handouts on Stanford
Web Design  Development – CS506 VU 
© Copyright Virtual University of Pakistan 
242 
Lesson 25 
Web Application Development 
Introduction 
Because of the re becoming vital part of IT 
infrastructure of ance management systems 
are used by orga hand online course 
registration and examination systems can allow students to study while staying at their homes. 
Web Applic o 
wide spread use of internet, web based applications a 
large organizations. For example web based employee perform 
nizations for weekly or monthly reviews of employees. On the other 
atins In general a we 
connected to w se 
ommunication ent (usually a web-browser) sends 
b application is a piece of code running at the 
server which facilitates a remote user eb server through HTTP protocol. HTTP protocol follows stateless Request-Responmodel. Cli 
c Figure 1: A typical web application 
A web server is software which provides users, access to the services that are present on the internet. These 
servers can provide support for many protocols used over internet or intranet like HTTP, FTP, telnet etc 
HTTP Basics 
A protocol defines the method and way of communication between two parties. For example when we talk 
to our teacher we use a certain way which is different from the way that we adopt with our fiends or 
parents. Similarly there are many different protocols used by computers to communicate with each other 
depending on applications. 
Figure 2: HTTP communication model 
-HTTP is as request-response oriented protocol. 
-It is a stateless protocol since there is no built-in state management between successive requests. We 
will discuss state later.
Web Design  Development – CS506 VU 
© Copyright Virtual University of Pakistan 
243 
Par f 
ts o an HTTP request -Request Method: It tells the server the type of action that a client wants to perform 
-URI: Uniform Resource Indictor specifies the address of required document or resource 
-Header Fields: Optional headers can be used by client to tell server extra 
Figure 3: HTTP request example 
-Body: Contains data sent by client to the server 
-Other request headers like FROM (email of the person responsible for request) and VIA (used by 
gateways and proxies to show intermediate sites the request passes) can also be used. 
1. In URL as query string e.g. http://www.gmail.com/register?name=alistate=punjab 
2. As part of request body (see Figure 3) 
Parts of HTTP response 
Request Parameters ƒ Request can also contain addition information in form of request parameters 
Result Code: A numeric status code and its description. -Header Fields: 
Servers use these fields to tell client about server information like 
configurations and software etc. -Body: Data sent by server as part of response 
that is finally seen by the user.
Web Design  Development – CS506 VU 
© Copyright Virtual University of Pakistan 
244 
Figure 4: HTTP response example 
HTTP Response Codes 
ƒ An HTTP Response code tell the client about the state of the response i.e. whether it’s a valid 
response or some error has occurred etc. HTTP Response codes fall into five general categories 
• 100-199 
Codes in ld respond with some 
other action. 
100: Continue with partial request. 
• 200-299 
Values in the 200s signify that the request was successful. 
200: Means every thing is fine. 
• 300-399 
Values in the 300s are used for files that have moved and usually include a Location header 
indicating the new address. 
300: Document requested can be found several places; they'll be listed in the returned 
document. 
• 400-499 
Values in the 400s indicate an error by the client. 
404: Indicates that the requested resource is not available. 
401: Indicates that the request requires HTTP authentication. 
403: Indicates that access to the requested resource has been denied. 
• 500-599 
Codes in the 500s signify an error by the server. 
503: Indicates that the HTTP server is temporarily overloaded and unable to handle the 
request. 
the 100s are informational, indicating that the client shou
Web Design  Development – CS506 VU 
© Copyright Virtual University of Pakistan 
245 
ƒ 404: indicates that the requested resource is not available 
ƒ 401: Indicates that request requires HTTP authentication 
Server Side Programming 
Web server pages can be either static pages or dynamic pages. A static web page is a simple HTML (Hyper 
Text Transfer Language) file. When a client requests an HTML page the server simple sends back response 
with the required page.
Web Design  Development – CS506 VU 
© Copyright Virtual University of Pakistan 
246 
Figure 5: Static web page request and response 
An example of static web page is given below While in case of dynamic web pages server executes an 
application which generates HTML web pages according to specific requests coming from client. These 
dynamically generated web pages are sent back to client with the response. 
Figure 6: Dynamic web page request and response
Web Design  Development – CS506 VU 
© Copyright Virtual University of Pakistan 
247 
Why build Pages Dynamically? 
Wr 
confirmation pages at on line stores. ] 
e need to create dynamic web pages when the content of site changes frequently and client specific esponse is required. Some of the scenarios are listed below -The web page is based on data submitted by the user. e.g. results page from search engines and order 
Web page is derived from data that changes frequently. e.g. a weather report or news headline The s page.
Web Design  Development – CS506 VU 
© Copyright Virtual University of Pakistan 
248 
The Web page uses information from databases or other server-side resources. 
e.g. an e-commerce site could use a ser Web page that lists the current price and 
availability of each item that is for sale. 
vlet to build a -Using technologies for developing web pages that include dynamic content. 
-Developing web based applications which can produce web pages that contain information that is 
connection-dependent or time-dependent. 
Dyn 
Dynamic web content development technologies have evolved through time in speed, security, ease of use 
te based technologies like 
plex web pages. Sun Java 
vlets and JSP that provided more speed and security as well as better tools for web page 
amic Web Content Technologies Evolution 
and complexity. Initially C based CGI programs were on the server Then templaASP and PHP were then introduced which allowed ease of use for designing com 
introduced Ser 
creation. Figure 7: Dynamic web content technologies evolution
Web Design  Development – CS506 VU 
© Copyright Virtual University of Pakistan 
249 
Layers and Web Application 
ally web applications are partitioned into logical layers. Each layer performs a specific 
ixed with other layers. Layers are isolated from each other 
upling between them but they provide interfaces to communicate with each other. 
Norm 
functionality which should not be m 
to reduce co Figure 8: Simplified view of a web application and its layers 
user interface for client to interact with application. This is the only part of application 
visible to client. 
-Business Layer 
The business or service layer implements the actual business logic or functionality of the application. 
This layer consists of objects that represent real-world business objects such as an Order, 
OrderLineItem, Product, and so on. 
ere ar nologies available for web application development which includes Java Servlets, 
-Presentation Layer: Provides a 
For example in case of online shopping systems this layer handles transaction management. -Data Layer 
The several Java tech 
JavaServer Pages, JavaServer Faces etc. Figure 9: Java web application technologies (presentation/web tier) 
References: 
ƒ Java, A Practical Guide by Umair Javed 
ƒ Java tutorial by Sun: http://java.sun.com/docs/books/tutorial/
Web Design  Development – CS506 VU 
© Copyright Virtual University of Pakistan 
250 
Lesson 26 
Java Servlets 
Servlets are java technology’s answer to CGI programming. CGI was widely used for generating dynamic 
content before Servlets arrived. They were programs written mostly in C,C++ that run on a web server and 
a 
servlet, servlet generates dynamic content, mostly in the form of HTML pages, and returns it back to the 
server, which sends it back to the client. Hence we can say that servlet is extending the functionality of the 
webserver (The job of the earlier servers was to respond only to request, by may be sending the required 
html file back to the client, and generally no processing was performed on the server) 
used to build web pages. As you can see in the figure below, a client sends a request to web server, server forwards that request to What Servlets can do? 
ƒ Servlets can do anything that a java class can do. For example, connecting with database, 
reading/writing data to/from file etc. 
ƒ Handles requests sent by the user (clients) and generates response dynamically (normally HTML 
pages). 
ƒ The dynamically generated content is send back to the user through a webserver (client) 
Servlets vs. other SSP technologies 
The java’s servlet technology has following advantage over their counter parts: 
Convenient 
Servlets can use the whole java API e.g. JDBC. So if you already know java, why learn Perl or C. Servlets 
have an extensive infrastructure for automatically parsing and decoding HTML form data, reading and 
sending HTTP headers, handling cookies and tracking session etc and many more utilities 
Efficient 
With traditional CGI, a new process is started for each request while with servlets each request is handled 
by a lightweight java thread, not a heavy weight operating system process. (more on this later) 
Powerful 
Java servlets let you easily do several things that are difficult or impossible with regular CGI. For example, 
servlets can also share data among each other
Web Design  Development – CS506 VU 
© Copyright Virtual University of Pakistan 
251 
Portable 
Since java is portable and servlets is a java based technology therefore they are generally portable across web 
servers 
Inexpensive 
There are numbers of free or inexpensive web servers available that are good for personal use or low 
volume web sites. For example Apache is a commercial grade webserver that is absolutely free. However 
some very high end web and application servers are quite expensive e.g BEA weblogic. We’ll also use 
Apache in this course 
Software Requirements 
To use java servlets will be needed 
ƒ J2SE 
ƒ Additional J2EE based libraries for servlets such as servlet-api.jar and jsp-api.jar. Since these 
libraries are not part of J2SE, you can download these APIs separately. However these APIs are 
also available with the web server you’ll be using. 
ƒ A capable servlet web engine (webserver) 
Jakarta Servlet Engine (Tomcat) 
Jakarta is an Apache project and tomcat subprojects. Apache Tomcat is an open source web 
server, which is used as an official reference implementation of Java Servlets and Java Server Pages 
technologies. 
Tomcat is developed in an open and participatory environment and released under the Apache software 
license 
Environment Setup 
is one of its 
To work with servlets and JSP technologies, you first need to set up the environment. Tomcat installation 
can be performed in two different ways (a) using .zip file (b) using .exe file. This setup process is broken 
down into the following steps: 
1 Download the Apache Tomcat Server 
2 Install Tomcat 
3 Set the JAVA_HOME variable 
4 Set the CATALINA_HOME variable 
5 Set the CLASSPATH variable 
6 Test the Server 
Environment Setup Using .zip File 
Let’s take a detail look on each step and get some hands on experience of environment setup. 1. Download the Apache Tomcat Server From the http://tomcat.apache.org, download the zip file for the current release (e.g. jakarta-tomcat- 5.5.9.zip or any latest version) on your C: drive. There are different releases available on site. Select to 
dow a 
ote: J2SE 5.0 must be installed prior to use the 5.5.9 version of tomcat. 
nlod .zip file from the Binary Distributions Æ core section. 
N
Web Design  Development – CS506 VU 
© Copyright Virtual University of Pakistan 
252 
2. Installing Tomcat using .zip file 
-Unzip the file into a location (e.g. C:). (Rightclick on the zip file and select unziphere option ) 
hen the zip file will unzipped a directory structure will be created on your computer such as: 
-W -Th : or CATALINA_HOME 
No 
s create their own directory and unzip the file there such as C:jakarta-tomcat-5.5.9jakarta-tomcat- 
5.5.9.This causes problems while giving path information 
3. Set 
ƒ JAVA_HOME indicates the root directory of your jdk. Set the JAVA_HOME environment 
bin 
r icon. Select the advanced tab, a System Properties window 
n below. Select the Environment Variables button to proceed. 
ƒ On clicking Environment Variable button, the Environment Variables window will open as shown 
next 
ƒ Create a new User variable by clicking New button as shown above, the New User Variable 
window will appear 
ƒ Set name of variable JAVA_HOME 
ƒ The value is the installation directory of JDK (for example C:ProgramFilesj2sdk_nbj2sdk1.4.2). 
This is shown below in the picture. Please note that bin folder is not included in the path. 
ƒ Press Ok button to finish 
e Cjakarta-tomcat-5.5.9 folder is generally referred as root directory 
te: After extraction, make sure C:jakarta-tomcat-5.5.9 contains a bin subdirectory. Sometimesstudent 
theJAVA_HOME variable 
variable to tell Tomcat, where to find java ase JDK installation directory, not the subdirectory 
ƒ This variable should list the b ƒ To set it, right click on My Co 
mputewill appear in front of you like show
Web Design  Development – CS506 VU 
© Copyright Virtual University of Pakistan 
253
Web Design  Development – CS506 VU 
© Copyright Virtual University of Pakistan 
254 
4. Set the CATALINA_HOME variable 
CATALINA_HOME is used to tell the system about the root directory of the TOMCAT. There are various 
files (classes, exe etc) needed by the system to run. CATALINA_HOME is used to tell your system (in this 
case your web server Tomcat) where the required files are. 
ƒ To Set the CATALINA_HOME environment variable, create another User Variable. 
ƒ Type CATALINA_HOME as the name of the environment variable. 
ƒ Its value should be the path till your top-level Tomcat directory. If you have unzipped the Tomcat 
in C drive. It should be C:jakarta-tomcat-5.5.9.This is shown below: 
ƒ Press Ok button to finish Note: To run Tomcat (web server) you need to set only the two environment variables 
NA_HOME 
f the Java 2 platform, standard edition, you have to identify the 
servlet classes to the compiler. The server already knows about the servlet classes, but the compiler (i.e., 
r compiling source files of servlet does not. So if you don't set your CLASSPATH, any 
ƒ To Set the CLASSPATH environment variable, create another User Variable. 
ƒ Type CLASSPATH as the name of the environment variable. 
ƒ Its value should be the path for servlet-api.jar and jsp-api.jar. These file can be found on following 
path: 
commonlibjsp-api.jar 
• Both these api’s are specified as values with semicolon between them. Remember to add 
semicolon dot semicolon (;.;) at the end too. For example 
and these are JAVA_HOME  CATALI 
5. Set the CLASSPATH variable 
Since servlets and JSP are not part o 
javac) you use fo 
attempt to compile servlets, tag libraries, or other classes t 
hat use the servlet API will fail with error messages about unknown classes. 
• C:jakarta-tomcat-5.5.9commonlibservlet-api.jar • C:jakarta-tomcat-5.5.9
Web Design  Development – CS506 VU 
© Copyright Virtual University of Pakistan 
255 
Classpath = C:jakarta-tomcat-5.5.9commonlibservlet-api.jar;C:jakarta-tomcat 
5.5.9commonlibjsp-api.jar;.; 
This is also shown in the figure below 
— Press OK button to finish the setting of CLASSPATH variable 
6. Test the server 
Before making your own servlets and JSP, verify that the server is working properly. Follow these steps 
in order to do that: 
ƒ Open the C:jakarta-tomcat-5.5.9bin folder and locate the startup.batfile. 
ƒ Double clicking on this file will open up a DOS window, which will disappear, and another DOS 
window will appear, the second window will stay there. If it does not your paths are not correctly 
set. 
ƒ Now to check whether your server is working or not, open up a browser window and type 
http://localhost:8080. This should open the default page of Tomcat as shown in next diagram: 
Note: If default page doesn’t displayed, open up an internet explorer window, move on to Tools Æ 
Internet Options Æ Connections LAN Settings. Make sure that option of “Bypass proxy server 
for local addresses” is unchecked.
Web Design  Development – CS506 VU 
© Copyright Virtual University of Pakistan 
256 
There is another easier way to carry out the environment setup using .exe file. However, it is strongly 
recommended that you must complete the environment setup using .zip file to know the essential 
fundamentals. 
t Setup Using .exe File 
Environmen 
Let’s look at the steps involved to accomplish the environment setup using .exefile. 
Download the Apache Tomcat Server 
Fro 
1. 
m the http://tomcat.apache.org, download the .exe file for the current release (e.g. jakarta-tomcat- ) on your C: drive. There are differen 5.5.9.zip t releases available on site. Select to download Windows 
executable (.exe) file from Binary Distributions Core section. 
Note: J 5.9 version of tomcat. 
2. I 
uble clicking on it. 
-Moving forward in setup, you will reach to the following window -Select install type “Full” and 
press Next button to proceed. 
2SE 5.0 must be installed to use the 5. 
nstalling Tomcat using .exe file -Run the .exefile by do
Web Design  Development – CS506 VU 
© Copyright Virtual University of Pakistan 
257 
-Choose the folder in which you want to install Apache Tomcat and press Next to proceed. 
The configuration window will be opened. Leave the port unchanged (since by default web servers run on 
port 8080, you can change it if you really want to). Specify the user name  password in the specified 
coming next: 
- 
fields and press Next button to move forward. This is also shown in the diagram
Web Design  Development – CS506 VU 
© Copyright Virtual University of Pakistan 
258 
-The setup will automatically select the Java Virtual Machine path. Click Install button to move ahead. 
-Fin Run Apache Tomcat option selected. It will cause the tomcat server to run in 
quick launch bar as shown in diagram below. The Apache Tomcat shortcuts will also added to 
ish the setup with the 
Programs menu. -Double clicking on this button will open up Apache Tomcat Properties window. From here you can start 
s configure many options if you want to. This properties window 
below: 
or top your web server. You can also is shown 
3C 
. Se E variable 
5. Set the CLASSPATH variable 
Same as step 5 of .zip installation mode 
6. Test the server 
If tomcat installation is made using .exe file, follow these steps 
t the JAVA_HOM 
hoosing .exe mode does not require completing this step. 4. Set the CATALINA_HOME variable Choosing .exe mode does not require completing this step.
Web Design  Development – CS506 VU 
© Copyright Virtual University of Pakistan 
259 
-Open the Apache Tomcat properties window by clicking on the Apache Tomcat button from Quick 
Launch. 
-Start the tomcat server if it is not running by clicking on Start button. 
/localhost:8080 
-Open up a browser window and type http:/ . This should open the default page of 
Note: If default page doesn’t displayed, open up an internet explorer window, move on to Tools Æ 
Internet Options Æ Connections LAN Settings. Make sure that option of “Bypass proxy server for 
local addresses” is unchecked. 
Tomcat as shown in the next diagram: 
References: 
. Java, A Lab Course by Umair Javed 
. Jav e 
a Srvlet  JSP tutotrial http://www.apl.jhu.edu/~hall/java/Servlet-Tutorial/
Web Design  Development – CS506 VU 
© Copyright Virtual University of Pakistan 
260 
Lesson 27 
Creating a Simple 
Web Application in Tomcat 
iscuss the standard tomcat directory structure, a pre-requisite for building any web 
d bolts of Servlets will also be discussed. In the later part of this handout, we’ll 
pplication using servlet. 
ion 
web a 
be used 
ƒ Unp 
g development 
ƒ Pac 
o Known as Web Archive (WAR) file 
The web s folder is the t n the 
server. Each app 
In this handout, we’ll dapplication. Different nuts ana 
lso learn how to make a simple web a Standard Directory Structure of a J2EE Web ApplicatA 
pplication is defined as a hierarchy of directories and files in a standard layout. Such hierarchies can in two forms 
ack o Where each directory  file exists in the file system separately o Used mostly durin 
k 
o Mostly used to deploy web applications 
app 
op-level Tomcat directory that contains all the web applications deployed olication is deployed in a separate folder often referred as “context”. 
To make a new application e.g myapp in tomcat you need a specific folder hierarchy. 
-Create a folder named myapp in C:jakarta-tomcat-5.5.9webapps folder. This name will also appear in 
/localhost:8080/myapp/index.html 
the URL for your application. For example 
http:/ 
-All JSP and n folder (C:jakartatomcat-5.5.9webappsmyapp) 
-Create another folder inside myapp folder and change its name to WEB-INF. Remember WEB-INF is 
case sensitive 
html files will be kept in main applicatio 
and it is not WEB_INF
Web Design  Development – CS506 VU 
© Copyright Virtual University of Pakistan 
261 
-Configuration EB-INF folder (C:jakarta-tomcat- 
B-INF folder and change its name to classes. Remember classes name 
is also case sensitive. 
files such as web.xml will go in W 
5.5.9webappsmyappWEB-INF) -Create another folder inside WE 
-Servlets and Java Beans will go in classes folder (C:jakarta-tomcat5.5.9webappsmyappWEB- INFclasses) 
That’s the minimum directory structure required in order 
to get started. This is also shown in the figure below: 
n hierarchy, make a simple html file e.g. index.html file. W -To test applicatio rite some basic HTML code 
into it and save it in main application directory i.e. 
C:jakarta-tomcat-5.5.9webappsmyapp 
-Restart the server and access it by using the URL 
http://localhost:8080/myapp/index.html 
-A more detailed view of the Tomcat standard directory structure is given below.
Web Design  Development – CS506 VU 
© Copyright Virtual University of Pakistan 
262 
-Here you can see some other folders like lib tags under the WEB-INF. 
-The lib folder is required if you want to use some achieve files (.jar). For example an API in jar format 
that can help generating .pdf files. 
-Similarly tags folder is helpful for building custom tags or for using .tagfiles. 
Note: Restart Tomcat every time you create a new directory structure, a servlet or a java bean so that it 
can recognize it. For JSP and html files you don’t have to restart the server. 
Writing Servlets 
Servlet or HttpServlet 
ilable in javax.servlet package 
ailable in javax.servlet.http package 
ƒ Extends from GenericServletclass 
Servlet Types -Servlet related classes are included in two main packages javax.servletand javax.servlet.http. -Every servlet must implement the javax.servlet.Servlet interface, it contains the servlet’s life cycle methods etc. (Life cycle methods will be discussed in next handout) 
- o 
Inrder to write your own servlet, you can subclass from Gerneric 
GenericServlet class 
ƒ Ava ƒ Implements javax.servlet.Servlet 
ƒ Extend your class from this class if you are interested in writing protocol independent servlets HttpServlet class ƒ Av
Web Design  Development – CS506 VU 
© Copyright Virtual University of Pakistan 
263 
ƒ Adds functionality for writing HTTP specific servlets as compared to GernericServlet ƒ Extend your class from HttpServlet, if you want to write HTTP based servlets Servlet Class Hierarchy The Servlet class hierarchy is given below. Like all java classes GenericServletalso inherits from Object class. 
Apart from GenericServlet and HttpServlet classes, ServletRequest, HttpServletRequest, ServeltResponse 
and HttpServletResponse are also helpful in writing a servlet. 
As you can guess ServletRequest  ServletResponse are used in conjunction with GenericServlet. These 
classes are used for processing protocol independent requests and generating protocol independent 
responses respectively. 
javax.servlet.http 
HttpServletRequest  HttpServletRespose are used for processing HTTP protocol specific requests and 
generating HTTP specific response. Obviously these classes will be used in conjunction with HttpServet 
class, which means you are making a HTTP protocol specific servlet. 
Types of HTTP requests 
HTTP supports different types of request to be sent over to server. Each request has some specific 
purpose. The most important ones are get  post. Given below a brief overview of each request type is 
given. You can refer to RFC of HTTP for further details. 
-GET: Requests a page from the server. This is the normal request used when browsing web pages. 
-POST: This request is used to pass information to the server. Its most common use is with HTML forms. 
-PUT: Used to put a new web page on a server. 
-DELETE: Used to delete a web page from the server. 
-OPTIONS: Intended for use with the web server, listing the supported options.
Web Design  Development – CS506 VU 
© Copyright Virtual University of Pakistan 
264 
-TRACE: Used to trace servers 
-Attribute-Value pair is attached with requested URL after ‘?’. 
xample if attribute is ‘name’ and value is ‘ali’ then the request will be 
http://www.gmail.com/register?name=ali 
. POST 
-Attribute-Value pair attached within the request body. For your reference HTTP request diagram is 
GET  POST, HTTP request types Some details on GET and POST HTTP request types are given below. . GET 
-For e 
-For HTTP based servlet, override doGet() methods of HttpServlet class to handle these type of 
requests. 
given below again: -Override doPost() method of HttpServlet class to handle POST type requests. 
Steps for making a Hello World Servlet 
To get started we will make a customary “HelloWorldServlet”. Let’s see what are the steps involved in 
writing a servlet that will produce “Hello World” 
1. Create a directory structure for your application (i.e. helloapp). This is a one time process for any 
application 
2. Create a HelloWorldServlet source file by extending this class from HttpServlet and overriding your 
desired method. For example doGet() or doPost(). 
3. Compile it (If get error of not having required packages, check your class path) 
4. Place the class file of HelloWorldServlet in the classes folder of your web application (i.e. myapp). 
Note: If you are using packages then create a complete structure under classes folder 
5. Create a deployment descriptor (web.xml) and put it inside WEB-INF folder 
6. Restart your server if already running 
7. Access it using Web browser
Web Design  Development – CS506 VU 
© Copyright Virtual University of Pakistan 
265 
Example Code: HelloWorldServlet.java 
ages 
import java.io.*; 
import javax.servlet.*; 
import javax.servlet.http.*; 
// extending class from HttpServelt 
public class HelloWorldServlet extends HttpServlet { 
/* overriding doGet() method because writing a URL in the browserby default generate request of 
GET type 
As you can see, HttpServletRequest andHttpServletResponse are passed to this 
method. Theseobjects will help in processing of HTTP request andgenerating 
response for HTTP 
This method can throw ServletException or IOException, so wemention these exception 
types after method signature 
*/ 
public void doGet(HttpServletRequest request,HttpServletResponse response) 
throws ServletException, IOException 
etWriter 
method on it 
As mentioned, for generating response, we will 
World in the browser using PrintWriter 
object. You can also write HTML like 
out.println(“h1 Hello World /h1”) */ 
Xtensible Markup Language (xml) contains custom defined tags which convey information about the 
ontent. To learn more about XML visit http schools.com 
//File HelloWorldServlet.java // importing required pack 
{ 
/* getting output stream i.e PrintWriter from responseobject by calling g 
useHttpServletResponse object*/ PrintWriter out = response.getWriter(); 
/* printing Hello 
out.println(“Hello World! ”); } // end doGet() } // end HelloWorldServlet xample Code: web.xml 
E 
ec 
://ww.w3 . 
?xml version=1.0 encoding=ISO-8859-1? 
w 
Inside web.xml, the web-app is the root ta 
g representing the web application. All other tags come inside of it. 
eb-app 
servlet servlet-name HelloWorldServlet /servlet-name servlet-class 
HelloWorldServlet /servlet-class 
/servlet servlet-mappingservlet-name HelloWorldServlet
Web Design  Development – CS506 VU 
© Copyright Virtual University of Pakistan 
266 
/servlet-nameurl-pattern /myfirstservlet /url- 
The class. To specify the name of servlet, servlet-name 
tag is used. Similarly to specify the class name of servlet (it is the same name you used for making a 
No 
This name is used for referring to servlet in later part of web.xml. You can think of it as your id assigned to 
your university while you have actually different name (like servlet-class). 
ext w 
g using servlet-name tag and then you will define the URL pattern using url-pecifying 
the url. You can specify any name of 
ation. 
url-pattern /myfirstservlet /url-pattern 
Now you can access HelloWorldServelt (if it is placed in myapp application) by giving the following url in 
ote: Save this web.xml file by placing double quotes(“web.xml”) around it as you did to save .java files. 
Compiling and Invoking Servlets 
-Compile HelloWorldServlet.java using javac command. 
-Put HelloWorldServlet.class in C:jakarta-tomcat5.5.9/webapps/myapp/WEB-INF/classes folder 
-Put web.xml file in C:jakarta-tomcat5.5.9/webapps/myapp/WEB-INF folder 
-Invoke your servlet by writing following URL in web browser. Don’t forget to restart your tomcat 
server if already running 
http://localhost:8080/myapp/myfirstservlet 
Note: By using IDEs like netBeans® 4.1, you don’t have to write web.xml by yourself or even to worry 
about creating directory structure and to copy files in appropriate locations. However manually 
undergoing this process will strengthen your concepts and will help you to understand the 
underlying mechanics☺. 
References: 
pattern/servlet-mapping /web-app 
servlet tag represents one’s servlet name and its 
servlet), servlet-classtag is used. 
te: It is important to note here that you can specify any name for a servlet inside servlet-name tag. 
you by N 
e will define the servlet mapping. By defining servlet mapping we are specifying URL to access a servlet. servlet-mapping tag is used for this purpose. Inside servlet-mapping tag, first you will write the name of the servlet for which you want to specify the URL mappin 
pattern tag. Notice the forward slash (/ ) is used before sURL. The forward slash indicates the root of your applic 
the browser http://localhost:8080/myapp/myfirstservlet 
N 
Entire material for this handout is taken from the book JAVA A Lab Course by Umair Javed. This 
material is available just for the use of VU students of the course Web Design and Development and not 
for any other commercial purpose without the consent of author.
Web Design  Development – CS506 VU 
© Copyright Virtual University of Pakistan 
267 
Lesson 28 
Servlets Lifecycle 
en how to write a simple servlet. In this handout we will look more 
ed. What different set of method are invoked during the 
fecycle 
reading HTML form data through servlet technology. This will be explored in 
etail using code example 
e 
e passage of time a servlet passes through these 
stages one after another. 
In the last handout, we have sespecifically on how servlets get created and destroy 
li of a typical servlet. 
The second part consists on 
d 
Stages of Servlet Lifecycl 
A servlet passes through the following stages in its life. 1 Initialize 2 Service 
3Destroy 
As you can conclude from the diagram below, that with th 1. Initialize 
When the servlet is first created, it is in the initialization stage. The webserver invokes he init() method of 
the servlet in this stage. It should be noted here that init() is only called once and is not called for each 
requ t. itialization 
ng 
ge 
The service() method is the engine of the servlet, which actually processes the client’s request. On every 
request from the client, the server spawns a new thread and calls the service() method as shown in the figure 
below. This makes it more efficient as compared to the technologies that use single thread to respond to 
es Since there is no constructor available in Servlet so this urges its use for one time in of resources, setting of parameters etc) just as the init() method of applet. 
(loadiIn 
itialize stage has the following characteristics and usa ƒ Executed once, when the servlet gets loaded for the first time ƒ Not called for each client request ƒ The above two points make it an ideal place to perform the startup tasks which are done in 
constructor in a normal class. 2. Service 
requests.
Web Design  Development – CS506 VU 
© Copyright Virtual University of Pakistan 
268 
The figur am, 
we assum let. (Remember, GenericServlet is used for 
constructing protocol independent servlets.). To provide the desired functionality, service() method is 
to the web server; a new thread is created to serve this request 
service() method. Finally a response is prepared and sent back to the user according 
e below show both versions of the implementation of service cycle. In the upper part of diagr 
e that servlet is made by sub-classing from GenericServ 
overridden. The client sends a request followed by calling the 
to 
the request. The second part of the figure illustrates a situation in which servlet is made using HttpServlet class. Now, 
this servlet can only serves the HTTP type requests. In these servlets doGet() and doPost() are overridden 
provide desired behaviors. When a request is sent to the web server, the web server after creating a 
thread, passes on this request to service() method. The service() method checks the HTTP requests type 
(GET, POST etc) and calls the doGet() or doPost() method depending on how the request is originally sent. 
st() method, the response is sent back to the service() 
erver. 
to 
After forming the response by doGet() or doPomethod that is finally sent to the user by the web s
Web Design  Development – CS506 VU 
© Copyright Virtual University of Pakistan 
269 
3. Destroy 
The web server may decide to remove a previously loaded servlet instance, perhaps because it is explicitly 
sked to do so by the server administrator, or perhaps servlet container shuts down or the servlet is idle for 
e, or may be the server is overloaded. Before it does, however it calls the servlets destroy() 
method. This makes it a perfect spot for releasing the acquired resources. 
Summary 
ƒ is constructed and initialized. The initialization can be performed inside of init() method. 
ƒ e() method that may decide to call further 
methods depending upon t ype (Generi TTP specific) 
ƒ s down, Servlet is destroyed and garbage is collected 
The following figure can help to summarize the life cycle of the Servlet 
a 
a long tim 
A Servlet 
Servlet services zero or more requests by calling serviche Servlet tc or H 
Server shut The web sever creates a servlet instance. After successful creation, the servlet enters into initialization phase. 
Here, init() method is invoked for once. In case web server fails in previous two stages, the servlet instance 
is unloaded from the server. 
After initialization stage, the Servlet becomes available to serve the clients requests and to generate response 
accordingly. Finally, the servlet is destroyed and unloaded from web server. 
Reading HTML Form Data Using Servlets 
In the second part, the required concepts and servlet technology is explored in order to read HTML form 
data. To begin with, let’s first identify in how many ways a client can send data
Web Design  Development – CS506 VU 
© Copyright Virtual University of Pakistan 
270 
HTML  Servlets 
Generally HTML is used as a Graphic a Servlet. In the figure below, HTML form is 
ents. 
s User Interface for 
being used as a GUI interface for MyServlet. The data entered by the user in HTML form is transmitted to the MyServlet that can process this data once it read out. Response may be generated to fulfil the application requirem Types of Data send to Web Server 
When a user submits a browser request to a web server, it sends two categories of data: 
HTML form. For example: registration information provided 
. HTTP Request Header Data 
Data, which is automatically, appended to the HTTP Request from the client for example, cookies, 
browser type, and browser IP address. 
Based on our understanding of HTML, we now know how to create user forms. We also know how to 
gather user data via all the form controls: text, pass checkbox, radio buttons, etc. Now, the 
question arises: if I submit form data to a Servlet, h w do I extract this form data from servlet? Figuring 
Reading HTML Form Data from Servlet 
Now let see how we can read data from “HTML form” using Servlet. The HttpServletRequest object 
contains three main methods for extracting form data submitted by the user: 
. getParameter(String name) 
-Used to retrieve a single form parameter and returns String corresponding to name specified. 
-Empty String is returned in the case when user does not enter any thing in the specified form field. 
-If the name specified to retrieve the value does not exist, it returns null. 
Note: You should only use this method when you are sure that the parameter has only one value. 
If the parameter might have more than one value, use getParamterValues(). 
. Form Data Data, that the user explicitly type into anfor creating a new email account. 
word, select, o 
this out, provides the basis for creating interactive web applications that respond to user requests.
Web Design  Development – CS506 VU 
© Copyright Virtual University of Pakistan 
271 
. getParameterValues(String name) er names, this method will be helpful 
s of the parameters that come with the 
-If meration. 
ote: All these methods discussed above work the same way regardless of the request type(GET or 
“userName” is not the same as 
the e 
html), one servlet (MyServlet.java) and one xml file 
(we eters: firstName and surName. The Servlet 
extracts thes e browser after appending “Hello”. 
Note: The example given below and examples later i coming handouts are built using netBeans®4.1. It’s 
important to note that tomcat server bundled with netBeans® runs on 8084 port by default. 
-Returns an array of Strings objects containing all of the given values of the given request parameter. -If the name specified does not exist, null is returned 
. getParameterNames() -If you are unsure about the paramet 
-It returns Enumeration of String objects containing the namerequest. 
the request has no parameters, the method returns an empty Enu 
N 
POST). Also remember that form elements are case sensitive for example, 
“usrname.” 
E 
xample Code: Reading Form Data using Servlet This example consists of one HTML page (inde. 
x 
b.xml) file. The HTML page contains two form parame specific parameters and echoes them back to th 
n 
index.html
Web Design  Development – CS506 VU 
© Copyright Virtual University of Pakistan 
272 
Let’s struct the above page. 
html 
title Reading Two Parameters /title 
body 
H2 Pleas 
FORM OD=GET 
ACTION=http://localhost:8084/paramapp/formservletNAME=myform  
BR Firstname: 
INPUT TYPE = “text” NAME=firstName 
BR Surname: 
NPUT TYPE = “text” NAME=surName 
t Form INPUT TYPE=reset 
/body 
/html 
Let’s discuss the code of above HTML form. As you can see in the FORM tag, the attribute 
ME to “GET”. The possible values for this attribute can be GET and POST. Now what do 
the 
od attribite to “GET” means that we want to send the HTTP request using the 
the doGet() method of the servlet. In the GET 
method the information in the input fields entered by the user, merges with the URL as the query 
string and are visible to the user. 
ƒ s the entered information from the user as this 
mes the part of request body and activates doPost() method of the servlet. 
Attribute ACTION of FROM tag is set to http://localhost:8084/paramapp/formservlet. The form 
nsmitted to this URL. paramapp is the name of web application created using netBeans. 
alue of url-pattern defined in th web.xml. The code of web.xml is given at the end. 
The NAME attribute is set to “myform” that helps when the same page has more than one forms. 
However, here it is used only for demonstration purpose. 
To create the text fields where user can enter data, following lines of code come into play 
INPUT TYPE = “text” NAME=firstName 
INPUT TYPE = “text” NAME=surName 
Each text field is distinguished on the basis of name assigned to them. Later these names also help in 
extracting the values entered into these text fields. 
have a look on the HTML code used to con 
head /head 
e fill out this form: /H2 
METH 
I 
BR INPUT TYPE=submit value=Submi value=Reset 
/FORM 
THODis set 
se values mean? ƒ Setting the methGET method which will evantually activate 
Setting METHOD value to “POST” hideinformation beco 
data will be traformservlet is the v 
e
Web Design  Development – CS506 VU 
© Copyright Virtual University of Pakistan 
273 
MyServlet.java 
Now lets take a look at the servlet code to which HTML form data is submitted. 
ervlet extends HttpServlet{ 
public void doGet(HttpServletRequest req, 
HttpServletResponse res)throws ServletException, 
// reading first name parameter/textfield 
etParameter(“firstName”); 
// gettting stream from HttpServletResponse objectPrintWriter out = res.getWriter(); 
out.println(Hello:  + fName + “ “ +sName ); 
out.close(); 
}// d 
We started the code with importing three packages. 
import java.io.*, 
import javax.servlet.*; 
import javax.servlet.http.*; 
These packages are imported to have the access on PrintWriter, HttpServlet, HttpServletRequest, 
Htt 
he s 
alue of mehtod attribute was set to “GET”. So in this case, 
we only need to override doGet()Method. 
Entering inside doGet() method brings the crux of the code. These are: 
String fName = req.getParameter(“firstName”); 
r(“surName”); 
t” NAME=firstName 
INPUT TYPE = “text” NAME=surName 
In the last part of the code, we get the object of PrintWriter stream from the object of 
import java.io.*;import javax.servlet.*;import javax.servlet.http.*; public class MyS 
IOException{ 
String fName = req.g 
// reading surname parameter/textfield String sName = req.getParameter(“surName”); 
} en FormServlet 
pServletResponse, ServletException and IOException classes. 
THTML code (index.html) discussed above, the v 
clas MySevlet extends from HttpServlet to inherit the HTTP specific functionality. If you recall 
String sName = req.getParamete 
Two String variables fName and sName are declared that receive String values returned by getParameter() method. As discussed earlier, this method returns Stringcorresponds to the form parameter. Note that the values of name attributes of input tags used in index.html have same case with the ones passed to getParameter() methods as parameters. The part of HTML code is reproduced over here again: 
 
INPUT TYPE = “tex
Web Design  Development – CS506 VU 
© Copyright Virtual University of Pakistan 
274 
HttpServletResponse. This object will be used to send data back the response. Using PrintWriter object 
(out s are printed with appended “Hello” that becomes visible in the browser. 
web.xml 
?xml version=1.0 encoding=ISO-8859-1? 
web-app 
serv 
/s 
servlet-mapping 
servlet-name FormServlet /servlet-name 
url-pattern /formservlet /url-pattern 
mapping 
/web-app 
The servlet-mapping tag contains two tags servlet-name and urlpatteren containing name and 
pattern of the URL respectively. Recall the value of action attribute of the form element in the HTML 
ost:8084/paramapp/formservlet 
Re 
), the name 
 
let servlet-name FormServlet /servlet-name servlet-class MyServlet /servlet-class 
ervlet 
/servlet- 
 
page. You can see it is exactly the same as mentioned in url-pattern tag. http://localh 
ferences: 
ƒ JAVA a Lab Course by Umair Javed 
ƒ Java API documentation 
ervlets and JSP by Marty Hall 
ƒ Core S
Web Design  Development – CS506 VU 
© Copyright Virtual University of Pakistan 
275 
Lesson 29 
More on Servlets 
The objective of this handout is to learn about the use and implementation of initialization parameters for a 
Servlet. M and forwarding or including requests also 
discussed in detail. 
Initializat 
Some times at the time of starting up the application we need to provide some initial information e,g, name 
of the file where server can store logging information, DSN for database etc. Initial configuration can be 
defined for a Servlet by defining some string parameters in web.xml. This allows a Servlet to have initial 
parameters from outside. This is similar to providing command line parameters to a standard console based 
application. 
init-param //defining param 1 
param-name param1 /param-name 
param-value value1 /param-value 
init-param //defining param 2 
param-param 
In the above code, it is shown that for each parameter we need to define separate initparam tag that 
have two sub tags param-name and param-value, which contain the name and values of the 
parameter respectively. 
ServletConfig 
h it as shown in the fig. below. It contains 
levant mation about the Servlet like initialization parameters defined in web.xml 
oreover different ways of redirecting response 
ion Parameters 
Example: setting init parameters in web.xml Let’s have a look on the way of defining these parameters in web.xml 
/init-param 
name param2 /param-name -value value2 /param-value 
Every Servlet has an object called ServletConfig associated witre infor
Web Design  Development – CS506 VU 
© Copyright Virtual University of Pakistan 
276 
Reading Initialization Parameters 
t’s see tParameter()of 
r, matches it with 
param-name 
One way is to override init() method as shown in the code below. The ServletConfig object can then be 
used to read init 
public void init(ServletConfig config) throws ServletException { 
String nam etInitParameter(“paramName”); 
other way to read initialization parameters out side the init () method is 
ƒ Call getServletConfig() to obtain the ServletConfig object 
ƒ Use getInitParameter() of ServletConfig to read initialization parameters 
thod() // defined inside servlet{ 
ServletConfig config = getServletConfig(); 
String name = config.getInitParameter(“param_name); 
} 
Example Code: Reading init parameters 
MyServlet.java will read the init parameter (log file name) defined inside web.xml. The code is given below: 
import java.io.*; 
import java.net.*; 
import javax.servlet.*; 
import javax.servlet.http.*; 
public class MyServlet extends HttpServlet { 
// attribute used to store init-parameter value 
String fileName; 
// overriding init() method 
public void init(ServletConfig config) throws ServletException{ 
super.init(config); 
// reading init-parameter “logfilename” stored in web.xmlfileName = 
config.getInitParameter(logfilename); 
} 
/* Both doGet()  doPost() methods are override over here.processRequest() is called from both 
rvlet to handle both POST and GET 
requestsidentically. 
*/ 
// Handles the HTTP GET request type 
ServletRequest request, 
est, response); 
} 
Now le, how we can access init parameters inside the Servlet. The method getIniServletConfig is usually used to access init parameters. It takes a String as paramete 
tag under all init-param tags and returns param-value from the web.xml 
ialization parameter. 
e = config.g 
} 
An 
public void anyMe 
these methods. This makespossible for a se 
protected void doGet(Http 
HttpServletResponse response)throws ServletException, IOException{ processRequest(requ
Web Design  Development – CS506 VU 
© Copyright Virtual University of Pakistan 
277 
// Handles the HTTP POST request type 
pr quest request, 
st() 
protected void processRequest(HttpServletRequest request, 
HttpServletResponse response)throws ServletException, IOException{ 
PrintWriter out = response.getWriter(); 
// writing init-parameter value that is store in fileNameout.println(fileName); 
out.close(); 
} 
web.xml 
?xml version=1.0 encoding=UTF-8?web-app 
servlet servlet-name MyServlet /servlet-name servlet-class MyServlet /servlet-class 
init-param param-name logfilename /param-name param-value logoutput.txt 
/param-value 
/init-param 
/servlet 
servlet-mapping 
/web-app 
otected void doPost(HttpServletRe 
HttpServletResponse response)throws ServletException, IOException{ processRequest(request, response); } // called from doGet()  doPo 
servlet-name MyServlet /servlet-name 
url-pattern /myservlet /url-pattern /servlet-mapping
Web Design  Development – CS506 VU 
© Copyright Virtual University of Pakistan 
278 
Response Redirection 
We can redirect the response of the Servlet to another application resource (another Servlet, an HTML 
page or a JSP) but the resource (URL) must be available to the calling Servlet, in the same Servlet context 
(discussed later). 
There are two forms of response redirection that can be possible: 
ƒ Sending a standard redirect 
ƒ Sending a redirect to an error page 
Sending a standard Redirect 
let will not have access to the original request 
object. For example, if the request is redirected from servlet1 to servlet2, then servlet2 would not 
bject of servlet1. 
ƒ 
Sending a redirect to an error page 
Instead o 
This me 
class (lis cond the appropriate error message. The steps to redirect the user to an error page 
are: 
ƒ An error code is sent as a parameter of response.sendError(int, msg)method 
ƒ The error page is displayed with the msg passed to method 
r numbers are predefined constants of the HttpServletResponse class. For example: 
_NOT_FOUND (404) 
-SC_NO_CONTENT (204) 
-SC_REQUEST_TIMEOUT (408) 
xample Code: Response Redirection 
n leads to welcome page or otherwise to a registration page. 
This example consists of login.html, welcome.html, register.html and MyServlet.java files. Let’s examine 
these one after another. 
login.html 
This page contains two text fields; one for entering username and another for password. The data from this 
page is submitted to MyServlet.java. 
ƒ Using response.sendRedirect(“myHtml.html”) method, a new request is generated which redirects the user to the specified URL. ƒ If the URL is of another Servlet, that second Serv 
be able to access the request o 
To have access to the original request object, you must use the request dispatching technique (discussed later) instead of redirect. 
f using response.sendRedirect(), we can use response.sendEorror() to show user an error page. thods takes two parameters, first the error number that is a predefined constant of the response ted below) and se 
ƒ The erro 
-SC 
E 
The example given below demonstrates a typical sign on example in which a user is asked to provide login/password, providing correct informatio
Web Design  Development – CS506 VU 
© Copyright Virtual University of Pakistan 
279 
html 
h2 Please provide login details/h2 
FROM METHOD=POST 
ACTION=http://localhost:8084/redirectionex/myservletNAME=myFor 
m  
name=userid/ 
BR Password: 
INPUT TYPE=password name=pwd/ 
BR BR 
input type=submit value=Submit Form/ 
ome.html 
displays a 
successfully logged-in message to the user. 
html 
bod 
h2 Y ed in /h2 /body 
/body 
/html 
register.html 
The use n/password information. The user can 
enter user id, address and phone number here to register. 
Note: T the user. It does not register user as no such 
function 
html 
bo 
FORM METHOD=POST ACTION= NAME=myForm 
BR Name: 
body 
BR User Id: INPUT TYPE=text 
/form 
/body 
/html 
welc 
The user is directed to this page only if user provides correct login / password. This page only 
y 
ou have successfully logg 
r is redirected to this page in case of providing incorrect logi 
he code given below will only show fields to 
ality is added into this small example. 
dy 
h2Your login is incorrect. Please register yourself/h2
Web Design  Development – CS506 VU 
© Copyright Virtual University of Pakistan 
280 
INPUT TYPE=text NAME=userid/ 
BR Address: INPUT TYPE=text NAME=address/ 
BR Phone No: INPUT TYPE=text NAME=phoneno/ 
BR BR input type=submit value=Register/ 
/form 
/body 
/html 
MyServ 
MyServl m login.html and redirects the user to welcome.html or register.html 
based o me  password provided. Username  password are compared with fix 
values in this exam ou can verify these from database or from a text file etc. 
import java.io.*; 
import jav 
port javax.servlet.*; 
port javax.servlet.http.*; 
// Handles the HTTP GET request type 
protected void doGet(HttpServletRequest request, HttpServletResponse response)throws 
ServletException, IOExc 
processRequest(request, response); 
} 
// Handles the HTTP POST request type 
equest request, HttpServletResponse response)throws 
ServletException, IOException{ 
processRequest(request, 
} 
ServletRequest request, HttpServletResponse response)throws 
ception, IOException{ 
g id = request.getParameter(userid);String pwd = request.getParameter(pwd); 
// comparing id  password with fix values 
if(id.equals(ali)  pwd.equals(vu)) { 
// redirectign user to welcome.html 
response.sendRedirect(welcome.html); 
 
le.java 
et.java accepts requests fro 
n the verification of usernaple, however y 
a.net.*; 
im 
im 
public class MyServlet extends HttpServlet { 
eption{ 
protected void doPost(HttpServletR 
response); 
protected void processRequest(Http 
ServletEx 
Strin
Web Design  Development – CS506 VU 
© Copyright Virtual University of Pakistan 
281 
else {// redirecting user to register.htmlresponse.sendRedirect(register.html); 
/* if you want to display an error message to theuser, you can use the following method 
response.sendError(response.SC_PROXY_AUTHENTICATION_REQUIRED,Send 
Error Demo );*/ 
e 
} 
ServletContext 
ServletC sed for sharing resources among 
servlets 
As initiali onfig, ServetContext can store 
initializa ation. These parameters are also called context attributes 
or the lifetime of the application. The following figure illustrates the sharing of context attributes 
mong all the servlets of a web application. 
}// end els 
} 
ontext belongs to one web application. Therefore it can be uin the same web application. 
zation parameters, for a single servlet are stored in ServletC 
tion parameters for the entire web applic 
and exist fa 
Note: 
ServletContextper web application 
) of ServletContext returns a RequestDispatcher object associated with the 
ƒ There is a single 
ƒ Different Sevlets will get the same ServletContext object, when calling getServletContext()during different sessions Request Dispatcher RequestDispatcher provides a way to forward or include data from another source. The method getRequestDispatcher(String path
Web Design  Development – CS506 VU 
© Copyright Virtual University of Pakistan 
282 
resource at the given path passed as a parameter. 
wo important methods of RequestDispatcher are: 
sponse resp) 
sponse resp) 
RequestDispatcher: forward 
Charact rward methods are: 
ƒ It allows esource (Servlet, JSP or HTML file) in the 
same Se 
ƒ Forward res.sendRedirect(String location). You can not 
see the chang 
ƒ ct is available to the called resource. In other words, it remains in scope. 
ƒ arding request to another source, headers or status codes can be set, but 
tent cannot be added. 
To clarify the co User initates the request to servlet1. 
servlet1 forwards the request to servlet2 by calling forward(request,response). Finally a response is returned 
back to rvlet2. 
T 
ƒ forward(ServletRequest req, ServletRe ƒ include(ServletRequest req, ServletRe 
eristics of fo 
a Servlet to forward the request to another rrvlet context. 
ing remains transparent to the client unlike es in the URL. 
Request Obje 
Before forwoutput con 
ncepts, lets take the help from following figure. 
the user by se 
RequestDispatcher: include 
It allows a Servlet to include the results of another resource in its response. The two major differences from 
forward are: 
ƒ Data can be written to the response before an include 
ƒ The first Servlet which receive the request, is the one which finishes the response 
It will be more cleared from the following figure. User sends a HTTPRequest to Servlet1. Serlet2 is called 
by Servlet1 by using include(request, response) method. The response generated by Servlet2 sends back to
Web Design  Development – CS506 VU 
© Copyright Virtual University of Pakistan 
283 
Servlet1. Servlet1 can also add its own response content and finally send it back to user. 
References: 
ƒ Java A Lab Course by Um 
ƒ Core Servlets an 
ƒ Java API docum 
air Javed d JSP by Marty Hall 
entation
Web Design  Development – CS506 VU 
© Copyright Virtual University of Pakistan 
284 
Lesson 30 
ests 
In this handout st dispatching techniques and give some examples related to that. 
Further more some method HttpRequestwill also be discussed. Finally, this handout 
will be concluded by discussing the importance of session tracking. Before starting, let’s take a look at the 
summery of the 
Recap 
In the previous lecture we had some discussion about Response Redirection and Request Dispatcher. We 
said that Respon Servlet to another application resource. 
This resource m . 
Two forms of Resp 
. Sending a 
Using res od, a new request is generated which 
redirects ther servlet, that second servlet will not be 
able to a 
. Redirection to an error page: 
An err rror(int, msg) 
method lar error page in case of occurrence of 
specified error. 
Similarly request ility to forward the request processing to another servlet, or 
to include the output of another resource (servlet, JSP or HTML etc) in the response. Unlike Response 
Redirection, request object of calling resource is available to called resource. The two ways of Request 
ispatching are: 
. Fo 
ssing to another resource. 
. In 
Allows a servlet to include the results of another resource in its response. So unlike forward, the 
first servlet to receive the request is the on 
Example Code: Request Dispatching – Include 
Lets sta ow a Servlet includes the output of another resource in 
its respo eServlet, who’s 
output will be included in the calling Servlet. 
The code of MyServlet.java servlet is given below. 
Dispatching Requ 
we will start with reque 
s of HttpResponse and 
previous lecture. 
se Redirection was used to redirect response of the 
ight be another Servlet or any JSP pageonse redirection were discussed. These were: 
standard request: 
ponse.sendRedirect(“path of resource”) meth the user to the given URL. If the URL is of ano 
ccess the original request object. 
or code is passed as a parameter along with message to response.sendE 
. This method redirects the user to the particu 
dispatching provides us the fac 
D 
rward: Forwards the responsibility of request proce 
clude: 
e which finishes the response. 
rt with the example of include. We will see h 
nse. The following example includes a calling Servlet MyServlet and Servlet Includ
Web Design  Development – CS506 VU 
© Copyright Virtual University of Pakistan 
285 
MyServlet.java 
import java.io.*; 
t.*; 
p.*; 
ublic class MyServlet extends HttpServlet { 
/* this method is being called by both doGet() and doPost().We 
usually 
type of incoming request to the servlet. So the ac 
processing is be 
*/ 
rotected void processRequest(HttpServletRequest request, HttpServletResponse response) 
ception { 
response.setContentType(text/html); 
PrintWr 
out.prin (html); 
out.prin 
out.prin equest /h1); 
out.flush 
// gettin ed to 
// obtai ispacther 
ServletC letContext(); 
// gettin ispatcher by passing the path 
// of in meter 
Request udeservlet); 
import java.net.*; 
import javax.servle 
import javax.servlet.htt 
p 
follow this practice, when we are not sure about the 
tual 
ing done in the processRequest(). 
p 
throws ServletException, IOEx 
iter out = response.getWriter(); 
tln 
tln(body); 
tln(h1Start of include r 
(); 
g the object of ServletContext, that will be us 
n the object of RequestD 
ontext context = getServ 
g the object of RequestD 
cluded resource as a para 
Dispatcher rd = context.getRequestDispatcher(/incl
Web Design  Development – CS506 VU 
© Copyright Virtual University of Pakistan 
286 
// calling include method of RequestDispatcher by passing 
// requ parameters. This will execute 
//the se ut in the first servlet 
rd.includ sponse); 
er including the 
out.println(h1End o 
out.prin 
t.println(/html); 
out.close(); 
} 
This method only calls processRequest() 
rotected void doGet(HttpServletRequest request, HttpServletResponse response) 
throws ServletException, IOException { 
// This method only calls processRequest() 
protected void d tResponse response) 
ption, IOException { 
est(request, response); 
} // end 
est and response objects as 
cond servlet and include its outp 
e(request, re 
/* the statements below will be executed aft 
output of the /includeservlet */ 
f 
tln(/body); 
ou 
// closing PrintWriter stream 
// 
p 
processRequest(request, response); 
} 
oPost(HttpServletRequest request, HttpServle 
throws ServletExce 
processRequ 
} 
MyServlet
Web Design  Development – CS506 VU 
© Copyright Virtual University of Pakistan 
287 
Include 
Now lets take a look 
import java.io.*; 
import j 
port javax.servlet.*; 
import j 
public class Inclu 
// this method is being called by both doGet() and doPost() 
sRequest(HttpServletRequest request, HttpServletResponse response) 
throws ServletException, IOException { 
// Obtaining the object of PrintWriter, this will return the 
ct we have in MyServlet 
// Including a HTML tag using PrintWriter 
throws ServletException, IOException { 
processRequest(request, response); 
ServletResponse response) 
throws ServletException, IOException { 
the processRequest(), firstly we get the PrintWriter stream from the HttpServletResponse object. Then 
tag to the output of the calling servlet. One thing that must be considered is that 
sed again in the calling servlet. 
Servlet 
at the code of IncludeServlet.java 
ava.net.*; 
im 
avax.servlet.http.*; 
deServlet extends HttpServlet { 
protected void proces 
// same PrintWriter obje 
PrintWriter out = response.getWriter(); 
out.println(h1 marqueeI am included /marquee/h1); } protected void doGet(HttpServletRequest request, HttpServletResponse response) 
} protected void doPost(HttpServletRequest request, Http 
} 
} // end IncludeServlet 
In 
we include an HTML 
P 
rintWriter stream is not closed in the end, because it is the same stream that is being used in the calling servlet and this stream may also be used in the calling servlet again. So, if it is closed over here, it can not be 
u
Web Design  Development – CS506 VU 
© Copyright Virtual University of Pakistan 
288 
web.xml 
?xml version=1.0 encoding=UTF-8? 
web-app 
servlet 
servlet-nameMyServlet/servlet-name 
me 
vlet-classIncludeServlet/servlet-class 
url-pattern/myservlet/url-pattern 
servlet-mapping 
servlet-nameIncludeServlet/servlet-name 
/servlet-mapping 
servlet-classMyServlet/servlet-class /servlet 
servlet 
servlet-nameIncludeServlet/servlet-na 
ser 
/servlet servlet-mapping servlet-nameMyServlet/servlet-name 
/servlet-mapping 
url-pattern/includeservlet/url-pattern 
 
/web-app
Web Design  Development – CS506 VU 
© Copyright Virtual University of Pakistan 
289 
Code Example: Request Dispatcher - forward 
As discussed earlier, we can forward the request pro o another resource using forward method of 
form method=POST ACTION = “firstservlet NAME=myForm 
h2 Enter your name/h2 
INPUT TYPE=text name=name/ 
br/ 
h2 Salary/h2 
INPUT TYPE=text name=salary/ 
BR/BR/ 
INPUT type=submit value=Submit/ 
/form 
/html 
import java.net.*; 
import javax.servlet.*; 
import javax.servlet.http.*; 
public class FirstServlet extends HttpServlet { 
// this method is being called by both doGet() and doPost() 
protected void processRequest(HttpServletRequest request, HttpServletResponse response) 
sthrows ServletException, IOException { 
// getting value of salary text filed of the HTML form 
String salary = request.getParameter(salary); 
cessing t 
request dispatcher. In this example, the user enters his/her name and salary on the index.html and submits the form to FirstServlet, which calculates the tax on salary and forwards the request to another servlet for further processing i.e. SecondServlet. index.html 
html body 
FirstServlet.java import java.io.*;
Web Design  Development – CS506 VU 
© Copyright Virtual University of Pakistan 
290 
// converting 
int sal = Integer.parseInt(salary); 
5); 
// converting tax into string 
String taxValue = tax + ; 
alues in key-value form, later it 
// can be retrieved by using getAttribute() method 
request.setAttribute(tax, taxValue); 
// getting object of servletContext 
ServletContext sContext = getServletContext(); 
// getting object of request dispatcher 
RequestDispatcher rd = sContext.getRequestDispatcher(/secondservlet); 
// calling forward method of request dispatcher 
rd.forward(request, response); 
} 
// This method is calling processRequest() 
protected void doGet(HttpServletRequest request, HttpServletResponse response) 
throws ServletException, IOException { 
processRequest(request, response); 
} 
// This method is calling processRequest() 
protected void doPost(HttpServletRequest request, HttpServletResponse response) 
throws ServletException, IOException { 
processRequest(request, response); 
} 
} 
Note: It the case of Forward, it is illegal to make the reference of PrintWriter stream in the calling Servlet. 
Only the called resource can use PrintWriter stream to generate response 
it to the integer. 
// calculating 15% tax int tax = (int)(sal * 0.1 
// request object can store v
Web Design  Development – CS506 VU 
© Copyright Virtual University of Pakistan 
291 
SecondServlet.java 
ublic class SecondServlet extends HttpServlet { 
// this method is being called by both doGet() and doPost() 
Request(HttpServletRequest request, HttpServletResponse response) 
// obtaining values of name and salary text fields of index.html 
/* getting attribute value that has been set by the calling 
servlet i.e. FirstServlet */ 
String tax = (String)request.getAttribute(tax); 
using PrintWriter 
out.println(html); 
out.println(head); 
out.println(titleSecondServlet/title); 
body); 
tln(h1 Welcome  + name+ /h1); 
out.println(h3 Salary  + salary+ /h3); 
import java.io.*; import java.net.*; import javax.servlet.*; 
import javax.servlet.http.*; 
p 
protected void process 
throws ServletException, IOException { response.setContentType(text/html); 
PrintWriter out = response.getWriter(); 
String name = request.getParameter(name); String salary = request.getParameter(salary); 
// generating HTML tags 
out.println(/head); 
out.println( 
out.prin
Web Design  Development – CS506 VU 
© Copyright Virtual University of Pakistan 
292 
out.println(h3 Tax  + tax+ /h3 ); 
out.println(/body); 
throws ServletException, IOException { 
} 
// This method is calling processRequest() 
p te tResponse response) 
} 
} 
web.xml 
TF-8? 
web-app 
servlet-nameFirstServlet/servlet-name 
servlet-classSecondServlet/servlet-class 
/servlet 
 
out.println(/html); out.close(); 
} // This method is calling processRequest() 
protected void doGet(HttpServletRequest request, HttpServletResponse response) 
processRequest(request, response); 
rocted void doPost(HttpServletRequest request, HttpServle 
throws ServletException, IOException { 
processRequest(request, response); 
?xml version=1.0 encoding=U 
servlet 
servlet-classFirstServlet/servlet-class /servlet 
servlet 
servlet-nameSecondServlet/servlet-name
Web Design  Development – CS506 VU 
© Copyright Virtual University of Pakistan 
293 
servlet-mapping 
firstservlet/url-pattern 
/w 
Http 
Let’s discuss some methods of HttpServletRequestclass 
s 
We c 
attrib 
Disp been illustrated in the above example. These attributes are available every where in 
the same web application so th cess them by using getAttribute() 
method. 
getA 
Th 
in th 
in the co 
getMethod() 
This method returns the name of HTTP method which was used to send the request. The two possible 
returning values could be, get or post. 
getRequestURL() 
It can be used to track the source of Request. It returns the part of the request’s URL with out query string. 
servlet-nameFirstServlet/servlet-name 
url-pattern/ 
/servlet-mapping 
servlet-mapping 
servlet-nameSecondServlet/servlet-name 
url-pattern/secondservlet/url-pattern /servlet-mapping 
eb-app 
ServletRequest Methods 
etAttribute(String, Object) 
an put any object to the context using setAttribute() method in the key-value pair form.. These utes are also set or reset between requests. These are often used in conjunction with Request atcher. This has also 
at any other Servlet or JSP resource can ac 
ttribute(String) 
e 
objects set by the setAttribute() method can be accessed using getAttribute() method. Passing the key e form of string as a parameter to this method will return the object associated with that particular key ntext. Cast the object into its appropriate type.
Web Design  Development – CS506 VU 
© Copyright Virtual University of Pakistan 
294 
getProtocol( 
It returns the name and version of the protocol used. 
getHeaderName 
It returns the enum t are contained in the request. 
getHearderName() 
It takes a String parameter ts the header name and returns that appropriate header. Null value 
is returned if there is no header exists with the specified name. 
HttpServletRe 
Let’s discuss some methods of HttpServletResponse class 
ore getting the PrintWriter Stream. It is used to set the 
on the client’s browser. 
This method is used to set the content length. It takes length as an integer parameter. 
e header. It takes a Cookie object as a parameter and 
ad kies in the session tracking part. 
se 
T cepts the relative URL. It takes 
U 
) 
s() 
eration of all available header names tha 
that represen 
sponse Methods 
setContentType() Almost every Servlet uses this header. It is used bef 
Content Type that the PrintWriter is going to use. Usually we set “text/html”, when we want to send text output or generate HTML tags 
setContentLength( ) 
addCookie() 
This method is used to add a value to the Set-Cooki 
ds it to the Cookie-header. We will talk more about CoondRedirect() 
his method redirects the user to the specific URL. This method also acRL strser to that resource. 
ing as parameter and redirects the u
Web Design  Development – CS506 VU 
© Copyright Virtual University of Pakistan 
295 
Many applications require a series of requests from the same client to be associated with one another. For 
exam s the state of a user's shopping cart across multiple requests. 
Web-based applications are responsible for maintaining such state, because HTTP protocol is stateless. To 
supp ate, Java Servlet technology provides an API for managing 
sessions and allows several mechan 
Befo tracking mechanism lets see the limitation of HTTP protocol to get the 
real p an happen with out maintaining the session. 
Con nuity problem- user’s point of view 
Session Tracking 
ple, any online shopping application save 
ort applications that need to maintain stisms for implementing sessions. 
re looking inside the sessionicture of problems that cti Suppose a user logs on t t. He enters his 
billing address a fin as it is stateless in nature and user 
thinks that the choices made on page1 are remembered on page3 
o the online bookshop, selects some books and adds them to his carally submits the order. HTTP cannot track session 
nd
Web Design  Development – CS506 VU 
© Copyright Virtual University of Pakistan 
296 
Continuity problem- Server’s point of view 
The server has a very different point of view. It considers each request independent from other even if the 
requests are made by the same client. 
References 
ƒ Java A Lab Course by Umair Javed 
ƒ Core Servlet and JSP by Marty Hall
Web Design  Development – CS506 VU 
© Copyright Virtual University of Pakistan 
297 
Lesson 31 
the 
Store State Somewhere 
To maintain the conversational state, the straightforward approach is to store the state. But where? These 
states either can be stored on server or on client. However, both options have their merits and demerits. 
Let’s cast a glance on these options: 
Storing state on server side makes server really complicated as states needed to be stored for each client. 
Some one can imagine how much space and processing is required in this scenario as some web servers are 
hit more than hundred times in a second. E.g. Google, Yahoo etc. 
What if states are stored on client side in order to maintain a conversation? Do all the clients permit you 
doing that? What if client (user) wiped out these states from the machine? 
Concluding this discussion, state is stored neither completely on server side nor on client. States are 
maintained by the mutual cooperation of both client  server. Generally modern servers give the capability 
to store state on the server side and some information (e.g. client ID/state ID) passed from the client will 
relate each client with its corresponding state. 
Post–Notes 
In order to maintain the conversational state, server puts little notes (some text, values etc) on the client 
slide. When client submits the next form, it also unknowingly submits these little notes. Server reads these 
notes and able to recall who the client is. 
Three Typical Solutions 
Session Tracking We have discussed the importance of session tracking in the previous handout. Now, we’ll discover 
basic techniques used for session tracking. Cookies are one of these techniques and remain our focus in this handout. Cookies can be used to put small information on the client’s machine and can be used for various other purposes besides session tracking. An example of simple “Online Book Store”, using cookies, will 
also be surveyed. As mentioned elsewhere, HTTP is a stateless protocol. Every request is considered independent of every other request. But many applications need to maintain a conversational state with the client. A shopping cart is a classical example of such conversational state. 
Three typical solutions come across to accomplish session tracking. These are: 1 Cookies 
2 URL Rewriting 3 Hidden Fields
Web Design  Development – CS506 VU 
© Copyright Virtual University of Pakistan 
298 
Cookies 
ing off. In fact, in computer terminology, “a cookie is 
a piece hard disk”. 
Cookies allow the ent machine and later retrieve it. The pieces of 
inform value pair on the client. Later while reconnecting to the same site (or same 
doma depending upon the cookie settings), client returns the same name-value pair to the server. 
Cook 
To reve ample. We are assuming here that the web application 
we ar 
ƒ wser sends a request for that web page 
e www.amazon.com 
What a cookie is? 
Don’t be tempted? These are not, what you might be think 
of text that a web server can store on a client’s (user) web sites to store information on a cliation are stored as name- in 
ie’s Voyage 
al the mechanism of cookies, let’s take an exe using will set some cookies 
If you type URL of a Web site into your browser, your bro 
o For example, when you typ a request is send to the Amazon’s server 
ƒ Before sending a request, browser looks for cookie files that amazon has set 
o If browser finds one or more cookie files related to amazon, it will send it along with the 
ent with the request 
ƒ Amazaon web server receives the request and examines the request for cookies 
hat you have not visited before or the cookies 
that were previously set got expired. 
eader of HTTP Response 
ed on the client machine. 
os or cons is arguable. However, cookies are helpful in the following 
For example, this book is added into shopping cart 
s are saved on your machine 
mail-inbox in a different look form others. This sort 
e used to format 
e, a web site can store information in the form of cookies about the 
or. 
request 
o If not, no cookie data will be s 
o If cookies are received, amazon can use them o If no cookie is received, amazon knows t 
o Server creates a new cookie and send to your browser in the h 
so that it can be sav 
Potential Uses of Cookies 
Whether cookies have more pr 
situations 
ƒ Identifying a user during an e-commerce session. 
by this client. ƒ Avoiding username an 
d password as cookie ƒ Customizing a site. For example, you might like e 
of information can be stored in the form of cookies on your machine and latter can binbox according to your choice. 
ƒ Focused Advertising. For examplkinds of books, you mostly hunt f
Web Design  Development – CS506 VU 
© Copyright Virtual University of Pakistan 
299 
Send 
Follo ookie to a browser (client). 
1 
ie constructor, which takes two strings: the cookie 
Cookie c = new Cookie (“name”, “value”); 
2 
Before adding the cookie to outgoing headers (response), various characteristics of the cookie can be 
ie persists on the disk or not. If yes then how long. 
urrent user session (i.e. until the user quits the session) and 
before the 
ne hour 
3. Place the Cookie into HTTP response 
attributes, the most important and unforgettable step is to add this 
onse. If you forget this step, no cookie will be sent to the browser. 
e.addCookie(c); 
owing steps are generally followed. 
okies 
t of the HttpServeltRequest by calling 
following method 
s[] = request.getCookies(); 
T 
2 
ies, you can iterate over it. Two important methods of Cookie class are 
() getValue(). These are used to retrieve cookie name and value respectively. 
ing Cookies to Browser 
wing are some basic steps to send a c 
. Create a Cookie Object 
A cookie object can be created by calling the Cookname and the cookie value. 
. Setting Cookie Attributes 
set. For example, whether a cook 
A cooki 
es by default, lasts only for the c 
will not be stored on the disk. Using setMaxAge(int lifetime) method indicates how much time (in seconds) should elapse cookie expires. 
c.setMaxAge(60); // expired after o 
After making changes to cookiecurrently created cookie into resp 
respons Reading Cookies from the Client To read the cookies that come back from the client, foll1. Reading incoming co 
To read incoming cookies, get them from the request objec 
Cookie cookie 
This call returns an array of Cookies object corresponding to the name  values that came in the HTP request header. 
. Looping down Cookies Array Once you have an array of cookgetName
Web Design  Development – CS506 VU 
© Copyright Virtual University of Pakistan 
300 
// looping down the whole cookies array 
ookie c = cookies[i]; 
ar cookie 
someName”) { 
n do something with cookieor with the help of cookie. 
her, loop canalso be stopped using break 
*/ 
} 
Exam 
In the exam a unique cookie, named “repeat”. If the cookie is present, servlet 
disp ndicates that the user is visiting this site for the first time thus 
serv rd”. 
This exa code snippet 
of web 
Not sing netBeans4.1. This IDE will write web.xml for you. 
How ose only, or for those which are not using any IDE to 
strengthen their concepts 
RepeatVisitorServlet.java 
import java.io.*;import java.net.*;import 
javax.servlet.*;import javax.servlet.http.*; 
publi VisitorServlet extends HttpServlet { 
tion, IOException{ 
// Handles od. 
protected v 
HttpServletResponse response)throws ServletException, IOException{ 
processRequest(request, response); 
// called from both doGet()  doPost() 
for(int i=0; icookies.length; i++) { // getting each cookie from the arrayC 
// in search for particulif( c.getName().equals(“ /* if found, you ca 
If don’t want to process furtstatement 
} // end for 
ple Code1: Repeat Visitor ple below, servlet checks for 
lays “Welcome Back”. Absence of cookie ilet displays a message “Welcome Aboa 
mple contains only one servlet “RepeatVisitorServlet.java” and its code is given below. A .xml is also accompanied. 
e: As a reminder, all these examples are built uever, here it is given for your reference purp 
c class Repeat 
// Handles the HTTP codeGET/code me 
thod. 
protected void doGet(HttpServletRequest request, 
HttpServletResponse response)throws ServletExcep 
processRequest(request, response); 
} 
the Hde meth 
TTP codePOST/co 
oid doPost(HttpServletRequest request, 
} 
protected void processRequest(HttpServletRequest request,
Web Design  Development – CS506 VU 
© Copyright Virtual University of Pakistan 
301 
H response)throws ServletException, IOException{ 
respo 
boolean repeatVisitor = false; 
okie[] cookies = request.getCookies(); 
t object 
Cookie c = cookies[i]; 
okie 
firming if cookie name equals “repeat” and 
// value equals “yes” 
if( name.equals(repeat)  val.equals(yes)) 
{ 
k;repeatVisitor = true;break; 
// if no cookie with name “repeat” is foundif (repeatVisitor == false){ 
// create a new cookie 
Cookie c1 = new Cookie(repeat, yes); 
// setting time after which cookies expires 
c1.setMaxAge(60); 
// adding cookie to the response 
response.addCookie(c1); 
msg = Welcome Aboard; 
} 
ttpServletResponse 
nse.setContentType(text/html); 
PrintWriter out = response.getWriter(); // writing html out.println(html); out.println(body); 
out.println(h2Cookie Example /h2); 
String msg = ; 
// reading cookies Co 
cookies are returned from reques 
// if 
if (cookies != null) {//search for cookie -- repeatfor (int i = 0; i  cookies.length; i++) { // retrieving one cookie out of array 
// retrieving name  value of the coString name = c.getName(); String val = c.getValue(); 
// con 
msg= Welcome Bac 
} 
} // end for } // end if
Web Design  Development – CS506 VU 
© Copyright Virtual University of Pakistan 
302 
// displaying message value 
out.println(h2 + msg + / 
ervlet-class RepeatVisitorServlet 
/servlet-c 
/servlet 
servlet-map /servlet-nameurl-pattern /repeatexample 
/url-pattern 
Ou 
On first time visiting this URL, an output similar to the one given below would be displayed 
h2); 
out.println(/body); out.println(/html); out.close();}}// end RepeatVisitorServlet 
web.xml ?xml version=1.0 encoding=UTF-8? web-app servlet servlet-name RepeatVisitorServlet /servlet-names 
lass 
pingservlet-name RepeatVisitorServlet  
/servlet-mapping /web-app 
tpu 
t On r mins), following 
utp should 
refeshing this page or revisiting it within an hour (since the age of cookie was set to 60ut be expected. 
o
Web Design  Development – CS506 VU 
© Copyright Virtual University of Pakistan 
303 
Example Code2: Online Book Store using cookies A sc f online book store is goin 
aledown version ontain the session. 
g to be built using cookies. For the first time, cookies 
will be used to mai 
Three b g with check boxes. User can select any check box to add the 
boo art of the application is, it remembers the books previously selected by the 
user. 
“Yo a were added to cart one after another. The important thing is server 
that remembers the previously added books by the same user and thus maintains the session. Session 
managem 
ooks will be displayed to the user alon 
k in the shopping cart. The he 
The following figure will help you understand the theme of this example. Books displayed under the heading of 
u hve selected the following books” 
ent is accomplished using cookies. Online Bo es around one ShoppingCartServlet.java. This Servlet has one global 
HashM . This 
(sessio ores the books selected by the user. 
What’s e part of cookies? Cookie (named JSESSIONID, with unique value) is used to keep the unique 
sessionID associated with each user. This sessionID is passed back and forth between user and the server and 
is used to retrieve the HashMap (sessionInfo) of the user from the global HashMap at the server. It should be 
noted here that, HashMaps of individual users are stored in a global HashMap against a sessionID. 
ok Store example revolv 
ap (globalMap) in which HashMap of individual user (sessionInfo) are going to be stored 
nInfo) HashMap st th
Web Design  Development – CS506 VU 
© Copyright Virtual University of Pakistan 
304 
ShoppingC 
import java.io.*;import java.net.*;import 
javax.servlet.*;import javax.servlet.http.*; 
public class ShoppingCartServlet extends HttpServlet { 
ap(); 
ion, IOException{ 
se); 
} 
hod. 
t(HttpServletRequest request, 
HttpServletResponse response)throws ServletException, IOException{ 
/ 
HttpServletResponse response) 
throw 
response.setContentType(text/html;charset=UTF-8); 
hMap 
s used to determine whether browser// has send any cookie named 
JSESSIONID 
is visiting the site for the first time. 
// make a unique string 
sID = makeUniqueString(); 
artServlet.java 
// used to generate a unique value w 
hich is // used as a cookie value 
public static int S_ID = 1; 
// used to store HashMaps of indiviual users public static HashMap globalMap = new HashM// Handles the HTTP GET method. 
protected void doGet(HttpServletRequest request, 
HttpServletResponse response)throws ServletExceptprocessRequest(request, respon 
// Handles the HTTP codePOST/code metprotected void doPos 
processRequest(request, response); } 
/ called from both doGet()  doPost() 
protected void processRequest(HttpServletRequest request, 
s ServletException, IOException { 
// declaring user's HasHashMap sessionInfo = null;String sID = ; // method findCookie i 
Cookie c = findCookie(request); 
// if no cookies named JSESSIONID is recieved, means that// userif (c == null) {
Web Design  Development – CS506 VU 
© Copyright Virtual University of Pakistan 
305 
// creating a HashMap where books selected by the// user will be stored 
; 
// add the user's HashMap (sessionInfo) into the// globalMap against unique string i.e. sID 
// create a cookie named JSESSIONID alongwith 
Cookie sessionCookie = new Cookie(JSESSIONID, sID); 
respon 
} else { 
/ retrieve a HashMap from the globalMap 
against// cookie value i.e. unique string which is your//sessionID 
alMap.get( c.getValue() ); 
} 
PrintWriter out = response.getWriter(); 
u 
// user will submit the fr 
out.println(form action= + url + +h3input type=checkbox name=firstCB value=firstCB 
/ + java core servlts/h3 +br+ 
“h3input type=checkbox name=secondCB value=secondCB / + 
 java how to program/h3 + 
br+ 
h3input type=checkbox name=thirdCB value=thirdCB / + 
 java complete reference/h3 + 
br+ 
input type=submit value=Add to Cart / + 
/from 
); 
out.println(br/); 
out.println(h1You have selected followig books/h1); 
out.println(br/); 
sessionInfo = new HashMap() 
globalMap.put(sID, sessionInfo); 
// value of sID i.e. unique string 
// add the cookie to the response se.addCookie(sessionCookie); 
// if cookie is found named JSESSIONID,/ 
sessionInfo = (HashMap) glob 
out.println(html); 
out.println(head); out 
.println(titleShooping Cart Example/title); t.println(/head); 
oo 
ut.println(body); out.println(h1Online Book Store/h 
1); 
String url =http://localhost:8084/cookiesessionex/shoppingcartex; 
om to the same servlet
Web Design  Development – CS506 VU 
© Copyright Virtual University of Pakistan 
306 
//reteriving params of check boxes 
ook = request.getParameter(firstCB); 
if ( fBook != null  fBook.equals(firstCB) ) { 
sessionInfo.put(firstCB, java core servlets); 
} 
rogram);} 
// user's HashMap i.e. sessionInfo 
if (tBook != null  tBook.equals(thirdCB)){sessionInfo.put(thirdCB, java 
// the user's HashMap i.e. sessionInfo 
out.close(); 
} // end processRequest() // method used to generate a unique string 
public String makeUniqueString(){return ABC + S_ID++;} 
// returns a reference global HashMap. 
public static HashMap findTableStoringSessions(){return globalMap;} 
/ method used to find a cookie named JSESSIONID 
ttpServletRequest request){ 
me().equals(JSESSIONID)){// doSomethingWith cookiereturn 
} 
// used to print the books currently stored in// user's HashMap. i.e. sessionInfo 
String fB 
String sBook = request.getParameter(secondCB); String tBook = request.getParameter(thirdCB); 
// if first book is selected then add it to // user's HashMap i.e. sessionInfo 
// if second book is selected then add it to 
// user's HashMap i.e. sessionInfo 
if (sBook != null  sBook.equals(secondCB)){sessionInfo.put(secondCB, java how to p// if third book is selected then add it to 
complete reference);} // used to display the books currently stored in 
printSessionInfo(out, sessionInfo); out.println(/body); out.println(/html); 
/ 
public Cookie findCookie(H 
Cookie[] cookies = request.getCookies(); if (cookies != null) { 
for(int i=0; icookies.length; i++) { Cookie c = cookies[i]; if (c.getNa 
c; 
} } } return null;
Web Design  Development – CS506 VU 
© Copyright Virtual University of Pakistan 
307 
public void printSessionInfo(PrintWriter out,HashMap sessionInfo){ 
String title = ; 
title= (String)sessionInfo.get(firstCB); 
if (title != null){ 
out.println(h3 + title +/h3); 
} 
title= (String)sessionInfo.get(secondCB); 
out.println(h3 + title +/h3); 
onInfo.get(thirdCB);if (title != 
null){out.println(h3 + title +/h3);}} 
web.xml 
?x 
we 
servlet s 
/se 
servlet-mapping 
servlet-name ShoppingCart /servlet-name 
References: 
if (title != null){ 
} title= (String)sessi 
} // end ShoppingCartServlet 
ml version=1.0 encoding=UTF-8? b-app ervlet-name ShoppingCart /servlet-nameservlet-class ShoppingCartServlet /servlet- cla 
ss rvlet 
url-pattern /shoppingcartex /url-pattern 
/servlet-mapping /web-app ƒ Java A Lab Course by Umair Javed 
lets and JSP by Marty Hall 
ƒ Stanford Course – Internet Technologies 
mentation 
ƒ Core Serv 
ƒ Java API docu
Web Design  Development – CS506 VU 
© Copyright Virtual University of Pakistan 
308 
Lesson 32 
In the last handout we have discussed the solutions for session tracking and talked about one important 
mechan ient machine and 
later retrieve it. Now we will see acility to maintain a session between 
user’s requests. These are URL R we will discuss a session tracking 
API provided by java. 
URL Rewriting 
URL rewriting provides king. With URL rewriting, the parameter that we want to 
pass bac een the server and client is appended to the URL. This appended information can be 
retrieve by parsing the URL. This information can be in the form of: 
. Added parameters, or 
Note: Due to limited space available in r s usually limited to a unique 
session ID. 
The following URLs have been rewritten to pass the session ID 123 
. Original – 
. Extra path i ://server: port/servlet/rewrite/123 
. Added parameters – http://server: port/servlet/rewrite?id=123 
. Custom change – rewrite;$id$123 
Disadvantages of URL rewriting 
The following D are considerable: - 
ƒ What if the user bookm e if server is not assigning a unique 
session 
ƒ Every URL on a page, which needs the session information, must be rewritten each time page is 
served, which can cause 
o 
o 
ƒ Unlike c 
ƒ This mechani 
Example Code: OnlineBookStore using URL Rewriting 
This is the mod y, however you can add in on your 
own) that is built using cookies in the last handout. Another important difference is books are displayed in the 
form of hyperlin to maintain session information. 
How to make Query String 
Before jumping on to example, one important technique is needed to be learned i.e. making on query string. If 
you ever noticed the URL of a servlet in a browser that is receiving some HTML form values, also contains the 
HTML fields name with . 
Now, if you want to pass some attribute and values along with URL, you can use the technique of query string. 
Session Tracking 2 
ism cookies in detail. We said cookies allow the server to store information on a cl 
two more mechanisms that provide us fewriting and Hidden Form Fields. After that 
another way for session trac 
k and forth betw 
. Extra path information, 
. Some custom, server-specific URL change 
ewriting a URL, the extra information i 
http://server: port/servlet /rewrite 
nformation – http 
http://server: port/servlet/ 
isadvantages of URL rewriting, 
arks the page and the problem get worsid. 
Computationally expensive Can increase communication overhead 
ookies, state information stored in the URL is not persistent sm limits the client interaction with the server to HTTP GET request. 
ified version of online book store (selling two books onl 
k instead of check boxes. URL rewriting mechanism is used 
values entered/selected by the user
Web Design  Development – CS506 VU 
© Copyright Virtual University of Pakistan 
309 
Attribute names lues are written in pair form after the ?. For example, if you want to send attribute 
“name” and its value “ali”, the URL will look like 
ƒ Original URL 
http://server:por 
ƒ After adding parameters 
http://server:port/servletex/register ?name=ali 
If you want to add more t equent parameters are separated by  sign. For example 
ƒ Adding two parameters – 
http://server:port/servletex/register ?name=aliaddress=gulberg 
URLRewriteServlet.java 
port java.io.*;import java.net.*;import 
javax.servlet.*;import javax.servlet.http.*; 
public class URL 
// used to gener ch is 
// used as 
public stat 
// used to users 
public static HashMap globalMap = new HashMap(); 
// Handles 
protected void doGet(HttpServletRequest request, 
HttpServletRespons 
proce 
} 
// Handles 
protected voi 
HttpServletResponse response)throws ServletException, IOException{ 
processRequest(reques 
} 
// called from both doGet()  doPost()protected void 
pro ttpServletRequest request,HttpServletResponse 
response)throws ServletException, IOException { 
g user's HashMap 
null; 
g sessionId 
String sID = request.getParameter(“JSESSIONID”); 
/* if parameter JSESSIONID is received, means that user isvisiting the site for the first time. */ 
if (sID == null) 
{ 
ue string 
and va 
t/servletex /register 
han one parameter, all subs 
im 
RewriteServlet extends HttpServlet { 
ate a unique value whia cookie value 
ic int S_ID = 1; 
store HashMaps of indiviual 
the HTTP GET method. 
e response)throws ServletException, IOException{ ssRequest(request, response); 
the HTTP codePOST/code method. d doPost(HttpServletRequest request, 
t, response); 
cessRequest(H 
// declarin 
HashMap sessionInfo = // readin 
// make a uniq
Web Design  Development – CS506 VU 
© Copyright Virtual University of Pakistan 
310 
sID = makeUniqueString(); 
// creating a HashMap where books selected by the 
// user will be stored 
sessionInfo = new HashMap(); 
d the user's HashMap (sessionInfo) into the 
// globalMap against unique string i.e. sID 
ap.put(sID, sessionInfo); 
}else { 
eve a HashMap from the globalMap against 
unique string which is your sessionID 
ashMap)globalMap.get(sID); 
} 
resp -8); 
Prin riter out = response.getWriter(); 
html); 
out.println(head); 
out.println(titleShopping Cart Example/title); 
l =http://localhost:8084/urlbookstore/urlrewriteservlet?JSESSIONID= 
+ 
String s ookstore/urlrewriteservlet?JSESSIONID= 
out.p re servlts /a /h3 
+br+ 
h3a href= + secondurl +  + 
 java how to program /a /h3 + 
br+ 
); 
out.println(br/); 
out.println(h1You have selected following books/h1); 
out.println(br/); 
//retrieving params that are emebded in URLs 
String fBook = request.getParameter(firstCB);String sBook = 
request.getParameter(secondCB); 
// ad 
globalM 
// if parameter JSESSIONID has some value // retri 
// sID i.e. 
sessionInfo = (H 
onse.setContentType(text/html;charset=UTFtW 
out.println( 
out.println(/head); out.println(body); 
out.println(h1Online Book Store/h1); // Making three URLS by using query string mechanism// The attributes/parameters are JSSESSIONID and book name (like// firstCB) along with values sID and book name respectively 
String firstur 
sID + firstCB=firstCB; econdurl =http://localhost:8084/urlb 
+sID + secondCB=secondCB; rintln(h3a href= + firsturl +  +  java co
Web Design  Development – CS506 VU 
© Copyright Virtual University of Pakistan 
311 
// if first book is selected then add it to 
// user's HashMap i.e. sessionInfo 
if ( fBook != null  fBook.equals(firstCB) ) { 
sessionInfo.put(firstCB, java core servlets); 
} 
/ s 
if (sBook != null  sBook.equals(secondCB)){ 
// used to display the books currently stored in 
// the user's HashMap i.e. sessionInfo 
printSessionInfo(out, sessionInfo); 
out.p 
out.cl 
used to generate a unique string 
 + S_ID++;} 
// retur 
public st Sessions(){return globalMap;} 
/ used to print the books currently stored in// user's HashMap. i.e. sessionInfo 
ionInfo){ String title = ; 
title= (String)sessionInfo.get(firstCB); 
out.println(h3 + title +/h3); 
t(secondCB); 
} // 
// if second book is selected then add it to 
/ uer's HashMap i.e. sessionInfo 
sessionInfo.put(secondCB, java how to program); } 
out.println(/body); 
rintln(/html); 
ose(); 
} // end processRequest() // methodpubli 
c String makeUniqueString(){return ABC 
ns a reference global HashMap. atic HashMap findTableStoring 
/ 
public void printSessionInfo(PrintWriter out,HashMap sess 
if (title != null){ 
} 
title= (String)sessionInfo.geif (title != null){ 
out.println(h3 + title +/h3); 
} end URLRewriteServlet
Web Design  Development – CS506 VU 
© Copyright Virtual University of Pakistan 
312 
web.xml 
?xml version=1.0 encoding=UTF-8? 
web-app 
s Servlet 
/ 
serv meurl-pattern 
/u 
/se 
/web-app 
Hidden 
HTML nt that looks like the following: 
INP 123 / 
Hidden appearance of HTML page. They actually contain the information that 
is neede Thus, hidden fields can also be used to store information (like sessionid) in 
order to 
ervlet servlet-name URLRewriteServlet /servlet-nameservlet-class URLRewrite/servlet-class servlet 
let-mappingservlet-name URLRewriteServlet /servlet-na 
rlrewriteservlet /url-pattern rvlet-mapping 
Form Fields forms can have an elemeUT TYPE=HIDDEN NAME=sessionid VALUE= Forms Fields do not affect the d to send to the server. maintain session. 
In the above figure you can see the use of Hidden form fields for storing particular information. 
Java Solution for Session Tracking 
lent solution to all the problems that occurred in tracking a session. The Servlet API 
ndle session tracking. In other words, servlets 
king. 
t. HttpSession tacking API built on top of URL rewriting and 
ism is hidden and most application server uses cookies but 
ookies are unsupported or explicitly disabled. Using 
ervlets is straightforward and involves looking up the session object associated with the 
curr ssion, 
Java provides an excelprovides several methods and classes specifically designed to hahave built in session tracSessions are r 
epresented by an HttpSession objeccookies. All cookies and URL rewriting mechan 
automatically revert to URL rewriting when c 
HttpSessionAPI in s 
ent request, creating new session object when necessary, looking up information associated with a se
Web Design  Development – CS506 VU 
© Copyright Virtual University of Pakistan 
313 
storing information in a session, and discarding completed or abandoned sessions. 
Wor 
Let’s 
1. Ge 
To ge t, we call the getSession() method of HttpServeltRequestthat returns the 
obje 
HttpSession sess = request.getSession(true); 
If true is passed to the getSession() method, this method returns the current session associated with this 
request, or, if the request does not have a session, it creates a new one. We can confirm whether this 
sess eturned by using isNew() method of HttpSession. In case of 
passing false, null is returned if the session doesn’t exist. 
2. Stori ion in a Session 
ion object (sess), we use setAttribute() method of HttpSession class. Session 
ou can store number of 
a Session 
To retrieve back the stored information from session object, getAttribute()method of HttpSession class is 
used. For example, 
Note: -getAttribute() method returns Object 
4. Terminat 
, session gets terminated automatically. We can see its maximum activation time 
eInterval() method of HttpSession class. However, we can also terminate any 
For this, we need to call invalidate() method of HttpSessionclass as shown 
below. 
sess.invalidate() 
xample Code: Showing Session Information 
To understand HttpSession API properly we need to have a look on an example. In this example, we will get 
ject and check whether it is a new user or not. If the user is visiting for the first time, we will 
print “Welcome” Moreover, we will print the session 
inf 
im 
import java.net.*; 
king with HttpSession have a look on HttpSession working step by step. t 
ting the user’s session object t the user’s session objec 
ct of HttpSession 
ion object (sess) is newly created or r 
ng informat 
To store information in Sess 
object works like a HashMap, so it is able to store 
any java object against key. So ykeys and their values in pair form. For example, 
sess.setAttribute(“sessionid”, ”123”); 
3. Looking up information associated with 
String sid=(String)sess.getAttribute(“sessionid”); type, so typecast is required. 
ing a Session am 
After theount of timeby using getMaxInactiv 
existing session manually. 
E 
the session ob 
and if we find the old one, we’ll print “Welcome Back”. he number of access 
ormation and count tes for every user ; 
port java.io.*
Web Design  Development – CS506 VU 
© Copyright Virtual University of Pakistan 
314 
im 
im ; 
wSessionServlet extends HttpServlet { 
// Handles the HTTP codeGET/code method. 
protected void doGet(HttpServletRequest request, HttpServletResponse response) 
ws ServletException, IOException 
{ 
processRequest(request, response); 
d doPost(HttpServletRequest request, HttpServletResponse response) 
throws ServletException, IOException 
processRequest(request, response); 
} 
ServletRequest request, HttpServletResponse response) 
throws ServletException, IOException 
{ 
// used for displaying message (like Welcomem, Newcomer) to user 
private String heading; 
response.setContentType(text/html); 
// Getting session object 
HttpSession session = request.getSession(true); 
/* Getting stored information using getAttribute() method */ 
port javax.servlet.*; 
port javax.servlet.http.* 
public class Sho 
thro 
} 
// Handles the HTTP codePOST/code method. 
protected voi 
{ 
// called from both doGet()  doPost() 
protected void processRequest(Http
Web Design  Development – CS506 VU 
© Copyright Virtual University of Pakistan 
315 
Integer accessCount = (Integer)session.getAttribute(sessionCount); 
/* If user comes for the first ti ill be 
assigned null, so we can guess easily that this a new user */ 
if (accessCount == null) 
{ 
{ 
heading = Welcome Back; 
// Incrementing the value 
accessCount = new Integer(accessCount.intValue() + 1); 
} 
/* Storing the new value of accessCount in the session using 
ute() method */ 
Getting the PrintWriter 
PrintWriter out = response.getWriter(); 
 H3 Session ID:  + session.getId() + /H3 + 
me, accessCount w 
accessCount = new Integer(1); heading = Welcome, Newcomer; } else 
setAttrib 
session.setAttribute(sessionCount, accessCount); 
// 
/*Generating HTML tags using PrintWriter to print session info 
and no of times this user has accessed this page */ out.println(HTML +  BODY +  h1Session Tracking Example/h1 +  H2Information on Your Session:/H2n +
Web Design  Development – CS506 VU 
© Copyright Virtual University of Pakistan 
316 
 H3Number of Previous Accesses:  + accessCount + 
/BODY + 
 /HTML 
); 
} // d 
eb.xml 
ing=UTF-8? 
s e ShowSession /servlet-nameservlet-class ShowSessionServlet /servlet-apping 
e ShowSession /servlet-name 
url-pattern /showsession /url-pattern 
tpSession – Behind the scenes 
method, there is a lot going on behind the scenes. For every user, a unique session 
is assigned automatically. As the server deals with lot of users at a time, this ID is used to distinguish one 
ƒ Option 1: If the browser supports cookies, the Servlet will automatically creates a session cookie and 
store the session ID within that cookie. 
et 
 /H3 + 
 
//Closing the PrintWriter stream out.close(); } // end processRequest 
en ShowSessionServlet class 
w 
?xml version=1.0 encodweb 
-app ervlet servlet-namclass 
/servlet servlet-m servlet-nam 
/servlet-mapping /web-app 
Ht 
When we call getSession() 
ID 
user from another. Now here is the question, how this ID sends to the user? Answer is, there are two options 
ƒ Option 2: If the first option fails because of browser that does not support cookies then the Servlwill try to extract the session ID from the URL
Web Design  Development – CS506 VU 
© Copyright Virtual University of Pakistan 
317 
Encoding URLs sent to Client Servlet will automatically switch to URL rewriting when cookies are not supported or disabled by the clienWhen Session Tracking is based on URL rewriting, it requires additional help from the Servlets. Forto support session tracking via URL rewriting, it has to rewrite (encode) every local URL before sending ithe client. Now see how this encoding work 
t. 
a Servlet 
t to 
s 
perform encoding 
ƒ String encodeURL(String URL) 
Cookies are disabled, both methods encode (rewrite) the specific URL to include the session ID and returns 
new URL. However, if cookies are enabled, the URL is returned unchanged. 
Difference between encodeURL() and encodeRedirectURL() 
encodeURL() is used for URLs that are embedded in the webpage, that the servlet generates. For example, 
let/sessiontracker”; 
String eURL = response.encodeURL(URL); 
” ” + eURL + ” ” …… /A”); 
Whereas ers yours site is in sendRedirect() call. For 
example, 
String URL = ”/servlet/sessiontracker”; 
String eURL = response.encodeRedirectURL(URL); 
Respons Redirect(eURL); 
Example Code: OnlineB 
This book store is mod rewriting mechanism. Here, 
HttpSession will be used to maintain session. 
ShoppingCartServlet.java 
import java.io.*;import ja 
javax.servlet.*;import javax.servlet.http.*; 
public class ShoppingCartServlet extends HttpServlet { 
// Handles the HTT 
protected void doG 
HttpServletResponse response)throws ServletException, IOException{ 
processRequest(request, response); 
} 
// Handles the HTTP codePOST/code method. 
protected void doPost(HttpServletRequest request, 
HttpServletResponse respon 
HttpServletResponse provides two methods to 
ƒ String encodeRedirectURL(String URL) 
If 
the 
String URL = ”/serv 
out.println(“A HREF= 
encodeRedirectURL() is used for URLs that ref 
e.send 
ookStore using HttpSession 
ified version of last one, which is built using URL 
va.net.*;import 
P GET method. et(HttpServletRequest request, 
se)throws ServletException, IOException{
Web Design  Development – CS506 VU 
© Copyright Virtual University of Pakistan 
318 
processRequest(request, response); 
} 
// called from both doGet()  doPost()protected void 
processRe est request,HttpServletResponse response)throws 
ServletException, IOException { 
response.setContentType(text/html;charset=UTF-8); 
HttpSession session = request.getSession(true); 
PrintWriter out = response.getWriter(); 
out.println(html); 
out.println(head); 
out.println(titleShopping Cart Example/title); 
out.println(/head); 
out.println(body); 
out.println(h1Online Book Store/h1); 
// Second URL built using query string, representing second book// Note that parameter name is still book, 
so t parameter 
String secondURL =http://localhost:8084/urlrewritebookstore/shoppingcart?book=second 
// c 
String eURL1 = response.encodeURL( firstURL );String eURL2 = 
RL ); 
out.println(h3a href= + eURL1 +  +  java core servlets /a /h3 +br+ 
h3a href= + eURL2 +  + 
o Program /a /h3 
); 
out.println(br/); 
out.println(h1You have selected following books/h1); 
out.println(br/); 
//retrieving params that are emebded in URLs 
String fBook = sBook = 
request.getParameter(secondCB); 
out.println( 
out.println(h1You have selected following books/h1); 
out.println(br/); 
//retrieving param that is embedded into URL 
String book = request.getParameter(book); 
if (book != null){ 
// if firstURL, value of first hyperlink is clicked// then storing the book into session object against 
quest(HttpServletRequ 
// First URL built using query string, representing first book String firstURL =http://localhost:8084/urlrewritebookstore/shoppingcart?book=first 
hat later we need // to read only this 
Enoding URLs 
response.encodeURL( secondU 
 java How t 
request.getParameter(firstCB);String 
br/);
Web Design  Development – CS506 VU 
© Copyright Virtual University of Pakistan 
319 
fBook 
if (book.equals(first)){session.setAttribute(fBook, java core 
servlets);} 
// if secondURL, value of second hyperlink is clicked// then storing the book into session object 
against sBook 
else if(book.equals(second)){session.setAttribute(sBook, java 
how to program);} 
}//outer if ends 
// used to display the books currently stored in 
// the HttpSession object i.e. session 
printSessionInfo(out, session); 
out.println(/body); 
out.println(/html); 
out.close(); 
} // end processRequest() 
if (title != null){ 
out.println(h3 + title +/h3); 
e against key sBook from session,// if exist displays it 
title= (Stri ttribute(sBook); 
tle +/h3); 
} 
} // end printSessionInfo 
web.xml 
?xml 
web- 
servlet servlet-name ShoppingCartServlet /servlet-name 
servlet-class 
/s 
// used to display values stored in HttpSession object public void printSessionInfo(PrintWriter out,HttpSession session){ String title = ; // reading value against key fBook from session,// if exist displays it title= (String)session.getAttribute(fBook); 
} 
// reading valung)session.getA 
if (title != null){ println(h3 + ti 
out. 
} // end ShoppingCartServlet 
version=1.0 encoding=UTF-8? app 
 ShoppingCartServlet /servlet-class ervlet
Web Design  Development – CS506 VU 
© Copyright Virtual University of Pakistan 
320 
servlet-mappingservlet-name ShoppingCartServlet /servlet-name 
 art /url-pattern 
/s 
/web-app 
Some 
Now let’s explore some methods of HttpSessionclass 
. setAttr 
. getAttribute(String) 
d value from a session object. It returns nullif no value is associated with the 
. re 
d removes values associated with the name 
. getId( ) 
This method returns the unique identifier of this session 
. getCreationTime( ) 
This method returns time at which session was first created 
. getMaxInactiveInterval( ) , setMaxInactiveInterval(int) 
To get or s nvalidated. 
References: 
url-pattern /shoppingcervlet-mapping 
Methods of HttpSession 
ibute(String, Object) This method associates a value with a name. 
Extracts previously storegiven name moveAttribute(String) This metho 
et the amount of time session should go without access before being i 
ƒ Java A Lab Course by Umair Javed 
ƒ Core Servlets and JSP by Marty Hall 
ƒ Stanford Course – Internet Technologies 
ƒ Java Tutorial on Servlets 
http://java.sun.com/j2ee/tutorial/1_3-fcs/doc/Servlets11.html 
ƒ Java API documentation
Web Design  Development – CS506 VU 
© Copyright Virtual University of Pakistan 
321 
Lesson 33 
AddressBook Case Study 
Using Sevlets 
Design Process 
In this handout, we will discuss the design process of a simple address book. A step by step procedure of 
creating a simple address book is given below. 
Layers  Web Application 
As discussed previously, normally web applications are partitioned into logical layers. Each layer performs a 
specific functionality which should not be mixed with other layers. For example data access layer is used to 
interact with database and we do not make any direct calls to database from the presentation layer. Layers are 
isolated from each other to reduce coupling between them but they provide interfaces to communicate with 
each other. 
Simplified view of a web application and its layers 
-Presentation Layer 
Provides a user interface for client to interact with application. This is the only part of application visible to 
client. 
-Business Layer 
The business or service layer implements the actual business logic or functionality of the application. For 
example in case of online shopping systems this layer handles transaction management. 
- Data Layer 
This layer consists of objects that represent real-world business objects such as an Order, 
OrderLineItem, Product, and so on. It also encapsulates classes which are used to interact with the 
data providing services such as databases, other web services etc. 
In our case study of address book, we will also try to make use of the layered architecture. We will create a 
separate layer for working with data, and our presentation and business logic will be merged into servlets. It 
means that we will not have separate layers for presentation and business rather one layer (formed by servlets) 
will do the job of both presentation and business logic. The extent to which you divide your application into 
layers depends upon the size of the application and some other factors such as scalability, portability etc.
Web Design  Development – CS506 VU 
© Copyright Virtual University of Pakistan 
322 
Step 1 
ƒ Create a database (AddressBook) 
ƒ Make a table named Person according to the figure shown below. It has columns name, address, phomeNum 
Step 2 The next step is to create a class that can hold the information of a single person. Remember we have stored 
the information in the database, now when we extract this information from the database as a result of some 
search, we will require some object to store the data for that particular person. The PersonInfo class will be 
used at that point to store the retrieved data and transport it to presentation layer. Also we extend this 
application and add the functionality of “AddingNewContacts” in the database. The PersonInfo class can be 
used to transport data from front end to the database. 
ƒ Make a PersonInfo class with the following consideration 
ƒ It has three three attributes: name, address, ph. No. 
ƒ It has a parameterized constructor which takes in the above mentioned parameters 
ƒ Override the toString() method 
//File: PersnInfo.java 
String name; 
s; 
pub g pn) { 
nam n; 
public String toString( ){ 
public class PersonInfo { 
String addres 
String phoneNum; 
lic PersonInfo(String n, String a, Strin 
e = 
address = a; phoneNum = pn; }
Web Design  Development – CS506 VU 
© Copyright Virtual University of Pakistan 
323 
return Name:  + name +  Address:  + address +  Phone No:  + phoneNum; 
} 
}// end class PersonInfo 
Note: To keep the code simple, attributes (name, address  phoneNum) are not declared as private, which is 
indeed not a good programming approach. 
Step 3 
Now we will create a class that will be used to interact with the database for the search, insert, update and 
delete operations. We will call it PersonDAO where DAO stands for the “data access object”. The 
PersonDAO along with the PersonInfo class forms the data layer of our application. As you can see that these 
two classes do not contain any code related to presentation or business logic (There is not much of business 
logic in this application anyway). So PersonDAO along with PersonInfo is used to retrieve and store data in 
this application. If at some stage we choose to use some other way of storing data (e.g. files) only the 
PersonDAO class will change and nothing else, which is a sign of better design as compared to a design in 
which we put every thing in a single class. 
ass which contains: 
eturns 
PersonInfo object after searching the information of the specified person from the database. 
//File: PersonDAO.java 
// method searchPerson 
public PersonInfo searchPerson(String sName){ 
PersonInfo person = null; 
try { 
Class.forName(sun.jdbc.odbc.JdbcOdbcDriver); 
String url = jdbc:odbc:AddressBookDSN; 
Connection con = DriverManager.getConnection(url); 
String sql = SELECT * FROM Person WHERE name = ?; 
PreparedStatement pStmt = con.prepareStatement(sql); 
So, Make a PersonDAOcl 
ƒ a searchPerson(String name) method that first establishes a connection to the database and r 
import java.sql.*; 
public class PersonDAO {
Web Design  Development – CS506 VU 
© Copyright Virtual University of Pakistan 
324 
pStmt.setString(1 
String add = rs.getString(address); 
um = rs.getString(phoneNum); 
Num); 
ch(E 
System.out.println(ex); 
} 
Step 4 
an interface through which he/she can enter the input. 
The Sear s job for us, It will collect the data from the user and submit that data 
to another class. The SearchPersonServlet forms the part of our presentation layer. As you can see that it is 
bein form to the user and collect input. 
ƒ Write Se hPersonS 
to search in address book 
//File: Searc Pe Serv 
port java.io.*; 
import java.net.*; 
import javax.servlet.*; 
import javax.servlet.http.*; 
, sName); 
ResultSet rs = pStmt.executeQuery(); if (rs.next( ) ) { String name = rs.getString(name); 
String pN 
person = new PersonInfo(name, add, p 
} 
con.close(); 
}catxception ex){ 
return person; }// end method 
} 
To find what user wants to search, we need to give user 
chPesonServlet.java will do thi 
g used to present a 
arcervlet.java 
ƒ Will take input for name ƒ Subitsrequ 
m the est to ShowPersonServlet 
hrsonlet.java 
im
Web Design  Development – CS506 VU 
© Copyright Virtual University of Pakistan 
325 
public class SearchPersonServlet extends HttpServlet { 
xt/html); 
PrintWriter out = response.getWriter(); 
out.println(html + body +h1 Address Book /h1 +form action=showperson 
n of 
// ShowPersonServleth2 Enter name to 
pName / br/ +input 
n / +/form +/body +/html 
out.close(); 
} 
// Handles the HTTP GET method.protected void 
(HttpServletRequest request,HttpServletResponse response) 
throws ServletException, IOException { 
// Handles the HTTP POST method protected void doPost(HttpServletRequest 
request,HttpServletResponse response) 
throws ServletException, IOException { 
proc sR 
} 
} 
Step 5 
The data submitted by the SearchPersonServlet will be submitted to another servlet i.e. ShowPersonServlet, 
which will interact with the DataLayer(Business logic processing) collects the output and show it to the user. 
The ShowPersonServlet forms the part of our presentation layer and business layer. As you can see that it is 
being used to do processing on the incoming data and giving it to data layer (business layer) and present 
data/output to the user (presentation layer) 
. Write ShowPersonServlet.java 
. Receives request from SearchPersonServlet 
. Instantiate objects of PersonInfo and PersonDAO class 
. Call searchPerson() method of PersonDAOclass 
. Show results 
//File : ShowPersonServlet.java 
import java.io.*; 
import java.net.*; 
import javax.servlet.*; 
import javax.servlet.http.*; 
protected void processRequest(HttpServletRequest request,HttpServletResponse esponse) throws ServletException, IOException { 
response.setContentType(te 
 + // showperson is alias or // url patter 
search /h2 br/ +inputpe=submit value=Search Perso 
type=text name= 
ty); 
doGet 
processRequest(request, response);} 
esequest(request, response);
Web Design  Development – CS506 VU 
© Copyright Virtual University of Pakistan 
326 
public class ShowPersonServlet extends HttpServlet { 
protected void processRequest(HttpServletRequest request,HttpServletResponse response) throws 
ServletException, IOException { 
response.setContentType(text/html); 
PrintWriter out = response.getWriter(); 
String name = request.getParameter(pName); 
// creating PersonDAO object, and calling searchPerson() method 
PersonDAO personDAO = new PersonDAO(); 
PersonInfo person = personDAO.searchPerson(name); 
out.println(html); 
out.println(body); 
out.println(h1Search Results/h1); 
if (person != null){ 
out.println(h3+ person.toString() +/h3 ); 
} 
else{ 
out.println(h3Sorry! No records found/h3 ); 
out.close(); 
} 
response)throws ServletException, IOException 
{processRequest(request, response);} 
// Handles the HTTP POST method.protected void 
doPost(HttpServletRequest request,HttpServletResponse 
response)throws ServletException, IOException 
} out.println(/body); out.println(/html); 
// Handles the HTTP GET method.protected void doGet(HttpServletRequest request,HttpServletResponse 
{processRequest(request, response); } } // end ShowPersonServlet
Web Design  Development – CS506 VU 
© Copyright Virtual University of Pakistan 
327 
Sequence Diagram: Address Book (search use case)
Web Design  Development – CS506 VU 
© Copyright Virtual University of Pakistan 
328 
Package 
is put all java files 
to one k, easy and harmless. However if our small project gets bigger, and 
es into the same directory would be a nightmare for us. In 
java we can avoid this sort of problem by using Packages. 
What is a package? 
organized for convenience in the same directory to avoid the name 
es according to 
packaging is the 
Many times when we get a chance to work on a small project, one thing we intend to do toin single directory (folder). It is quic 
the number of files is increasing, putting all these fil 
In simple terms, a set of Java classes 
collisions. Packages are nothing more than the way we organize files into different directoritheir functionality, usability as well as category they should belong to. An obvious example of JDK package from SUN (java.xxx.yyy) as shown below: Figure. Basic structure of JDK package 
Basically, file in e dire nality from those of another directory. 
For example, files in java.i t files in java.net package give us the way 
to deal with t e Network. 
Packaging al h s us t ollision when we use the same class name as that of others. For 
example, if we have a class s name would crash with the ArrayList class from JDK. 
Howeve ens because JDK use java.util as a package name for the ArrayList class 
(java.util.ArrayList). So our ArrayList class can be named as ArrayList or we can put it into another package 
like com.mycompany.ArrayList without fighting with a ne. The benefits of using package reflect the ease of 
maintenance, organization, and increase collaboration among developers. Understanding the concept of 
package will also help us manage and use files stored in jar files in more efficient ways. 
How to create a package 
Suppose we have a file called HelloWorld.java, and we want to put this file in a package world. First thing we 
have to do is to specify the keyword package with the name of the package we want to use (world in our case) 
on top of our source file, before the code that defines the real classes in the package, as shown in our 
HelloWorld class below: 
// only comment can be here 
s onctory (or package) would have different functio 
o package do something related to I/O, buh 
soelpo avoid class name c name called ArrayList, it 
r, this never happ 
nyo
Web Design  Development – CS506 VU 
© Copyright Virtual University of Pakistan 
329 
package world; 
System.out.println(Hello World);} 
} 
One thi ate nested subdirectories to represent 
package hierarchy of the class. In our case, we have the world package, which requires only one directory. So, 
we create a directory (folder) world and put it. 
public class HelloWorld { public static void main(String[] args) { 
ng you must do after creating a package for the class is to cre 
our HelloWorld.java into 
Figure: HelloWorld in world package (C:worldHelloWorld.java) 
package 
package can be imported. For example, 
// we can use any public classes inside world package 
import world.*; 
// import all public classes from java.util package 
import java.util.*; 
// import only ArrayList class (not all classes in 
// java.util package) 
rt java.util.ArrayList; 
ote: hile w folders (packages) and to place classes at right 
cation Many orms this job on your behalf. 
How to use 
By using import keyword, all class files reside only in that 
impoNWorking with IDEs, You don’t have to createlos.IDEs (like netBeans® 4.1) perf
Web Design  Development – CS506 VU 
© Copyright Virtual University of Pakistan 
330 
JavaServer Pages (JSP) 
Like Servlets, JSP is also a specification. JSP technology enables Web developers and designers to rapidly 
ges that leverage existing business systems. As 
part of the Java technology family, JSP technology enables rapid development of Web-based applications that 
are platform independent. JSP technology separates the user interface from content generation, enabling 
designers to change the overall page layout without altering the underlying dynamic content. 
The Need for JSP 
ƒ With servlets, it is easy to 
Read form data 
est headers 
headers 
— Use cookies and session tracking 
vlets 
een requests 
Get fun, high-paying jobs 
ƒ Bu 
— Use those println()statements to generate HTML 
tain that HTML 
The JSP Framework 
Use regular HTML for most of the pages 
tags 
ed 
ent to produce a JSP file. 
develop and easily maintain, information-rich, dynamic Web pa 
— — Read HTTP requ — Set HTTP status codes and response 
— Share data among ser — Remember data betw 
— t, it sure is a pain to 
— Main 
— 
— Mark servlet code with special 
— Entire JSP page gets translated into a servlet (once), and servlet is what actually gets invok(for each request) — The Java Server Pages technology combine with Java code and HTML tags in the same docum 
AagSP over Competing Technologies dvant es of J 
ƒ 
e for dynamic part i.e. java 
ltiple servers and operating systems 
ƒ 
ƒ Versus pure servlets 
— JSPs provide more convenient way to create HTML 
— JSPs can use standard front end tools (e.g., UltraDev) 
— JSPs divide and conquer the problem of presentation and business logic. 
Versus ASP or ColdFusion — JSPs offer better languag 
— JSPs are portable to muVersus PHP 
— JSPs offer better language for dynamic part — JSPs offer better tool support
Web Design  Development – CS506 VU 
© Copyright Virtual University of Pakistan 
331 
Setting Up Your Environment 
In order to create a web-application that entirely consists of JSP pages and Html based pages, the setup is 
fairly simple as compared to a servlet based webapplication. 
ƒ Set your CLASSPATH. No. 
ompile your code. No. 
ƒ Use packages to avoid name conflicts. No. 
ƒ e WEB-INF for servlets No. 
o tomcat_install_dir/webapps/ROOT 
run_install_dir/servers/default/default-app 
ƒ 
ƒ However 
o If you want to use java based classes in an application along with JSPs, previous rules about 
apply to regular classes used by JSP 
Refe 
ƒ air Javed 
ƒ 
http l 
ƒ Java 
.html 
ƒ C 
Put JSP page in special directory, lik 
o j Use special URL to invoke JSP page. No 
CLASSPATH, install dirs, etc, still 
rences: 
Java A Lab Course by Um 
Java Package Tutorial by Patrick Bouklee 
://jarticles.com/package/package_eng.htm 
Server Pages Overview 
http://java.sun.com/products/jsp/overview
Web Design  Development – CS506 VU 
© Copyright Virtual University of Pakistan 
332 
Lesson 34 
Java Server Pages 
g either static or 
dynamic content to a client’s browser. Static content and dynamic content can be intermixed. The examples of 
static content are HTML, XML  Text etc. Java code, displaying properties of JavaBeans and invoking 
dynamic content. 
es a JSP passed through before displaying result. 
As we concluded in our discussion on JSP, JSP is a text based document capable of returnin 
business logic defined in custom tags are all examples of First run of a JSP Figure below shows what phas 
The web browser makes a request to JSP source code. This code is bifurcated into HTML and java code by the 
ler resulting in producing a servlet equivalent 
displayed to the user. It is important to note 
voked for the first time or when the changes have 
been made to JSP. Any later call to JSP does not undergo of compilation phase. 
Benefits of JSP 
Convenient 
• We alre nothing new to be learned to work with JSP. 
Like gets converted into a servlet), provides an 
• extensive infrastructure for 
Tracking sessions 
Reading and sending HTML headers 
Parsing and decoding HTML form data 
Every request for a JSP is handled by a simple JSP java thread as JSP gets converted into a servlet. Hence, the 
te a JSP document is not dominated by starting a process. 
Portable 
Like Servlets, JSP is also a specification and follows a well standardized API. The JVM which is used to execute 
JSP ile 
JSP parser. The java source code is compiled by the Java compicode of a JSP. The servlet code is intermixed with HTML and 
that a JSP only passes through all these phases when it is in 
ady know java and HTML. So • servlets (as seen, ultimately a JSP 
time to execu 
a 
f is supported on many architectures and operating systems.
Web Design  Development – CS506 VU 
© Copyright Virtual University of Pakistan 
333 
Inexpensive 
There are number of free or inexpensive are good for commercial quality websites 
JSP vs. Servlet 
of 
so there are no signs of doGet(), doPost(). 
%@ page import=“java.util.*” % 
 
h 
Current Date is:%= new Date()% 
/h3 
/b 
/html 
Now, compare the JSP code above with the Servlet code given below that is also displaying the current date. 
//File: SearchPersonServlet.java 
import java.net.*; 
import javax.servlet.*; 
ttp.*; 
public cl rvlet extends HttpServlet { 
prot ocessRequest(HttpServletRequest request,HttpServletResponse response)throws 
response 
PrintWriter out = response.getWriter(); 
out.p tln( 
); 
Web Servers that 
Let’s compare JSP and Servlet technology by taking an example that simply plays current date. First have a look on JSP that is displaying a current date. This page more looks like a HTML page except two strangely written lines of codes. Al 
html body 
3 
ody 
import java.io.*; 
import avax.servlet.h 
import java.util.*; ass SearchPersonSe 
ec 
ted void pr 
ServletException, IOException { .setContentType(text/html); 
rin 
“html” + “body” + “h3” + “Current Date is:“ + new Date() + “/h3” + “/body” + “/html”
Web Design  Development – CS506 VU 
© Copyright Virtual University of Pakistan 
334 
// Handles the HTTP GET method. 
st,HttpServletResponse response)throws 
processRequest(request, response); 
} 
protected void doPost(HttpServletRequest request,HttpServletResponse response)throws 
ServletException, IOException { 
processRequest(request, response); } 
} 
Clearly, a lot of code is needed to be written in the case of servlet example to perform a basic job. 
ing elements. 
Directive Elements 
– Provides global control of JSP ……..…………….. %@ % 
ƒ Scripting Elements 
P comments ……………………………………... %----% 
– declarations ……………………………………... %! % 
ce variables  methods 
– expressions ……………………………………... %= % 
• A java code fragment which returns String 
– scriptlets ……………………………………... % % 
Blocks of java code 
ƒ 
– Special JSP tags ……..…………………………….. jsp: .…. / 
We’ll discuss in detail all the ingredients of JSP. This handout will cover only scripting elements, remaining 
ones will be discussed in next handouts. 
protected void doGet(HttpServletRequest reque ServletException, IOException { 
// Handles the HTTP POST method. 
Besides HTML, a JSP may contain the follow 
ƒ 
– JS 
• Used to declare instan 
• 
Action Elements
Web Design  Development – CS506 VU 
© Copyright Virtual University of Pakistan 
335 
Scripting Elements 
Comments 
Comments are ignored by JSP-to-servlet translator. Two types of comments are possibly used in JSP. 
HTML comment: 
These comments are shown in browser, means on taking view source of the web page; these sorts of 
comments can be read. Format of HTML comments is like to: 
!-- comment text-- 
– JSP comment: 
These comments are not displayed in browser and have format like: 
%-- comment text --% 
Expressions 
The format of writing a Java expression is: %= Java expression % 
These express ML page at the place it occurred in 
JSP page Examples of writing Expressions are: 
–  
will print current data  time after converting it to String 
– /h2 
will print the name attribute 
The format of writing a scriptlet is: %= Java code % 
After ening up the sc de can be written inside it. This code is inserted verbatim 
into corresponding servlet. 
ptlet is: 
String n = request.getParameter(“name”); 
out.println(“welcome ” + n); 
% 
iptlet reads the name attribute and prints it after appending “welcome” 
– 
ions are evaluated, after converted to strings placed into HT 
h2 Time: %= new java.util.Date() % /h2 
h2 Welcome: %= request.getParameter(“name”)% 
Scriptlets 
opriptlet tag, any kind of java co 
Example of writing a scri 
% 
The above scr
Web Design  Development – CS506 VU 
© Copyright Virtual University of Pakistan 
336 
Declarations 
laration tag is: %! Java code % 
This tag is used to declare variables and methods at class level. The code written inside this tag is inserted 
verbat into servlet’s 
) variable is: 
– %! 
% 
Example of declaring a class level method is: 
– %! 
public void someMethod ( …… ) { 
……………. 
} 
xample: Using scripting elements 
The next example code consists on two JSP pages namely first.jsp and second.jsp. The user will enter two 
nd after pressing the calculate sum button, able to see the sum of entered numbers 
on sec nd.jsp 
first.jsp 
numbers along with a button. 
html 
body 
eir sum/h1 
!—the form values will be posted to second.jsp -- 
form name = myForm action=second.jsp  
h3 First Number /h3 
e=text name=num1 / 
h3 Second Number /h3 
pe=text name=num2 /br/br/ 
input type=submit value=Calculate Sum / 
/form 
/body 
/html 
The format of writing a dec 
imclass definition. 
Example of declaring a class level (attribute 
private int someField = 5; 
% 
Code E 
numbers on the first.jsp a 
o 
This page only displays the two text fields to enter 
h2Enter two numbers to see th 
input typ 
input ty
Web Design  Development – CS506 VU 
© Copyright Virtual University of Pakistan 
337 
secon 
This nverting the numbers into integers, displays their 
sum. 
html 
o numbers -- 
%-- Declaration--% 
%! 
public int sum(int op1, int op2) { 
return op1 + op2; 
} 
% 
%-- Scripltet--% 
% 
String op1 = request.getParameter(num1);String op2 = 
er(num2); 
int secondNum = Integer.parseInt(op2); 
// calling method sum(), declared above in declartion tag 
res = sum(firstNum, secondNum); 
% 
%-- expression used to display sum --% 
h3Sum is: %=res% /h3 
/body 
/html 
Writing JSP scripting Elements in XML 
Now days, the preferred way for composing a JSP pages is using XML. Although writing JSP pages in old style 
is still heavily used as we had shown you in the last example. Equivalent XML tags for writing scripting 
elements are given below: 
ƒ Comments: No equivalent tag is defined 
ƒ Declaration: jsp:declartion /jsp:declaration 
ƒ Expression: jsp:expression /jsp:expression 
ƒ Scriptlet: jsp:scriptlet /jsp:scriptlet 
It’s important to note that every opening tag also have a closing tag too. The second.jsp of last example is 
given below in XML style. 
d.jsp 
page retrieves the values posted by first.jsp. After co 
body !-- JSP to sum tw 
// declaring a variable to store sum int res; // method helps in calculating the sum 
request.getParametint firstNum = Integer.parseInt(op1);
Web Design  Development – CS506 VU 
© Copyright Virtual University of Pakistan 
338 
? xml version=1.0 encoding=UTF-8? 
jsp:direc t=UTF-8/ 
ere, e.g.: -- 
jsp:element name=text 
jsp:decl on 
public int sum(int op1, int op2) { 
n 
jsp:scri 
tParameter(num1); 
); 
int firstNum = Integer.parseInt(op1); 
m, secondNum); 
/jsp:scriptlet 
jsp:text Sum is: /jsp:text 
jsp:expression res /jsp:expression 
/jsp:body 
/jsp:element 
/jsp:root 
References 
ƒ Java A Lab Course by Umair Javed 
ƒ Core Servlets and JSP by Marty Hall 
jsp:root xmlns:jsp=http://java.sun.com/JSP/Page version=2.0 !-- to change the content type or response encoding change thefollowing line-- 
tive.page contentType=text/xml;charse 
!-- any content can be specified h 
jsp:body 
arati 
int res; 
retu 
rn op1 + op2; } /jsp:declaratio 
ptlet 
String op1 = request.ge 
String op2 = request.getParameter(num2 
int secondNum = Integer.parseInt(op2); 
res = sum(firstNu
Web Design  Development – CS506 VU 
© Copyright Virtual University of Pakistan 
339 
Lesson 35 
e have started JSP journey in the last handout and thoroughly discussed the JSP scripting elements. JSP 
ements and implicit objects will be discussed in this handout. Let’s review JSP journey again to find 
at part we have already covered. 
ƒ Directive Elements 
– Provides global control of JSP ……..…………….. %@ % 
– JSP comments ……………………………………... %----% 
– declarations ……………………………………... %! % 
• Used to declare instance variables  methods 
– 
JavaServer Pages 
W 
directive elout wh 
ƒ Scripting Elements 
• A java code fragment which returns String 
. Action Elements 
– Special JSP tags ……..…………………………….. jsp: .…. / 
We start our discussion from implicit objects. Let’s find out what these are? 
Implicit Objects 
To simplify code in JSP expressions and scriptlets, you are supplied with eight automatically defined variables, 
sometimes called implicit objects. The three most important variables are request, response  out. Details of 
these are given below: 
– request 
This variable is of type HttpServletRequest, associated with the request. It gives you access to the 
request parameters, the request type (e.g. GET or POST), and the incoming HTTP request headers 
(e.g. cookies etc). 
– response 
This variable is of type HttpServletResponse, associated with the response to client. By using it, you 
can set HTTP status codes, content type and response headers etc.
Web Design  Development – CS506 VU 
© Copyright Virtual University of Pakistan 
340 
–out 
This is the object of JspWriterused to send output to the client. 
Code Example: Use of Implicit Objects 
The following example constitutes of 4 JSP pages. These are index.jsp, controller.jsp, web.jsp and java.jsp. The 
user will select either the option of “java” or “web” from index.jsp, displayed in the form of radio buttons and 
sed on the selection made by the user, controller.jsp will redirect the user 
to respective pages (web.jsp or java.jsp). 
shown below in the pictorial form. 
submits the request to controller.jsp. Ba 
The flow of the example is 
The code of these entire pages is given below. 
index.jsp html 
h2 
input type=radio name = page value=web/ 
Web Design  Develoment 
/h3 br 
h3 
input type=radio name = page value=java/ 
body 
Select the page you want to visit/h2 
form name=myForm action=controller.jsp  
h3
Web Design  Development – CS506 VU 
© Copyright Virtual University of Pakistan 
341 
Java /h3 
br 
/html 
controller. 
html 
body 
!-- scri 
, name of radio button using 
// implicit object request 
String pageName = request.getParameter(page); 
// deciding which page to move on based on “page” value 
// redirecting user by using response implicit object 
if (pageName.equals(web)) { 
response.sendRedirect(web.jsp); 
} else if (pageName.equals(java) ) { 
response.sendRedirect(java.jsp); 
} 
% 
/body 
/html 
input type=submit value=Submit / 
/form 
/body 
jsp ptlet -- 
 // reading parameter “page” 
%
Web Design  Development – CS506 VU 
© Copyright Virtual University of Pakistan 
342 
web.jsp html 
body 
// use of out implicit object, to generate HTML 
% 
out.println( h2 + 
Welcome to Web Design  Development Page + 
/h2 
); 
% 
/body 
/html 
java.jsp 
html 
body 
// use of out implicit object, to generate HTML 
% 
out.println( h2 + 
Welcome to Java Page + 
/h2 
); 
% 
/body 
/html
Web Design  Development – CS506 VU 
© Copyright Virtual University of Pakistan 
343 
Th 
t. 
ƒ application 
configuration options e.g. 
init-parameters etc. 
ƒ pageContext 
This variable is of type javax.servlet.jsp.PageContext, to give a single point of access 
to many of the page attributes. This object is used to stores the object values 
associated with this object. 
ƒ exception 
This variable is of type java.lang.Throwable. Represents the exception that is passed 
to JSP error page. 
ƒ page 
This variable is of type java.lang.Object. It is synonym for this. 
e details of remaining 5 implicit objects are given below: ƒ session This variable is of type HttpSession, used to work with session objec 
This variable is of type ServletContext. Allows to store values in key-value pair form that are shared by all servlets in same web application ƒ config This variable is of type ServletConfig. Represents the JSP
Web Design  Development – CS506 VU 
© Copyright Virtual University of Pakistan 
344 
JSP Directives 
JSP processing information about the page to JSP container. It affects the 
ov programmer to: 
from other resources 
specify custom-tag libraries 
Fo 
%@ directive {attribute=”val”}* % 
In JSP, there are three types of directives: page, include  taglib. The formats of using these are: 
–page: %@ page {attribute=”val”}* % 
– include: %@ include {attribute=”val”}* % 
%@ taglib {attribute=”val”}* % 
JSP page Directive 
Gi about servlet that will result from JSP page. It can be used anywhere in the 
do 
rted 
– What MI 
– How multit 
n session 
pected errors etc. 
Th lists of attributes that can be used with page directive are: 
language = “java” 
extends = “package.class” 
import = “package.*,package.class,…” 
Info = “text” 
eType” 
isThreadSafe = “true | false” 
isErrorPage = “true | false” 
Some exam e uses 
like java.util 
%@page import=“java.util.*” info=“using util package” % 
– To declare this page as an error page 
rPage = “true” % 
ead sheet 
page contentType = “application/vnd.ms-excel” % 
directives are used to convey special 
erall structure of the servlet that results from the JSP page. It enables – Specify page settings – To Include content – To 
rmat 
– taglib: 
ve high level information 
cument. It can control 
– Which classes are impo– What class the servlet extends 
ME type is generated hreading is handled 
– If the participates i– Which page handles unex 
e 
session = “true | false” 
contentType = “mim 
errorPage = “relativeURL” 
pl are: 
– To import package 
%@ page isErro– To generate the excel spr 
%@
Web Design  Development – CS506 VU 
© Copyright Virtual University of Pakistan 
345 
JS 
Lets you include (reuse) navigation bars, tables and other elements in JSP page. You can include files at 
– Translation Time (by using include directive) 
– Request Time (by using Action elements, discussed in next handouts) 
Fo 
% 
Purpose 
To i t. It may contain JSP code that 
affects the main page such as response page header settings etc. 
Ex e 
This example contains three JSP pages. These are index.jsp, header.jsp  footer.jsp. The header.jsp will display 
the text of “web design and development” along with current date. The footer.jsp will display only “virtual 
university”. The outputs of both these pages will be included in index.jsp by using JSP include directive. 
header.jsp 
% .*% 
html 
Development /h3 
h3%=new Date()%/h3 
/marquee 
/body 
/html 
P include Directive 
rmat 
@include file=“relativeURL”% 
nclude a file in a JSP document at the time document is translated into a servle 
ample Code: using include directiv 
@page import=java.util 
body marquee h3 Web Desing
Web Design  Development – CS506 VU 
© Copyright Virtual University of Pakistan 
346 
footer.jsp 
html 
body 
marquee 
h3 Virtual University /h3 
/marquee 
/body 
/html 
index.jsp 
html 
body 
TABLE BORDER=1 
TRTH/THTHApplesTHOranges 
TRTHFirst QuarterTD2307TD4706 
TRTHSecond QuarterTD2982TD5104 
5TD5287 
/TABLE 
// includes the output of footer.jsp 
%@include file=footer.jsp % 
// includes the output of header.jsp %@include file=header.jsp % 
TRTHThird QuarterTD3011TD5220 TRTHFourth QuarterTD305 
 
/body 
/html
Web Design  Development – CS506 VU 
© Copyright Virtual University of Pakistan 
347 
Example Code: setting content type to generate excel spread sheet 
In d to generate excel spread sheet of the last example. The change is shown in 
bo 
in 
// 
%@page contentType=application/vnd.ms-excel % 
html 
body 
// includes the output of header.jsp 
%@include file=header.jsp % 
 
HTHApplesTHOranges 
irst QuarterTD2307TD4706 
econd QuarterTD2982TD5104 
TRTHThird QuarterTD3011TD5220 
TRTHFourth QuarterTD3055TD5287 
/TABLE 
// includes the output of footer.jsp 
%@include file=footer.jsp % 
/body 
/ 
this example, index.jsp is modifield face. dex.jsp setting content type to generate excel sheet using page directive 
TABLE BORDER=1TRTH/T 
TRTHFTRTHS 
html
Web Design  Development – CS506 VU 
© Copyright Virtual University of Pakistan 
348 
JS Life C 
Th JSP are jspInit(), _jspService() and jspDesroy(). On receiving each request, _jspService() 
me 
Pycle Methods e life cycle methods ofthod is invoked that generates the response as well. 
Re 
ƒ Java A Lab Course by Umair Javed 
ƒ Co e Servle 
ferences: 
rts and JSP by Marty Hall
Web Design  Development – CS506 VU 
© Copyright Virtual University of Pakistan 
349 
Lesson 36 
Java Server Pages 3 
irectives and the use of implicit objects. In this 
s and what affect they produce. Before learning JavaBeans, let’s start with 
nd the impact of using JavaBeans. 
Outline 
his example is actually the modification of the last one we had discussed in previous handout. User will select 
ld be 
. The 
In the last handout, we learned how to work with JSP d 
handout, we’ll learn about JavaBeanan example that helps us to understa 
Code Example: Displaying Course T 
either course “web design and development” or “java”. On submitting request, course outline woudisplayed of the selected course in tabular format. This course outline actually loaded from databaseschema of the database used for this example is given below: The flow of this example is shown below: 
This page is used to display the course options to the user in the radio button form. 
html 
body 
h2Select the page you want to visit/h2 
ent 
index.jsp 
form name=myForm action=controller.jsp  
h3 input type=radio name = page value=web/ 
Web Design  Develom 
/h3 br
Web Design  Development – CS506 VU 
© Copyright Virtual University of Pakistan 
350 
h3 input type=radio name = page value=java/Java 
/h3br 
it value=Submit / 
/ 
controller.jsp 
on made by the user, this page will redirect the user to respective pages. Those are 
web.jspand java.jsp 
body 
!-- scriptlet -- 
 
// reading parameter named page 
String pageName = request.getParameter(page); 
ing user based on selection made 
if (pageName.equals(web)) 
{ 
response.sendRedirect(web.jsp); 
} 
else if (pageName.equals(java) ) 
{ 
endRedirect(java.jsp); 
} 
% 
input type=subm 
/form 
 
/body 
html 
Based upon the selecti 
html 
% 
// redirect 
response.s
Web Design  Development – CS506 VU 
© Copyright Virtual University of Pakistan 
351 
/body 
/html 
web.jsp 
course outline of “web design and development” in a tabular format after reading 
them from database. The code is: 
%@page import=java.sql.*% 
body 
b Design  Development Page /h2 
line/h3 
TABLE BORDER=1  
TH 
THAssignments/TH 
/TR 
% // establishing conection 
Class.forName(sun.jdbc.odbc.JdbcOdbcDriver); 
String conUrl = jdbc:odbc:CourseDSN; 
Connection con = DriverManager.getConnection(conUrl); 
This page is used to display 
// importing java.sql package using page directive, to work with database 
html 
center h2 Welcome to We h3 Course Out 
TR THSession No./TH THTopics/ 
%-- start of scriptlet --%
Web Design  Development – CS506 VU 
© Copyright Virtual University of Pakistan 
352 
// preparing query u sing join statements 
String sql =  SELECT sessionNo, topic, assignment  + 
FROM Course, SessionDetail + WHERE courseName = ?  +  
e.courseId = SessionDetail.courseID; 
PreparedStatement pStmt = con.prepareStatement(sql); 
parameter value ”web”.pStmt.setString( 1 , web); 
ResultSet rs = pStmt.executeQuery(); 
String sessionNo; 
String topic; 
assignment; 
// iterating over resultset 
o = rs.getString(sessionNo); 
topic = rs.getString( c); 
assignment = rs.getString(assignment); 
if (assignment == null){ 
assignment = ; 
 
%-- end of scriptlet --% 
are displayed in tabular format usingexpressions, 
however it can also be done usingout.println(sessionNo) like statements 
--% 
AND Cours 
// setting 
String 
while (rs.next()) { 
sessionN 
topi 
} 
% 
%-- The values
Web Design  Development – CS506 VU 
© Copyright Virtual University of Pakistan 
353 
TR 
TD %=topic% /TD 
TD %=assignment% /TD 
java.jsp 
The code of this page is very much alike of “web.jsp”. The only change is in making of query. Here the value 
is set “java” instead of “web” 
/ imp ith database 
%@page impor 
html 
body 
come o Java 
Outline/ 
TABLE BORDER=1  
THSession No./TH 
THTopics/TH 
/TR 
TD %=sessionNo% /TD 
/TR 
% 
} // end while % 
/TABLE  
/center /body /html 
/orting java.sql package using page directive, to work w 
t=java.sql.*% 
center 
h2 Wel tPage /h2 
h3 Course h3 
TR 
THAssignments/TH
Web Design  Development – CS506 VU 
© Copyright Virtual University of Pakistan 
354 
%-- start of scriptlet --% % // establishing connection 
Calss.forName(“sun.jdbc.odbc.JdbcOdbcDriver”); 
String conUrl = jdbc:odbc:CourseDSN; 
Connection con = DriverManager.getConnection(conUrl); 
// preparing query using join statements 
, topic, assignment  + 
= ?  +  
AND Course.courseId = SessionDetail.courseID; 
pareStatement(sql); 
String topic; 
String assignment; 
o); 
getString(topic); 
assignment = rs.getString(assignment); 
String sql =  SELECT sessionNo 
FROM Course, SessionDetail + WHERE courseName 
PreparedStatement pStmt = con.pre 
// setting parameter value ”web”.pStmt.setString( 1 , java); 
ResultSet rs = pStmt.executeQuery(); 
String sessionNo; 
// iterating over resultset while (rs.next()) { sessionNo = rs.getString(sessionN topic = rs. 
if (assignment == null)
Web Design  Development – CS506 VU 
© Copyright Virtual University of Pakistan 
355 
{ 
assignment = ; 
% 
%-- end of scriptlet --% 
%-- The values are displayed in tabular format usingexpressions, however it can also be done 
usingout.println(sessionNo) like statements 
--% 
TR 
%=sessionNo% /TD 
TD %=topic% /TD 
TD %=assignment% /TD 
/TR 
% 
} // end while 
% 
/TABLE  
/center 
/body 
/html 
and java.jsp. This makes it very difficult to understand (probably you 
enced it by yourself) and to make changes/enhancements. 
A single page is doing everything that is really a bad approach while making of web applications. The tasks 
ts (Presentation logic) 
atabase (DB connectivity logic) 
g (Business Logic) 
answer lies in the use of JavaBeans technology. 
} 
TD 
Issues with Last Example Too much cluttered code in web.jsp 
experi 
performed by web.jspor java.jspare: ƒ Displaying conten ƒ Connecting with d ƒ Results Processin Can we simplify it? Yes, the
Web Design  Development – CS506 VU 
© Copyright Virtual University of Pakistan 
356 
JavaBeans 
A java class that can be easily reused and composed togethercertain design conventions can be a JavaBean. 
in an application. Any java class that follows 
JavaBeans Design Conventions 
These conventions are: 
ƒ A bean class must have a zero argument constructor 
ƒ A bean class should not have any public instance variables/attributes (fields) 
ƒ ld be accessed through setters/getters 
For boolean data types, use boolean isXXX( )  setXXX(boolean) 
ust be serializable 
A Sample JavaBean 
that satisfies all the conventions described above. The 
e; // zero argument constructor 
pub 
name = “”; 
ame(String n) { 
n; 
} 
ublic String getName( ) { 
return name; 
} 
ny other method 
public void print( ) { 
me is: ” + name); 
} // end Bean class 
Private values shou 
ƒ A bean class m 
The code snippet of very basic JavaBean is given belowMyBean.java class has only one instance variable. 
public class MyBean implements Serializable { private String nam 
lic MyBean( ){ 
} 
// standard setter public void setNname = 
// standard getter 
p 
// a 
System.out.println(“Na 
}
Web Design  Development – CS506 VU 
© Copyright Virtual University of Pakistan 
357 
Example Code: Displaying course outline by incorporating JavaBeans 
his exa Two JavaBeans are included in this 
example code. These are CourseOutlineBean CourseDAO. 
The CourseOutlineBean is used to represent one row of the table. It contains the following attributes: 
ƒ sessionNo 
ƒ topic 
ƒ assignment 
e DAO stands of Data Acess Object) bean encapsulates database connectivity and 
Beans. The code of these and the JSPs used in this example are 
CourseOutlineBean.java 
package vu; 
tlineBean implements Serializable{ 
private int sessionNo; 
private String topic; 
private String assignment; 
// no argument constructor 
assignment = ; 
} 
// setters 
public void setTopic(String t){ 
Tmple is made by making more enhancements to the last one. 
The CourseDAO (wherresult processing logic. The web.jsp and java.jsp will use both these Javagiven below. 
import java.io.*; 
public class CourseOu 
public CourseOutlineBean() { sessionNo = 0; 
topic = ; 
public void setSessionNo(int s){ sessionNo = s; 
} 
topic = t; 
}
Web Design  Development – CS506 VU 
© Copyright Virtual University of Pakistan 
358 
public void setAssignment(String a){ assignment = a; 
} 
lic 
No( ){ 
nNo; 
public String getTopic( ){ 
return topic; 
public String getAssignment( ){ 
} // end class 
CourseDAO.java 
import java.util.*; 
public class CourseDAO implements Serializable{ 
private Connection con; 
public CourseDAO() { 
establishConnection(); 
// getterspub int getSession return sessio } 
} 
return assignment; 
} 
package vu; 
import java.io.*; import java.sql.*;
Web Design  Development – CS506 VU 
© Copyright Virtual University of Pakistan 
359 
} //********** establishConnection method ************* method used to make connection with 
databaseprivate 
void establishConnection(){ 
// establishing conection 
N; 
con = DriverManager.getConnection(conUrl); 
}catch(Exception ex){ 
System.out.println(ex); 
} 
//*********** retrieveCourseList method ******************** 
ng cName){ 
t courseList = new ArrayList(); 
ic, assignment  + 
FROM Course, SessionDetail + 
WHERE courseName = ?  +  
AND Course.courseId = SessionDetail.courseID ; 
PreparedStatement pStmt = con.prepareStatement(sql); 
pStmt.setString(1, cName); 
ResultSet rs = pStmt.executeQuery(); 
try{ 
Class.forName(sun.jdbc.odbc.JdbcOdbcDriver); 
String conUrl = jdbc:odbc:CourseDS 
} 
public ArrayList retrieveCourseList(Stri 
ArrayLis 
try{ String sql =  SELECT sessionNo, top
Web Design  Development – CS506 VU 
© Copyright Virtual University of Pakistan 
360 
int sNo; 
String topic; 
String assignment; 
while ( rs.next() ) { 
sNo = rs.getInt(sessionNo); 
topic = rs.get tring(topic); 
rs.getString(assignment); 
if (assignment == null) 
{ 
assignment = ; 
} 
// creating a CourseOutlineBean object 
CourseOutlineBean cBean = new CourseOutlineBean(); 
cBean.setSessionNo(sNo); 
cBean.setTopic(topic);cBean.setAssignment(assignment); 
// adding a bean to arraylist 
courseList.add(cBean); 
} 
}catch(Exception ex){ 
System.out.println(ex); 
} finally { 
// to close connection 
releaseResources(); 
} 
// returning ArrayList object 
return courseList; 
} // end retrieveCourseOutline 
S 
assignment =
Web Design  Development – CS506 VU 
© Copyright Virtual University of Pakistan 
361 
//********** releaseResources method ******************** 
private void releaseResources(){ 
if(con 
}catc 
System.out.println(); 
}//end ourseDAO 
index.jsp 
This page is used to display the course options to the user in the radio button form. 
html 
body 
e you want to visit/h2 
form name=myForm action=controller.jsp  
e=radio name = page value=web/ 
/h3 
page value=java/Java 
input submit value=Submit / 
/html 
try{ != null 
){ con.close(); 
} h(Exception ex){ 
} 
} // end releaseResources 
C 
h2Select the pag 
h3 input typ 
Web Design  Develoment br 
h3 input type=radio name = 
/h3br 
type 
= /form 
/body
Web Design  Development – CS506 VU 
© Copyright Virtual University of Pakistan 
362 
controller.jsp 
Based on user selection, redirects the user to desired page. 
!-- scriptlet -- 
sponse.sendRedirect(java.jsp); 
% 
/body 
/html 
e also uses the JavaBeans (CourseOutlineBean  CourseDAO). 
center 
html 
body 
% equest.getParameter(page); 
String pageName = r 
if (pageName.equals(web)) { 
response.sendRedirect(web.jsp); } else if (pageName.equals(java) ) 
{ re 
} 
 
web.jsp This page is used to display course outline of “web design and development” in a tabular format after reading them from database. Moreover, this pag 
%@page import=java.util.* % 
%-- importing vu package that contains the JavaBeans--% %@page import=vu.* % 
html 
body
Web Design  Development – CS506 VU 
© Copyright Virtual University of Pakistan 
363 
h2 Welcome to Web Design  Development Course /h2 
TABLE BORDER=1  
TR 
THSession No./TH 
THTopics/TH 
THAssignments/TH 
/TR 
%-- start of scriptlet --% 
% 
// creating CourseDAO object 
CourseDAO courseDAO = new CourseDAO(); 
// calling retrieveCourseList() of CourseDAO class and 
// passing “web” as value. This method returns ArrayListArrayList 
courseList = courseDAO.retrieveCourseList(web); 
CourseOutlineBean webBean = null; 
for(int i=0; icourseList.size(); i++){ 
ean = (CourseOutlineBean)courseList.get(i); 
tlet --% 
T 
TD %= webBean.getSessionNo()% /TD 
TD %= webBean.getTopic()% /TD 
h3 Course Outline/h3 
// iterating over ArrayList to display course outline 
webB% 
%-- end of scripR
Web Design  Development – CS506 VU 
© Copyright Virtual University of Pakistan 
364 
TD 
% 
/TAB 
/center 
java.js 
The code contains by this page is almost same of web.jsp. Here, “java” is passed to retieveCourseList( ) 
ethod. This is shown in boldface. 
%@page import=java.util.* % 
%-- importing vu package that contains the JavaBeans--%%@page import=vu.* % 
html 
body 
center 
h2 W 
h3 C tline/h3 
E BORDER=1  
TR 
THSession No./TH 
THTopics/TH 
THAssignments/TH 
/TR 
%= webBean.getAssignment()% /TD / 
TR 
% } // end for 
LE  
/body 
/html 
p 
m 
 
 elcome to Java Course /h2 ourse Ou 
TABL
Web Design  Development – CS506 VU 
© Copyright Virtual University of Pakistan 
365 
%-- start of scriptlet --% 
% 
// creating CourseDAO object 
CourseDAO courseDAO = new CourseDAO(); 
// calling retrieveCourseList() of CourseDAO class and 
thod returns ArrayList 
etrieveCourseList(java); 
CourseOutlineBean javaBean = null; 
// iterati to display course outline 
% 
%-- end of scriptlet --% 
TR 
TD %= javaBean.getSessionNo()% /TD 
.getTopic()% /TD 
TD %= javaBean.getAssignment()% /TD 
/TR 
% 
} // end for 
% 
/TABLE  
// passing “java” as value. This meArrayList courseList = courseDAO.r 
ng over ArrayList 
for(int i=0; icourseList.size(); i++){ 
javaBean = (CourseOutlineBean)courseList.get(i); 
TD %= javaBean
Web Design  Development – CS506 VU 
© Copyright Virtual University of Pakistan 
366 
/center 
/body 
/html 
for this handout is taken from the book JAVA A Lab Course by Umair Javed. This material is 
ava le r the use of VU students of the course Web Design and Development and not for any other 
commercial purpose without the consent of author. 
References: Entir m 
eaterialilab just fo
Web Design  Development – CS506 VU 
© Copyright Virtual University of Pakistan 
367 
Lesson 37 
JSP Action Elements and Scope 
T 
wc 
Let’s first quic n the JSP journey to find out where we have reached. 
ƒ Directive Elements 
– Provides global control of JSP ……..…………….. %@ % 
ƒ Scripting Elements 
– JSP comments ……………………………………... %----% 
– declarations ……………………………………... %! % 
ƒ Used to declare instance variables  methods 
ƒ Action Elements 
– Special JSP tags ……..…………………………….. jsp: .…. / 
JSP Action Elements 
JSP action elements allow us to work with JavaBeans, to include pages at request time and to forward 
requests to other resources etc. 
dy body 
-Closing tag /jsp:actionElement 
Some JSP Action Elements 
ƒ To work with JavaBeans 
-jsp:useBean / 
he journey we had started of JSP is very much covered except of JSP action elements. In this handout, e’ll study the use of JSP action elements. Further also learn how and where to store JavaBean objects that an be shared among JSP pages. kly look o 
Format Expressed using XML syntax -Opening tag jsp:actionElement attribute=”value” …..  
-Bo 
Empty tags (without body) can also be used like jsp:actionElement attribute=”value” …..  
-jsp:setProperty / -jsp:getProperty / 
ƒ To include resources at request time -jsp:include / ƒ To forward request to another JSP or Servlet
Web Design  Development – CS506 VU 
© Copyright Virtual University of Pakistan 
368 
-jsp:forward / 
applets 
-jsp:plugin / 
Working with JavaBeans using JSP Action Elements 
The three action elements are used to work with JavaBeans. These are discussed in detail below. 
JSP useBean Action Element 
It is used to obtain a reference to an existing JavaBean object by specifying id(name of object) and scope in 
which bean is stored. If a reference is not found, the bean is instantiated. 
The format of this action element is: 
jsp:useBean id = “name” scope = “page|request|session|application” 
class=“package.Class ” / 
The id attribute specifies the name of the JavaBean object that is also used for later references. The scope 
attribute can have one possible value out of page, request, session and application. If this attribute is omitted, 
the default value of scope attribute is page. We’ll discuss in detail about scope shortly. 
The class attribute specifies the type of object is going to be created. 
jsp:useBean is being equivalent to building an object in scriptlet. For example to build an object of 
MyBeanusing scriptlet is: 
% MyBean m = new MyBean( );% 
Achieving above functionality using jsp:useBean action element will look like this: 
jsp:useBean id = “m” scope = “page” class=“vu.MyBean” / 
In the above code snippet, we are assuming that MyBean lies in vu package. 
JSP setProperty Action Element 
To set or change the property value of the specified bean. String values are converted to types of properties by 
using the related conversion methods. 
The format of this action element is: 
jsp:setProperty name = “beanName or id” property = “name”value =“value” / 
The name attribute should match the id given in jsp:useBean. The propertyattribute specifies the name of the 
property to change and the value attribute specifies the new value. 
jsp:setProperty is being equivalent to following code of scriptlet. For example to change the name property of 
m (instance of MyBean) using scriptlet is: 
% 
m.setProperty(“ali”); 
% 
Achieving above functionality using jsp:setProperty action element will look like this: 
jsp:setProperty name = “m” property = “name” value = “ali” / 
ƒ To work with
Web Design  Development – CS506 VU 
© Copyright Virtual University of Pakistan 
369 
JSP getProperty Action Element 
Use to retrieves the value of property, converts it to String and writes it to output stream. The format of this 
action element is: 
jsp:getProperty name = “beanName or id” property = “name” / 
jsp:getProperty is being equivalent to following code of scriptlet. For example to retrieve the name property of 
m (instance of MyBean) followed by writing it to output stream, scriptlet code will look like: 
% 
String name = m.getName( ); 
out.println(name); 
% 
chieving above functionality using jsp:getProperty action element will look like this: 
jsp:getProperty name = “m” property = “name” / 
ndex.jsp and result.jsp and one JavaBean i.e. SumBean. User will enter two numbers on 
be displayed on result.jsp. Let’s examine these one after another 
SumBean.java 
The SumBean has following attributes 
nd secondNumbers are “write-only” properties means for these only setters would be 
efined. Whereas sum is a “read-only” property as only getter would be defined for it. 
The SumBean also contain one additional method for calculating sum i.e. calulateSum(). After performing 
import java.io.*; 
public class SumBean implements Serializable{ 
private int firstNumber; 
private int secondNumber; 
private int sum; 
// no argument constructor 
public SumBean() { 
firstNumber = 0; 
secondNumber = 0; 
sum = 0; 
} 
A 
Example Code: Calculating sum of two numbers by using action elements and JavaBean his example contains i 
Tindex.jsp and their sum will 
– firstNumber – secondNumber – sum 
The firstNumber a 
d 
addition of firstNumber with secondNumber, this method will assign the result to sum attribute. package vu;
Web Design  Development – CS506 VU 
© Copyright Virtual University of Pakistan 
370 
// firstNumber  secondNumber are writeonly properties// setterspublic void setFirstNumber(int n){ 
firstNumber = n; 
} 
public void setSecondNumber(int n){ 
secondNumber = n; 
} 
// no setter for sum 
// sum is a read only property 
public int getSum( ){ 
return sum; 
} 
// method to calculate sum 
public void calculateSum() { 
sum = firstNumber + secondNumber; 
} 
} 
index.jsp 
This page will display two text fields to enter number into them. 
html 
body 
h2Enter two numbers to calculate their sum/h2 
form name=myForm action=result.jsp 
input type=text name=num2 / 
br/ 
input type=submit value=Calculate Sum / 
/h3 
/form 
/body 
/html 
h3 Enter first numebr input type=text name=num1 /br/ Enter second numebr
Web Design  Development – CS506 VU 
© Copyright Virtual University of Pakistan 
371 
result.jsp 
This page will calculate the sum of two entered numbers by the user and displays the sum back to user. The 
ddition is performed using SumBean 
%-- importing vu package that contains the SumBean -- 
%%@page import=vu.*% html body 
element -- % 
n id=sBean class=vu.SumBean scope=page/ 
%-- setting firstNumber property of sBean 
using action elements 
-- % 
%-- implicit conversion from string to int as num1 is of typeString and 
firstNumber is of type int--% 
%--//Servlet equivalent code of setProperty for num1int no = 
Integer.parseInt(request.getParameter(num1));sBean.setFirstNumber(no); 
--% 
1 / 
%--//Servlet equivalent code of setProperty for num2int no = 
property=secondNumber param=num2 / 
// calling calculateSum() method that will set the value of// sum attribute 
sBean.calculateSum(); 
% 
ying sumint res = sBean.getSum();out.println(res); 
jsp:getProperty name=sBean property=sum / 
/h2 
/body 
/html 
a 
h2The sum is: %-- instantiating bean using action //Servlet equivalent code of useBean 
SumBean sBean = new SumBean(); 
--% jsp:useBea 
jsp:setProperty name=sBeanproperty=firstNumber param=num 
Integer.parseInt(request.getParameter(num2));sBean.setSecondNumber(no); --% 
jsp:setProperty name=sBean 
% 
%--// servlet equivalent code of displa--%
Web Design  Development – CS506 VU 
© Copyright Virtual University of Pakistan 
372 
Sharing Beans  Object Scopes 
So far, we have learned the following techniques to create objects. 
-Implicitly through JSP di 
-Explicitly through actions 
-Directly using scripting code 
Although the beans are indeed bound to local variables, that is not the only behavior. They are also stored in 
four different locations, depending on the value of the optional scope attribute of jsp:useBean. The scope 
attribute has the following possible values: page, request, sessionand application. 
Let’s discover what impact these scopes can produce on JavaBeans objects which are stored in one of these 
This is the default value of scope attribute, if omitted. It indicates, in addition to being bound to local 
variable, the bean object should be placed in the pageContextobject. The bean’s values are only available 
and persist on JSP in which bean is created. 
of 
following diagram: 
rectives 
scopes. ƒ page 
In practice, beans created with page scope are always accessed (their values) by jsp:getProperty, jsp:setProperty, scriptlets or expressions later in the same page. This will be more cleared with the help 
PageContext In the diagram above, first.jsp generates a request “request 1” that is submitted to second.jsp. Now, second.jsp 
creates an object m of MyBeanby calling its default constructor and stores a value “ali” for the name 
property by making a call to appropriate setter method. Since, the scope specified in this example is 
t of MyBean is instantiated using jsp:useBean action element. Therefore, object (m) 
of MyBeanis stored in PageContext. 
st 
2), e 
ag 
“page”when the objec 
Whether, second.jsp forwards the same request (request 1) to third.jsp or generates a new request (requeat third.jsp, values (e.g. ali) stored in MyBean object m, are not available. Hence, specifying scop 
“pe” results in using the object on the same page where they are created.
Web Design  Development – CS506 VU 
© Copyright Virtual University of Pakistan 
373 
ƒ request 
This value signifies that, in addition to being bound to local variable, the bean object should be placed in 
Serv e duration of the current request. In other words, until you continue to 
forw r JSP/servlet, the beans values are available. This has been illustrated in the 
foll 
letRequest object for thard the request to anothe 
owing diagram. 
In the diagram above, MyBean is instantiated by specifying scope = “request”that results in storing object in 
second.jsp forwards the same request (request 1) to third.jsp, since scope of m (object of 
MyBean) is request, as a result third.jsp can access the values(e.g. ali) stored in m. According to 
the figure, third.jsp generates a new request (request 2) and submits it to fourth.jsp. Since a new 
q t erefore values stored in object m (e.g. ali) are not available to fourth.jsp. 
This value means that, in addition to being bound to local variable, the bean object will be stored 
in the HttpSession object associated with the current request. As you already know, object’s value 
stored n understanding 
this concept. 
ServletRequest. A value “ali” is also stored in m using setter method. 
re 
ues is generated th 
ƒ session 
in HttpSession persists for whole user’s session. The figure below helps i
Web Design  Development – CS506 VU 
© Copyright Virtual University of Pakistan 
374 
HttpSession 
In t is instantiated by specifying scope = “session”that results in storing object 
in HttpSession. A value “ali” is also stored in m using setter method. 
Irre uest forwarding or new request generation from second.jsp to other resources, the 
valu s stored sion is ended. 
ƒ application 
This very useful value means that, in addition to being bound to local variable, the bean object will be stored in 
ServletContext. The bean objects stored in ServletContext is shared by all JSPs/servlets in the same web 
application. The diagram given below illustrates this scenario: 
he diagram above, MyBean spective of reqe in HttpSession remains available until user’s ses 
ServletContext
Web Design  Development – CS506 VU 
© Copyright Virtual University of Pakistan 
375 
Summary of Object’s Scopes Let’s take another view of session, request  page scopes in the next figure that helps us to understand the 
und b 
er eneath things.
Web Design  Development – CS506 VU 
© Copyright Virtual University of Pakistan 
376 
The figure shows four JavaServer Pages. Each page has its own page scope. Therefore objects stored in page 
scope are only available to same pages on which they are created. 
Suppose page1 forwards the request to page2. Objects stored in request scope remains available to page1 as 
well to page 2. Similar case is true for page 3  page 4. 
If user makes a visit to all these pages in one session, object’s values stored in session scope remains available 
To d er the following figure: 
on all these pages. 
unerstand the difference between sessions  application scope, consid As you can conclude from the figure, for each user (client), objects are stored in different sessions. However, in 
the case of application scope, all users stores objects in single place.
Web Design  Development – CS506 VU 
© Copyright Virtual University of Pakistan 
377 
More JSP Action Elements 
Let’s talk about two important action elements. These are include forward. 
JSP include action Element 
It is used to include files at request time. For example, to reuse HTML, JSP or plain text content. It’s 
important to note that JSP content cannot affect main page (in which output is included); only output of 
included JSP is used. It also allows updating of the included content without changing the main JSP. 
The jsp:include action element requires two attributes: page flush. -page: a relative URL of the 
file to be in “true” 
jsp:include page = “relative URL” flush = “true” / 
jsp:in owing code of scriptlet. For example to include the output of one.jsp , 
scriptl 
% 
= request.getRequestDispatcher(“one.jsp”);rd.include(request, 
response); 
% 
unctionality using jsp:include action element will look like this: jsp:include page = 
JSP forward action Element 
rce. The format of jsp:forward action is: 
jsp:forward page = “one.jsp” / 
uivalent to following code of scriptlet. For example to forward the request to one.jsp , 
scriptlet code will l 
% RequestD 
References: 
cluded. -flush:must have the value 
clude is being equivalent to follet code will look like: 
RequestDispatcher rd 
Achieving above f 
“one.jsp” flush = “true” / 
It is used to forward request to another resou 
jsp:forward is being eqook like: ispatcher rd = request.getRequestDispatcher(“one.jsp”); rd(request, response); 
rd.forwa% 
. Java A Lab Course by Umair Javed. rver Pages by Marty Hall 
. Core Servlets and JavaSe
W VU 
© Copyright Virtual University of Pakistan 
eb Design  Development – CS506 
378 
Lesson 38 
JSP Custom Tags 
To begin with, let’s review our last code example of lecture 36 i.e. Displaying course outline. We incorporated 
JavaBeans to minimi P. But still, we have to write some lines of java code 
inside java SPs are built for presentation purpose only, so all the other 
code that involves business and database logic must be shifted else where like we used JavaBeans for such 
purpose. 
There is also another problem attached to it. Generally web page designers which have enough knowledge to 
work me scripting language, faced lot of difficulties in writing some simple lines of java 
code. ues, java provides us the mechanism of custom tags. 
Motivation 
ppet we used in JSP of the course outline 
t for your reference to give you a hint. 
% 
CourseDAO courseDAO = new CourseDAO(); 
ist 
for (…………………… ) { 
…………………… 
…………………… 
// displaying courseoutline 
} 
……………… 
Can we replace all the above code with one single line? Yes, by using custom tag we can write like this: 
By only g will display the course outline in tabular format. Now, you 
must ha anges custom tags can bring on. 
ƒ In simplistic terms, “a user defined component that is used to perform certain action”. This action 
could be as simple as displaying “hello world” or it can be as complex as displaying course outline of 
selected course after reading it form database. 
ƒ It provides mechanism for encapsulating complex functionality for use in JSPs. Thus facilitates the 
non-java coders. 
ze the database logic from the JS.jsp  web.jsp. As discussed earlier, J 
with HTML and soTo overcome these iss 
To give you an inspiration, first have a glance over the code sniexample of last lecture. Of course, not all code is given here; it’s jus 
……………… // iterating over ArrayL 
% 
mytag:coursetag pageName=“java” / specifying the course/page name, this tave realized how significant ch 
What is a Custom Tag?
Web Design  Development – CS506 VU 
© Copyright Virtual University of Pakistan 
379 
ƒ We already seen  used many built in tags like: 
- jsp:useBean …… / 
- jsp:include …… / 
Why Build Custom Tag? 
ƒ seBean and JavaBeans to incorporate complex, encapsulated 
ƒ H s cannot manipulate JSP content and Web page designers must have some 
kn aBeans in a page 
ƒ With page designers to use complex functionality without knowing 
any java 
Advantages ustom Tags 
ƒ rocessing logic and presentation, than JavaBeans. 
ƒ all JSP implicit objects like out, request etc. 
ƒ an be customized by specifying attributes. 
Types of Tags 
Three types of can be constructed. These are: 
1 Simple Tag 
2 Tag with Attribute 
3 Tag wit 
1. Simple Tag 
A simple tag has the following characteristics: 
-Start and End of tag -No body is specified within tag -No attributes -For example 
- jsp:forward …… / etc. 
We introduced action jsp:ufunctionality in a JSP. owever, JavaBeanowledge to use JavCustom tags, it is possible for web 
of using CProvides cleaner separation of pHave access toC 
h Body
Web Design  Development – CS506 VU 
© Copyright Virtual University of Pakistan 
380 
2. Tag with Attributes 
ith attributes has the following characteristics: 
-Start and End of tag 
-Attributes within tag 
-For example 
 mytag:hello attribute = “value” / 
3. Tag with Body 
A : 
-Start and End of tag 
-M 
-Body enclosed within tag 
-For example 
 mytag:hello optional_attributes …………  
some body 
/ mytag:hello  
A tag w 
-No body enclosed 
tag with body has the following characteristics 
ay be attributes
Web Design  Development – CS506 VU 
© Copyright Virtual University of Pakistan 
381 
Building Cu 
So far, we have used many built-in tags. Now the time has come to build your own one. Custom tags can be 
built either by using JSP 1.2 specification or JSP 2.0 (latest) specification. 
To develop custom tags u me (too difficult for James Gossling also☺). 
However, JSP 2.0 brings lots of goodies like 
ƒ Simple tag extensions to build custom tags 
ƒ Integrated Expression Language (will be discussed in coming lecture) 
ƒ Also provides an alternate mechanism for building custom tags using tag files (.tag) 
ƒ Improved XML syntax etc. 
Steps for Building 
The following steps are used in order to develop your own custom tag. These are: 
1 Develop the Tag Handler class 
2 Write Tag library Descriptor (.tld) file 
3 Deployment 
1. De s 
ƒ Tag Handler is also a java class that is implicitly called when the associated tag is encountered in the 
JSP. 
ƒ Must implement SimpleTaginterface 
ƒ Usually extend from SimpleTagSupport class that has already implemented SimpleTag interface. 
ƒ For example, 
public class MyTagHandler extends SimpelTagSupport { 
……………………… 
……………………… 
} 
ƒ doTag() method 
• By default does nothing 
• Need to implement / override to code/write functionality of tag 
• Invoked when the end element of the tag encountered. 
ƒ JSP implicit obje (e.g. out etc) are available to tag handler class through pageContextobject. 
ƒ pageContextobje n be obtained using getJspContext() method. 
ƒ For example to get the reference of implicit outobject, we write. 
PageContext pc = (PageContext) getJspContext(); 
JspWriter out = pc.getOut(); 
2. Write Tag Library Discriptor (.tld) file 
• It is a XML based document. 
• Specifies information required by the JSP container such as: 
stom Tags 
sing JSP 1.2 involves lot of cumberso 
Custom Tags 
velop the Tag Handler clas 
cts ct ca
Web Design  Development – CS506 VU 
© Copyright Virtual University of Pakistan 
382 
-Tag library version 
te names etc. 
Note: If you are using any IDE (like netBeans® 4.1, in order to build custom tags, the IDE will 
• Place Tag Handler class in myapp/WEB-INF/classes folder of web application. 
• Place .tld file in myapp/WEB-INF/tldsfolder of web application. 
Note: Any good IDE will also perform this step on your behalf Use taglib directive in JSP to 
lib uri=”TLD file name” prefix=“mytag” % 
The next step is to call the tag by its name as defined in TLD. For example, if tag name is hello then we 
write: 
 mytag:hello / where mytag is the name of prefix specified in taglibdirective. 
What actu propriate tag handler 
class. After that, 
Example Code: Building simple tag that displays “Hello World” 
h we have talked about what are custom tags, their types. Now, it is a time to build a custom tag that 
ays “Hello World”. 
Approach 
• Extend Tag Handler class from SimpleTagSupport class and override doTag() method 
• Build TLD file 
• Deploy 
Note: As mentioned earlier, if you are using any IDE (like netBeans® 4.1), the last two steps will be 
performed by the IDE. 
WelcomeTagHandler.java 
package vu; 
// importing required packages 
im 
import jav 
-JSP version -Tag name -Tag Handler class name 
-Attribu 
write .tldfile for you. 3. Deployment 
refer to the tag library. For example 
%@ tag 
ally happened behind the scenes? Container calls the doTag() method of apTag Handler will write the appropriate response back to the page. 
Enougdispl 
port javax.servlet.jsp.*; 
ax.servlet.jsp.tagext.*;
Web Design  Development – CS506 VU 
© Copyright Virtual University of Pakistan 
383 
// ov 
public void d 
// ob 
ntext)getJspContext();JspWriter out = pageContext.getOut(); 
); 
} catch (java.io.IOException ex) {throw new 
JspException(ex.getMessage());} 
} // end doTag() method 
} end W 
custom 
If using IDE, this file will be written automatically. In this file you specify the tag name along with Tag 
Handler class. 
?xm 
/java.sun.com/xml/ns/j2eexmlns:xsi=http://www.w3.org/2001/XM 
LSchema-instancexsi:schemaLocation=http://java.sun.com/xml/ns/j2ee web- 
short-namemytag/short-name 
used in JSP to refer to this tld -- 
!— Specifying the tag name and tag class. Also mentioning thatthis tag has no body 
tag-classvu.WelcomeTagHandler/tag-class 
body-contentempty/body-content 
erriding doTag() method 
oTag() throws JspException { taining the reference of out implicit object PageContext pageContext = (PageCotry { 
out.println( Hello World 
elcomeTagHandler class tags.tld 
l version=1.0 encoding=UTF-8? sion=2.0 
taglib verxmlns=http:/ 
jsptaglibrary_2_0.xsd tlib-version1.0/tlib-version 
!—the value of uri will be uri/WEB-INF/tlds/customtags/uri 
-- 
tag 
namewelcome/name 
ag 
/t 
/taglib
Web Design  Development – CS506 VU 
© Copyright Virtual University of Pakistan 
384 
%-- taglib directive, specifying the tld file namethe%@taglib uri=/WEB-INF/tlds/customtags. html bod 
using as well asprefix. Note that you you use any value for 
prefix attribtute --% 
tld prefix=mytag % 
y 
h2A Simple Tag Example/h2 
h3 %-- calling welcome tag with the help of prefix --%mytag:welcome / 
/h3 
/body/html 
Building tags with attributes 
If you w ld a tag that can also take attributes, for example 
mytag: ello attribute=”value” / 
To handle attribu 
• Instance 
• Corresponding setter methods 
Behind the scenes, contai 
attribute as an argument. 
In this example, we will modify our course outline example to incorporate tags. Based on attribute value, 
the tag will displ pective course outline in tabular format. 
Approach 
• Extend Tag ass from SimpleTagSupport class 
-Add instance variable of type String 
-Write setter method for this attribute 
verride doTag() method 
• Build TLD file 
• Deploy 
 
ant to bui 
h 
tes, you need to add s and 
variablener will call these setter methods implicitly and pass the value of the custom tag 
ay the res 
Handler cl 
-O
Web Design  Development – CS506 VU 
© Copyright Virtual University of Pakistan 
385 
CourseOutlineBean.java 
This is the same file used in the last example 
package vubean; 
a.io.*; 
public cl Bean implements Serializable{ 
pr t sessionNo; 
private String topic; 
private Stri 
// no argument con 
public CourseOutlin 
sessionNo = 0; 
topic = ; 
assignment = 
} 
etters 
public void setSessionNo(int s){ 
sessionNo = s; 
public void setTopic(String t){ 
} 
public void setAssignment(String a){ 
assignment = a; 
// getter 
public S tTopic( ){return topic;} 
public S } 
} // end class 
import jav 
ass CourseOutline 
ivate in 
ng assignment; 
structor eBean() { 
; 
// s 
} 
topic = t; 
} 
spublic int getSessionNo( ){return sessionNo;} 
tring ge 
tring getAssignment( ){return assignment;
Web Design  Development – CS506 VU 
© Copyright Virtual University of Pakistan 
386 
CourseDAO.java 
a.io.*;import java.sql.*;import 
java.util. 
public class Cou 
private Con 
public C ) { 
est onnection(); 
} 
//********** establishConnection method ********************// method used to make connection with 
da e void establishConnection(){ 
try{// establishing conectionClass.forName(sun.jdbc.odbc.JdbcOdbcDriver); 
String conUrl = jdbc:odbc:CourseDSN;con = 
DriverManager.getConnection(conUrl); 
} 
} 
ArrayList courseList = new ArrayList(); 
try{ 
String sql =  SELECT sessionNo, topic, assignment  + FROM Course, SessionDetail + 
WHERE courseName = ?  +  AND Course.courseId = 
SessionDetail.courseID ; 
PreparedStatement pStmt = con.prepareStatement(sql);pStmt.setString(1, cName); 
ResultSet rs = pStmt.executeQuery(); 
int sNo; 
String topic; 
String assignment; 
No changes are made to this file too. 
package vu; 
import jav 
*; 
rseDAO implements Serializable{ 
nection con; 
ourseDAO( ablishC 
tabaseprivat 
}catch(Exception ex){ System.out.println(ex);
Web Design  Development – CS506 VU 
© Copyright Virtual University of Pakistan 
387 
while ( rs.next() ) { 
sNo = rs.getInt(sessionNo);topic = 
rs.getString(topic); ng(assignment); 
rseOutlineBean cBean = new 
CourseOutlineBean(); 
n.setAssignment(assignment); 
// adding a bean to arraylist 
// to close connection 
releaseResources(); 
rn courseList; 
} // end retrieveCourseOutline 
try{ 
if(con != null){ 
con.close(); 
} 
}catch(Exception ex){ 
System.out.println(); 
} 
} // end releaseResources 
}// end CourseDAO 
assignment = rs.getStri 
if (assignment == null){assignment = ;} // creating a CourseOutlineBean objectCou 
cBean.setSessionNo(sNo);cBean.setTopic(topic);cBea 
courseList.add(cBean); } 
}catch(Exception ex){ System.out.println(ex); } finally { 
} 
// returning ArrayList object retu
Web Design  Development – CS506 VU 
© Copyright Virtual University of Pakistan 
388 
MyTagHandler.java The tag handler class uses JavaBeans (CourseOutlineBean.java  CourseDAO.java), and includes the logic 
/ importing package that contains the JavaBeansimport vubean.*; 
import javax.servlet.jsp.tagext.*;import 
javax.servlet.jsp.*;import java.util.*; 
public class MyTagHandler extends SimpleTagSupport { 
*/ 
g pageName; 
pu Tag() throws JspException { 
CourseDAO courseDAO = new CourseDAO(); 
ourseList = courseDAO.retrieveCourseList(pageName); 
course outline in tabular form, this method is// used – define below 
display(courseList); 
/** 
* Sette 
*/ 
public void setPageName(java.lang.String value) {this.pageName = value; 
} 
/** 
* display method used to print courseoutline in tabular form 
*/ ist courseList)throws JspException{ 
Page 
JspW 
t 
of displaying course outline in tabular format. package vutag; 
/ 
/** * Declaration of pageName property. 
private Strin 
blic void do 
ArrayList c 
// to display 
} 
r for the pageName attri 
bute. 
private void display(ArrayL 
Context pc = (PageContext)getJspContext(); riter out = pc.getOut(); 
ry{
Web Design  Development – CS506 VU 
© Copyright Virtual University of Pakistan 
389 
// displaying table headers 
ou 
ou 
out.print(TH Session No /TH); 
out.print(TH Topic /TH); 
TH Assignment /TH); 
/TR); 
t 
for (int i=0; icourseList.size(); i++){ 
CourseOutlineBean courseBean = (CourseOutlineBean)courseList.get(i); 
// displaying one row 
out.print(TR); 
out.print(TD + courseBean.getSessionNo() + /TD); 
out.print(TD + courseBean.getTopic() + /TD); 
out.print(TD + courseBean.getAssignment() + /TD); 
out.print(/TR); 
} 
out.print(/TABLE); 
}catch(java.io.IOException ex){throw new 
:xsi=http://www.w3.org/2001/XM 
LSchema-instancexsi:schemaLocation=http://java.sun.com/xml/ns/j2ee web-jsptaglibrary_ 
2_0.xsd 
tlib-version1.0/tlib-version 
short-namemytaglibrary/short-name 
!—the value of uri will be used in JSP to refer to this tld -- 
uri/WEB-INF/tlds/mytaglibrary/uri 
!— Specifying the tag name and tag class. Also mentioning thatthis tag has no body 
-- 
tag 
namecoursetag/name 
tag-classvutag.MyTagHandler/tag-class 
body-contentempty/body-content 
t.print(TABLE BORDER=1 ); 
t.print(TR); 
out.print( out.print( 
// loop to iterate over courseLis 
JspException(ex.getMessage());}} } // end clas MyTagHandler.java 
?xml version=1.0 encoding=UTF-8? 
taglib version=2.0 xmlns=http://java.sun.com/xml/ns/j2eexmlns
Web Design  Development – CS506 VU 
© Copyright Virtual University of Pakistan 
390 
!— 
Specifying the attribute name and its type 
ribute 
na epageName/name 
java.lang.String/type 
/tag 
This course options to the user in the radio button form. 
html 
ou want to visit/h2 
myForm action=controller.jsp  
h3 input type=radio name = page value=web/Web Design  Develoment 
/h3 
r 
 name = page value=java/Java 
submit value=Submit / 
/form 
/html 
-- 
att 
m type 
/attribute 
 
/taglib 
index.jsp 
page is used to display the 
body 
h2Select the page yform name= 
b 
h3 input type=radio 
/h3 br input type= 
/body
Web Design  Development – CS506 VU 
© Copyright Virtual University of Pakistan 
391 
controller.jsp 
Based upon the selection made by the user, this page will redirect the user to respective pages. Those are 
web.jspand java.jsp 
html 
body 
% 
String pageName = request.getParameter(page); 
if (pageName.equals(web)) { 
response.sendRedirect(web.jsp); 
response.sendRedirect(java.jsp);}% 
%-- using taglib directive, specifying the tld file and prefix --% 
%@taglib uri=/WEB-INF/tlds/mytaglibrary.tld prefix=mytag% 
html 
center h2 Welcome to Java Learning Center /h2h3 Course Outline/h3 
--% 
rsetag pageName=java / 
/center 
!-- scriptlet -- 
} else if (pageName.equals(java) ) { 
/body 
/html 
java.jsp 
 
 
body 
%--calling coursetag and specifying java as attribute value 
mytag:cou 
/body /html
Web Design  Development – CS506 VU 
© Copyright Virtual University of Pakistan 
392 
web.jsp 
%@taglib uri=/WEB-INF/tlds/mytaglibrary.tld prefix=mytag% 
elcome to Java Learning Center /h2h3 Course Outline/h3 
ute value 
ag pageName=java / 
/center 
urse by Umair Javed. 
and JavaServer Pages by Marty Hall 
%-- using taglib directive, specifying the tld file and prefix --% 
html 
body 
center 
h2 W%--calling coursetag and specifying java as attrib 
--% mytag:courset 
/body /html 
References 
• Java A Lab Co• Core Servlets
Web Design  Development – CS506 VU 
© Copyright Virtual University of Pakistan 
393 
Lesson 39 
e Study 
Ps in detail. Now, the time has come to learn 
e sake of web development. These architectures 
e components best fit in. In this handout, we’ll cover the most widely 
View Controller (MVC). 
also part of this handout that is based on MVC Model 1. Before 
oving on to MVC, let’s see what error pages are and how they are used? 
ages enables you to customize error messages. You can even hide them from the user's view 
makes possible to maintain a consistent look and feel throughout an 
application, even when those dreaded error messages are thrown. 
By means of page directive, a JSP can be given the responsibility of an Error page. An Error JSP is called by 
This exception is passed as an instance of 
r JSP (also accessible via implicit exception object). 
Defining and Using Error Pages 
• isErrorPage attribute of a page directive is used to declare a JSP as an error 
page. 
• JSP pages are informed about the error page by setting errorPage attribute of page directive 
In the figure below, error.jsp is defined as JSP Error page and index.jsp is informed to call error.jsp if any 
uncaught exception rose. This is done by setting attributes errorPage and isErrorPage of the page 
index.jsp error.jsp 
MVC + Cas 
We have covered an adequate amount of Servlets and JSdifferent architectures that are most commonly used for th 
also help us to understand where thesused/popular architecture i.e. Model A small case study “Address Book” ism 
Error Page Error P 
entirely, if you want. This also 
the web server when an uncaught exception gets occurred. 
java.lang.Throwable to Erro 
directive on these JSPs.
Web Design  Development – CS506 VU 
© Copyright Virtual University of Pakistan 
394 
Case Study – Address Book 
What we have learned is going to be implemented in this Address Book example. Here MS-Access is being 
sed as DBMS. This database will have only one table, Person with following attributes 
u 
Ingredients of Address Book 
rver Pages and Error Page that are being used in this Address Book example are: - 
. Java B 
. Perso Has following attributes: 
– n 
– address 
– phoneNum 
. Pers 
– En database logic. 
– The nfo data. 
. Java Server P 
. addperso 
– Used to collect new person info that will be saved in database. 
. saveper 
– Re n info from addperson.jsp 
– Saves it to database 
. searchperson.jsp 
oviding name 
Java B 
eans, Java Seeans 
nInfo– ame 
onDAO capsulates 
refore, it will be used to save and retrieve PersonI 
ages 
n.jsp 
son.jsp 
ceives perso 
– Used to provide search criteria to search Person’s info by pr
Web Design  Development – CS506 VU 
© Copyright Virtual University of Pakistan 
395 
. showpe 
– This page receive person’s name from searchperson.jsp to search in database 
– Retriev son record found against person name 
Error Page 
. 
the type of exception. 
ition to that, it also displays the message associated with the received exception to the user. 
P w 
N scuss the flow of program. Assume that the system has been deployed on a JSP compatible 
Web Server ke Tomcat and has been ready to use for clients. The following figure helps to understand the 
program flow of this small example. 
rson.jsp 
es and displays per 
addbookerror.jsp 
– This p– In add 
age is declared as an error page and used to identify 
rogram Flo 
ow let’s di li addperson.jsp takes person’s information from the user and sends it to saveperson.jsp. After receiving 
request, saveperson.jsp makes an object of PersonInfo using received information and saves it into the 
database using PersonDAOJava bean. 
Similarly, searchperson.jsp takes search criteria (name) from the user and passes it to showperson.jsp that 
searches the record in database using PersonDAO and shows the results to the user. 
If any uncaught exception is generated on these JSP, addbookerror.jsp is called implicitly, which displays an 
appropriate message to the user after identifying the exception type.
Web Design  Development – CS506 VU 
© Copyright Virtual University of Pakistan 
396 
Code for the Case Study 
PersonInfo represents the record of one person and its objects are used to interrupt the information about 
persons. 
package vu; 
port java.io.*; 
ublic class PersonInfo implements Serializable{ 
private String name; 
private String address; 
private int phoneNum; 
phoneNum = 0; 
setters 
public void setName(String n){ 
public void setAddress(String a){ 
} 
public void setPhoneNum(int pNo){ 
phoneNum = pNo; 
} 
// getters 
public String getName( ){ 
return name; 
Let’s have a look on the code of each component used in the case study; first start from JavaBeans. PersonInfo 
im 
p 
// no argument constructor 
public PersonInfo() { name = ; 
address = ; 
} 
// 
name = n; } 
address = a; 
} 
public String getAddress( ){ return address;
Web Design  Development – CS506 VU 
© Copyright Virtual University of Pakistan 
397 
} 
public int getPhoneNum( ){ 
return phoneNum; 
} // end class PersonInfo 
Pers 
This elp in retrieving and storing person’s records in database. The code is given below: 
packa 
im *; 
import jav 
public class PersonDAO{ 
private Connection con; 
public PersonDAO() throws ClassNotFoundException , SQLException { establishConnection(); } 
// method used to establish connection with db 
private void establishConnection() throws ClassNotFoundException , SQLException { 
// establishing conection 
Class.forName(sun.jdbc.odbc.JdbcOdbcDriver); 
String conUrl = jdbc:odbc:PersonDSN; 
con = DriverManager.getConnection(conUrl); 
} 
onDAO 
class will h 
ge vu; 
port java.util. 
a.sql.*; 
// default constructor
Web Design  Development – CS506 VU 
© Copyright Virtual University of Pakistan 
398 
} 
// used to search the person records against name and returns 
ly those PersonInfo objects 
// which matches the search criteria i.e. name 
publi trievePersonList(String Name) throws SQLException { 
ArrayLis ); 
// preparing query 
String 
PreparedStatement pStmt = con.prepareStatement(sql); 
pStmt.setS 
// executing quer 
ResultSet rs = pStm y(); 
String name; 
String add; 
int pNo; 
while ( rs.next() ) { 
name = rs.getStrin 
add = rs.getS ); 
pNo = rs.getI ber); 
// creating a CourseOutlineBean object 
PersonI nBean = new PersonInfo(); 
person me(nam 
personBean.setAddress(add); 
pe (pNo); 
// adding a bean to arraylist 
personList.add(personBean); 
} // end while 
return personList; 
// the ArrayList that contains on 
c ArrayList ret personList = new ArrayList( 
sql =  SELECT * FROM Person WHERE name = ?; 
tring( 1, pName); 
y 
t.executeQuer 
g(name) tring(address nt(phoneNum 
; 
nfo perso 
Bean.setNa 
e); 
rsonBean.setPhoneNum
Web Design  Development – CS506 VU 
© Copyright Virtual University of Pakistan 
399 
} // end retrievePersonList 
PreparedStatement pStmt = con.prepareStatement(sql); 
String name = person.getName(); 
String add = person.getAddress(); 
o = person.getPhoneNum(); 
pStmt.setString( 1 , name ); 
iding finalize method to release acquired resources 
try{ 
if(con ! 
con.close(); 
} 
}catch( 
System.ou 
} 
} // end finalize 
} // end PersonDAO class 
// this method accepts an object of PersonInfo, and stores it into // the database public void addPerson(PersonInfo person) throws SQLException{ String sql =  INSERT INTO Person VALUES (?, ?, ?); 
int pN 
pStmt.setString( 2 , add ); pStmt.setInt( 3 , pNo ); 
pStmt.executeUpdate(); 
} // end addPerson 
// overr 
public void finalize( ) { 
= null){ 
SQtion sqlex){ 
LExcept.println(sqlex);
Web Design  Development – CS506 VU 
© Copyright Virtual University of Pakistan 
400 
Now let’s t pages 
addperson. 
This SP the user. It contains three Input 
ields for name, address and phone number as shown in the diagram. This page sends this information to 
p for further processing, 
ake a look at the code for JSP 
jsp 
J page gets person record’s information from 
Fsaveperson.js 
The code that is used to generate the above page is given below: 
%-- Although there are no chances of exception to arise on this page, for consistency, error page is 
defined on top of all JSPs 
--% 
%@page errorPage=addbookerror.jsp % 
html body 
center 
h2 Address Book /h2 
h3 Add New Person/h3 
%-- Form that contains Text input fields and sending it to 
saveperson.jsp --% 
form name =register action=saveperson.jsp /
Web Design  Development – CS506 VU 
© Copyright Virtual University of Pakistan 
401 
TABLE BORDER=1  
TR 
input type=text name=name / 
/TR 
/h4 /TD 
TD input type=tex name=address / /TD 
TR TD h4Phone Number/h4 /TD 
TD input type=text name=phoneNum / /TD 
/TR 
TR TD COLSPAN=2 ALIGN=CENTER  
input type=submit value=save /input type=reset 
value=clear / 
/TD 
/TR 
LE 
 
h4 
%-- A 
a href hperson.jsp  Search Person /a 
/h4 
/center 
/body 
/html 
TD h4  Name /h4 /TD TD /TD 
TR TD h4 Adt 
dress  
/TR 
/TAB/form 
 
link to searchperson.jsp --% =searc
Web Design  Development – CS506 VU 
© Copyright Virtual University of Pakistan 
402 
saveperso 
This JSP p ata from the addperson.jsp, makes an object of PersonInfo and saves it to the database 
using PersonDA also disp ys an informative message to the user if new person 
record is saved hyperlinks to navigate on to the desired pages as 
shown in the following diagram: 
The code e is given below: 
error page --% 
errorPage=addbookerror.jsp % 
%@ page import=java.sql.* % 
body 
%-- creating PersonDAO object and storing in page scope --% 
jsp:useBean id=pDAO class=vu.PersonDAO scope=page / 
%-- creating PersonBean object and storing in page scope --% 
jsp:useBean id=personBean class=vu.PersonInfo scope = page / 
%-- 
setting all properties of personBean object with input 
parameters using * 
--% 
jsp:setProperty name=personBean property=* / 
%-- 
to save Person record into the database, calling addperson 
n.jsp 
age gets d 
O class. Apart from these, it lasuccessfully into the database and two 
of this pag 
%-- defining 
%@page 
 
html
Web Design  Development – CS506 VU 
© Copyright Virtual University of Pakistan 
403 
method of PersonDAO --% % pDAO.addPerson(personBean); % 
h4 
a href=addperson.jsp  Add Person /a 
a href=searchperson.jsp  Search Person /a 
/h4 
/center 
 
/html 
sea 
It g d sends it to showperson.jsp to display the search results. 
he outlook of the page is given below: 
center h3 New Person Record is saved successfully!/h3 
/h4 
h4 
/body 
rchperson.jsp ets search criteria from the user (i.e. name) an 
T
Web Design  Development – CS506 VU 
© Copyright Virtual University of Pakistan 
404 
The code used to generate the above page given page is: 
%@page errorPage=addbookerror.jsp % 
center 
h2 Address Book /h2 
h3 Search Person/h3 
TABLE BORDER=1  
h4 Name/h4 /TD 
TD input type=text name=name / /TD 
it value=search /input type=reset 
/TD 
/TR 
/TABLE 
/form 
h4 
on.jsp  Add Person /a 
/center/body 
/html 
%-- defining error page --% 
html body 
%-- Form that contains Text input field and sending it to showperson.jsp --% form name =search action=showperson.jsp / 
TR TD  
/TR TR TD COLSPAN=2 ALIGN=CENTER input type=subm 
value=clear / 
a href=addpers /h4
Web Design  Development – CS506 VU 
© Copyright Virtual University of Pakistan 
405 
showperson.jsp 
showperson.jsp receives search criteria on.jsp, that is entered by the user to 
find the matching record. This page retrieves the complete list of matching records from the database using 
t, when person named “saad” is searched. 
(i.e. name) from the searchpers 
PersonDAO, and shows them to the user. This following figure gives you the sigh 
Below, the code of showperson.jsp is given: 
%@page errorPage=addbookerror.jsp % 
vu.* % 
html 
body 
center 
h2 Address Book /h2 
h3 Following results meet your search criteria/h3 
TABLE BORDER=1  
TH Name /TH 
%-- defining error page --% 
%-- importing required packages --% %@page import=java.util.* % %@page import= 
TR 
TH Address /TH TH PhoneNum /TH 
/TR
Web Design  Development – CS506 VU 
© Copyright Virtual University of Pakistan 
406 
DAO class=vu.PersonDAO scope=page / 
the Database using // retrievePersonList() method 
of PersonDAO 
rsonDAO.retrievePersonList(pName); 
PersonInfo person = null; 
% 
/TD 
TD %= person.getAddress()% /TD 
% 
} // end for 
% 
/TABLE  
a href=addperson.jsp  Add Person /a 
a href=searchperson.jsp  Search Person /a 
/center 
/body 
/html 
jsp:useBean id=p 
% 
// getting search criteria sent by searchperson.jsp 
String pName = request.getParameter(name); // retrieving matching records from 
ArrayList personList = pe 
// Showing all matching records by iterating over ArrayList 
for(int i=0; ipersonList.size(); i++) { person = (PersonInfo)personList.get(i); 
TR TD %= person.getName()%  
TD %= person.getPhoneNum()% /TD /TR
Web Design  Development – CS506 VU 
© Copyright Virtual University of Pakistan 
407 
addbookerror.jsp 
This JSP error page is called implicitly by all other JSP pages whenever any uncaught / unhandled exception 
ccurs. It also finds out the type of the exception that is generated, and shows an appropriate message to 
e user: 
%-- indicating that this is an error page --% 
% a 
%-- importing class --% 
html 
head titleError/title /head 
body 
h2 
Error Page 
/h2 
h3 
%-- scriptlet to determine exception type --% 
% 
if (exception instanceof SQLException) { 
% 
An SQL Exception 
% 
} else if (exception instanceof ClassNotFoundException){ 
% 
} else { 
% 
%-- end scriptlet to determine exception type --% 
occured while interacting with the database 
oth 
@pge isErrorPage=true % 
 
%@page import = java.sql.SQLException % 
% A Class Not Found Exception 
A Exception % } // end if-else 
%
Web Design  Development – CS506 VU 
© Copyright Virtual University of Pakistan 
408 
/h3 
The Error Message was 
%= exception.getMessage() % 
/h3 
h ter! /h3 
eturn back to addperson.jsp or searchperson.sjp 
--% 
a href=controller.jsp?action=addperson  Add 
Person /a 
a href=controller.jsp?action=searchperson  Search 
Person /a 
/h3 
/body 
/html 
Model 
Now, more t plications need to support multiple types of users with multiple types of 
interfaces. Fo xample, an online store may require an HTML front for Web customers, a WML front for 
wireless customers, a JavaTM (JFC) / Swing interface for administrators, and an XML-based Web service for 
supplier 
h3 
3  Please Try Again La%-- hyperlinks to r 
h3 
 
View Controller (MVC) han ever, enterprise apr e 
s
Web Design  Development – CS506 VU 
© Copyright Virtual University of Pakistan 
409 
Also, several problems can arise when applications contain a mixture of data access code, business logic 
code, and presentation code. Such applications are difficult to maintain, because interdependencies between 
oupling 
makes classes difficult or impossible to reuse because they depend on so many other classes. Adding new 
ata views often requires re-implementing or cutting and pasting business logic code, which then requires 
n multiple places. Data access code suffers from the same problem, being cut and pasted 
among business logic methods. 
The Model-View-Controller architecture solves these problems by decoupling data access, business logic, 
and data presentation and user interaction. Such separation allows multiple views to share the same 
enterprise data model, which makes supporting multiple clients easier to implement, test, and maintain. 
Partici 
The in (model, view  controller) is given below: 
The model represents the state of the component (i.e. its data and the methods required to manipulate 
it) in ed. 
View 
ers the contents of a model and specifies how that data should be presented. There can 
be multiple views for the same model within single applications or model may have different views in 
different applications or operating systems. 
. Controller 
The the model. In a web 
app HTTP requests. The actions performed by the model 
include activating business processes or changing the state of the model. Based on the user interactions 
and the outcome of the model actions, the controller responds by selecting an appropriate view. 
Evolution of MVC Architecture 
In the beginning, we used no MVC. Then we had MVC Model 1 and MVC Model 2 architectures. And 
peop uch as Apache Struts based on Model 2 
archi ndard web based application framework i.e. JavaServer Faces (JSF). 
In this handout, we’ll only talk about MVC Model 1. 
all of the components cause strong ripple effects whenever a change is made anywhere. High c 
d 
maintenance i 
pants and Responsibilities dividual’s responsibility of three participants 
. Model 
dependent of how the component is viewed or render 
. 
The view rend 
controller translates interactions with the view into actions to be performed by lication, they appear as GET and POST 
le came up with so called web application frameworks s 
tecture. And finally we have a sta
Web Design  Development – CS506 VU 
© Copyright Virtual University of Pakistan 
410 
MVC 
A M ecture consists of a Web browser directly accessing Web-tier JSP pages. The JSP pages 
access JavaBeans that represent the application model. And the next view 
to di let, HTML page, and so on) is determined either by hyperlinks selected in the 
source document or by request parameters. 
Model 1 odel 1 archit 
splay (JSP page, serv In M is decentralized, because the current page being displayed 
deter age to display. In addition, each JSP page or servlet processes its own inputs 
(parameters from GET or POST). And this is hard to maintain, for example, if you have to change the view 
selection, then several JSP pages need to be changed. In some Model 1 architectures, choosing the next 
page riptlet code, but this usage is considered poor form. 
In MVC Model 1 architecture, the JSP page alone is responsible for processing the incoming request and 
rom content, because all data access is 
performed using JavaBeans. 
lthough the Model 1 architecture should be perfectly suitable for simple applications, it may not be 
cture usually leads to a significant 
nt of scriptlets or Java code embedded within the JSP page, especially if there is a significant amount 
f re em to be much of a problem for Java 
devel d maintained by designers which are only 
aware 
Note nking about the case study discussed earlier in this handout. 
Indee ecture. 
References: 
ƒ 
ƒ 
http://java.sun.com/blueprints/patterns/MVC-detailed.html 
odel 1 architecture, view selection mines the next p 
to display occurs in sc 
replying back to the client. There is still separation of presentation f 
A 
desirable for complex implementations. Random usage of this archite 
amouo 
quest processing to be performed. While this may not seopers, it is certainly an issue if your JSP pages are created an 
of HTML and some scripting language. 
: Probably some of you must be thid, it is based on MVC Model 1 archit 
Java A Lab Course by Umair Javed Java BluePrints - J2EE Patterns 
ƒ Exploring the MVC Design Pattern 
.html 
http://www.javaworld.com/javaworld/jw-12-1999/jw-12-ssj-jspmvc
Web Design  Development – CS506 VU 
© Copyright Virtual University of Pakistan 
411 
Lesson 40 
MVC Model 2 Architecture 
ch and page-with-bean approach until now. You must be wondering 
n w ad covered these. Probably these buzz words are new one for you but we already covered these 
ics. L s review these once again. 
e-C 
that is collection of JSPs. Generally this approach is followed to get started with 
plications. This approach is represented in the following diagram: 
We have studied page-centric approa 
whee htopet’ 
Pagentric Approach A web applicationdeveloping web ap 
The page-centric approach has lot of draw backs such as the code becomes a mixture of presentation, 
e. 
Page-with-Bean Approach (MVC Model1) 
This approach is different from page-centric approach in a way that all the business logic goes into 
JavaBeans. Therefore, the web application is a collection of JSPs and JavaBeans. But still this approach is 
ogics. We have made an address book example in the last handout 
MVC Model 2 Architecture 
This architecture introduces a controller. This controller can be implemented using JSP or servlet. 
Introducing a controller gives the following advantages: 
ƒ It centralizes the logic for dispatching requests to the next view based on: 
-The Request URL 
business and data access logic. The maintenance and up-gradation of the application becomes a nightmarScaling of such kind of application is also difficult and lots of code is also get duplicated. 
insufficient to separate different kind of l 
using this approach.
Web Design  Development – CS506 VU 
© Copyright Virtual University of Pakistan 
412 
-Input Parameters 
-Application state 
ƒ It gives the single point of control to perform security checks and to record 
ƒ It also encaps a form that is usable by the back-end MVC model. We’ll 
discuss it with the help of an example. 
The following n that is 
built using MVC Mod 
logging information 
ulates the incoming data into 
figure will help you to understand the architecture and functioning of the applicatioel 2 architecture. 
The client (browser) sends all the requests to the ccharge of the request processing and creation oJSoas and there is notre 
ontroller. Servlet/JSP acts as the Controller and is in 
f any beans or objects (Models) used by the JSP. 
P is w rking View much processing logic within the JSP page itself, it is simply 
sponsible for retrieving objects and/or beans, created by the Servlet, extracting dynamic content from 
them and put them into the static templates. 
Case Study Address Bo k usin 
The address book example that is built using page-with-bean approach will be modified to incorporate 
controller. We’ to implement controller using JSP as well as with servlet. Let’s first 
incorporate controller 
: og MVC Model 2 
ll show you how using JSP.
Web Design  Development – CS506 VU 
© Copyright Virtual University of Pakistan 
413 
Introducing a JSP as Controller 
r JSP (controller.jsp) that 
ƒ Acts as a controller 
ƒ Recieves requests form addperson.jsp  searchperson.jsp 
ƒ Identifies the page which initiates the request 
ƒ Uses JavaBeans to save or search persons to/from database 
ƒ Forwards or redirects the request to appropriate (saveperson.jsp or showperson.jsp) page. 
The program flow of this example is shown in the following diagram: 
Add anothe As you can see in the diagram that all the requests are submitted to controller which uses the JavaBeans and 
forwards/redirects the user to another view (JSP)? If any exception arises on controller or JSPs, the control 
would automatically be transferred to addbookerror.jsp to display an appropriate message. 
How controller differentiates between requests? 
Most likely, you must be thinking about it. The simplest solution lies in using the consistent name (e.g. 
action) of the submit button across all the pages but with different and unique values. The same rule applies 
to hyperlinks that send the action parameter along with value by using query string technique. 
This eases the controller’s job to identify which page is actually generated the request and what to do next. 
The controller simply retrieves the value of action parameter using request.getParameter() method. Now, 
if-else structure can be used to compare the possible values of action to act upon the requested task. 
Now, let’s first see the code of JavaBean that is used in this example.
Web Design  Development – CS506 VU 
© Copyright Virtual University of Pakistan 
414 
PersonInfo 
This JavaBean is used to represent one person record. The code is given below: 
package vu; 
import java.io.*; 
public class PersonInfo implements Serializable{ 
private String name; 
private String address; 
private int phoneNum; 
// no argument constructor 
public PersonInfo() { 
name = ; 
address = ; 
phoneNum = 0; 
} 
// setters 
public void setName(String n){ 
public void setAddress(String a){ 
address = a; 
} 
setPhoneNum(int pNo){ 
eNum = pNo; 
// getters 
return address; 
} 
public int getPhoneNum( ){ 
retu 
} 
} // end class PersonInfo 
name = n; } 
public void phon 
} 
public String getName( ){ return name; 
} public String getAddress( ){ 
rn phoneNum;
Web Design  Development – CS506 VU 
© Copyright Virtual University of Pakistan 
415 
PersonDAO 
This class will help in retrieving and storing person’s records in database. The code is given below: 
package vu; 
import java.util.*; import java.sql.*; 
ublic class PersonDAO{ 
private Connection con; 
// default constructor 
public PersonDAO() throws 
ClassNotFoundException , SQLException { 
establishConnection(); } 
// method used to establish connection with db 
priv te 
throws ClassNotFoundException , SQLException { 
// establishing conection 
sun.jdbc.odbc.JdbcOdbcDriver); 
String 
con = tion(conUrl); 
} 
// used to search the person records against name and returns the ArrayList that contains only 
nfo objects which matches the search criteria i.e. name 
public ArrayList retrievePersonList(String pName) throws SQLException { 
ArrayList personList = new ArrayList(); 
// preparing query 
String sql =  SELECT * FROM Person WHERE name = ?; 
PreparedStatement pStmt = con.prepareStatement(sql); 
pStmt.setString( 1, pName); 
// executing query 
ResultSet rs = pStmt.executeQuery(); 
p 
avoid establishConnection() 
Class.forName( conUrl = jdbc:odbc:PersonDSN; DriverManager.getConnec 
// those PersonI
Web Design  Development – CS506 VU 
© Copyright Virtual University of Pakistan 
416 
String name; 
String add; 
name = rs.getString(name); 
pNo = rs.getInt(phoneNumber); 
PersonInfo personBean = new PersonInfo(); 
personBean.setName(name); 
personBean.setAddress(add); 
personBean.setPhoneNum(pNo); 
// adding a bean to arraylist 
} // end while 
d retrievePersonList 
// this method accepts an object of PersonInfo, and stores it into 
// the database 
public void addPerson(PersonInfo person) throws SQLException{ 
ES (?, ?, ?); 
PreparedStatement pStmt = con.prepareStatement(sql); 
String name = person.getName(); 
Str 
int pNo = person.getPhoneNum(); 
pStmt.setString( 1 , name ); 
pSt 
pSt 
pSt 
} // end addPerson // overriding finalize method to release acquired resources 
int pNo; 
while ( rs.next() ) { 
add = rs.getString(address); 
// creating a CourseOutlineBean object 
personList.add(personBean); 
return personList; 
} // en 
String sql =  INSERT INTO Person VALU 
ing add = person.getAddress(); 
mt.setString( 2 , add ); 
mt.setInt( 3 , pNo ); 
mt.executeUpdate();
Web Design  Development – CS506 VU 
© Copyright Virtual University of Pakistan 
417 
con.close(); 
}catch(SQLException sqlex){ 
System.out.println(sqlex); 
} 
} // e 
} // en 
addperson.jsp 
This page is u tabase. Note that a hyperlink is also given at 
the bott the page that takes the user to searchperson.jsp. 
Note: Since we are following MVC model 2 architecture, so all the hyperlinks will also sends the request 
to controller first which redirects the user to requested page. 
public void finalize( ) { 
try{ 
} 
nd finalize 
d PersonDAO class 
sed for entering a new person record into the daom of 
The code of above page is given below:
Web Design  Development – CS506 VU 
© Copyright Virtual University of Pakistan 
418 
%-- Although there are no chances of exception to arise on this page, for consistency, error page is 
defined on top of all JSPs 
%@page errorPage=addbookerror.jsp % 
html 
body 
center 
h3 Add New Person/h3 
%-- As mentioned in MVC2, all the requests are submitted to controller, that’s why action’s 
ns the value of “controller.jsp” 
form name =register action=controller.jsp / 
TABLE BORDER=1  
TR TD h4 Name /h4 /TD TD input type=text 
name=name / /TD 
/TR 
TR TD h4 Address /h4 /TD TD input type=text 
name=address / /TD 
TR TD h4Phone Number/h4 /TD TD input type=text 
name=phoneNum / /TD 
/TR 
TR TD COLSPAN=2 ALIGN=CENTER 
%-- As described above the technique to differentiate between the requests, 
“save”. 
--% 
input type=submit name =action value=save / 
input type=reset value=clear / 
/TD 
/TR 
--% 
h2 Address Book /h2 
contai --% 
 
/TR 
the name of the button is “action” with value
Web Design  Development – CS506 VU 
© Copyright Virtual University of Pakistan 419 
/TABLE 
/form 
h4 
%- The hyperlink will also sends the request to controller 
Note the action parameter with its value are also part of hyperlink using 
the query string technique. 
--% 
a 
href=controller.jsp?action=searchperson  
Search Person /a 
/h4 
/body 
/html 
/center
Web Design  Development – CS506 VU 
© Copyright Virtual University of Pakistan 420 
searchperson.jsp 
This JSP is used to sear n at 
the bottom of add 
ch the person record against name given in the text field. A hyperlink is also given.jsp. 
perso 
The code that is used to generate that above page is given below: 
%-- defining error page --% 
%@page errorPage=addbookerror.jsp % 
 html 
body 
center 
h2 Address Book /h2 
h3 Search Person/h3 
form name =search action=controller.jsp / 
TABLE BORDER=1  
TR TD h4 Name /h4 /TD TD input type=text 
name=name / /TD 
/TR 
TR 
TD COLSPAN=2 ALIGN=CENTER
Web Design  Development – CS506 VU 
© Copyright Virtual University of Pakistan 421 
%- The name of the button is still “action” but with different value “search”. 
tion value=search / 
input type=reset value=clear / 
/TR 
/TABLE 
/form 
h4 
%- The action parameter with different value “addperson” are part of hyperlink here as 
--% 
  Add Person /a 
/center 
/body 
/html 
--% 
input type=submit name =ac 
/TD 
well. 
a href=controller.jsp?action=addperson/h4
Web Design  Development – CS506 VU 
© Copyright Virtual University of Pakistan 422 
controller.jsp 
As mentio that controller.jsp identifies the page which initiates the request and use JavaBeans to 
save/searc to/from database. Also its job list includes redirecting the user to appropriate page. 
Since this JSP is available. Let’s check it out its code: 
%-- defining error page --% 
%@page errorPage=addbookerror.jsp % 
%-- impor avaBeans --% 
%@page import =java.util.* % %@page 
import =  
html 
body 
%-- declaring PersonDAO object--% 
jsp:useBean id=pDAO class=vu.PersonDAO scope=page / 
%- scriptlet to identify JSP for redirection purpose if request comes from hyperlinks 
% 
// Remember that “action” is the name of buttons as well 
// it is used in hyperlinks in making of query string 
String action = request.getParameter(action); 
// if Add Person hyperlink is clicked 
if (action.equals(addperson) ){ 
response.sendRedirect(addperson.jsp); 
// if Search Person hyperlink is clicked 
} else if (action.equals(searchperson)){ 
response.sendRedirect(searchperson.jsp); 
// if save button is clicked of addperson.jsp 
}else if (action.equals(save)) { 
% 
ned earlier 
h persons 
doing only processing therefore no view 
ting required packages. package vu contains J 
vu.* % 
--% 
// retrieving action parameter value
Web Design  Development – CS506 VU 
© Copyright Virtual University of Pakistan 423 
// declaring PersonInfo obeject 
jsp:useBean id=personBean class=vu.PersonInfo scope=page/ 
%-- 
--% 
jsp:setProperty name=personBean property=* / 
%-- to insert record into database--% 
ean); 
// redirecting user to saveperson.jsp 
response.sendRedirect(saveperson.jsp); 
%-- if search button is clicked on searchperson.jsp --% 
% 
// storing personList(contains PersonInfo objects) into // request hashmap 
List); 
% 
- forwarding request to showperson.jsp to retrievestored arraylist (“list”) 
person.jsp / 
% 
ch 
% 
/body 
/html 
setting all properties of personBean object with input parameters using * 
% pDAO.addPerson(personB 
% 
}else if (action.equals(search) ) { 
String pName = request.getParameter(name); ArrayList personList = pDAO.retrievePersonList(pName); 
request.setAttribute(list, person 
%- --% 
jsp:forward page=show 
} // end if page == sear
Web Design  Development – CS506 VU 
saveperson.jsp This page displays a successful message indicating that person record is saved. Its also give the options to 
the user to move on to addperson.jsp or searchperson.jsp through hyperlinks. Note that these hyperlinks 
also first take the user to controller.jsp then on to requested page. 
The code of saveperson.jspis given below: 
%-- defining error page --% 
%@page errorPage=addbookerror.jsp % 
body 
center 
sfully!/h3 
a href=controller.jsp?action=addperson  
Add Person /a 
/h4 
hperson  Search 
/center 
/body 
/html 
html 
h3 New Person Record is saved succes 
h4 
/h4 
a href=controller.jsp?action=searc 
Person /a /h4 
© Copyright Virtual University of Pakistan 424
Web Design  Development – CS506 VU 
© Copyright Virtual University of Pakistan 425 
showperson.jsp 
aad” is searched. 
T 
his following figure gives you the view when name “s 
Below, the code of showperson.jsp is given: 
ng error page --% 
%@page errorPage=addbookerror.jsp % 
%-- importing required packages --% 
%@  %@page 
impo 
html body 
center 
h3 Following results meet your search criteria/h3 
TR 
TH Name /TH 
/TR 
on controller.jsp to display PersonInfo objects 
%-- defini 
page import=java.util.* % rt=vu.* % 
h2 Address Book /h2 
TABLE BORDER=1  
TH Address /TH TH PhoneNum /TH 
% 
// retrieving arraylist stored
Web Design  Development – CS506 VU 
© Copyright Virtual University of Pakistan 426 
ArrayList personList = (ArrayList)request.getAttribute(list); PersonInfo person 
= null; 
{ 
%-- displaying PersonInfo details--% 
TR TD %= person.getName()% /TD TD %= 
/TD TD %= person.getPhoneNum()% 
/TR 
% 
} // end for 
h4 
a href=controller.jsp?action=addperson Add Person /a a 
href=controller.jsp?action=searchpersonSearch Person/a 
/h4 
/c enter 
/body 
/h 
for(int i=0; ipersonList.size(); i++) 
person = (PersonInfo)personList.get(i); % 
person.getAddress()% /TD 
% 
/TABLE  
tml
Web Design  Development – CS506 VU 
© Copyright Virtual University of Pakistan 427 
addbookerror.jsp 
User will view this page only when any sort of exception is generated. The code of this page is given below: 
%-- indicating that this is an error page --% 
%@ 
%-- im 
%@page import = java.sql.SQLException % 
html 
head titleError/titl 
body 
h2 
h3 
%-- scriptlet to determine exception type --% 
% 
if (exception instanceof SQLException) { 
L Exception 
% 
} else if (exception instanceof ClassNotFoundException){ 
% 
A Class Not Found Exception 
% 
} else { 
% 
A Exception 
%-- end scriptlet to determine exception type --% 
page isErrorPage=true % 
porting class --% 
e /head 
Error Page /h2 
% 
An SQ 
% } // end if-else 
%
Web Design  Development – CS506 VU 
© Copyright Virtual University of Pakistan 428 
occured while interacting with the database 
/h3 
h3 
The Error Message was 
%= exception.getMessage() % 
/h3 
%-- hyperlinks to return back to adperson.jsp orsearchperson.sjp 
--% 
h3 
a 
href=controller.jsp?action=addperso 
n  Add Person /a 
a 
href=controller.jsp?action=searchperso 
n  Search Person /a 
/h3 
/body 
/html 
JSP is the Right Choice as a Controller? 
Since JSP that is performing the job of controller is doing only processing and there is no view available of 
it. It includes the logic of selecting JSP and to retrieve/store records from/to dataset using JavaBeans. 
But remember the reason for introducing JSPs? JavaServer Pages are built for presentation (view) only so 
JSP is really not a good place for such kind of logic. Concluding, what’s the option we have? The answer is, 
use Servlets as controller. 
Introducing a Servlet as Controller 
Remove the controller.jsp from the previous example code and add ControllerServlet.java (a servlet) into 
this example. This ControllerServlet.java performs the same job that was previously performed by 
controller.jsp. 
Besides adding ControllerServlet.java, you have to modify all the addresses which are previously pointing to 
controller.jsp. For example the value of action attribute of form tag  the address of hyperlink in all 
/h3 
h3  Please Try Again Later!
Web Design  Development – CS506 VU 
© Copyright Virtual University of Pakistan 429 
concerned pages. 
If controller is defined in web.xml as an alias of ControllerServlet.java, consider the following fragment of 
code which shows the value of action attribute of form tag before and after introducing change. 
form name =register action=controller / 
When controller.jsp is acting as a controller 
Search Person 
/a 
When ControllerServlet.java is acting as a controller 
a href=controller?action=searchperson  
Search Person 
/a 
For example, the following code snippet is taken from ControllerServlet.java to demonstrate how to pass 
SQLExceptionto addbookerror.jsp 
… 
……………… 
}catch (SQLException sqlex){ 
// setting SQLException instance 
request.getRequestDispatcher(addbookerror.jsp); 
rd.forward(request, response); 
} // end catch 
When controller.jsp is acting as a controller form name =register action=controller.jsp / When ControllerServlet.java is acting as a controller then value of action attribute becomes: 
Similarly, the following comparison shows the code of hyperlinks used in the previous example before and after making changes 
a href=controller.jsp?action=searchperson  
Passing Exceptions to an Error JSP from a Servlet Servlet can use existing error pages (like addbookerror.jsp) to pass on the exceptions. Set the request attribute to javax.servlet.jsp.JspExcpetion with the exception object you want to pass. After that forwards the request to error page. 
…………… 
request.setAttribute(javax.servlet.jsp.JspException , sqlex); RequestDispatcher rd =
Web Design  Development – CS506 VU 
C 
© Copyright Virtual University of Pakistan 430 
otrollerServlet.java 
The following code is of servlet that is acting as a controller 
ackage controller; 
import vu.*; 
import java.io.*;import java.net.*; 
extends HttpServlet { 
// This method only calls processRequest() 
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws 
xception { 
processRequest(request, response); 
} 
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws 
ServletException, IOException { 
} 
equest(HttpServletRequest request, 
HttpServletResponse response) throws ServletException, IOException { 
// retrieving value of action parameter 
String userAction = request.getParameter(action); 
// if request comes to move to addperson.jsp from hyperlink 
if (userAction.equals(addperson) ) { 
response.sendRedirect(addperson.jsp); 
// if request comes to move to searchperson.jsp from hyperlink 
} else if (userAction.equals(searchperson)) { 
response.sendRedirect(searchperson.jsp); 
p 
import java.sql.*; import java.util.*; import javax.servlet.*; import javax.servlet.http.*; public class ControllerServlet 
ServletException, IOE 
// This method only calls processRequest() 
processRequest(request, response); 
protected void processR
Web Design  Development – CS506 VU 
// if “save” button clicked on addperson.jsp to add new record 
} if (userAction.equals(save)) { 
// this method defined below 
addPerson(request,response); 
// if “search” button clicked on searchperson.jsp for search 
searchPerson(request,response); 
} // end processRequest() 
// if request comes to add/save person 
private void addPerson(HttpServletRequest request, HttpServletResponse response) 
throws ServletException, IOException 
{ try 
{ 
// creating P 
PersonDAO w PersonDAO(); 
// creating PersonInfo object 
PersonInfo person = new PersonInfo(); 
// setting properties of Person object 
// setting name property 
String pName = request.getParameter(name); 
person.setName(pName); 
ess(add); 
// setting phoneNumb property 
String pNo = request.getParameter(phoneNum); 
on(person); 
// redirecting page to saveperson.jsp 
response.sendRedirect(saveperson.jsp); 
} else if (userAction.equals(search)) { // this method defined below 
} 
ersonDAO object 
pDAO = ne 
// setting address propertyt String add = request.getParameter(address); person.setAddr 
int phoneNum = Integer.parseInt(pNo); person.setPhoneNum(phoneNum); // calling PersonDAO method to save data into database pDAO.addPers 
© Copyright Virtual University of Pakistan 431
Web Design  Development – CS506 VU 
© Copyright Virtual University of Pakistan 432 
}catch (SQLException sqlex){ 
request.setAttribute(javax.servlet.jsp.JspException , sqlex); 
RequestDispatcher rd = request.getRequestDispatcher(addbookerror.jsp); 
catch (ClassNotFoundException cnfe){ 
// setting ClassNotFoundException instance 
request.setAttribute(javax.servlet.jsp.JspException , cnfe); 
RequestDispatcher rd = 
request.getRequestDispatcher(add 
bookerror.jsp); rd.forward(request, 
response); 
} 
}// end addperson() 
// if request comes to search person record from database 
private void searchPerson(HttpServletRequest request, 
tion, IOException { 
try { 
String pName = request.getParameter(name); 
// calling DAO method to retrieve personlist from database // against name 
ArrayList personList = pDAO.retrievePersonList(pName); 
request.setAttribute(list, personList); 
// setting SQLException instance 
rd.forward(request, response); } 
HttpServletResponse response) throws ServletExcep 
// creating PersonDAO object PersonDAO pDAO = new PersonDAO();
Web Design  Development – CS506 VU 
© Copyright Virtual University of Pakistan 433 
// forwarding request to showpeson, so it can render personlist 
RequestDispatcher rd = request.getRequestDispatcher(showperson.jsp); 
rd.forward(request, response); 
request.setAttribute(javax.servlet.jsp.JspException , sqlex); 
RequestDispatcher rd = 
request.getRequestDispatcher(add 
bookerror.jsp); rd.forward(request, 
response); 
ClassNotFoundException instance 
request.setAttribute(javax.servlet.jsp.JspException , cnfe); 
RequestDispatcher rd = request.getRequestDispatcher(addbookerror.jsp); 
rd.forward(request, response); 
}// end searchPerson() 
} // end ControllerServlet 
web.xml 
As you already familiar, for accessing a servlet, you need to define a URL pattern in web.xml. This is shown 
below: 
?xml version=1.0 encoding=UTF-8? web-app 
servlet 
servlet-name ControllerServlet /servlet-name 
servlet-class controller.ControllerServlet /servlet-class 
/servlet 
}catch (SQLException sqlex){ // setting SQLException instance 
}catch (ClassNotFoundException cnfe){ // setting 
}
Web Design  Development – CS506 VU 
© Copyright Virtual University of Pakistan 434 
servlet-mapping 
servlet-name ControllerServlet /servlet-name 
/controller /url-pattern 
/servlet-mapping 
References: 
urse by Umair Javed. 
. Java E-commerce course at Stanford 
url-pattern 
/web-app 
. Java A Lab Co
Web Design  Development – CS506 VU 
Lesson 41 Layers and Tiers How do you structure an application to support such operational requirements as maintainability, 
reusability, scalability and robustness? The answer lies in using Layers and Tiers? What different 
technologies Java provides to support layered or tiered architectures. The answer to these questions will 
remain our focus in this handout. A small case study will also be used to comprehend the concept of layers. 
Layers are merely logical grouping of the software components that make up the application or service, 
whereas Tiers refer to the physical residence of those layers. 
In general, 
. Layers – represents the logical view of application 
. Tiers – represents physical view of application 
However, both terms are used intractably very often. You must be confused what does logical  physical 
view mean? Let’s elaborate layers and tiers further in detail to differentiate between them. 
Layers 
The partitioning of a system into layers such that each layer performs a specific type of functionality and 
communicates with the layer that adjoin it. 
The separation of concerns minimizes the impact of adding services/features to an application. The 
application developed in layers also enables tiered distribution (discussed later). Furthermore easier 
maintenance, reuse of code, high cohesion  loose coupling sort of additional benefits are also enjoyed by 
the use of tiered architecture. 
To begin with, layered architecture based on three layers. These are 
ƒ Presentation Layer 
ƒ Business Layer 
ƒ Data Layer 
Note: 
However, there is no upper limit of number of layers an application can have. Each layer can also be further 
break down into several layers depending upon the requirement and size of the application. 
Layers vs. Tiers © Copyright Virtual University of Pakistan 435
Web Design  Development – CS506 VU 
The figure given below shows a simplified view of an application and its layers. 
As you can see in the figure, users can only interact with the presentation layer. The presentation layer 
passe he user request to the business layer, which further passes the request to the data layer. The data 
layer com ces (like Database etc.) or other external services in order to 
accomplish 
Let’s discu nsibility in detail: 
Presentation Layer 
It prov nt/user to interact with the application. This is the only part of the 
application visible to client. 
Its job lis input, validating user’s input (on client side using JavaScript like 
technologies OR on server side), presenting the results of the request made by the user and controlling the 
screen flow (which page/view will be visible to the user). 
Business La 
Also called application layer, it is only concerned with the application specific functionality. It is used to 
implement business rules and to perform business tasks. 
For example, in a banking system, this layer will provide the functionality of banking functions such as 
opening an account, transferring of balance from one account to another, 
Calculation of taxes etc. 
s tmunicates with the data sour the user request. ss each layer’s respo 
ides a user interface to the clie t includes collecting user’s 
yer © Copyright Virtual University of Pakistan 436
Web Design  Development – CS506 VU 
© Copyright Virtual University of Pakistan 437 
Data Layer 
is concerned with the management of the data  data sources of the system. Data sources can be 
database, XML, web services, flat file etc. Encapsulates data retrieval  storage logic For example, the 
address book application needs to retrieve all person records from a database to display them to the user. 
Tiers 
As mentioned, layers help in building a tiered architecture. Like layers, there is no restriction on using 
er of tiers. An application can be based on Single-tier, Two-tier, Three-tier or N-Tier (application 
hich have more than three tiers). The choice of using a tiered architecture is contingent to the business 
requirements and the size of the application etc. 
Tiers are physically separated from each other. Layers are spread across tiers to build up an application. 
Two or more layers can reside on one tier. The following figure presents a three-tier architectural view of an 
application. 
The client tier represents the client machine where actually web browser is running and usually displays 
HTML. You can think of a Presentation as of two parts; one is on client side, for example, HTML. There is 
lso a presentation layer that is used to generate the client presentation often called server presentation. We’ll 
discuss about it later. 
The server machine can consist on a single server machine or more. Therefore, it is possible web server is 
running on one server machine while application server on another. Web server is used to execute web pages 
The client tier represents the client mThe database server is often running on a separate tier, i.e. DB 
machine often called Enterprise information tier. 
It 
numbw 
Presentation Layer 
EIS Layer 
a 
like JSPs whereas application server is used to run special business objects like Enterprise JavaBeans (discussed later). The web layer and applications server can be on two separate machines or they can be on same tier as shown in the diagram
Web Design  Development – CS506 VU 
© Copyright Virtual University of Pakistan 438 
Layers Support in Java 
Th iding specific technology for each layer. This not only 
e nt by freeing the programmer for caring operational features but only reduces the 
production time of the software. 
In the foll on is bifurcated into two layers. These are Client Presentation layer and 
Server Presentation Layer. What client sees in a browser forms client presentation layer while server 
p s the Java technology components? 
(JSP and Servlets etc.) that are used to generate the client presentation. 
Layers Java/J2EE Technology 
e secret of wide spread use of Java lies in provases the developme 
owing figure, Presentati 
resentation layer include On business layer, JavaBeans (also referred as Plain Old Java Objects (POJO) ) can be used. While moving 
tow hitecture, the J2EE hat fits in business layer i.e. Enterprise 
Ja 
EJ sed to encapsulate business logic. They provide additional benefits in 
building up an application such as scalability, robustness, scalability etc. 
On data layer, Data Access Objects (DAO) can be used. Similarly you can use connectors. There are other 
different specialized components provided in java that ease the development of data layer. 
ards a bigger arcprovides the special class tvaBean (EJB). 
Bs are special java classes that are u
Web Design  Development – CS506 VU 
© Copyright Virtual University of Pakistan 439 
J2EE Multi-Tiered Applications 
In a ing based application or a web based. 
As you can see in the following figure, clients can access the web server from behind the firewall as well. 
Supp web 
server. JSP at can be used in a web server. However, there are 
some Frameworks such as JSF etc that can be used in a web server. The classes which form the 
prese eb server and of course controllers are also used over here. 
typical J2EE Multi-Tiered application, a client can either be a sw 
ose, our client is HTML based. Client does some processing on HTML and transports it to and Servlets are possible technologies th 
ntation layer reside on w I wants to perform some business process, it usually gets help from some business layer 
components. The business layer component can be a simple JavaBean (POJO) but in a typical J2EE 
architecture, EJBs are used. Enterprise JavaBeans interacts with the database or information system to store 
and retrieve data. 
EJBs a ks in two different servers. As you already know, JSP and Servlets runs in a web 
s application server. But, generally application server contains the web 
server as well. 
Application server including web server generally resides on a single tier (machine), which is often called 
m retrieves data from the Enterprise Information Tier (EIS) which is a 
separate tier. The response sends back to the client by the middle tier can be HTML, XML etc. This 
response can be seen on the separate tier know as client tier. 
f web server, 
nd JSP/Servlets worerver where as EJBs requires an 
iddle tier. This tier stores and
Web Design  Development – CS506 VU 
© Copyright Virtual University of Pakistan 440 
Case Study: Matrix Multiplication using Layers 
Proble 
as well as shown to the user. 
rmat 
. Inpu 
-inpu where 4,2 represents entries of the first row 
. Display format 
. Storage format for DB 
the order of the matrix 
-The following figure shows the table design that will be used to store the results. 
m Statement 
. Calculate product of two m 
atrices of order 2 * 2 . Result of multiplication should be stored in DB 
Fo 
t format t will be in 4,2,6,5 format separated by commas 
-Displays the matrix as a square 
-Matrix will be stored as a string in the database along with 
Layer by Layer View 
A picture’s worth than thousand words. Therefore, before jumping on to code, let’s put a glance over layers 
that tionality 
irst, loo the whole story. 
will be used in this small case study. The classes that will be used on each layer and what func 
each class will perform will also be discussed. Fk on the following picture that will describe
Web Design  Development – CS506 VU 
The data layer has a class MatrixDAO that is used to save the matrix result into database. As mentioned in 
MatrixDAO called by the MatrixMultiplier, a business layer class. The functionality list of MatrixMultiplier 
ƒ Converting the user input string (e.g.2, 3, 4, 1) into a proper object i.e. a matrix 
ƒ Helps in g product of two matrices 
Controller layer’s class ControllerServlet calls the MatrixMultiplier. This layer calls the various business 
methods (like multiplication of two matrices) of business layer class and got the resultant matrix. 
Furthe nds the ou from 
ri 
atrixBean representing matrix data structure, as you can see in the figure is used across several layers. 
act, t o o 
irst, loo 
the problem statement, that resultant matrix should be saved in the database. So, MatrixDAOis used toaccomplish that. 
includes: 
ƒ data structure. calculatin 
rmore, ControllerServlet setput to the matrixresult.jsp and receives the input xin 
matput.jsp. The M 
In fhe object formed by MatrixMultiplier from a user input string is f MatrixBean type. It is used ttransfer data from one layer to another. 
Fk on the MatrixBean code given below: 
© Copyright Virtual University of Pakistan 441
Web Design  Development – CS506 VU 
© Copyright Virtual University of Pakistan 442 
MatrixBean 
package bo; 
import java.io.*; 
public class MatrixBean implements Serializable{ 
// a 2D array representing matrix 
public int matrix[ 
// construc 
matrix = new int[2][2]; 
matrix[0][1] = 0; 
matrix[1][0] = 0; 
matrix[1][1] = 0; 
} 
// setter tha to array 
public void t y, int z) 
{ 
matrix[1][0] = y; 
matrix[1][1] = z; 
} 
turning a 2D array 
{ 
return m 
} 
rt 2D array into string 
toString(){ return matrix[0][0] + , + 
, + 
matrix[1][0] + , +matrix[1][1] ; } 
} // end MatrixBean 
][ ] ; 
tor 
public MatrixBean() { 
matrix[0][0] = 0; 
t takes 4 int values and assigns these setMatrix(int w, int x, in 
matrix[0][0] = w; 
matrix[0][1] = x; 
// getter re public int[ ][ ] getMatrix() atrix; 
// used to conve 
public String matrix[0][1] +
Web Design  Development – CS506 VU 
matrixinput.jsp 
T of string such as 2,3,5,8. The data will be 
s this page. 
/h2 
h3 
%-- “controller” is an alias/URL pattern of ControllerServlet -% 
for ller  
First Matrix: 
input type=text name = firstMatrix / E.g. 2,3,4,1 
br/ 
Matrix / 
br/ 
input type = submit value = Calculate Product / 
/form 
/h3 
/body 
/html 
ControllerServlet 
This servlet acting as a controller receives the input from matrixinput.jsp. Furthermore, it will interact with 
the business layer class MatrixMultiplier to convert the string into a MatrixBean object, and to multiply two 
matrices. 
his JSP is used to collect the input for two matrices in the form 
ubmitted to ControllerServlet from 
html 
body 
h2 
Enter Two Matrices of order 2 * 2 to compute Product 
m name=matrixInput action=contro 
Second Matrix: input type=text name = second 
© Copyright Virtual University of Pakistan 443
Web Design  Development – CS506 VU 
package © Copyright Virtual University of Pakistan 444 
controller; 
import bl.*; 
import bo.* ; 
o.*; 
import java.net.*; 
import javax.servlet.*; 
import javax.servlet.http.*; 
ontrollerServlet extends HttpServlet { 
nly calls processRequest() 
prote 
HttpServletResponse response) throws 
OException { 
processRequest(request, response); 
} 
// This method only calls processRequest() 
prote tRequest request, 
HttpServletResponse response) throws 
ServletException, IOException { 
processRequest(request, response); 
} 
protected void processRequest(HttpServletRequest request, 
HttpServletResponse response) throws 
ServletException, IOException { 
// retrieving values from input fields of matrixinput.jsp 
String sMatrix1 = req.getParameter(firstMatrix); 
String sMatrix2 = req.getParameter(secondMatrix); 
// Creating MatrixMultipler object 
MatrixMultiplier mm = new MatrixMultiplier(); 
// Passing Strings to convertToObject() method of MatrixMultiplier // convertToObject() is used 
to convert strings into MatrixBean 
import java.i 
public class C 
// This method octed void doGet(HttpServletRequest request, ServletException, I 
cted void doPost(HttpServle
Web Design  Development – CS506 VU 
© Copyright Virtual University of Pakistan 445 
MatrixBean fMatrix = mm.convertToObject(sMatrix1); 
MatrixBean sMatrix = mm.convertToObject(sMatrix2); 
// passing MatrixBean’s objects to multiply() method of // MatrixMultiplier and receiving the 
product matrix in the form // of MatrixBean 
MatrixBean rMatrix = mm.multiply(fMatrix, sMatrix); 
// saving results in database 
mm.saveResult(rMatrix); 
// storing the product of matrices into request, so that it can be // retrieved on matrixresult.jsp 
req.setAttribute(product, rMatrix); 
// forwarding request to matrixresult.jsp 
RequestDispatcher rd = req.getRequestDispatcher(matrixresult.jsp); rd.forward(req, res); 
} // end processRequest() 
} // end ControllerServlet 
MatrixMultiplier 
The business layer class that’s primary job is to calculate product of tow matrices given in the form of 
MatrixBean. This class also has a method convertToObject that takes a String and returns back a 
MatrixBean object. MatrixMultiplier will also interact with the data layer class MatrixDAOto store results in 
the database. 
package bl; 
import bo.*; 
import dal.*; 
public class MatrixMultiplier { 
//constructor 
public MatrixMultiplier( ) { 
} 
// used to convert a String (like 2,3,4,5) into a MatrixBean object 
public MatrixBean convertToObject(String sMatrix){
Web Design  Development – CS506 VU 
© Copyright Virtual University of Pakistan 446 
//splitting received string into tokens by passing “,” as delimeter 
String tokens[] = sMatrix.split(,); 
//creating MatrixBean object 
MatrixBean matrixBO = new MatrixBean( 
// converting tokens into integers 
int w = Integer.parseInt(tokens[0]); 
int x = Integer.parseInt(tokens[1]); 
int y = Integer.parseInt(tokens[2]); 
int z = Integer.parseInt(tokens[3]); 
matrixBO.setMatrix(w , x , y, z); 
return matrixBO; 
ixBean objects 
form of MatrixBean as well 
an sMatrix){ 
// creating MatrixBean object where product of the matrices will be tored 
MatrixBean resultMatrix = new MatrixBean(); 
// r eans object to // perform multipication 
trix(); 
trix(); 
; 
// code to multiply two matrices 
for (int i=0; i2; i++) { 
] += (matrixA[i][k] * matrixB[k][j]); 
} 
} 
// storing the product from 2d array to MatrixBean object by // calling setter 
); 
// setting values into MatrixBean object by calling setter 
} // end convertToObject() // used to multiply two matrices , receives two Matr 
// and returns the product in the 
public MatrixBean multiply(MatrixBean fMatrix , MatrixBe 
retieving two dimensional arrays from MatrixB 
int matrixA[ ][ ] = fMatrix.getMaintmatrixB[ ][ ] = sMatrix.getMa 
int matrixC[ ][ ] = resultMatrix.getMatrix() 
for (int j=0; j2; j++) { for (int k=0; k2; k++){ 
matrixC[i][j 
}
Web Design  Development – CS506 VU 
© Copyright Virtual University of Pakistan 447 
re xC[0][0], matrixC[0][1], matrixC[1][0], matrixC[1][1] ); 
} // end MatrixMulitplier 
} // end multiply() 
// save results (MatrixBean containg product of two matrices) into // database using DAO 
public void saveResult( MatrixBean resultMatrix ) 
atrixDAO dao = new MatrixDAO(); 
dao.saveMatrix(resultMatrix); 
} // end MatrixMu 
As class name depicts, it is used to store product results into database. Let’s look on the code to see how it 
is accomplished. 
import java.util.*; import java.sql.*; 
import bo.*; public class MatrixDAO{ 
private Connection con; 
// constructor public MatrixDAO() throws ClassNotFoundException , SQLException { 
ablishConnection(); 
} 
method used to estab lishConnection() throws 
ClassNotFoundException , SQLException { 
// establishing conection 
Class.forName(sun.jdbc.odbc.JdbcOdbcDriver); 
ng conUrl = jdbc:odbc:MatrixDSN; 
con = DriverManager.getConnection(conUrl); 
} 
sultMatrix.setMatrix( matri 
return resultMatrix; 
{ 
M 
} 
litplier 
MatrixDAO 
package dal; 
est 
// 
lish connection with db private void estab 
Stri
Web Design  Development – CS506 VU 
// used to store MatrixBean into database after converting it to // a String 
) 
try 
{ 
String sql = INSERT INTO Matrix(mOrder, mValues) VALUES (?,?); 
t pStmt = con.prepareStatement(sql); 
// converting MatrixBean into String by calling toString() 
String sMatrix = matrix.toString(); 
// setting order of matrix 
pStmt.setString( 1 , 2*2 ); 
tring( 2 , sMatrix ); 
pdate(); 
}catch(SQLException sqlex){ 
System.out.println(sqlex); 
} 
} // end saveMatrix 
overriding d to 
public void finalize( ) { 
if(con != null){ 
}catch(SQ x){ 
System.out.println(sex); 
} 
} // end finalize 
} // end MatrixDAO class 
public void saveMatrix(MatrixBean matrix 
PreparedStatemen 
// setting matrix values in the form of string pStmt.setS 
pStmt.executeU 
// 
finalize metho 
release acquired resources 
try{ 
con.close(); 
} 
LException se 
© Copyright Virtual University of Pakistan 448
Web Design  Development – CS506 VU 
matrixresult.jsp 
Used to display resultant product o 
%-- importing “bo” package th 
%@ page import=bo.*% 
html 
body 
h1The resultant Matrix is /h1 
llerServlet 
% MatrixBean productMatrix = (MatrixBean)request.getAttribute(product); 
at it can be displayed 
int matrix[][] = productMatrix.getMatrix() ; 
ABLE 
TR 
TD %= matrix[0][0] % /TD 
TD %= matrix[1][0] % /TD 
/body 
/html 
f two matrices. The code is given below: at contains MatrixBean -% 
%-- retrieving MatrixBean object from request, that was set on Contro --% 
// retrieving values in 2d array so th 
% %-- displaying MatrixBean’s object values -% 
T 
TD %= matrix[0][1] % /TD 
/TR 
TR 
TD %= matrix[1][1] % /TD 
/TABLE 
 
© Copyright Virtual University of Pakistan 449
Web Design  Development – CS506 VU 
web.xml 
?xml version=1.0 encoding=UTF-8? 
web-app 
servlet-name ControllerServlet /servlet-name 
se let-class 
/servlet 
servlet-let- 
name ControllerServlet /servlet-name 
url-pattern /controller /url-pattern 
/servlet- 
/web-app 
References: 
. Java A Lab Course by Umair Javed. 
Sang Shin 
servlet 
rvlet-class controller.ControllerServlet /serv 
mapping serv 
mapping 
. Java Passion by © Copyright Virtual University of Pakistan 450
Web Design  Development – CS506 VU 
© Copyright Virtual University of Pakistan 451 
Lesson 42 
Expression Language 
Sun Microsystems introduced the Servlet API, in the later half of 1997, positioning it as a powerful 
alternative for CGI developers who were looking around for an elegant solution that was more efficient and 
ortable than CGI (Common Gateway Interface) programming. However, it soon became clear that the 
Servlet ion difficult to implement, from the 
perspective e 
community ore a solution that would allow embedding Java Code in HTML – Java Server Pages 
(JSP) emerge 
Java as the s ough 
knowledge t imple 
lines of java c r? Yes, by using Expression 
Language (EL). 
JavaServer Pages Standard Tag Library (JSTL) 1.0 introduced the concept of the EL but it was constrained 
to only the JSTL tags. With JSP 2.0 you can use the EL with template text. 
Note: - JSTL will be discussed in the following Handout. 
Overview 
ions on them. It is inspired form both the ECMAScript and the XPath expression language. 
JSP Before and After EL 
To factor so that you start learning EL with renewed zeal and zest, a comparison is 
give e EL affects the JSPs. 
he following figure depicts the situation of a JSP before EL. We have to declare a variable before using it, 
ata type must be known in advance and most importantly have to use awkward syntax and many more. All 
ese pr 
p 
API had its own drawbacks, with developers finding the solut 
of code maintainability and extensibility. It is in some ways, this drawback that prompted thto expl 
d as a result of this exploration. 
cripting language in JSP scares many people particularly web page designers which have eno work with HTML and some scripting language, faced lot of difficulties in writing some s 
ode. Can we simplify this problem to ease the life of web designe 
The Expression Language, not a programming or scripting language, provides a way to simplify expressions in JSP. It is a simple language that is geared towards looking up objects, their properties and performing simple operat 
add in motivational 
n blow that illustrates how 
T 
dth 
oblems are highlighted in the following figure:
Web Design  Development – CS506 VU 
© Copyright Virtual University of Pakistan 
452 
Contrary to the above figure, have a look on the subsequent figure that gives you a hint how useful EL can 
c:if test = “$ {p.address == param.add }”  
t pieces of EL. These are: 
ƒ Syntax of EL 
ƒ Automatic type conversion 
ƒ Access to beans, arrays, lists  maps 
ƒ Access to set of implicit objects 
EL Syntax 
The format of writing any EL expression is: 
$ { validExpression } 
The valid expressions can consist on these individuals or combination of these given below: 
ƒ Literals 
be? 
Person Name: $ { p.name } … 
Expression Language Nuggets We’ll discuss the following importan 
ƒ Expressions  identifiers ƒ Arithmetic, logical  relational operators
Web Design  Development – CS506 VU 
ƒ Operators 
ƒ Variables (object references) 
ƒ Implicit call to function using property name 
EL Literals 
ar 
The list of literals that can be used as an EL expression and their possible values are given in the tabulformat below: Literals 
Literal Values Bo n 
olea true or false 
Integer Similar to Java e.g. 243, -9642 
Floating Point Similar to Java e.g. 54.67, 1.83 
String Any string delimited by single or double quote e.g. 
“hello” , ‘hello’ 
Null Null 
Exa l 
--% 
EL Operators 
The lists of operators that can be used in EL expressi are given below: 
mpes of using EL literals are: . ${ false } %-- evaluates to false --% . ${ 8*3 } %-- evaluates to 24  
on 
Typ 
e Operator 
Arithmetic + -* / (div) % (mod) 
Grouping 
( ) 
Logical 
(and) ||( or) !(not) 
Relational == (eq) != (ne)  (lt)  (gt) = (le) = (ge) 
Empty value is null or empty. It returns a Bool 
The empty operator is a prefix operation used to determine if a 
ean value. 
Con io 
ditnal ?: 
© Copyright Virtual University of Pakistan 453
Web Design  Development – CS506 VU 
Let us look at some examples that use operators as valid expression: 
ƒ ${ (6*5) + 5 } %-- evaluate to 35 --% 
ƒ ${ (x = min)  (x = max) } 
ƒ ${ empty name } 
Returns true if name is 
Empty string (“”), 
Null etc. 
EL Identifiers 
Identifiers in the expression language represent the names of objects stored in one of the JSP scopes: 
on, or application. These types of objects are referred to scoped variables throughout 
EL has 11 reserved identifiers, corresponding to 11 implicit objects. All other identifiers assumed to refer to 
les. 
he Expression Language defines a set of implicit objects given below in tabular format: 
page, request, sessi 
this handout. 
scoped variab 
EL implicit Objects 
T 
Category Implicit Object Operator 
JSP pageContext The context for the JSP page, used to access the JSP 
implicit objects such as request, response, session, out, 
servletContext etc. 
A Map associating names  values of page scoped 
attributes 
pageScope 
requestScope A Map associating names  values of request scoped 
attributes 
Scopes 
sessionScope A Map associating names  values of session scoped 
attributes 
applicationScope A Map associating names  values of application 
scoped attributes 
param Maps a request parameter name to a single String 
Request parameter value. 
Parameters 
paramValues Maps a request parameter name to an array of values 
Request header Maps a request header name to a single header value. 
Headers 
headerValues Maps a request header name to an array of value. 
Cookies cookie A Map storing the cookies accompanying the request 
by name 
© Copyright Virtual University of Pakistan 454
Web Design  Development – CS506 VU 
© Copyright Virtual University of Pakistan 455 
Initialization 
Parameters initParam A Map storing the context initialization parameters of 
the web application by name 
Examples of using implicit objects are: 
. $ ates to response implicit object of JSP 
. ${ param.name } -This expression is equivalent to calling 
request.getParameter(“name”); 
${ cookie.name.value } -Returns the value of the first cookie with the given 
-Equivalent to if (cookie.getName().equals(“name”){ String val = 
cookie.getValue(); } 
umbers using EL 
his simple example demonstrates you the capabilities of EL. index.jsp is used to collect input for two 
numbers and their sum is displayed on result.jsp using EL. Let’s first see the code of index.jsp 
html 
body Enter two numbers to see their sum 
um 
br Second Number: inpu / 
value=Calculate Sum / 
/form 
/body 
/html 
{ pageContext.response } -Evalu 
. name 
Example Code: Summation of Two N 
T 
index.jsp 
 
form action=result.jsp  First Number : input type=text name=n 
1 / t type=text name=num2 
input type=submit
Web Design  Development – CS506 VU 
© Copyright Virtual University of Pakistan 456 
result.jsp 
html 
bers if we used scriptlet 
 
quest .getParameter(num1); 
= request .getParameter(num2); 
int num1 = Integer.parseInt(no1); 
int num2 = Integer.parseInt(no2); 
Resul 
--% 
ing two numbers 
m2} 
/body 
EL Identifiers (cont.) 
We had started our discussion on EL identifiers. Let’s find out how these identifiers (variables) can be 
om different scopes. 
Storing Scoped Variables 
By using java code, either in pure servlet or in a scriptlet of JSP, we can store variables in a particular scope. 
For example, 
. S session scope using Java code 
Assu lass and we want to store its object pin session scope then we can write 
the following lines of code to accomplish that: 
HttpSess ; PersonInfo p = new PersonInfo(); 
p.setName(“ali”); ses.setAttribute(“person” , p); 
t scope using Java code 
For the following lines of code, assume that request is of HttpServletRequest type. To store PersonInfo 
object p in request scope, we’ll write: 
body 
%-- The code to sum two num 
% String no1 = reString no2 
% 
t is: %= num1 + num2 % 
%-- implicit Object param is used to access request parameters By Using EL summ 
--% Result is: ${param.num1 + param.nu 
/html 
stored/retrieved in/fr 
toring a variable in 
me that we have PersonInfo c 
ion ses = request.getSession(true) 
. Storing a variable in reques
Web Design  Development – CS506 VU 
© Copyright Virtual University of Pakistan 457 
PersonInfo p = new PersonInfo(); p.setName(“ali”); 
request.setAttribute(“person” , p); 
ome another method (with which you are already familiar) to store a variable in a 
scope, certainly by using JSP action tags, we learned how to store a variable in any particular scope. 
. Storing a variable in request scope using JSP action tag 
If we want to store p of type PersonInfo in request scope by using JSP action tags, then we’ll 
write: 
jsp:useBean id=”p” class 
Later, you c ject p by using action tag as well. For example 
jsp:setProperty  
Retrieving Scoped Variab 
ou are already very much familiar o able by using java code and JSP 
ction tags. Here, we’ll discuss h ieves scoped variables. As already mentioned, identifiers in the 
valid expression represent t cts stored in one of the JSP scopes: page, request, session and 
licati n. 
hen th pres counters an identifier, it searches for a scoped variable with that name first 
ƒ 
e 
d finally in application scope 
If no such object is located in four scopes, null is returned. 
in session scope by mean of any mechanism discussed 
previously and have written the following EL expression to access the name property of p 
${p.name} 
Then EL searches for p first in page scope, then in request scope, then in session scope where it found p. 
After that it calls p.getName() method. This is also shown in pictorial form below: 
You must be thinking of s 
=”PersonInfo” scope=”request”/ 
an change the properties of ob 
n 
ame=“p” property=“name” value=“ali” / 
les 
Ya 
f retrieving any stored scoped vari 
ow EL retrhe names of obje 
appo 
We exsion language en 
in page scope, 
ƒ then in request scope, ƒ then in session scop 
ƒ an 
Note: - 
For example, if we’ve stored PersonInfo object p
Web Design  Development – CS506 VU 
© Copyright Virtual University of Pakistan 
458 
EL Accessors 
The dot (.) and bracket ([ ]) operator let you access identifies and their properties. The dot operator 
typically used for accessing the properties of an object and the bracket operator is generally used to retrieve 
elements of arrays and collections. 
. Dot (.) operator 
as name property and its object person is stored in some scope. 
Then to access the name property of person object, we’ll write the following expression using EL: 
Assume that JavaBean PersonInfo h The EL accesses the object’s properties using the JavaBeans conventions therefore getName() must be 
define sonInfo. Moreover, if property being accessed itself an object, the dot operator can be 
applied recurs example 
d in Perively. For 
${user. address. city}
Web Design  Development – CS506 VU 
© Copyright Virtual University of Pakistan 459 
. Brack 
This operator can be applied to arrays  collections implementing List interface e.g. ArrayList etc. 
ƒ 
ƒ ample, ${ personList[2] } returns the 3rd element stored in it 
Moreover, this operator can also be applied to collections implementing Map interface e.g. HashMapetc. 
ƒ Key is specified inside brack 
ƒ For example, ${ myMap[“id”] } returns the value associated with the id(key) 
EL – Robust Features 
racteristics of Expression Language are: 
e 
$ { “Hello” ${user.firstName} ${user.lastName} } 
ƒ EL also supports automatic type conversion; as a result primitive can implicitly wrap and unwrap 
java classes. For example 
ƒ Most importantly, if object/identifier is null, no NullPointerException would be thrown☺. For 
xample 
Assum ha exception would be thrown and the result would also be null. 
Using Expressio Language 
Expression Language can be used in following situations 
ƒ A  custom actions. E.g. 
jsp:setProperty id = “person” value = ${….} / 
et ([ ]) operator 
Index of the element appears inside brackets 
For ex 
ets 
Some powerful cha 
ƒ Multiple expressions can be combined and intermixed with static text. For exampl 
into/from their corresponding 
e. If the expression written is: 
${person.name} 
e tt person is null, then non 
s attribute values in standard
Web Design  Development – CS506 VU 
© Copyright Virtual University of Pakistan 460 
ƒ In template text – the value of the expression is inserted into the current output. E.g. 
h3 $ { …… } /h3 
ƒ With JSTL (discussed in the next handout) 
Example 
So far, we have example in number of different ways. This 
time EL will be i n.jsp, 
showperson.jsp, C look on the code of each of 
ese components: 
PersonInfo.java 
The JavaB rson record. 
import java.io.*; 
public class PersonInfo implements Serializable{ 
private Str 
private String address; 
private int 
// no argument cons 
public PersonIn 
nam 
address = ; 
// setters 
public void setName(String n){ 
name = n; 
address = a; 
} 
public void setPhoneNum(int pNo){ 
phoneNum = pNo; 
} 
// getters 
Code: AddressBook using EL 
shown you implementation of AddressBook 
ncorporated in this example. AddressBook code example consists on searchpersoontrollerServlet, PersonInfo and PersonDAO classes. Let’s 
th 
ean used to represent one pe 
package vu; 
ing name; 
phoneNum; 
tructor fo() { 
e = ; 
phoneNum = 0; } 
} 
public void setAddress(String a){
Web Design  Development – CS506 VU 
public String getName( ){ 
return name; 
} 
public String getAddress( ){ 
address; 
} 
} 
} 
It is used to retrieve/search person records from database. 
package vu; import java.util.*; import 
java.sql.*; public class PersonDAO{ 
private Connection con; 
// constructor 
public PersonDAO() throws ClassNotFoundException , SQLException { 
} 
//used to establish connection with database 
private void establishConnection() throws 
ClassNotFoundException , 
SQLException { 
// establishing connection 
Class.forName(sun.jdbc.odbc.JdbcOdbcDriver); 
String conUrl = jdbc:odbc:PersonDSN; 
con = DriverManager.getConnection(conUrl); 
} 
// used to search person records against name 
public ArrayList retrievePersonList(Strin g pName) 
throws SQLException { 
ArrayList personList = new ArrayList(); 
return 
public int getPhoneNum( ){ return phoneNum; 
PersonDAO.java 
establishConnection(); 
© Copyright Virtual University of Pakistan 461
Web Design  Development – CS506 VU 
© Copyright Virtual University of Pakistan 462 
String sql =  SELECT * FROM Person WHERE name = ?; 
PreparedStatement pStmt = con.prepareStatement(sql); 
pStmt.setString( 1, pName); 
System.out.println(retrieve person list); 
int pNo; 
while ( rs.next() ) { 
name = rs.getString(name); 
add = rs.getString(address); 
pNo = rs.getInt(phoneNumber); 
// creating a PersonInfo object 
PersonInfo personBean = new PersonInfo(); 
to arraylist 
personList.add(personBean); 
// end while 
} // end retrievePersonList 
//overriding finalize method to release resources 
public void finalize( ) { 
try{ 
xception sex){ 
System.out.println(sex); 
} 
} // end finalize 
} // end class 
ResultSet rs = pStmt.executeQuery(); String name; String add; 
personBean.setName(name); personBean.setAddress(add); personBean.setPhoneNum(pNo); // adding a bean 
} 
return personList; 
if(con != null){ 
con.close(); 
} }catch(SQLE
Web Design  Development – CS506 VU 
© Copyright Virtual University of Pakistan 463 
s 
T its this data to the ControllerServlet. 
html 
h3 Search Person/h3 
FORM =search action=controllerservlet / 
 
4 /TD 
TD input type=text name=name / /TD 
/TR 
TR TD COLSPAN=2 ALIGN=CENTER 
input type=submit value=search / input 
/TD 
/TR 
/FORM 
/center 
/body 
/html 
ControllerServlet.java 
The Controller Servlet receives reques and after fetching search results from 
tabase, forwards the request to showperson.jsp. 
pack ller; 
import vu.*; 
import java.io.*; 
earchperson.jsp 
his JSP is used to gather person’s name from the user and subm 
body 
center h2 Address Book /h2 
name 
TABLE BORDER=1  
TR TD h4 Name/h 
type=reset value=clear / 
/TABLE 
t from searchperson.jsp 
da 
age contro 
import java.net.*;
Web Design  Development – CS506 VU 
import javax.servlet.*; 
import javax.servlet.http.*; 
public class ControllerServlet extends HttpServlet { 
// end processRequest() 
// This method only calls processRequest() 
protected void doGet(HttpServletRequest request, 
HttpServletResponse response) throws 
ServletException, IOException { 
processRequest(request, response); 
} 
// This method only calls processRequest() 
protected void doPost(HttpServletRequest request, 
HttpServletResponse response) throws 
processRequest(request, response); 
} 
protected void processRequest(HttpServletRequest request, 
e response) throws 
} // end ControllerServlet 
rson(HttpServletRequest request, 
HttpServletResponse response) throws 
ServletException, IOException { 
// retrieving request parameter “name” entered on showperson.jsp 
String pName = request.getParameter(name); 
} 
ServletException, IOException { 
HttpServletRespons 
ServletException, IOException { // defined below searchPerson(request, response); 
protected void searchPe 
try { 
// creating PersonDAO object PersonDAO pDAO = new PersonDAO(); © Copyright Virtual University of Pakistan 464
Web Design  Development – CS506 VU 
// calling DAO method to retrieve personlist from database // against the name 
entered by the user 
A 
// storing personlist in request scope, later it is retrieved // back on showperson.jsp 
request.setAttribute(plist, personList); 
atcher(showperson.jsp); 
} // end searchPerson 
showperson.jsp 
yList (personList) from 
play records. 
%-- importing required packages--% 
%@page import=java.util.* % 
%@page import=vu.* % 
html 
body 
center 
h2 Address Book /h2 
ing results meet your search criteria/h3 
TABLE BORDER=1  
TR 
Address/TH 
THPhoneNum/TH 
/TR 
%-- start of scriptlet --% 
rrayList personList = pDAO.retrievePersonList(pName); 
// forwarding request to showperson, so it renders personlist RequestDispatcher rd = request.getRequestDisp 
rd.forward(request, response); 
}catch (Exception ex) { 
System.out.println(Exception is + ex); } 
This page is used to display the search results. To do so, it reclaims the stored Arrathe request scope. Furthermore, this page also uses the Expression Language to dis 
 
 
h3 Follow 
THName/TH TH 
© Copyright Virtual University of Pakistan 465
Web Design  Development – CS506 VU 
% 
// retrieving ArrayList from request scope 
ArrayList personList =(ArrayList)request.getAttribute(plist); 
=0; ipersonList.size(); i++) { 
person = (PersonInfo)personList.get(i); 
// storing PersonInfo object in request scope /* As mentioned, an object must be 
ome scope to work with Expression Language*/ 
request.setAttribute(p, person); 
% 
%-- accessing properties of stored PersonInfo object with name “p” using EL --% 
/TD 
TD ${ p.phoneNum} /TD 
%-- The following expressions are now replaced by EL statements written above--% 
%--%= person.getName()% --% %--%= 
person.getAddress()% --% %--%= 
 
% 
/body 
PersonInfo person = null; 
for(int i 
stored in s 
%-- end of scriptlet --% 
TR 
TD ${ p.name } /TD TD ${ p.address} 
person.getPhoneNum()% --% /TR % 
} // end for 
/TABLE  
/center 
/html 
© Copyright Virtual University of Pakistan 466
Web Design  Development – CS506 VU 
© Copyright Virtual University of Pakistan 467 
web.xml 
web-app 
servlet-name ControllerServlet /servlet-name 
. Java A Lab Course by Umair Javed. 
l by Sun 
va.sun.com/j2ee/1.4/docs/tutorial/doc/JSPIntro7.html 
?xml version=1.0 encoding=UTF-8? 
servlet 
servlet-class controller.ControllerServlet /servlet-class /servlet servlet-mapping 
servlet-name ControllerServlet /servlet-name url-pattern /controllerservlet /url-pattern /servlet-mapping /web-app 
References: 
. Expression Language Tutoria 
http://ja 
The JSTL Expression Language by David M. Geary 
http://www.informit.com/articles/article.asp?p=30946rl=1
Web Design  Development – CS506 VU 
Lesson 43 JavaServer Pages Standard Tag Library (JSTL) 
Introduction 
Thfuncti 
e JSP Standard Tag Library (JSTL) is a collection of custom tag libraries that implement general-purpose 
onality common to Web applications, including iteration and conditionalization, data management 
ting, manipulation of XML, and database access. Like JSP, JSTL is also a specification not an 
implementation. The development theme of JSTL is “scriptlet free JSP”. 
These tag libraries provide a wide range of custom action functionality that most JSP authors have found 
themselves in need of in the past. Having a defined specification for how the functionality is implemented 
author can learn these custom actions once and then use and reuse them on all future 
pplication containers that support the specification. Using the JSTL will not only make 
your JSPs more readable and maintainable, but will allow you to concentrate on good design and 
implementation practices in your pages. 
JSTL  EL 
JSTL includes supports for Expression Language thus EL can be used to specify dynamic attribute values 
ming language. Prior to JSP 2.0, EL can only be used in 
becomes a standard part of JSP 2.0. This allows the use of EL anywhere 
tioned, JSTL encapsulates common functionality that a typical JSP author would encounter. This set 
m rious members of the expert group. 
Since this expert group has a good cross-section of JSP authors and users, the actions provided in the JSTL 
uld L is commonly referred to as a single tag library, it is actually 
composed of four separate tag libraries: 
ƒ - co o access variables etc. 
ƒ ML m d processing 
ƒ SQL - contains tags for accessing and working with database. 
ƒ Internationalization and formatting - contains tags to support locale messages, text, numbers and 
date formation 
format 
means that a pageproducts on all a 
for JSTL actions without using full-blown program 
attributes of JSTL tags but EL now in the document. 
Functional Overview 
As men 
of comon functionality has come about through the input of the va 
shosuit a wide audience. While the JST 
Corentains tags for conditions, control flow and tXanipulation - contains tags for XML parsing an 
© Copyright Virtual University of Pakistan 468
Web Design  Development – CS506 VU 
Twin Tag Libraries 
JSTL comes in two flavors to support various skill set personal 
) version 
- Dynamic attribute values of JSTL tags are specified using JSTL expression language (i.e. 
sion}) 
ƒ Expression Language (EL 
${expres 
- The EL based JSTL tag libraries along with URIs and preferred prefixes are given below in tabular format 
Library URI Prefix 
Core http://java.sun.com/jsp/jstl/core c 
SQL http://java.sun.com/jsp/jstl/sql sql Internationalization/ Format http://java.sun.com/jsp/jstl/fmt fmt 
XML http://java.sun.com/jsp/jstl/xml x 
ƒ Request Time (RT) version 
ries along with URIs and preferred prefixes are given below in tabular format 
- Dynamic attribute values of JSTL tags are specified using JSP expression 
(i.e. %= expression %) 
- The RT based JSTL tag libra 
Library URI Prefix 
Core http://java.sun.com/jsp/jstl/core_rt c_rt 
SQL 
http://java.sun.com/jsp/jstl/sql_rt sql_rt Internationalization/ http://java.sun.com/jsp/jstl/fmt_rt fm Format t_rt 
XML http://java.sun.com/jsp/jstl/xml_rt x_rt 
Using JSTL 
As we discussed earlier, JSTL includes f 
© Copyright Virtual University of Pakistan 469 
our standard tag libraries. As is true with any JSP custom tag library, 
t be included in any page that you want to be able to use this library's tags. 
For example, to use EL based core tag library, the taglib directive appears as: 
%@taglib prefix=“c” uri=http://java.sun.com/jsp/jstl/core % 
a taglib directive mus
Web Design  Development – CS506 VU 
And to use RT based core tag library, the taglib directive appears as: 
%@taglib prefix=“c_rt” uri=http://java.sun.com/jsp/jstl/core_rt % 
Working with Core Actions (tags) 
The set of tags that are available in the Core tag library come into play for probably most anything you will 
be doing in your JSPs such as: 
ore actions: 
Provides a tag based mechanism for creating and setting scope based variables. Its syntax is as follows: 
c:set v nam expression” / 
Where the var attribute specifies the name of the scoped variable, the scope attribute indicates which scope 
(page | request | session | application) the variable resides in, and the value attribute specifies the value to 
If the specified variable already exists, it will simply be assigned the indicated value. 
If not, a new scoped variable is created and initialized to that value. 
The scope attribute is optional and default to page. 
Three examples of using c:set are given below. In the first example, a page scoped variable “timezone” is set 
to a value“Asia / Karachi”. 
c:set var=“timezone” value=“Asia/Karachi” / 
equest scoped variable “email” email is set to a value “me@gmail.com” 
c:set var=“email” scope=”request” value=“me@gmail.com” / 
In the third example, a page scoped variable “email” is set to value of request parameter “email” by using 
paramimplicit object. If email parameter is defined in JSP page as: 
input type=”text” value = “email” / 
ƒ Manipulation of scoped variables ƒ Output ƒ Conditional logic 
ƒ loops ƒ URL manipulation ƒ and Handling errors. 
Let’s walk through some important c 
c:set 
ar=“e” scope = “scope” value = “ 
be bound to the variable. 
 
In the second example, a r 
© Copyright Virtual University of Pakistan 470
Web Design  Development – CS506 VU 
© Copyright Virtual University of Pakistan 471 
Then c:set tag would be used as: 
c:set var=“email” scope=”request” value=“param.email” / 
Using c:set with JavaBeans  Map 
tag can also be used to change the property of a bean or the value against some key. For this purpose, 
the syntax of the c:set tag would look like this: 
c:set target=“bean/map” property=”property/key” value=“value” / 
ƒ If target is a bean, sets the value of the property specified. This process is equivalent to 
jsp:setProperty … / JSP action tag. 
ƒ If target is a Map, sets the value of the key specified 
And of course, these beans and maps must be stored in some scope prior to any attempt is made to change 
their properties. 
For example, consider the following snippet of code that stores PersonInfo’s object person into request 
scope using jsp:useBean … / tag. Then using c:set tag, person’s name property is set to “ali”. 
jsp:useBean id=“person” class=“vu.PersonInfo” scope=“request” / 
c:set target=“person” property =“name” value = “ali” / 
c:out 
A developer will often want to simply display the value of an expression, rather than store it. This can be 
done by using c:out core tag, the syntax of which appears below: 
c:out value = “expression” default = “expression” / 
bute, and then prints the result. If the optional 
default attribute is specified, the c:out action will print its (default) value if the value attribute's expression 
valuates either to null or an empty String. This tag is equivalent to JSP expression i.e. %=expression %. 
Consider the following examples in which the usage of c:out tag has shown. In the first example, string 
r an empty string then default value “0” 
would be displayed. 
c:out value = “${param.num}” default = “0” / 
c:set 
This tag evaluates the expression specified by its value attri 
e 
“Hello” would be displayed c:out value = “Hello” / In the second example, if request parameter num evaluates to null o
Web Design  Development – CS506 VU 
The above fragment of code is equivalent to following scriptlet: 
est.getParameter(“num”); 
no.equals(“”)) 
(0); 
Out.println(no); 
} 
bean like name, we’ll write 
c:out value= “${person.name}” default = “Not Set” / 
As its name suggests, the c:removeaction is used to delete a scoped variable, and takes two attributes. The 
var attribute names the variable to be removed, and the optional scope attribute indicates the scope from 
ich it should be removed and defaults to page. 
For example, to remove a variable named square from page scope, we’ll write: 
c:remove var = “square” / 
d if variable email is required to be removed from request scope, then c:remove tag will look like: 
c:remove var = “email” scope = “request” / 
the context of Web applications, iteration is primarily used to fetch and display collections of data, 
typically in the form of a list or sequence of rows in a table. The primary JSTL action for implementing 
iterative content is the c:forEach core tag. This tag supports two different styles of iteration: 
er range (like Java language's for statement) 
ƒ Iteration over a collection (like Java language's Iterator and Enumeration classes). 
% 
tring no = requ 
if (no == null || 
{ 
stem.out.println 
} 
Else 
{ 
% 
If we want to display the property of a 
c:remove 
wh 
An 
c:forEach 
In 
ƒ Iteration over an integ 
© Copyright Virtual University of Pakistan 472
Web Design  Development – CS506 VU 
Iteration over an Integer range 
To iterate over a range of integers, the syntax of the c:forEach tag will look like: 
c:forEach var=“name” begin=“expression” end=“expression” step=“expression”  
Body Content 
/c:forEach 
The begin and end attributes should be either constant integer values or expressions evaluating to integer 
values. They specify the initial value of the index for the iteration and the index value at which iteration 
should cease, respectively. When iterating over a range of integers using c:forEach, these two attributes are 
required and all others are optional. 
The step attribute specifies the amount to be added to the index after each iteration. Thus the index of the 
iteration starts at the value of the begin attribute, is incremented by the value of the step attribute, and halts 
iteration when it exceeds the value of the endattribute. Note that if the stepattribute is omitted, the step size 
defaults to 1. 
If the var attribute is specified, then a scoped variable with the indicated name will be created and assigned 
the current value of the index for each pass through the iteration. This scoped variable has nested visibility 
that is it can only be accessed within the body of the c:forEachtag. 
For example to generate squares corresponding to range of integer values, the c:forEachtag will be used as: 
c:forEach var=“x” begin=“0” end=“10” step=“2”  
c:out value=“${x * x}” / 
/c:forEach 
By executing the above code, following output would appear: 4 16 36 64 100 
Iteration over a Collection 
When iterating over the members of a collection and arrays etc, one additional attribute of the c:forEach tag 
is used: the items attribute. Now the c:forEach tag will look similar to this: 
c:forEach var=“name” items=“expression”  
Body Content 
/c:forEach 
© Copyright Virtual University of Pakistan 473
Web Design  Development – CS506 VU 
© Copyright Virtual University of Pakistan 474 
When you use this form of the c:forEach tag, the items attribute is the only required attribute. T 
the items attribute should be the collection/array over whose members the iteration is to occur, and is 
typically specified using an EL expression. If a vari o specified using var attribute, then the 
named variable will be bound to collection for each iteration pass. 
For example, to iterate over a Str java code, we used to write in JSP: 
for(int i=0; imessages.length; i++) { 
String msg = messag s[i]; 
% 
%= msg % 
% 
 
his can be done using c:forEach tag in much simpler way as shown below: 
c:forEach var=“msg” items=“${messages}”  
c:out value= “${msg}” / 
/c:forEach 
Similarly, to iterate over a persons ArrayList that contains PersonInfo objects, we used to write in JSP: 
% 
{ 
PersonInfo p == (PersonInfo)persons.get(i); 
String name = p.getName(); 
% 
%= name % 
% 
} // end for 
% 
he value of 
able name is alssuccessive elements of theing array (messages) using 
% 
e 
} // end for 
% 
T 
ArrayList persons = (ArrayList)request.getAttribute(“pList”); for(int i=0; ipersons.size(); i++)
Web Design  Development – CS506 VU 
© Copyright Virtual University of Pakistan 475 
Indeed, the above task can be achieved in much simpler way using c:forEach tag as shown below: 
c:forEach var=“p” items=“${persons}”  
c:out value= “${p.name}” / 
/c:forEach 
The c:forEach tag processes each element of this list(persons) in turn, assigning it to a scoped variable 
quired. 
are 
c:if 
Like ordinary Java’s if, used to conditionally process the body content. It simply evaluates a single test 
expression and then processes its body content only if that expression evaluates to true. If not, the tag's body 
c:if test= “expression”  
Body Content 
/c:if 
 b are equal, the c:if tag is used as: 
c:if test= “${a == b}”  
/c:if 
c:choose 
c:choose the second conditionalization tag, used in cases in which mutually exclusively test are required to 
splayed. The syntax is shown below: 
c:choose 
c:when test= “expression”  
Body content 
…………… 
named p. Note that typecast is also not re 
Furthermore, you can use the begin, end, and step attributes to restrict which elements of the collectionincluded in the iteration. 
content is ignored. The syntax for writing c:iftag is: 
For example, to display a message “a equals b” if two strings a 
h2 A equals B /h2 
determine what content should be di 
/c:when
Web Design  Development – CS506 VU 
© Copyright Virtual University of Pakistan 476 
c:otherwise  
Body content 
/c:otherwise 
/c:choose 
Each condition to be tested is represented by a corresponding c:when tag, of which there must be at least 
c:when tag whose test evaluates to true will be processed. If none 
n tests return true, then the body content of the c:otherwisetag will be processed. 
, that the c:otherwise tag is optional; a c:choose tag can have at most one nested 
 tag. If all c:when tests are false and no c:otherwise action is present, then no 
c:choose body content will be processed. 
The example code given below illustrates the usage of c:choose tag in which two strings a  b are compared 
nd appropriates messages are displayed: 
c:choose 
c:when test= “a == b”  
h2 a equals b/h2 
/c:when 
c:when test= “a = b”  
h2 a is less than b/h2 
/c:when 
c:otherwise  
h2 Don’t know what a equals to /h2 
/c:otherwise 
/c:choose 
netBeans 4.1 and JSTL 
If you are using netBeans 4.1 IDE then you have to add JSTL library to your project manually. To do so, 
right click on the libraries folder, you can find it under project’s name and select the Add Library option. 
This is also shown in the following figure: 
one. Only the body content of the first  of the c:whe 
Note, though 
c:otherwise 
a
Web Design  Development – CS506 VU 
© Copyright Virtual University of Pakistan 477 
Thed 
Ad Library dialog box opens in front of you. Select JSTL 1.1 option and press Add Library button. 
Now you can 
refer to any JSTL library in your JSPs.
Web Design  Development – CS506 VU 
© Copyright Virtual University of Pakistan 478 
Note: Remember that the JSTL 1.1 library is only added to current project. You have to repeat this step for 
each project in which you want to incorporate JSTL. 
Example Code: AddressBook using JSTL core tags 
This is the modified version of AddressBook that was built using Expression Language in the last handout. 
Only showperson.jsp is modified to incorporate JSTL core tags along with Expression Language in place of 
scriptlets. The remaining participants searchperson.jsp, ControllerServlet, PersonInfo and PersonDAO left 
unchanged. Let’s look on the code of each of these components: 
PersonInfo.java 
The JavaBean used to represent one person record. 
package vu; 
ublic class Pers 
private String name; 
private String address; 
private int phoneNum; 
// no argument constructor 
public PersonInfo() { 
name = ; 
address = ; 
phoneNum = 0; 
// setters 
public void setName(String n){ 
import java.io.*; 
p 
onInfo implements Serializable{ 
} 
name = n; } public void setAddress(String a){ 
address = a; 
}
Web Design  Development – CS506 VU 
© Copyright Virtual University of Pakistan 479 
public void setPhoneNum(int pNo){ 
phoneNum = pNo; 
} 
} 
public String getAddress( ){ 
} 
public in 
// getters public String getName( ){ return name; 
return address; 
t getPhoneNum( ){ return phoneNum; 
} }
Web Design  Development – CS506 VU 
Lesson 44 
Client Side Validation 
 
JavaServer Faces (JSF) 
out client side validation and also learn about growing in 
For v l --it saves time and bandwidth, and gives you 
ore options to point out to the user where they've gone wrong in filling out the form. 
want to send the browser to the server 
validate that all of the required fields on a form were filled out. 
e can be used to achieve the said objective. However, JavaScript and 
V 
hy is Client Side Validation Good? 
There are two good reasons to use client-side validation: 
ƒ It's a fast form of validation: if something's wrong, the alarm is triggered upon 
submission of the form. 
ƒ You can safely display only one error at a time and focus on the wrong field, to 
help ensure that the user correctly fills in all the details you need. 
Code Example: Form Validation using JavaScript 
For example on the following form, we want to make sure that text filed for name should 
not be left empty and age field does not contain any negative value. To accomplish this 
we’ll use JavaScript. 
If user forgets to provide name and/or enters a negative value, a message would be 
displayed to the user that indicates what was went wrong? However, if user conforms to 
requirements, he/she would be taken to another page that displays a greeting message. 
Note: In this example, JavaScript semantics isn’t discussed over here as I am assuming 
that you might be familiar with some scripting language. Otherwise, 
www.w3schools.com 
In 
this handout, we’ll talk ab 
demand Java technology i.e. JSF. First start with client side validation Clie S 
ntide Validation 
ms alidation on the client-side is essentia 
m 
Furthermore, the browser doesn't have to make a round-trip to the server to perform routine client-side tasks. For example, you wouldn't 
to 
Any scripting languag 
BScript are two popular options 
W 
is an excellent resource to learn about scripting languages 
© Copyright Virtual University of Pakistan 480
Web Design  Development – CS506 VU 
The code that is used to generate this page is given below: HTML 
HEAD 
SCRIPT TYPE = text/javascript 
!— defining a function that receives form’s reference, defined inside the body and returns false if any 
quirement violated -- 
nction validateForm(thisform) 
of the name field, if it is left empty then displaying a message -- 
if ( f name.value == ) 
{ 
return false; 
} 
!— if value of age is negative, displaying a message -- 
!— start of scripting code and mentioning type -- 
 
re 
fu 
{ 
!— checking the value 
thisorm.name.value == null || thisform. 
alert(Username is required); 
© Copyright Virtual University of Pakistan 481
Web Design  Development – CS506 VU 
© Copyright Virtual University of Pakistan 482 
if (thisform.age.value  0 ) 
{ 
alert(Age can't be negative); 
return false; 
} 
} 
 
 
alue of onsubmit value, if this method returns 
false, the user remains on the same page -- 
FORM method=post onsubmit=return validateForm(this) action = “greeting.jsp”  
h2 Client Side Validation Example /h2 
Age: INPUT type=text name=age size=30 / 
 
 
/HTML 
// end of function 
/SCRIPT !—end of script--  
/HEAD 
!— validateForm method is called and specified as a v 
BR/ 
Name: INPUT type=text name=name size=30 / 
BR/ BR/ 
BR/ BR/ 
INPUT type=submit value=Submit /FORM 
/BODY
Web Design  Development – CS506 VU 
© Copyright Virtual University of Pakistan 483 
JavaServer Faces (JSF) 
JSF technolog 
le 
b 
D 
A popular open source JSP-based Web application framework helps in defining a structured 
tion framework and reduces tedious coding but… 
sn’t provide UI tags 
imilar sort of problems as with Struts. 
Ja 
ƒ A framework which provides solutions for: 
ƒ Managing their state 
ƒ Input val 
g 
ƒ Automat 
ƒ Supporting internationalization and accessibility. 
If you are familiar with Struts and Swing (the standard Java user interface framework for desktop 
applicatio on of those two frameworks. Like Swing, JSF provides 
a rich m del that eases event handling and component rendering; and like Struts, JSF provides 
Web applicati 
JS 
Some t rver Faces components are shown below: 
y simplifies building the user interface for web applications. It does this by providing a higher- vel framework for working with your web applications. Some distinct features will be discussed provided y this technology. To begin with, have a look on some popular existing frameworks 
ifferent existing frameworks ƒ Struts 
programming model (MVC), also valida ƒ Adds complexity and doe 
ƒ Very Java programmer centric 
ƒ Tapestry Another popular framework that is extensively used in the industry is Tapestry. It has almost s 
vaServer Faces 
ƒ Representing UI components 
ƒ Handling eve 
nts idation 
ƒ Data bindin 
ic conversion age navigation 
ƒ Defining p 
ns), think of JavaServer Faces as a combinati 
coponent mo 
on lifecycle management through a controller servlet 
F UI Components 
of he standard JavaSe
Web Design  Development – CS506 VU 
S 
ome custom JavaServer Faces components are 
aServer Faces components are also available like: 
And some open course Jav © Copyright Virtual University of Pakistan 484
Web Design  Development – CS506 VU 
© Copyright Virtual University of Pakistan 485 
And some third-party JavaServer Faces components are also available: 
A JSF application works by processing events triggered by the JSF components on the pages. These events 
are caused by user actions. For example, when the user clicks a button, the button triggers an event. You, the 
JSF programmer, decide what the JSF application will do when a particular event is fired. You do this by 
writing event listeners. In other words, a JSF application is event-driven. 
For example, if you write a JSF code to create a button, you will write: 
h:commandButton value=Login“ 
actionListener=“#{customer.loginActionListener}” 
action=“#{customer.login}” / 
The value attribute specifies the text that appeared on the face of a button, the actionListener attributes 
specifies to call the loginActionListener method written somewhere in a Customer class if an event is 
triggered and on which to go next, is decided by the login method of Customer class and given as a value of 
action attribute. The method specified in action attribute should return a String value as the returned 
Stringvalue is used in page navigation. 
Note: Many IDE provides visual support for JSF so you can drag and drop components instead of writing 
tedious coding for defining JSF components as shown above. Sun Studio Creator® is a free open 
source IDE that provides visual support for JSF and can be downloaded form Sun site. The code 
examples are also built using this IDE. 
A code snippet of a Customer class is given below: 
class Customer { 
public void loginActionListener(ActionEvent e) { 
………………… } 
public String login() { 
return “OK”; 
} 
}
Web Design  Development – CS506 VU 
© Copyright Virtual University of Pakistan 
486 
Example Code: Hello User 
The example code (“hello user 1”) is given along with the handout. It is strongly advised that you must see 
the lecture video in order to learn how this example is built. 
User will provide a name in the text field and his/her name after appending “hello” to it, would be displayed 
on the same page. 
Validators make input validation simple and save developers hours of programming. JSF provides a set of 
validator classes for validating input values entered into input components. Alternatively, you can write your 
own validator if none of the standard validators suits your needs. Some built-in validators are: 
ƒ DoubleRangeValidator 
Any numeric type, between specified maximum and minimum values 
ƒ LongRangeValidator 
Any numeric type convertible to long, between specified maximum and minimum values 
ƒ LengthValidator 
Ensures that the length of a component's local value falls into a certain range (between minimum  maximum). The value must be of String type. 
Example Code: Hello User 
The example code (“hello user 2”) is given along with the handout. You can open it using Sun Studio Creator IDE. It is strongly advised that you must see the lecture video in order to learn how this example is built. 
It is actually a modified version of the last example. This time, we’ll make sure that user couldn’t left blank 
the name field and must enter a name between ranges of 2 to 10 characters. If any condition fails, an appropriate message would be displayed. 
JSF – Managed Bean-Intro These are JavaBeans defined in the configuration file and are used to hold the data from JSF components. Managed beans represent the data model, and are passed between business logic and pages. Some other salient features are: 
ƒ Use the declarative model 
ƒ Entry point into the model and event handlers 
ƒ Can have beans with various states 
Here is an example of a managed-bean element whose scope is session, meaning that an instance of this 
bean is created at the beginning of a user session. 
managed-bean 
managed-bean-namemyBean/managed-bean-name 
managed-bean-classmyPackage.MyBean/managed-bean-class 
managed-bean-scopesession/managed-bean-scope /managed-bean
Web Design  Development – CS506 VU 
© Copyright Virtual University of Pakistan 
487 
JSF – Value Binding 
Value binding expressions can be used inside of JSF components to: ƒ Automatically instantiate a JavaBean and place it in the request or session scope. 
ƒ Override the JavaBean's default values through its accessor methods. 
ƒ Quickly retrieve Map, List, and array contents from a JavaBean. 
ƒ Synchronize form contents with value objects across a number of requests. 
The syntax of binding expressions is based on the JavaServer Pages (JSP) 2.0 Expression Language. In JSP, expressions are delimited with ${}, but in JSF they are delimited with #{}. JSF – Method Binding 
Unlike a value binding, a method binding does not represent an accessor method. Instead, a method binding represents an activation method. For example, binding an event handler to a method 
h:commandButton …… actionListener=“#{customer.loginActionListener}” 
……… / 
JSF Navigation 
Page navigation determines the control flow of a Web application. JSF provides a default navigational 
handler and this behavior can be configured in configuration. However, you can do it visually in most tools 
like Sun Studio Creator 
Note: We have quickly breezed through the JSF technology essentials due to shortage of time. You must 
explore it by yourself to excel on it. You can find the resources in the last handout to acquire further skills. 
References: 
ƒ Java A Lab Course by Umair Javed 
ƒ Intrduction to JavaServer Faces by Sun 
Uhttp://java.sun.com U 
ƒ JavaServer Faces Programming by Kumiawan
Web Design  Development – CS506 VU 
© Copyright Virtual University of Pakistan 
488 
Lesson 45 
JavaServer Faces 
In the last lecture, we have covered the basic nutshells of JSF. Having a belief on “learning by doing”, in this lecture another example is also given to show you the capabilities of JSF. 
Example Code: Addition of Two Numbers 
The example code (“AddNumbers”) is given along with the handout. It is strongly advised that you must see the lecture video in order to learn the making plus working of this example. 
This example demonstrates the usage of value and method binding expressions, managed beans, and how to use page navigation technique using IDE etc. 
Web Services 
In the remaining handout, we’ll take an overview of web services’ potential, their types and working model. 
Resources are given at the end for those who are interested in learning new technologies. 
Introduction Web services are Web-based enterprise applications that use open, XML-based standards and transport protocols to exchange data with calling clients. 
Web Service is becoming one of those overly overloaded buzzwords these days. Due to their increasing popularity, Java platform Enterprise Edition (J2EE) provides the APIs and tools you need to create and 
deploy interoperable web services and clients. 
Web service, Definition by W3C 
W3C recently has come up with a decent definition of web services. According to W3C, “A Web service is a 
software application identified by a URI, whose interfaces and binding are capable of being defined, described 
and discovered by XML artifacts and supports direct interactions with other software applications using XML based messages via internet-based protocols”. 
Distributed Computing Evolution Let's think a little bit on how distributed computing technology has evolved. 
In the beginning, things were built and deployed typically in the form of client and server model in which 
clients talk to a single server, for example, remote procedure calls (RPC).
Web Design  Development – CS506 VU 
© Copyright Virtual University of Pakistan 
489 
The second phase can be called web-based computing in which many clients talk to many servers through the 
net. In this phase, communicating partners still have to go through some pre-arrangement in terms of what 
common object model they have to use or what common communication protocol they have to agree upon. 
Finally, the web services model in which service users and service providers can be dynamically connected. 
And the pretty much every computing device and application participates as both service user and service 
provider. 
Characteristics of Web services 
Web services are XML-based throughout. Pretty much everything in the domain of Web services is defined in 
XML. For example, the format of the data being exchanged between service user and service provider is 
defined in XML or the description of web service is defined in XML. Because the only contract that has to be agreed upon between service user and service provider is syntax 
and semantics of XML messages, as long as valid messages can be generated and understood, it does not 
matter what programming language is used. So a web service is said to be programming language 
independent. 
Web services can be dynamically located and invoked. And typically they will be accessed and 
invoked over both internet and intranet. 
ƒ Interoperable 
Connect across heterogeneous networks using ubiquitous web-based standards 
ƒ Economical 
Recycle components, no installation and tight integration of software ƒ Automatic 
No human intervention required even for highly complex transactions 
ƒ Accessible 
Legacy assets  internal apps are exposed and accessible on the web 
ƒ Available 
Services on any device, anywhere, anytime ƒ Scalable 
No limits on scope of applications and amount of heterogeneous applications 
Types of Web service 
ƒ Data providers 
For example, a service providing stock quotes 
ƒ Business-to-business process integration 
For example, purchase orders 
ƒ Enterprise application integration 
Different applications work together simply by adding a webservice wrapper
Web Design  Development – CS506 VU 
© Copyright Virtual University of Pakistan 
490 
Comparison between Web page  Web service 
Just to give you a sense on the difference between a web page and a web service, consider the following table: 
Web page Web Service 
Has a UI No GUI 
Interacts with user Interacts with application 
Works with web browser client Works with any type of client 
Web service Architectural Components 
Following are the core building blocks of web service architecture. 
ƒ Service Description – how do clients know how it works (which functions, parameters etc.)? 
At the minimum, you need a standard way of describing a web service that is universally 
understood by all potential service users and service providers. This is important because without 
commonly agreed upon description of service, a service provider might have to produce individually 
tailored way of describing its service to all its potential service users. 
Web Service Description Language (WSDL pronounced as viz-dal) is industry agreed upon XML 
language that can be used to describe web service. It provides XML format for describing web services 
in terms of methods, properties, data types and protocols. 
ƒ Service Registration (Publication) and Discovery There has to be registry by which a service can 
be published and discovered. 
Universal Description, Discovery  Integration (UDDI), a way to publish and find web services. 
A repository of web services on the internet where a machine or a human can find different web services. 
TUwww.uddi.orgUT 
ƒ Service Invocation Then there has to be standard way of invoking a service. Finally, for business transactions in which secure and reliable message delivery is important, there has to be a standard 
electronic business framework. 
The following figure represents simplified web service architecture and summarizes the working of web 
services:
Web Design  Development – CS506 VU 
© Copyright Virtual University of Pakistan 
491 
References: 
ƒ Java A Lab Course by Umair Javed 
ƒ Web services overview by sang shin Resources: 
An excellent resource for learning Java related technologies is: 
Uhttp://www.apl.jhu.edu/~hall/java/ U 
ƒTUhttp://java.sun.comUT 
ƒTUhttp://www.javaworld.comUT 
ƒTUhttp://www.theserverside.comUT 
ƒTUhttp://www.jsfcentral.comUT 
ƒTUhttp://www.jspolympus.comUT 
ƒ http://www.onjava.com

Web design and development cs506 handouts

  • 1.
    Web Design &Development – CS506 VU © Copyright Virtual University of Pakistan 1 Table of Contents Chapter No.1 Java Fratures 12 1.1 Designing Goals of Java 12 1.2 Right Language, Right Time 12 1.3 Java Buzzwords 12 1.4 Java Language + Libraries 12 1.5 Simple 12 1.6 Object Oriented 13 1.7 Distributed/Network Oriented 13 1.8 Robust/Secure/Safe 13 1.9 Portable 14 1.10 Support for Web & Enterprise Web Applications 14 1.11 High Performance 14 1.12 Multi Threaded 14 1.13 Dynamic 14 1.14 Java Compiler Structure 14 1.15 Java Programmer Efficiency 15 1.16 OOP 15 1.17 Libraries 15 1.18 Microsoft vs. Java 15 Chapter No.2 Java Virtual Machine & Runtime Enviornment 16 2.1 Basic Concepts 16 2.2 Byte Code 17 2.3 Java Virtual Machine (JVM) 17 2.4 Java Runtime Environment (JRE) 18 2.5 2.5.1 Edit 20 Java Program Development and Execution Steps 19 2.5.2 Compile 20 2.5.3 Loading 20 2.5.4 Verify 21 2.2.5 Execute 21 2.6 Installation & Environment Setting 22 2.6.1 Installation 22 2.6.2 Environment Setting 22 2.7 First Program in Java 26 2.8 HelloWorldApp 26 2.9 HelloWorldApp Description 27 2.10 Compiling & Running HelloWorldApp 28 2.11 Points to Remember 28 2.12 An Idiom Explained 29 Chapter No.3 Learning Basics 30 3.1 Strings 30 3.1.1 String Concatenation 30 3.1.2 Comparing Strings 30 3.2 Command Line Arguments 32 3.3 Primitives vs. Objects 34 3.4 Stack vs. Heap 34
  • 2.
    Web Design &Development – CS506 VU © Copyright Virtual University of Pakistan 2 3.5 Wrapper Classes 35 3.6 Wrapper Use 35 3.7 Converting String to Numeric Primitive Data Types 35 3.8 Input/Output Example 37 3.9 Selection & Control Structure 38 Chapter No.4 Object Oriented Programming 40 4.1 OOP Vocabulary Review 40 4.1.1 Class 40 4.1.2 Object 40 4.1.3 Constructor 40 4.1.4 Attributes 40 4.1.5 Methods 40 4.2 Defining a Class 41 4.3 Comparison with C++ 41 4.4 Defining a Student Class 43 4.5 Getters/Setters 43 4.6 Using a Class 45 4.7 Static 47 4.8 Garbage Collection & Finalize 47 Chapter No.5 Inheritance 52 5.1 Comparison with C++ 52 5.2 Object (Root Class) 56 5.3 Polymorphism 57 5.4 Type Casting 59 5.4.1 Up-Casting 59 5.4.2 Down-Casting 59 Chapter No.6 Collections 60 6.1 Collection Design 60 6.2 Collection Messages 60 6.3 ArrayList 61 6.3.1 Useful Methods 61 6.4 HashMap 62 6.4.1 Useful Methods 62 6.5 Address Book 65 6.5.1 Problem 65 6.5.2 Approach for Solving Problem 65 Chapter No.7 Intro to Exceptions 70 7.1 Types of Errors 70 7.1.1 Syntax Errors 70 7.1.2 Logical Errors 70 7.3.1 Runtime Errors 70 7.2 What is an Exception? 70 7.3 Why Handle Exceptions? 70 7.4 Exceptions in Java 71 7.5 Exceptions Hierarchy 71 7.5 Types of Exceptions 72
  • 3.
    Web Design &Development – CS506 VU © Copyright Virtual University of Pakistan 3 7.5.1 Unchecked Exceptions 72 7.5.2 Checked Exceptions 72 7.6 How Java Handles exceptions 72 7.6.1 try Block 72 7.6.2 catch block 72 7.6.3 finally block 72 7.6.4 throw 74 7.6.5 throws 74 7.7 Examples of Unchecked Exceptions 75 7.8 Examples of Checked Exceptions 77 7.9 The finally Block 79 7.10 Multiple catch blocks 80 7.11 The throws clause 82 7.12 printStackTrace Method 83 Chapter No.8 Streams 85 8.1 The Concept of Streams 85 8.2 Types of Systems 86 8.3 Stream Classification Based on Functionality 86 8.4 Example of Reading from File 88 8.5 Example of Writing to File 89 Chapter No.9 Modification of Address Book Code 90 9.1 Adding Persistence Functionality 90 9.1.1 Scenario 1- Startup 90 9.1.2 Scenario 2- End/Finish up 93 9.2 Abstract Classes & Interfaces 96 9.3 Problems & Requirements 96 9.4 Abstract Classes 96 9.4.1 Example of Abstract Classes 97 9.5 Interfaces 98 9.5.1 Defining an Interface 98 9.5.2 Implementing Interface 98 9.5.3 Example of Interface 98 9.5.4 Interface Characteristics 99 9.5.5 Example: Interface Based Polymorphism 100 Chapter No.10 Graphical User Interfaces 102 10.1 Support for GUI in Java 102 10.2 GUI Classes vs. Non GUI Support Classes 102 10.3 java.awt package 102 10.4 javax.swing package 102 10.5 A Part of the framework 103 10.6 GUI Creation Steps 104 10.6.1 import required package 104 10.6.2 Setup the Top Level Containers 104 10.6.3 Get the Component Area of Top Level Container 105 10.6.4 Apply Layout to Component Area 105 10.6.5 Create & Add Components 106 10.6.6 Set Size of Frame & Make it Visible 106
  • 4.
    Web Design &Development – CS506 VU © Copyright Virtual University of Pakistan 4 10.7 Making a Simple GUI 106 10.8 Important Points to Consider 108 10.9 Layout Managers 109 10.9.1 Flow Layout 109 10.9.2 Grid Layout 111 10.9.3 Border Layout 113 10.10 Making Complex GUIs 115 10.11 JPanel 115 10.12 Calculator GUI 116 Chapter No.11 Event Handling 119 11.1 Event Handling Model 120 11.2 Event Handling Steps 120 11.3 Event Handling Process 120 11.3.1 Event Generators 120 11.3.2 Event Handlers/Listeners 121 11.3.3 Registering Handler with Generator 123 11.4 How Event Handling Participants Interact Behind the Scene 125 11.4.1 Event Generator/Source 125 11.4.2 Event Object 125 11.4.3 Event Listener/Handler 125 11.4.4 JVM 125 11.5 Making a Small Calculator 127 Chapter No.12 More Examples of Handling Events 130 12.1 Handling Mouse Events 130 12.1.1 MouseMotionListener Interface 130 12.3 MouseListener Interface 130 12.4 Example: Handling Mouse Events 131 12.5 Handling Window Events 133 Chapter No.13 Problem in Last Code Example 136 13.1 Problem 136 13.2 Solution 136 13.3 Adapter Classes 136 13.4 Available Adapter Classes 137 13.5 How to Use Adapter Classes 137 13.6 Example 138 13.7 Problem in Example 139 13.8 Inner Classes 139 13.9 Handling Window Events with Inner Classes 140 13.10 Handling Window & Mouse Events with Inner Classes 141 13.11 Small Calculator Making Inner Classes 143 13.12 Anonymous Inner Classes 146 13.13 Named vs. Anonymous Objects 146 13.14 Handling Window Events with Anonymous Inner Class 147 13.15 Summary of Approaches for Handling Events 148 Chapter No.14 Java Data Base Connectivity 149 14.1 Introduction 149
  • 5.
    Web Design &Development – CS506 VU © Copyright Virtual University of Pakistan 5 14.2 The java.sql package 149 14.3 Connecting with Microsoft Access 149 14.3.1 Create Database 149 14.3.2 Setup System DSN 150 14.4 Basic Steps in Using JDBC 151 14.4.1 Import Required Package 151 14.4.2 Load Driver 152 14.4.3 Define Connection URL 152 14.4.4 Establish Connection with Database 152 14.4.5 Create Statement 152 14.4.6 Execute Query 152 14.4.7 DELETE 153 14.4.8 Close the Connection 153 14.5 Retrieving Data from Resultset 153 Chapter No.15 More on JDBC 156 15.1 Useful Statement Methods 156 15.1.1 executeUpdate( ) 156 15.1.2 getMaxRows( )/setMaxRows(int) 158 15.1.3 getQueryTimeOut( )/setQueryTimeOut(int) 158 15.2 Different Type of Statements 158 15.2.1 Statement 159 15.2.2 PreparedStatement 159 15.2.3 CallableStatement 159 15.3 PreparedStatement 159 Chapter No.16 Result Set 162 16.1 ResultSet 162 16.2 Default ResultSet 162 16.3 Useful ResultSet’s Methods 162 16.3.1 next( ) 163 16.3.2 getters 163 16.3.3 close( ) 163 16.4 Updatable &/or Scrollable ResultSet 163 16.5 Getting Updatable & Scrollable ResultSet 163 16.5.1 previous( ) 164 16.5.2 absolute(int) 165 16.5.3 updaters 166 16.5.4 updateRow( ) 166 16.5.5 moveToInsertRow(int) 168 16.5.6 insertRow( ) 168 16.5.7 last( ) & first( ) 171 16.5.8 getRow( ) 171 16.5.9 deleteRow( ) 171 Chapter No.17 Meta Data 174 17.1 ResultSet Meta data 174 17.2 Getting ResultSet Meta Data Object 174 17.3 Useful ResultSetMetaData Methods 175 17.4 DataBaseMetaData 177
  • 6.
    Web Design &Development – CS506 VU © Copyright Virtual University of Pakistan 6 17.4.1 Creating DataBaseMetaData Object 177 17.5 JDBC Driver Types 179 Chapter No.18 Java Graphics 183 18.1 Painting 183 18.2 How Painting Works 183 18.3 Painting a Swing Component 186 18.4 Your Painting Strategy 187 Chapter No.19 How to Animate? 191 19.1 Problem & Solution 191 19.2 Coding Example 191 19.3 Ball Animation 195 Chapter No.20 Applets 199 20.1 Applets Support 199 20.2 What an Applet is? 199 20.3 The Genealogy of Applet 201 20.4 Applet Life Cycle Methods 202 20.5 Design Process 204 20.6 Generating Random Numbers 204 20.7 Program’s Modules 205 20.8 Merging Pieces 208 Chapter No.21 Socket Programming 211 21.1 Socket 211 21.2 Socket Dynamics 211 21.3 What is Port? 211 21.4 How Client Server Communicate 211 21.5 Steps to make a Simple Client 212 21.6 Steps to make a Simple Server 214 Chapter No.22 Serialization 219 22.1 What? 219 22.2 Motivation 219 22.3 Revisiting AddressBook 219 22.4 Serialization in Java 220 22.5 Serializable Interface 220 22.6 Automatic Writing 220 22.7 Automatic Reading 220 22.8 Serialization- How it Works? 220 22.9 Object Serialization & Network 222 22.10 Reading Objects over Network 223 22.11 Preventing Serialization 225 Chapter No.23 Multithreading 226 23.1 Introduction 226 23.2 Sequential Execution vs. Multithreading 226 23.3 Creating Threads in Java 228 23.4 Thread Creating Steps using Inheritance 228
  • 7.
    Web Design &Development – CS506 VU © Copyright Virtual University of Pakistan 7 23.5 Thread priority Scheduling 230 23.6 Problems with Thread Priorities 232 Chapter No.24 More on Multithreading 233 24.1 Reading Two Files Simultaneously 233 24.2 Threads’ Joining 240 Chapter No.25 Web Application Development 242 25.1 Introduction 242 25.2 Web Applications 242 25.3 HTTP Basics 242 25.3.1 Parts of HTTP Request 243 25.3.2 Parts of HTTP Response 243 25.4 HTTP Response Codes 244 25.5 Server Side Programming 245 25.6 Why Build Pages Dynamically? 247 25.7 Dynamic Web Content Technologies Evolution 248 25.8 Layers & Web Applications 249 Chapter No.26 Java Servlets 250 26.1 What Servlets can do? 250 26.2 Servlets vs. other SSP Technologies 250 26.3 Software Requirements 251 26.4 Jakarta Servlet Engine (Tomcat) 251 26.5 Environment Setup 251 26.6 Environment Setup using .zip File 251 26.7 Environment Setup using .exe File 252 Chapter No.27 Creating a Simple Web Application in Tomcat 260 27.1 Slandered Directory Structure of a J2EE Web Application 260 27.2 Writing Servlets 262 27.3 Servlet Types 262 27.4 Servlet Class Hierarchy 263 27.5 Types of HTTP Requests 263 27.6 GET & POST HTTP Request Types 264 27.7 Steps for Making Hello World Servlet 264 27.8 Compiling & Invoking Servlets 266 Chapter No.28 Servlets Lifecycle 267 28.1 Stages of Servlet Lifecycle 267 28.2 Reading HTML Form Data Using Servlets 269 28.3 HTML & Servlets 270 28.4 Types of Data Send to Web Server 270 28.5 Reading HTML Form Data from Servlets 270 Chapter No.29 More on Servlets 275 29.1 Initialization Parameters 275 29.2 ServletConfig 275 29.3 Reading Initialization Parameters 276 29.4 Response Redirection 278
  • 8.
    Web Design &Development – CS506 VU © Copyright Virtual University of Pakistan 8 29.5 Sending a Standered Redirect 278 29.6 Sending a Redirect to an Error Page 278 29.7 ServletContext 281 29.8 Request Dispatcher 281 Chapter No.30 Dispatching Requests 284 30.1 Recap 284 30.2 Example Code- Request Dispatching- Include 284 30.3 Example Code- Request Dispatcher- Forward 289 30.4 HttpServletRequest Methods 293 30.5 HttpServletResponse Methods 294 30.6 Session Tracking 295 Chapter No.31 Session Tracking 297 31.1 Store State Somewhere 297 31.2 Post Notes 297 31.3 Three Typical Solutions 297 31.4 Cookies 298 31.4.1 What a Cookie is? 298 31.4.2 Cookie’s Voyage 298 31.4.3 Potential Uses of Cookies 298 31.4.4 Sending Cookies to Browser 299 31.4.5 Reading cookies from Client 299 Chapter No.32 Session Tracking 2 308 32.1 URL Rewriting 308 32.2 Disadvantages of URL Rewriting 308 32.3 How to Make a QueryString 308 32.4 Hidden Form Fields 312 32.5 Java Solution for Session Tracking 312 32.6 Working with HttpSession 313 32.7 HttpSession- Behind the Scenes 316 32.8 Encoding URLs sent to Client 317 32.9 Difference between encodURL( ) & encodeRedirectURL( ) 317 32.10 Some Methods of HttpSession 317 Chapter No.33 Case Study Using Servlets 321 33.1Design Process 321 33.2 Layers and Web Application 321 33.3 Package 328 33.4 What is a Package? 328 33.5 How to Create a Package? 328 33.6 How to use Package? 329 33.7 JavaServer Pages (JSP) 330 33.8 The Need for JSP 330 33.9 JSP Framework 330 33.10 Advantages of JSP over Competing Technologies 330 33.11Setting Up Your Environment 331 Chapter No.34 Java Server Pages 1 332
  • 9.
    Web Design &Development – CS506 VU © Copyright Virtual University of Pakistan 9 34.1 First run of a JSP 332 34.2 Benifits of JSP 332 34.3 JSP vs. Servlet 333 34.4 Scripting Elements 335 34.5 Comments 335 34.6 Expressions 335 34.7 Scriplets 335 34.8 Declarations 336 34.9 Writing JSP Scripting Elements in XML 337 Chapter No.35 Java Server Pages 2 339 35.1 Implicit Objects 339 35.2 JSP Directives 344 35.3 JSP Page Directive 344 35.4 JSP Include Directive 345 35.5 JSP LifeCycle Methods 348 Chapter No.36 Java Server Pages 3 349 36.1 Displaying Course Outline 349 36.2 Java Beans 356 36.3 Java Beans Design Conventions 356 36.4 A Sample Java Bean 356 Chapter No.37 JSP Action Elements & Scope 367 37.1 JSP Action Elements 367 37.2 Working with JavaBeans using JSP Action Elements 368 37.3 JSP useBean Action Element 368 37.4 JSP setProperty Action Element 368 37.5 JSP getProperty Action Element 369 37.6 Sharing Beans & Object Scopes 372 37.7 Summary of Object’s Scopes 375 37.8 More JSP Action Elements 377 37.9 JSP include action Element 377 37.10 JSP forward action Element 377 Chapter No.38 JSP Custom Tags 378 38.1 Motivation 378 38.2 What is a Custom Tag? 378 38.3 Why Build Custom Tag? 379 38.4 Advantages of Using Custom Tags 379 38.5 Types of Tags 379 38.6Building Custom Tags 381 38.7 Building Tags with Attributes 384 Chapter No.39 MVC + Case Study 393 39.1 Error Page 393 39.2 Defining & Using Error Pages 393 39.3 Case Study- Address Book 394 39.4 Ingredients of Address Book 394 39.5 Program Flow 395
  • 10.
    Web Design &Development – CS506 VU © Copyright Virtual University of Pakistan 10 39.6 Model View Controller 408 39.7 Participants & Responsibilities 409 39.8 Evolution of MVC Architecture 409 39.9 MVC Model 1 409 Chapter No.40 MVC Model 2 Architecture 410 40.1 Page-Centric Approach 410 40.2Page-with-Bean Approach 410 40.3 MVC Model 2 Architecture 410 40.4 Case Study: Address Book Using MVC Model2 412 40.5Introducing a JSP as Controller 413 40.6 How Controller Differentiate between Requests? 413 40.7 JSP is the Right Choice as a Controller? 428 40.8 Introducing a Servlet as Controller 428 Chapter No.41 Layers & Tiers 435 41.1 Layers vs. Tiers 435 41.2 Layers 435 41.3 Presentation Layer 436 41.4 Business Layer 436 41.5 Data Layer 437 41.6 Tiers 437 41.7 Layers Support in Java 438 41.8 J2EE Multi-Tiered Applications 439 41.9 Case Study: Matrix Multiplication Using Layers 440 41.10 Layer by Layer View 440 41.11 ControllerServlet 443 41.12 Matrix Multiplier 445 41.13 Matrix DAO 447 Chapter No.42 Expression Language 451 42.1Overview 451 42.2JSP before & after EL 451 42.3 Expression Language Nuggets 452 42.4 EL Syntax 452 42.5 EL Literals 453 42.6 EL Operators 453 42.7 EL Identifiers 454 42.8 EL Implicit Objects 454 42.9 Storing Scoped Variables 456 42.10 Retrieving Scoped Variables 457 42.11EL Accessors 458 42.12 EL – Robust Features 459 42.13 Using Expression Language 459 Chapter No.43 JSTL 468 43.1 Introduction 468 43.2 JSTL and EL 468 43.3 Functional Overview 468 43.4 Twin Tag Libraries 469
  • 11.
    Web Design &Development – CS506 VU © Copyright Virtual University of Pakistan 11 43.5 Using JSTL 469 43.6 Working with Core Actions (Tags) 470 43.7 c:set 470 43.8Using with JavaBeans & Map 471 43.9c:out 471 43.10 c:remove 472 43.11 c:forEach 472 43.12 Iteration over an Integer range 473 43.13 Iteration over a Collection 473 43.14 c:if 475 43.15 c:choose 475 43.16 netBeans 4.1 & JSTL 476 Chapter No.44 Client Side Validation & JSF 480 44.1 Client side Validation 480 44.2 Why is client side Validation Good? 480 44.3 Form Validation using JavaScript 480 44.4 JavaServer Faces 483 44.5 Different Existing Frameworks 483 44.6 javaServer Faces 483 44.7 JSF UI Components 483 44.8 JSF - Managed Bean-Intro 486 44.9 JSF – Value Binding 487 44.10 JSF – Method Binding 487 44.11 JSF Navigation 487 Chapter No.45 JavaServer Faces 488 45.1 Example Code 488 45.2 Web Services 488 45.3 Introduction 488 45.4 Web Services, Definition by W3C 488 45.5 Distributed Computing Evolution 488 45.6 Characteristics of Web Services 489 45.7 Types of Web Service 489 45.8 Comparison between Web Page & Web Service 490 45.9 Web Service Architectural Components 490
  • 12.
    Web Design &Development – CS506 VU © Copyright Virtual University of Pakistan 12 Lesson 1 JAVA FEATURES This handout is a traditional introduction to any language features. You might not be able to comprehend some of the features fully at this stage but don’t worry, you’ll get to know about these as we move on with the course Design Goals of Java The massive growth of the Internet and the World-Wide Web leads us to a completely new way of looking at development of software that can run on different platforms like Windows, Linux and Solaris etc. Right Language, Right Time Java came on the scene in 1995 to immediate popularity. Before that, C and C++ dominated the software development 1. compiled, no robust memory model, no garbage collector causes memory leakages, not great support of built in libraries Java brings together a great set of "programmer efficient" features 2. Putting more work on the CPU to make things easier for the programmer. Java – Buzzwords (Vocabulary) From the original Sun Java whitepaper: "Java is a simple, object-oriented, distributed, interpreted, robust, secure, architecture-neutral, portable, high- performance, multi-threaded, and dynamic language." Here are some original java buzzwords... Java -- Language + Libraries Java has two parts... 1. The core language -- variables, arrays, objects o The Java Virtual Machine (JVM) runs the core language o The core language is simple enough to run on small devices -- phones, smart cards, PDAs. 2. The libraries o Java includes a large collection of standard library classes to provide "off the shelf" code. (Useful built-in classes that comes with the language to perform basic tasks) o Example of these classes is String, ArrayList, HashMap, StringTokenizer (to break string into substrings), Date ... o Java programmers are more productive in part because they have access to a large set of standard, well documented library classes. Simple Very similar C/C++ syntax, operators, etc. The core language is simpler than C++ -- no operator overloading, no pointers, and no multiple inheritance
  • 13.
    Web Design &Development – CS506 VU © Copyright Virtual University of Pakistan 13 The way a java program deals with memory is much simpler than C or C++. Object-Oriented Java is fundamentally based on the OOP notions of classes and objects. Java uses a formal OOP type system that must be obeyed at compile-time and run-time. This is helpful for larger projects, where the structure helps keep the various parts consistent. Contrast to Perl, which has a more anything-goes feel. D istributed / Network Oriented Java is network friendly -- both in its portable, threaded nature, and because common networking operations are built-in to the Java libraries. R obust / Secure / Safe • Java is very robust o Both, vs. unintentional errors and vs. malicious code such as viruses. o Java has slightly worse performance since it does all this checking. (Or put the other way, C can be faster since it doesn't check anything.) • The JVM "verifier" checks the code when it is loaded to verify that it has the correct structure -- that it does not use an uninitialized pointer, or mix int and pointer types. This is one-time "static" analysis -- checking that the code has the correct structure without running it. • The JVM also does "dynamic" checking at runtime for certain operations, such as pointer and array access, to make sure they are touching only the memory they should. You will write code that runs into • As a result, many common bugs and security problems (e.g. "buffer overflow") are not possible in java. The checks also make it easier to find many common bugs easy, since they are caught by the runtime checker. • You will generally never write code that fails the verifier, since your compiler is smart enough to only generate correct code. You will write code that runs into the runtime checks all the time as you debug -- array out of bounds, null pointer. • Java also has a runtime Security Manager can check which operations a particular piece of code is allowed to do. As a result, java can run un-trusted code in a "sandbox" where, for example, it can draw to the screen but cannot access the local file system.
  • 14.
    Web Design &Development – CS506 VU © Copyright Virtual University of Pakistan 14 Portable "Write Once Run Anywhere", and for the most part this works. Not even a recompile is required -- a Java executable can work, without change, on any Java enabled platform. Support for Web and Enterprise Web Applications Java provides an extensive support for the development of web and enterprise applications Servlets, JSP, Applets, JDBC, RMI, EJBs and JSF etc. are some of the Java technologies that can be used for the above mentioned purposes. High-performance The first versions of java were pretty slow. Java performance has gotten a lot better with aggressive just-in-time-compiler (JIT) techniques. Java performance is now similar to C -- a little slower in some cases, faster in a few cases. However memory use and startup time are both worse than C. Java performance gets better each year as the JVM gets smarter. This works, because making the JVM smarter does not require any great change to the java language, source code, etc. Multi-Threaded Java has a notion of concurrency wired right in to the language itself. This works out more cleanly than languages where concurrency is bolted on after the fact. Dynamic Class and type information is kept around at runtime. This enables runtime loading and inspection of code in a very flexible way. J ava Compiler Structure The source code for each class is in a .java file. Compile each class to produce “.class” file. Sometimes, multiple .class files are packaged together into a .zip or .jar "archive" file. On unix or windows, the java compiler is called "javac". To compile all the .java files in a directory use "javac *.java".
  • 15.
    Web Design &Development – CS506 VU © Copyright Virtual University of Pakistan 15 Java: Programmer Efficiency Faster Development Building an application in Java takes about 50% less time than in C or C++. So, faster time to market Java is said to be “Programmer Efficient”. OOP Java is thoroughly OOP language with robust memory system Memory errors largely disappear because of the safe pointers and garbage collector. The lack of memory errors accounts for much of the increased programmer productivity. Libraries Code re-use at last -- String, ArrayList, Date, ... available and documented in a standard way Microsoft vs. Java Microsoft hates Java, since a Java program (portable) is not tied to any particular operating system. If Java is popular, then programs written in Java might promote non-Microsoft operating systems. For basically the same reason, all the non- Microsoft vendors think Java is a great idea. Microsoft's C# is very similar to Java, but with some improvements, and some questionable features added in, and it is not portable in the way Java is. Generally it is considered that C# will be successful in the way that Visual Basic is: a nice tool to build Microsoft only software. Microsoft has used its power to try to derail Java somewhat, but Java remains very popular on its merits. J ava Is For Real Java has a lot of hype, but much of it is deserved. Java is very well matched for many modern problems Using more memory and CPU time but less programmer time is an increasingly appealing tradeoff. Robustness and portability can be very useful features A general belief is that Java is going to stay here for the next 10-20 years References Majority of the material in this handout is taken from the first handout of course cs193j at Stanford. The Java™ Language Environment, White Paper, by James Gosling & Henry McGilton Java’s Sun site: http://java.sun.com Java World: www.javaworld.com
  • 16.
    Web Design &Development – CS506 VU © Copyright Virtual University of Pakistan 16 Lesson 2 Java Virtual Machine & Runtime Environment Basic Concept When you write a program in C++ it is known as source code. The C++ compiler converts this source code into the machine code of underlying system (e.g. Windows) If you want to run that code on Linux you need to recompile it with a Linux based compiler. Due to the difference in compilers, sometimes you need to modify your code. Java has introduced the concept of WORA (write once run anywhere). When you write a java program it is known as the source code of java. The java compiler does not compile this source code for any underlying hardware system; rather it compiles it for a software system known as JVM (This compiled code is known as byte code). We have different JVMs for different systems (such as JVM for Windows, JVM for Linux etc). When we run our program the JVM interprets (translates) the compiled program into the language understood by the underlying system. So we write our code once and the JVM runs it everywhere according to the underlying system. This concept is discussed in detail below JAVA Source Code Java Compiler javac Java Byte Code Java Interpreter Machin Code e
  • 17.
    Web Design &Development – CS506 VU © Copyright Virtual University of Pakistan 17 B ytecode Java programs (Source code) are compiled into a form called Java bytecodes. The Java compiler reads Java language source (.java) files, translates the source into Java bytecodes, and places the bytecodes into class (.class) files. The compiler generates one class file for each class contained in java source file. Java Virtual Machine (JVM) The central part of java platform is java virtual machine Java bytecode executes by special software known as a "virtual machine". Most programming languages compile source code directly into machine code, suitable for execution he differenc T e with Java is that it uses bytecode - a special type of machine code. he JVM executes Java bytecodes, so Java bytecodes can be thought of as the machine language App1 s • JVM are available for almost all operating systems. • Java bytecode is executed by using any operating system’s JVM. Thus achieve portability. T of the JVM. A pp2 App3 App4 App5 Java Virtual Machine WindowOS X Solaris Linux Linux Intel PowerPC SPARC
  • 18.
    Web Design &Development – CS506 VU © Copyright Virtual University of Pakistan 18 J ava Runtime Environment (JRE) The Java Virtual Machine is a part of a large system i.e. Java Runtime Environment (JRE). Each operating system and CPU architecture requires different JRE. The JRE consists of set of built-in classes, as well as a JVM. Without an available JRE for a given environment, it is impossible to run Java software. References Java World: http://www.javaworld.com Inside Java: http://www.javacoffeebreak.com/articles/inside_java
  • 19.
    Web Design &Development – CS506 VU © Copyright Virtual University of Pakistan 19 Java Program Development and Execution Steps Java program normally go through five phases. These are 1. Edit, 2. Compile, 3. Load, 4. Verify and 5. Execute We look over all the above mentioned phases in a bit detail. First consider the following figure that summarizes the all phases of a java program. Phase 1 Phase 3 Phase 4 Phase 5 Editor Compiler Class Loader Disk Bytecode Verifier Interpreter Disk Disk Primary Memory Primary Memory Primary Memory Program is created in the editor and stored on disk. Compiler creates bytecodes and stores them on disk. Class loader puts bytecodes in memory. Bytecode verifier confirms that all bytecodes are valid and do not violate Java’s security restrictions. Interpreter reads bytecodes and translates them into a language that the computer can understand, possibly storing data values as the program executes.
  • 20.
    Web Design &Development – CS506 VU © Copyright Virtual University of Pakistan 20 Phase 1: Edit Phase 1 consists of editing a file. This is accomplished with an editor program. The programmer types a java program using the editor like notepad, and make corrections if necessary. When the programmer specifies that the file in the editor should be saved, the program is stored on a secondary storage device such as a disk. Java program file name ends with a .java extension. On Windows platform, notepad is a simple and commonly used editor for the beginners. However java integrated development environments (IDEs) such as NetBeans, Borland JBuilder, JCreator and IBM’s Ecllipse have built-in editors that are smoothly integrated into the programming environment. Phase 2: Compile In Phase 2, the programmer gives the command javac to compile the program. The java compiler translates the java program into bytecodes, which is the language understood by the java interpreter. To compile a program called Welcome.java, type javac Welcome.java at the command window of your system. If the program compiles correctly, a file called Welcome.class is produced. This is the file containing the bytecodes that will be interpreted during the execution phase. Phase 3: Loading In phase 3, the program must first be placed in memory before it can be executed. This is done by the class loader, which takes the .class file (or files) containing the bytecodes and transfers it to memory. The .class file can be loaded from a disk on your system or over a network (such as your local university or company network or even the internet). Applications (Programs) are loaded into memory and executed using the java interpreter via the command java. When executing a Java application called Welcome, the command Java Welcome Invokes the interpreter for the Welcome application and causes the class loader to load information used in the Welcome program.
  • 21.
    Web Design &Development – CS506 VU © Copyright Virtual University of Pakistan 21 Phase 4: Verify Before the bytecodes in an application are executed by the java interpreter, they are verified by the bytecode verifier in Phase 4. This ensures that the bytecodes for class that are loaded form the internet (referred to as downloaded classes) are valid and that they do not violate Java’s security restrictions. Java enforces strong security because java programs arriving over the network should not be able to cause damage to your files and your system (as computer viruses might). Phase 5: Execute Finally in phase 5, the computer, under the control of its CPU, interprets the program one bytecode at a time. Thus performing the actions specified by the program. Programs may not work on the first try. Each of the preceding phases can fail because of various errors. This would cause the java program to print an error message. The programmer would return to the edit phase, make the necessary corrections and proceed through the remaining phases again to determine id the corrections work properly. ----------------------------------------------- References: Java™ How to Program 5th edition by Deitel & Deitel Sun Java online tutorial: http://java.sun.com/docs/books/tutorial/java/index.html
  • 22.
    Web Design &Development – CS506 VU © Copyright Virtual University of Pakistan 22 Installation and Environment Setting Installation • Download the latest version j2se5.0 (java 2 standard edition) from http://java.sun.com or get it from any other source like CD. Note: j2se also called jdk (java development kit). You can also use the previous versions like jdk 1.4 or 1.3 etc. but it is recommended that you use either jdk1.4 or jdk5.0 • Install j2se5.0 on your system Note: For the rest of this handout, assume that j2se is installed in C:Program FilesJavajdk1.5.0 Environment Setting Once you successfully installed the j2se, the next step is environment or path setting. You can accomplish this in either of two ways. • Temporary Path Setting Open the command prompt from Start Æ Programs Æ Accessories Æ Comman Prompt. The command prompt screen would be opened in front of you. Write the command on the command prompt according to the following format path = < java installation directorybin > So, according to handout, the command will look like this path = C:Program FilesJavajdk1.5.0bin To Test whether path has been set or not, write javac and press ENTER. If the list ofn b options displayed as shown in the below figure means that you have successfully completed the steps of path setting. The above procedure is illustrates in the given below picture.
  • 23.
    Web Design &Development – CS506 VU © Copyright Virtual University of Pakistan 23 Note: The issue with the temporary path setting is you have to repeat the above explained procedure again and again each time you open a new command prompt window. To avoid this overhead, it is better to set your path permanently • Permanent Path Setting In Windows NT (XP, 2000), you can set the permanent environment variable. Right click on my computer icon click on properties as shown below
  • 24.
    Web Design &Development – CS506 VU © Copyright Virtual University of Pakistan 24 A System Properties frame would appeared as shown in the picture Select the advanced tab followed by clicking the Environment Variable button. The g box would be appeared. Environment variables frame would be displayed in front of you Locate the Path variable in the System or user variables, if it is present there, select it by single click. Press Edit button. The following dialo • Write; C:Program FilesJavajdk1.5.0bin at the end of the value field. Press OK button. Remember to write semicolon (;) before writing the path for java installation directory as illustrate in the above figure • If Path variable does not exist, click the New button. Write variable name “PATH”, variable value C:Program FilesJavajdk1.5.0bin and press OK button.
  • 25.
    Web Design &Development – CS506 VU © Copyright Virtual University of Pakistan 25 • Now open the command prompt and write javac, press enter button. You see the list of options would be displayed. • After setting the path permanently, you have no need to set the path for each new opened command prompt. References Entire material for this handout is taken from the book JAVA A Lab Course by Umair Javed. This material is available just for the use of VU students of the course Web Design and Development and not for any other commercial purpose without the consent of author.
  • 26.
    Web Design &Development – CS506 VU © Copyright Virtual University of Pakistan 26 First Program in Java Like any other programming language, the java programming language is used to create applications. So, we start from building a classical “Hello World” application, which is generally used as the first program for learning any new language. HelloWorldApp 1. Open notepad editor from Start Æ ProgarmFiles Æ AccessoriesÆ Notepad. 2. Write the following code into it. Note: Don’t copy paste the given below code. Probably it gives errors and you can’t able to remove them at the beginning stage. 1. /* The HelloWorldApp class implements an application that 2. simply displays "Hello World!" to the standard output. 3. */ 4. public class HelloWorldApp { 5. public static void main(String[] args) { 6. //Display the string. No global main 7. System.out.println(“Hello World”); 8. } 9. } 3. To save your program, move to File menu and choose save as option. 4. Save your program as “HelloWorldApp.java” in some directory. Make sure to add double quotes around class name while saving your program. For this example create a folder known as “examples” in D: drive Note: Name of file must match the name of the public class in the file (at line 4). Moreover, it is case sensitive. For example, if your class name is MyClass, than file name must be MyClass. Otherwise the Java compiler will refuse to compile the program. For the rest of this handout, we assume that program is saved in D:examples directory.
  • 27.
    Web Design &Development – CS506 VU © Copyright Virtual University of Pakistan 27 HelloWorldApp Described Lines 1-3 Like in C++, You can add multiple line comments that are ignored by the compiler. Lines 4 Line 4 declares the class name as HelloWorldApp. In java, every line of code must reside inside class. This is also the name of our program (HelloWorldApp.java). The compiler creates the HelloWorldApp.class if this program successfully gets compiled. Lines 5 Line 5 is where the program execution starts. The java interpreter must find this defined exactly as given or it will refuse to run the program. (However you can change the name of parameter that is passed to main. i.e. you can write String[] argv or String[] some Param instead of String[] args) Other programming languages, notably C++ also use the main( ) declaration as the starting point for execution. However the main function in C++ is global and reside outside of all classes where as in Java the main function must reside inside a class. In java there are no global variables or functions. The various parts of this main function declaration will be covered at the end of this handout. Lines 6 Again like C++, you can also add single line comment Lines 7 Line 7 illustrates the method call. The println( ) method is used to print something on the console. In this example println( ) method takes a string argument and writes it to the standard output i.e. console. Lines 8-9 Line 8-9 of the program, the two braces, close the method main( ) and the class HelloWorldApp respectively.
  • 28.
    Web Design &Development – CS506 VU © Copyright Virtual University of Pakistan 28 Compiling and Running HelloWorldApp 1. Open the command prompt from Start Æ Program Files Æ Accessories. OR alternatively you can write cmd in the run command window. 2. Write cd.. to came out from any folder, and cd [folder name] to move inside the specified directory. To move from one drive to another, use [Drive Letter]: See figure given below 3. After reaching to the folder or directory that contains your source code, in our case HelloWorldApp.java. 4. Use “javac” on the command line to compile the source file (“.java” file). D:examples> javac HelloWorld.java 5. If program gets successfully compiled, it will create a new file in the same directory named HelloWorldApp.class that contains the byte-code. 6. Use “java” on the command line to run the compiled .class file. Note “.class” would be added with the file name. D:examples> java HelloWorld 7. You can see the Hello World would be printed on the console. Hurrah! You are successful in writing, compiling and executing your first program in java ☺ Points to Remember ƒ Recompile the class after making any changes ƒ Save your program before compilation ƒ Only run that class using java command that contains the main method, because program executions always starts form main
  • 29.
    Web Design &Development – CS506 VU © Copyright Virtual University of Pakistan 29 An Idiom Explained You will see the following line of code often: – public static void main(String args[]) { …} • About main() “main” is the function from which your program starts Why public? Since main method is called by the JVM that is why it is kept public so that it is accessible from outside. Remember private methods are only accessible from within the class Why static? Every Java program starts when the JRE (Java Run Time Environment) calls the main method of that program. If main is not static then the JRE have to create an object of the class in which main method is present and call the main method on that object (In OOP based languages method are called using the name of object if they are not static). It is made static so that the JRE can call it without creating an object. Also to ensure that there is only one copy of the main method per class Why void? • Indicates that main ( ) does not return anything. What is String args[] ? Way of specifying input (often called command-line arguments) at startup of application. More on it latter References Entire material for this handout is taken from the book JAVA A Lab Course by Umair Javed. This material is available just for the use of VU students of the course Web Design and Development and not for any other commercial purpose with out the consent of author.
  • 30.
    Web Design &Development – CS506 VU © Copyright Virtual University of Pakistan 30 Lesson 3 Learning Basics Strings A string is commonly considered to be a sequence of characters stored in memory and accessible as a unit. Strings in java are represented as objects. String Concatenation “+” operator is used to concatenate strings – System.out.pritln(“Hello” + “World”) will print Hello World on console String concatenated with any other data type such as int will also convert that datatype to String and the result will be a concatenated String displayed on console. For example, – int i = 4; – int j = 5; System.out.println (“Hello” + i) will print Hello 4 on screen – However System,.out..println( i+j) ; will print 9 on the console because both i and j are of type int. Comparing Strings For comparing Strings never use == operator, use equals method of String class. – == operator compares addresses (shallow comparison) while equals compares values (deep comparison) E.g string1.equals(string2)
  • 31.
    Web Design &Development – CS506 VU © Copyright Virtual University of Pakistan 31 Example Code: String concatenation and comparison public class StringTest { public static void main(String[] args) { int i = 4; int j = 5; System.out.println("Hello" + i); // will print Hello4 System.out.println(i + j); // will print 9 String s1 = new String (“pakistan”); String s2 = “pakistan”; if (s1 == s2) { System.out.println(“comparing string using == operator”); } if (s1.equals( s2) ) { System.out.println(“comparing string using equal method”); } } } On execution of the above program, following output will produce
  • 32.
    Web Design &Development – CS506 VU © Copyright Virtual University of Pakistan 32 Taking in Command Line Arguments In Java, the program can be written to accept command-line-arguments. Example Code: command-line arguments /* This Java application illustrates the use of Java command-line arguments. */ public class CmdLineArgsApp { public static void main(String[] args){ //main method System.out.println(”First argument ” + args[0]); System.out.println(”Second argument ” + args[1]); }//end main }//End class. To execute this program, we pass two arguments as shown below: public void someMethod( ) { int x; //local variable System.out.println(x); // compile time error • These parameters should be separated by space. . • The parameters that we pass from the command line are stored as Strings inside the “args” array. You can see that the type of “args” array is String. Example Code: Passing any number of arguments In java, array knows their size by using the length property. By using, length property we can determine how many arguments were passed. The following code example can accept any number of arguments /* This Java application illustrates the use of Java command-line arguments. */ public class AnyArgsApp { public static void main(String[] args){ //main method for(int i=0; i < args.length; i++) System.out.println(“Argument:” + i + “value” +args[i]); }//end main }//End class.
  • 33.
    Web Design &Development – CS506 VU © Copyright Virtual University of Pakistan 33 Output C:java AnyArgsApp i can pass any number of arguments Argument:0 value i Argument:1 value can Argument:2 value pass Argument:3 value any Argument:4 value number Argument:5 value of Argument:6 value arguments
  • 34.
    Web Design &Development – CS506 VU © Copyright Virtual University of Pakistan 34 Primitives vs Objects • Everything in Java is an “Object”, as every class by default inherits from class “Object” , except a few primitive data types, which are there for efficiency reasons. • Primitive Data Types Primitive Data types of java boolean, byte 1 byte char, short 2 bytes int, float 4 bytes long, double 8 bytes • Primitive data types are generally used for local variables, parameters and instance variables (properties of an object) • Primitive datatypes are located on the stack and we can only access their value, while objects are located on heap and we have a reference to these objects • Also primitive data types are always passed by value while objects are always passed by reference in java. There is no C++ like methods – void someMethod(int &a, int & b ) // not available in java Stack vs. Heap Stack and heap are two important memory areas. Primitives are created on the stack while objects are created on heap. This will be further clarified by looking at the following diagram that is taken from Java Lab Course. int num = 5; Student s = new Student(); Stack Heap num 5 0F59 name ali 0F59
  • 35.
    Web Design &Development – CS506 VU © Copyright Virtual University of Pakistan 35 Wrapper Classes Each primitive data type has a corresponding object (wrapper class). These wrapper classes provides additional functionality (conversion, size checking etc.), which a primitive data type cannot provide. Wrapper Use You can create an object of Wrapper class using a String or a primitive data type • Integer num = new Integer(4); or • Integer num = new Integer(“4”); Note: num is an object over here not a primitive data type You can get a primitive data type from a Wrapper using the corresponding value function • int primNum = num.intValue(); Converting Strings to Numeric Primitive Data Types To convert a string containing digits to a primitive data type, wrapper classes can help. parseXxx method can be used to convert a String to the corresponding primitive data type. String value = “532”; int d = Integer.parseInt(value); String value = “3.14e6”; double d = Double.parseDouble(value);
  • 36.
    Web Design &Development – CS506 VU © Copyright Virtual University of Pakistan 36 The following table summarizes the parser methods available to a java programmer. Data Type Convert String using either … byte Byte.parseByte(string ) new Byte(string ).byteValue() short Short.parseShort(string ) new Short(string ).shortValue() int Integer.parseInteger(string ) new Integer(string ).intValue() long Long.parseLong(string ) new Long(string ).longValue() float Float.parseFloat(string ) new Float(string ).floatValue() double Double.parseDouble(string ) new Double(string ).doubleValue()
  • 37.
    Web Design &Development – CS506 VU © Copyright Virtual University of Pakistan 37 Example Code: Taking Input / Output So far, we learned how to print something on console. Now the time has come to learn how to print on the GUI. Taking input from console is not as straightforward as in C++. Initially we’ll study how to take input through GUI (by using JOPtionPane class). The following program will take input (a number) through GUI and prints its square on the console as well on GUI. 1. import javax.swing.*; 2. public class InputOutputTest { 3. public static void main(String[] args) { 4. //takes input through GUI 5. String input = JOptionPane.showInputDialog("Enter number"); 6. int number = Integer.parseInt(input); 7. int square = number * number; 8. //Display square on console 9. System.out.println("square:" + square); 10. //Display square on GUI 11. JOptionPane.showMessageDialog(null, "square:"+ square); 12. System.exit(0); 13. } 14. } On line 1, swing package was imported because it contains the JOptionPane class that will be used for taking input from GUI and displaying output to GUI. It is similar to header classes of C++. On line 5, showInputDialog method is called of JOptionPane class by passing string argument that will be displayed on GUI (dialog box). This method always returns back a String regardless of whatever you entered (int, float, double, char) in the input filed. Our task is to print square of a number on console, so we first convert a string into a number by calling parseInt method of Integer wrapper class. This is what we done on line number 6. Line 11 will display square on GUI (dialog box) by using showMessageDialog method of JOptionPane class. The first argument passed to this method is null and the second argument must be a String. Here we use string concatenation. Line 12 is needed to return the control back to command prompt whenever we use JoptionPane class.
  • 38.
    Web Design &Development – CS506 VU © Copyright Virtual University of Pakistan 38 Compile & Execute
  • 39.
    Web Design &Development – CS506 VU © Copyright Virtual University of Pakistan 39 erators that we use in C++ to perform comparisons are also available in java with same behavior. Likewise for, while and do-while control structures are alike to C++. Reference: Selection & Control Structure The if-else and switch selection structures are exactly similar to we have in C++. All relational op 1- Java tutorial: http://www.dickbaldwin.com/java 2- Example code, their explanations and corresponding figures for this handout are taken from the book JAVA A Lab Course by Umair Javed. This material is available just for the use of VU students of the course Web Design and Development and not for any other commercial purpose without the consent of author.
  • 40.
    Web Design &Development – CS506 VU © Copyright Virtual University of Pakistan 40 Lesson 4 Object Oriented Programming Java is fundamentally object oriented. Every line of code you write in java must be inside a class (not counting import directives). OOP fundamental stones Encapsulation, Inheritance and Polymorphism etc. are all fully supported by java. OOP Vocabulary Review • Classes – Definition or a blueprint of a user-defined datatype – Prototypes for objects – Think of it as a map of the building on a paper • Objects – Nouns, things in the world – Anything we can put a thumb on – Objects are instantiated or created from class • Constructor – A special method that is implicitly invoked. Used to create an Object (that is, an Instance of the Class) and to initialize it. • Attributes – Properties an object has. • Methods – Actions that an object can do
  • 41.
    Web Design &Development – CS506 VU © Copyright Virtual University of Pakistan 41 Defining a Class class Poin { t private int xCord; private int yCord; public Point (……) {……} public void display (……) { ………. } } //end of class in astance variables and symbolic constants constructor – how to create and initialize objects methods – how to manipulate those objects (may or may not include its own “driver”, e., main( )) i. Comparison with C++ Some important points to consider when defining a class in java as you probably noticed from the above given skeleton are – There are no global variables or functions. Everything resides inside a class. Remember we wrote our main method inside a class. (For example, in HelloWorldApp program) – Specify access modifiers (public, private or protected) for each member method or data members at every line. – public: accessible anywhere by anyone – private: Only accessible within this class – protect: accessible only to the class itself and to it’s subclasses or other classes in the same package. – default: default access if no access modifier is provided. Accessible to all classes in the same package. – There is no semicolon (;) at the end of class. – All methods (functions) are written inline. There are no separate header and implementation files. – Automatic initialization of class level data members if you do not initialize them Primitives o Numeric (int, float etc) with zero
  • 42.
    Web Design &Development – CS506 VU © Copyright Virtual University of Pakistan 42 o Char with null o Boolean with false Object References – With null Note: Remember, the same rule is not applied to local variables (defined inside method body). Using a local variable without initialization is a compile time error Public void someMethod( ) { int x; //local variable System.out.println(x); // compile time error } – Constructor – Same name as class name – Does not have a return type – No initialization list – JVM provides a zero argument (default) constructor only if a class doesn’t define it’s own constructor – Destructors – Are not required in java class because memory management is the responsibility of JVM.
  • 43.
    Web Design &Development – CS506 VU © Copyright Virtual University of Pakistan 43 Task – Defining a Student class The following example will illustrate how to write a class. We want to write a “Student” class that – should be able to store the following characteristics of student – Roll No – Name – Provide default, parameterized and copy constructors – Provide standard getters/setters (discuss shortly) for instance variables – Make sure, roll no has never assigned a negative value i.e. ensuring the correct state of the object – Provide print method capable of printing student object on console Getters / Setters The attributes of a class are generally taken as private or protected. So to access them outside of a class, a convention is followed knows as getters & setters. These are generally public methods. The words set and get are used prior to the name of an attribute. Another important purpose for writing getter & setters to control the values assigned to an attribute. Student Class Code // File Student.java public class Student { private String name; private int rollNo; // Standard Setters public void setName (String name) { this.name = name; } // Note the masking of class level variable rollNo public void setRollNo (int rollNo) { if (rollNo > 0) { this.rollNo = rollNo; }else { this.rollNo = 100; } } // Standard Getters public String getName ( ) { return name; }
  • 44.
    Web Design &Development – CS506 VU © Copyright Virtual University of Pakistan 44 public int getRollNo ( ) { return rollNo; } // Default Constructor public Student() { name = “not set”; rollNo = 100; } // parameterized Constructor for a new student public Student(String name, int rollNo) { setName(name); //call to setter of name setRollNo(rollNo); //call to setter of rollNo } // Copy Constructor for a new student public Student(Student s) { name = s.name; rollNo = s.rollNo; } // method used to display method on console public void print () { System.out.print("Student name: " +name); System.out.println(", roll no: " +rollNo); } } // end of class
  • 45.
    Web Design &Development – CS506 VU © Copyright Virtual University of Pakistan 45 Using a Class Objects of a class are always created on heap using the “new” operator followed by constructor • Student s = new Student ( ); // no pointer operator “*” between Student and s • Only String constant is an exception String greet = “Hello” ; // No new operator • However you can also use String greet2 = new String(“Hello”); Members of a class ( member variables and methods also known as instance variables/methods ) are accessed using “.” operator. There is no “Æ” operator in java s.setName(“Ali”); sÆsetName(“Ali”) is incorrect and will not compile in java Note: Objects are always passed by reference and primitives are always passed by value in java. Task - Using Student Class Create objects of student class by calling default, parameterize and copy constructor Call student class various methods on these objects Student client code // File Test.java /* This class create Student class objects and demonstrates how to call various methods on objects */ public class Test{ public static void main (String args[]){ // Make two student obejcts Student s1 = new Student("ali", 15); Student s2 = new Student(); //call to default costructor s1.print(); // display ali and 15 s2.print(); // display not set and 100 s2.setName("usman"); s2.setRollNo(20); System.out.print("Student name:" + s2.getName()); System.out.println(" rollNo:" + s2.getRollNo());
  • 46.
    Web Design &Development – CS506 VU © Copyright Virtual University of Pakistan 46 System.out.println("calling copy constructor"); Student s3 = new Student(s2); //call to copy constructor s2.print(); s3.print(); s3.setRollNo(-10); //Roll No of s3 would be set to 100 s3.print(); /*NOTE: public vs. private A statement like "b.rollNo = 10;" will not compile in a client of the Student class when rollNo is declared protected or private */ } //end of main } //end of class Compile & Execute Compile both classes using javac commad. Run Test class using java command.
  • 47.
    Web Design &Development – CS506 VU © Copyright Virtual University of Pakistan 47 More on Classes Static A class can have static variables and methods. Static variables and methods are associated with the class itself and are not tied to any particular object. Therefore statics can be accessed without instantiating an object. Static methods and variables are generally accessed by class name. The most important aspect of statics is that they occur as a single copy in the class regardless of the number of objects. Statics are shared by all objects of a class. Non static methods and instance variables are not accessible inside a static method because no this reference is available inside a static method. We have already used some static variables and methods. Examples are System.out.println(“some text”); -- out is a static variable JOptionPane.showMessageDialog(null, “some text”); -- showMessageDialog is a static method Garbage Collection & Finalize Java performs garbage collection and eliminates the need to free objects explicitly. When an object has no references to it anywhere except in other objects that are also unreferenced, its space can be reclaimed. Before an object is destroyed, it might be necessary for the object to perform some action. For example: to close an opened file. In such a case, define a finalize() method with the actions to be performed before the object is destroyed. finalize When a finalize method is defined in a class, Java run time calls finalize() whenever it is about to recycle an object of that class. It is noteworthy that a garbage collector reclaims objects in any order or never reclaims them. We cannot predict and assure when garbage collector will get back the memory of unreferenced objects. The garbage collector can be requested to run by calling System.gc() method. It is not necessary that it accepts the request and run.
  • 48.
    Web Design &Development – CS506 VU © Copyright Virtual University of Pakistan 48 Example Code: using static & finalize () We want to count exact number of objects in memory of a Student class the one defined earlier. For this purpose, we’ll modify Student class. Add a static variable countStudents that helps in maintaining the count of student objects. Write a getter for this static variable. (Remember, the getter also must be static one. Hoping so, you know the grounds). In all constructors, write a code that will increment the countStudents by one. Override finalize() method and decrement the countStudents variable by one. Override toString() method. Class Object is a superclass (base or parent) class of all the classes in java by default. This class has already finalize() and toString() method (used to convert an object state into string). Therefore we are actually overriding these methods over here. (We’ll talk more about these in the handout on inheritance). By making all above modifications, student class will look like // File Student.java public class Student { private String name; private int rollNo; private static int countStudents = 0; // Standard Setters public void setName (String name) { this.name = name; } // Note the masking of class level variable rollNo public void setRollNo (int rollNo) { if (rollNo > 0) { this.rollNo = rollNo; }else { this.rollNo = 100; } } // Standard Getters public String getName ( ) { return name; } public int getRollNo ( ) { return rollNo; }
  • 49.
    Web Design &Development – CS506 VU © Copyright Virtual University of Pakistan 49 // gettter of static countStudents variable public static int getCountStudents(){ return countStudents; } // Default Constructor public Student() { name = “not set”; rollNo = 100; countStudents += 1; } // parameterized Constructor for a new student public Student(String name, int rollNo) { setName(name); //call to setter of name setRollNo(rollNo); //call to setter of rollNo countStudents += 1; } // Copy Constructor for a new student public Student(Student s) { name = s.name; rollNo = s.rollNo; countStudents += 1; } // method used to display method on console public void print () { System.out.print("Student name: " +name); System.out.println(", roll no: " +rollNo); } // overriding toString method of java.lang.Object class public String toString(){ return “name: ” + name + “ RollNo: ” + rollNo; } // overriding finalize method of Object class public void finalize(){ countStudents -= 1; } } // end of class Next, we’ll write driver class. After creating two objects of student class, we deliberately loose object’s reference and requests the JVM to run garbage collector to reclaim the memory. By printing countStudents value, we can confirm that. Coming up code is of the Test class.
  • 50.
    Web Design &Development – CS506 VU © Copyright Virtual University of Pakistan 50 // File Test.java public class Test{ public static void main (String args[]){ int numObjects; // printing current number of objects i.e 0 numObjs = Student.getCountStudents(); System.out.println(“Students Objects” + numObjects); // Creating first student object & printing its values Student s1 = new Student("ali", 15); System.out.println(“Student: ” + s1.toString()); // printing current number of objects i.e. 1 numObjs = Student.getCountStudents(); System.out.println(“Students Objects” + numObjects); // Creating second student object & printing its values Student s2 = new Student("usman", 49); // implicit call to toString() method System.out.println(“Student: ” + s2); // printing current number of objects i.e. 2 numObjs = Student.getCountStudents(); System.out.println(“Students Objects” + numObjects); // loosing object reference s1 = null // requesting JVM to run Garbage collector but there is // no guarantee that it will run System.gc(); // printing current number of objects i.e. unpredictable numObjs = Student.getCountStudents(); System.out.println(“Students Objects” + numObjects); } //end of main } //end of class
  • 51.
    Web Design &Development – CS506 VU © Copyright Virtual University of Pakistan 51 The compilation and execution of the above program is given below. Note that output may be different one given here because it all depends whether garbage collector reclaims the memory or not. Luckily, in my case it does. Reference: Sun java tutorial: http://java.sun.com/docs/books/tutorial/java Thinking in java by Bruce Eckle Beginning Java2 by Ivor Hortan Example code, their explanations and corresponding execution figures for this handout are taken from the book JAVA A Lab Course by Umair Javed. This material is available just for the use of VU students of the course Web Design and Development and not for any other commercial purpose without the consent of author.
  • 52.
    Web Design &Development – CS506 VU © Copyright Virtual University of Pakistan 52 Lesson 5 Inheritance In general, inheritance is used to implement a “is-a” relationship. Inheritance saves code rewriting for a client thus promotes reusability. In java parent or base class is referred as super class while child or derived class is known as sub class. Comparison with C++ ƒJava only supports single inheritance. As a result a class can only inherit from one class at one time. ƒKeyword extends is used instead of “:” for inheritance. ƒAll functions are virtual by default ƒAll java classes inherit from Object class (more on it later). ƒTo explicitly call the super class constructor, use super keyword. It’s important to remember that call to super class constructor must be first line. ƒKeyword super is also used to call overridden methods.
  • 53.
    Web Design &Development – CS506 VU © Copyright Virtual University of Pakistan 53 Example Code: using inheritance We’ll use three classes to get familiar you with inheritance. First one is Employee class. This will act as super class. Teacher class will inherit from Employee class and Test class is driver class that contains main method. Let’s look at them one by one class Employee{ protected int id; protected String name; //parameterized constructor public Employee(int id, String name){ this.id = id; this.name = name; } //default constructor public Employee(){ // calling parameterized constructor of same (Employee) // class by using keyword this this (10, “not set”); } //setters public void setId (int id) { this.id = id; } public void setName (String name) { this.name = name; } //getters public int getId () { return id; } public String getName () { return name; } // displaying employee object on console public void display(){ System.out.println(“in employee display method”); System.out.println("Employee id:" + id + " name:" + name); } //overriding object’s class toString method public String toString() { System.out.println(“in employee toString method”); return "id:" + id + "name:" + name; } }//end class
  • 54.
    Web Design &Development – CS506 VU © Copyright Virtual University of Pakistan 54 The Teacher class extends from Employee class. Therefore Teacher class is a subclass of Employee. The teacher class has an additional attribute i.e. qualification. class Teacher extends Employee{ private String qual; //default constructor public Teacher () { //implicit call to superclass default construct qual = ""; } //parameterized constructor public Teacher(int i, String n, String q){ //call to superclass param const must be first line super(i,n); qual = q; } //setter public void setQual (String qual){ this.qual = qual; } //getter public String getQual(){ return qual; } //overriding display method of Employee class public void display(){ System.out.println("in teacher's display method"); super.display(); //call to superclass display method System.out.println("Teacher qualification:" + qual); } //overriding toString method of Employee class public String toString() { System.out.println("in teacher's toString method"); String emp = super.toString(); return emp +" qualification:" + qual; } }//end class
  • 55.
    Web Design &Development – CS506 VU © Copyright Virtual University of Pakistan 55 Objects of Employee & Teacher class are created inside main method in Test class. Later calls are made to display and toString method using these objects. class Test{ public static void main (String args[]){ System.out.println("making object of employee"); Employee e = new Employee(89, "khurram ahmad"); System.out.println("making object of teacher"); Teacher t = new Teacher (91, "ali raza", "phd"); e.display(); //call to Employee class display method t.display(); //call to Teacher class display method // calling employee class toString method explicitly System.out.println("Employee: " +e.toString()); // calling teacher class toString implicitly System.out.println("Teacher: " + t); } //end of main }//end class Output
  • 56.
    Web Design &Development – CS506 VU © Copyright Virtual University of Pakistan 56 Teacher Object – The Root Class The Od Java classes. For user defined classes, its not necessary to mention the Object class as a super class, java doesbject class in Java is a superclass for all other classes defined in Java's class libraries, as well as for user-define it automatically for you. The class Hierarchy of Employee class is shown below. Object is the super class of Employee class and Teacher is a subclass of Employee class. We can make another class Manager that can also extends from Employee class. Object Employe Manager
  • 57.
    Web Design &Development – CS506 VU © Copyright Virtual University of Pakistan 57 Polymorphism “Polymorphic” literally means “of multiple shapes” and in the context of OOP, polymorphic means “having multiple behavior”. A parent class reference can point to the subclass objects because of is-a relationship. For example a Employee reference can point to: o Employee Object o Teacher Object o Manager Object A polymorphic method results in different actions depending on the object being referenced o Also known as late binding or run-time binding Example Code: using polymorphism This Test class is the modification of last example code. Same Employee & Teacher classes are used. Objects of Employee & Teacher class are created inside main methods and calls are made to display and toString method using these objects. class Test{ public static void main (String args[]){ // Make employee references Employee ref1, ref2; // assign employee object to first employee reference ref1 = new Employee(89, "khurram ahmad"); // is-a relationship, polymorphism ref2 = new Teacher (91, "ali raza", "phd"); //call to Employee class display method ref1.display(); //call to Teacher class display method ref2.display(); // call to Employee class toString method System.out.println("Employee: " +ref1.toString()); // call to Teacher class toString method System.out.println("Teacher: " + ref2.toString()); } //end of main }//end class
  • 58.
    Web Design &Development – CS506 VU © Copyright Virtual University of Pakistan 58 Output
  • 59.
    Web Design &Development – CS506 VU © Copyright Virtual University of Pakistan 59 Type Casting In computer science, type conversion or typecasting refers to changing an entity of one datatype into another. Type casting can be categorized into two types 1. Up-casting Converting a smaller data type into bigger one Implicit – we don’t have to do something special No loss of information Examples of — Primitives int a = 10; double b = a; — Classes Employee e = new Teacher( ); 2. Down-casting Converting a bigger data type into smaller one Explicit – need to mention Possible loss of information Examples of — Primitives double a = 7.65; int b = (int) a; — Classes Employee e = new Teacher( ); // up-casting Teacher t = (Teacher) e; // down-casting References: Java tutorial: http://java.sun.com/docs/books/tutorial/java/javaOO/ Stanford University Example code, their explanations and corresponding figures for handout 5-1,5-2 are taken from the book JAVA A Lab Course by Umair Javed. This material is available just for the use of VU students of the course Web Design and Development and not for any other commercial purpose without the consent of author.
  • 60.
    Web Design &Development – CS506 VU © Copyright Virtual University of Pakistan 60 Lesson 6 Collections A collection represents group of objects know as its elements. Java has a built-in support for collections. Collection classes are similar to STL in C++. An advantage of a collection over an array is that you don’t need to know the eventual size of the collection in order to add objects to it. The java.util package provides a set of collection classes that helps a programmer in number of ways. Collections Design All classes almost provides same methods like get(), size(), isEmpty() etc. These methods will return the object stored in it, number of objects stored and whether collection contains an object or not respectively. Java collections are capable of storing any kind of objects. Collections store references to objects. This is similar to using a void* in C. therefore down casting is required to get the actual type. For example, if string in stored in a collection then to get it back, we write String element = (String)arraylist.get(i); Collection messages Some basic messages (methods) are: Constructor — creates a collection with no elements int size() — returns the number of elements in a collection boolean add(Object) — adds a new element in the collection — returns true if the element is added successfully false otherwise boolean isEmpty() — returns true if this collection contains no element false otherwise boolean contains(Object) — returns true if this collection contains the specified element by using iterative search boolean remove(Object) — removes a single instance of the specified element from this collection, if it is present
  • 61.
    Web Design &Development – CS506 VU © Copyright Virtual University of Pakistan 61 ArrayList It’s like a resizable array. ArrayList actually comes as a replacement the old “Vector” collection. As we add or remove elements into or from it, it grows or shrinks over time. Useful Methods add (Object) — With the help of this method, any object can be added into ArrayList because Object is the super class of all classes. — Objects going to add will implicitly up-cast. Object get(int index) — Returns the element at the specified position in the list — index ranges from 0 to size()-1 — must cast to appropriate type remove (int index) — Removes the element at the specified position in this list. — Shifts any subsequent elements to the left (subtracts one from their indices). int size( ) Example Code: Using ArrayList class We’ll store Student objects in the ArrayList. We are using the same student class which we built in previous lectures/handouts. We’ll add three student objects and later prints all the student objects after retrieving them from ArrayList. Let’s look at the code iport java.util.*; public class ArrayListTest { public static void main(String[] args) { // creating arrayList object by calling constructor ArrayList al= new ArrayList(); // creating three Student objects Student s1 = new Student (“ali” , 1); Student s2 = new Student (“saad” , 2); Student s3 = new Student (“raza” , 3); // adding elements (Student objects) into arralylist al.add(s1); al.add(s2); al.add(s3);
  • 62.
    Web Design &Development – CS506 VU © Copyright Virtual University of Pakistan 62 // checking whether arraylist is empty or not boolean b = al.isEmpty (); if (b = = true) { System.out.println(“arraylist is empty”); } else { int size = al.size(); System.out.println(“arraylist size: ” + size); } // using loop to iterate. Loops starts from 0 to one // less than size for (int i=0; i<al.size(); i++ ){ // retrieving object from arraylist Student s = (Student) al.get(i); // calling student class print method s.print(); } // end for loop } // end main } // end class Output HashM ap Store el ue pair form. A key is associated with each object that is stored. This al Useful M put(Object key, Object Value) Values are stored in the form of objects (implicit upcasting is performed). — Associates the specified value with the specified key in this map. ements in the form of key- vallows fast retrieval of that object. Keys are unique. hods et — Keys &
  • 63.
    Web Design &Development – CS506 VU © Copyright Virtual University of Pakistan 63 — If the map previously contained a mapping for this key, the old value is replaced. Object get(Object key) ing for this key. owncast to appropriate type when used int Example Code: usin In of strings as keys. Same Student cla iport java.util.*; public g[] args) { p object HashMap(); // creating Student objects = new Student (“ali” , 1); Student s2 = new Student (“saad” , dding elements (Student objects) where roll nos // are stored as keys and student objects as values h.put(“six”, s3); // checking whether hashmap is empty or not boolean b = h.isEmpty (); ty”); } else { int size = h.size(); .out.println(“hashmap size: ” + size); // retrieving student object against rollno two and performing downcasting Student s = (Student) h.get(“two”); // calling student’s class print method s.print(); — Returns the value to which the specified key is mapped in this identity hash map, or null if the map contains no mapp — Must d size( ) g HashMap class this example code, we’ll store St udent objects as values and their rollnos in the form ss is used. The code is; public c lass HashMapTest { static void main(Strin // creating HashMa HashMap h= new Student s1 2); Student s3 = new Student (“raza” , 6); // a h.put(“one” , s1); h.put(“two” , s2); if (b = = true) { System.out.println(“hashmap is emp System } //
  • 64.
    Web Design &Development – CS506 VU © Copyright Virtual University of Pakistan 64 } // end main } // end class Output Ref erences: J2SE 5.0 new features: http://java.sun.com/j2se/1.5.0/docs/relnotes/features.html Technical Article: http://java.sun.com/developer/technicalArticles/releases/j2se15/ Beginning Java2 by Ivor Horton Example code, their explanations and corresponding figures for this handout are taken from the book JAVA A Lab Course by Umair Javed. This material is available just for the use of VU students of the course Web Design and Development and not for any other commercial purpose without the consent of author.
  • 65.
    Web Design &Development – CS506 VU © Copyright Virtual University of Pakistan 65 Address Book Warning: It is strongly advised that you type the code given in this example yourself. Do not copy/paste it; most probably you will get unexpected errors that you have never seen. Some bugs are deliberately introduced as well to avoid copy- pasting. TAs will not cooperate with you in debugging such errors☺. Problem We want to build an address book that is capable of storing name, address & phone number of a person. Address book provides functionality in the form of a JOptionPane based menu. The feature list includes ƒ Add – to add a new person record ƒ Delete – to delete an existing person record by name ƒ Search – to search a person record by name ƒ Exit – to exit from application The Address book should also support persistence for person records Approach for Solving Problem Building a small address book generally involves 3 steps. Let us briefly discuss each step and write a solution code for each step Step1 – Make PersonInfo class First of all you need to store your desired information for each person. For this you can create a user- defined data type (i.e. a class). Make a class PersonInfo with name, address and phone number as its attributes. Write a parameterized constructor for this class. Write print method in Person class that displays one person record on a message dialog box.
  • 66.
    Web Design &Development – CS506 VU © Copyright Virtual University of Pakistan 66 The code for PersonInfo class is given below. import javax.swing.*; class PersonInfo { String name; String address; String phoneNum; //parameterized constructor public PersonInfo(String n, String a, String p) { name = n; address = a; phoneNum = p; } //method for displaying person record on GUI public void print( ) { JOptionPane.showMessageDialog(null, “name: ” + name + “address:” +address + “phone no:” + phoneNum); } } Note: Not declaring attributes as private is a bad approach but we have done it to keep things simple here. Step2 – Make AddressBook class Take the example of daily life; generally address book is used to store more than one person records and we don’t know in advance how many records are going to be added into it. So, we need some data structure that can help us in storing more than one PersonInfo objects without concerning about its size. ArrayList can be used to achieve the above functionality Create a class Address Book with an ArrayList as its attribute. This arraylist will be used to store the information of different persons in the form of PersonInfo Objects. This class will also provide addPerson, deletePerson & searchPerson methods. These methods are used for adding new person records, deleting an existing person record by name and searching among existing person records by name respectively. Input/Output will be performed through JOptionPane.
  • 67.
    Web Design &Development – CS506 VU Copyright Virtual University of Pakistan 67 The code for AddressBook class is import javax.swing.*; import java.util.*; class AddressBook { ArrayList persons; //constructor public AddressBook ( ) { persons = new ArrayList(); } //add new person record to arraylist after taking input public void addPerson( ) { String name =JOptionPane.showInputDialog(“Enter name”); String add = JOptionPane.showInputDialog(“Enter address”); String pNum = JOptionPane.showInputDialog(“Enter phone no”); //construt new person object PersonInfo p = new PersonInfo(name, add, pNum); //add the above PersonInfo object to arraylist persons.add(p); } //search person record by name by iterating over arraylist public void searchPerson (String n) { for (int i=0; i< persons.size(); i++) { PersonInfo p = (PersonInfo)persons.get(i); if ( n.equals(p.name) ) { p.print(); } } // end for } // end searchPerson //delete person record by name by iterating over arraylist public void deletePerson (String n) { for (int i=0; i< persons.size(); i++) { PersonInfo p = (PersonInfo)persons.get(i); if ( n.equals(p.name) ) { persons.remove(i); }
  • 68.
    Web Design &Development – CS506 VU Copyright Virtual University of Pakistan 68 } } } // end class The addperson method first takes input for name, address and phone number and than construct a PersonInfo object by using the recently taken input values. Then the newly constructed object is added to the arraylist – persons. The searchPerson & deletePerson methods are using the same methodology i.e. first they search the required record by name and than prints his/her detail or delete the record permanently from the ArrayList. Both the methods are taking string argument, by using this they can perform their search or delete operation. We used for loop for iterating the whole ArrayList. By using the size method of ArrayList, we can control our loop as ArrayList indexes range starts from 0 to one less than size. Notice that, inside loop we retrieve each PersonInfo object by using down casting operation. After that we compare each PersonInfo object’s name by the one passed to these methods using equal method since Strings are always being compared using equal method. Inside if block of searchPerson, print method is called using PersonInfo object that will display person information on GUI. On the other hand, inside if block of deletePerson method, remove method of ArrayList class is called that is used to delete record from persons i.e. ArrayList. Step3 – Make Test class (driver program) This class will contain a main method and an object of AddressBook class. Build GUI based menu by using switch selection structure Call appropriate methods of AddressBook class The code for Test class is import javax.swing.*; class Test { Public static void main (String args[]) { AddressBook ab = new AddressBook(); String input, s; int ch; while (true) { input = JOptionPane.showInputDialog(“Enter 1 to add ” + “n Enter 2 to Search n Enter 3 to Delete“ + “n Enter 4 to Exit”);
  • 69.
    Web Design &Development – CS506 VU Copyright Virtual University of Pakistan 69 ch = Integer.parseInt(input); switch (ch) { case 1: ab.addPerson(); break; case 2: s = JOptionPane.showInputDialog( “Enter name to search ”); ab.searchPerson(s); break; case 3: s = JOptionPane.showInputDialog( “Enter name to delete ”); ab.deletePerson(s); break; case 4: System.exit(0); } }//end while }//end main } Note that we use infinite while loop that would never end or stop given that our program should only exit when user enters 4 i.e. exit option. Compile & Execute Compile all three classes and run Test class. Bravo, you successfully completed the all basic three steps. Enjoy! ☺. Reference Entire content for this handout are taken from the book JAVA A Lab Course by Umair Javed. This material is available just for the use of VU students of the course Web Design and Development and not for any other commercial purpose.
  • 70.
    Web Design &Development – CS506 VU Copyright Virtual University of Pakistan 70 Lesson 7 Intro to Exceptions Types of Errors Generally, you can come across three types of errors while developing software. These are Syntax, Logic & Runtime errors. 1. Syntax Errors Arise because the rules of the language are not followed. 2. Logic Errors Indicates that logic used for coding doesn’t produce expected output. 3. Runtime Errors Occur because the program tries to perform an operation that is impossible to complete. Cause exceptions and may be handled at runtime (while you are running the program) For example divide by zero What is an Exception? An exception is an event that usually signals an erroneous situation at run time Exceptions are wrapped up as objects A program can deal with an exception in one of three ways: o ignore it o handle it where it occurs o handle it an another place in the program Why handle Exceptions? Helps to separate error handling code from main logic (the normal code you write) of the program. As different sort/type of exceptions can arise, by handling exceptions we can distinguish between them and write appropriate handling code for each type for example we can differently handle exceptions that occur due to division by Zero and exceptions that occur due to non-availability of a file. If not handled properly, program might terminate.
  • 71.
    Web Design &Development – CS506 VU Copyright Virtual University of Pakistan 71 Exceptions in Java An exception in java is represented as an object that’s created when an abnormal situation arises in the program. Note that an error is also represented as an object in Java, but usually represents an unrecoverable situation and should not be caught The exception object stores information about the nature of the problem. For example, due to network problem or class not found etc. All exceptions in java are inherited from a class know as Throwable. Exception Hierarchy Following diagram is an abridged version of Exception class hierarchy
  • 72.
    Web Design &Development – CS506 VU Copyright Virtual University of Pakistan 72 Types of Exceptions Exceptions can be broadly categorized into two types, Unchecked & Checked Exceptions. Unchecked Exceptions • Subclasses of RuntimeException and Error. • Does not require explicit handling • Run-time errors are internal to your program, so you can get rid of them by debugging your code • For example, null pointer exception; index out of bounds exception; division by zero exception; ... Checked Exceptions • Must be caught or declared in a throws clause • Compile will issue an error if not handled appropriately • Subclasses of Exception other than subclasses of RuntimeException. • Other arrive from external factors, and cannot be solved by debugging • Communication from an external resource – e.g. a file server or database How Java handles Exceptions Java handles exceptions via 5 keywords. try, catch, finally, throw & throws. ƒ try block • Write code inside this block which could generate errors ƒ catch block • Code inside this block is used for exception handling • When the exception is raised from try block, only than catch block would execute. ƒ finally block • This block always executes whether exception occurs or not. • Write clean up code here, like resources (connection with file or database) that are opened may need to be closed.
  • 73.
    Web Design &Development – CS506 VU Copyright Virtual University of Pakistan 73 The basic structure of using try – catch – finally block is shown in the picture below: try //try block { // write code that could generate exceptions } catch (<exception to be caught>) //catch block { } …… ....... //write code for exception handling catch (<exception to be caught>) //catch block { //code for exception handling } finally //finally block { //any clean-up code, release the acquired resources }
  • 74.
    Web Design &Development – CS506 VU Copyright Virtual University of Pakistan 74 ƒ throw • To manually throw an exception, keyword throw is used. Note: we are not covering throw clause in this handout ƒ throws • If method is not interested in handling the exception than it can throw back the exception to the caller method using throws keyword. • Any exception that is thrown out of a method must be specified as such by a throws clause. References: ƒ Java tutorial by Sun: http://java.sun.com/docs/books/turorial ƒ Beginning Java2 by Ivor Hortan ƒ Thinking in Java by Bruce Eckle ƒ CS193j Stanford University
  • 75.
    Web Design &Development – CS506 VU Copyright Virtual University of Pakistan 75 Code Examples of Exception Handling Unchecked Exceptions Example Code: UcException.java The following program takes one command line argument and prints it on the console // File UcException.java public class UcException { public static void main (String args[ ]) { System.out.println(args[0]); } } Compile & Execute If we compile & execute the above program without passing any command line argument, an ArrayIndexOutOfBoundsException would be thrown. This is shown in the following picture Since we have passed size of String args[ ] is zero, and we have tried to access the first element (first element has index zero) of this array. From the output window, you can find out, which code line causes the exception to be raised. In the above example, it is System.out.println(args[0]); Why? no argument, therefore the
  • 76.
    Web Design &Development – CS506 VU Copyright Virtual University of Pakistan 76 Modify UcException.java Though it is not mandatory to handle unchecked exceptions we can still handle Unchecked Exceptions if we want to. These modifications are shown in bold. // File UcException.java public class UcException { public static void main (String args[ ]) { try { System.out.println(args[0]); catch (IndexOutOfBoundsExceptoin ex) { System.out.println(“You forget to pass command line argument”); } } The possible exception that can be thrown is IndexOutOfBoundsException, so we handle it in the catch block. When an exception occurs, such as IndexOutOfBoundsException in this case, then an object of type IndexOutOfBoundesException is created and it is passed to the corresponding catch block (i.e. the catch block which is capable of handling this exception). The catch block receives the exception object inside a variable which is ex in this case. It can be any name; it is similar to the parameter declared in the method signature. It receives the object of exception type (IndexOutOfBoundsExceptoin) it is declared. Compile & Execute If we execute the modified program by passing command line argument, the program would display on console the provided argument. After that if we execute this program again without passing command line argument, this time information message would be displayed which is written inside catch block.
  • 77.
    Web Design &Development – CS506 VU Copyright Virtual University of Pakistan 77 Checked Exceptions Example Code: CException.java The following program reads a line (hello world) from a file and prints it on the console. The File reading code is probably new for you. We’ll explain it in the coming handouts (Streams). For now, assumed that the code written inside the main read one line from a file and prints that to console. // File CException.java import java.io.* ; public class CException { public static void main (String args[ ]) { FileReader fr = new FileReader (“input.txt”); BufferedReader br = new BufferedReader (fr); //read the line form file String line = br.readLine(); System.out.println(line); } } Compile & Execute If you try to compile this program, the program will not compile successfully and displays the message of unreported exception. This happens when there is code that can generate a checked exception but you have not handled that exception. Remember checked exceptions are detected by compiler. As we early discussed, without handling Checked exception, out program won’t compile.
  • 78.
    Web Design &Development – CS506 VU Copyright Virtual University of Pakistan 78 Modify CException.java As we have discussed earlier, it is mandatory to handle checked exceptions. In order to compile the code above, we modify the above program so that file reading code is placed inside a try block. The expected exception (IOException) that can be raised is caught in catch block. // File CException.java import java.io.* ; public class CException { public static void main (String args[ ]) { try{ FileReader fr = new FileReader (“input.txt”); BufferedReader br = new BufferedReader (fr); //read the line form file String line = br.readLine(); System.out.println(line); catch( IOExceptoin ex) { System.out.println(ex); } } } The code line written inside the catch block will print the exception name on the console if exception occurs Compile & Execute After making changes to your program, it would compile successfully. On executing this program, hello world would be displayed on the console Note: Before executing, make sure that a text file named input.txt must be placed in the same directory where the program is saved. Also write hello world in that file before saving it.
  • 79.
    Web Design &Development – CS506 VU Copyright Virtual University of Pakistan 79 The finally block The finally block always executes regardless of exception is raised or not while as you remembered the catch block only executes when an exception is raised. Exampel Code : FBlockDemo.java // File FBlockDemo.java import java.io.* ; public class FBlockDemo { public static void main (String args[ ]) { try{ FileReader fr = new FileReader (“strings.txt”); BufferedReader br = new BufferedReader (fr); //read the line form file String line = br.readLine(); System.out.println(line); catch( IOExceptoin ex) { System.out.println(ex); } finally { System.out.println(“finally block always execute”); } } } Compile & Execute The program above, will read one line from string.txt file. If string.tx is not present in the same directory the FileNotFoundException would be raised and catch block would execute as well as the finally block. If string.txt is present there, no such exception would be raised but still finally block executes. This is shown in the following output diagram
  • 80.
    Web Design &Development – CS506 VU Copyright Virtual University of Pakistan 80 Mul tiple catch blocks • Possible to have multiple catch clau ses for a single try statement • Evaluated in the order of the code – tion hierarchy when writing multiple catch clauses! – t and then IOException, the IOException will never be caught! Exam The f ing program would read a number form a file numbers.txt and than prints its square on the console g args[ ]) { try{ tion ers.txt”); BufferedReader br = new BufferedReader (fr); String s = br.readLine(); //may throws NumberFormatException, if s is not a no. number); toin nfEx) { catch( FileNotFoundExceptoin fnfEx) { – Essentially checking for different types of exceptions that may happen Bear in mind the Excep If you catch Exception firs ple code: MCatchDemo.java ollow // File MCatchDemo.java import java.io.* ; public class MCatchDemo { public static void main (Strin // can throw FileNotFound or IOExcep FileReader fr = new FileReader (“numb //read the number form file int number = Integer.parseInt(s); System.out.println(number * catch( NumberFormatExcep System.out.println(nfEx); }
  • 81.
    Web Design &Development – CS506 VU Copyright Virtual University of Pakistan 81 System.out.println(fnfEx); } } We read everything from a file (numbers, floating values or text) as a String. That’s why we first convert it to numb and than print its square on console. If file numbers.txt is not present in the same directory, the FileNotFoundException would be thrown during execution. catch( IOExceptoin ioEx) { System.out.println(ioEx); } } er Compile & Execute If numbers.txt present in the same directory and contains a number, than hopefully no exception would be thrown.
  • 82.
    Web Design &Development – CS506 VU © Copyright Virtual University of Pakistan 82 The throws clause The following code examples will introduce you with writing & using throws clause. Example Code: ThrowsDemo.java The ThrowsDemo.java contains two methods namely method1 & method2 and one main method. The main method will make call to method1 and than method1 will call method2. The method2 contains the file reading code. The program looks like one given below // File ThrowsDemo.java import java.io.* ; public class ThrowsDemo { // contains file reading code public static void method2( ) { try{ FileReader fr = new FileReader (“strings.txt”); BufferedReader br = new BufferedReader (fr); //read the line form file String s = br.readLine(); System.out.println(s); catch( IOExceptoin ioEx) { ioEx.printStackTrace(); } }// end method 2 //only calling method2 public static void method1( ) { method2(); } public static void main (String args[ ]) { ThrowsDemo.method1(); } }
  • 83.
    Web Design &Development – CS506 VU © Copyright Virtual University of Pakistan 83 printStackTrace method Defined in the Throwable class – superclass of Exception & Error classes Shows you the full method calling history with line numbers. Extremely useful in debugging Modify: ThrowsDemo.java Let method2 doesn’t want to handle exception by itself, so it throws the exception to the caller of method2 i.e. method1 So method1 either have to handle the incoming exception or it can re-throw it to its caller i.e. main. Let method1 is handling the exception, so method1& method2 would be modified as: // File ThrowsDemo.java import java.io.* ; public class ThrowsDemo { // contains file reading code public static void method2( ) throws IOEception{ FileReader fr = new FileReader (“strings.txt”); BufferedReader br = new BufferedReader (fr); //read the line form file String s = br.readLine(); System.out.println(s); }// end method 2 // calling method2 & handling incoming exception public static void method1( ) { try { method2(); catch (IOException ioEx) { ioEx.printStackTrace(); } } public static void main (String args[ ]) { ThrowsDemo.method1(); } }
  • 84.
    Web Design &Development – CS506 VU © Copyright Virtual University of Pakistan 84 Compile & Execute If file strings.txt is not present in the same directory, method2 will throw an exception that would be caught by method1 and the printStackTrace method will print the full calling history on console. The above scenario is shown in the output below: If file strings.txt exist there, than hopefully line would be displayed on the console. Reference Example code, their explanations and corresponding figures for this handout are taken from the book JAVA A Lab Course by Umair Javed. This material is available just for the use of VU students of the course Web Design and Development and not for any other commercial purpose without the consent of author.
  • 85.
    Web Design &Development – CS506 VU © Copyright Virtual University of Pakistan 85 Lesson 8 Streams I/O libraries often use the abstraction of a stream, which represents any data source or sink as an object capable of producing or receiving pieces of data. The Java library classes for I/O are divided by input and output. You need to import java.io package to use streams. There is no need to learn all the streams just do it on the need basis. The concept of "streams" • It is an abstraction of a data source/sink • We need abstraction because there are lots of different devices (files, consoles, network, memory, etc.). We need to talk to the devices in different ways (sequential, random access, by lines, etc.) Streams make the task easy by acting in the same way for every device. Though inside handling of devices may be quite different, yet on the surface everything is similar. You might read from a file, the keyboard, memory or network connection, different devices may require specialization of the basic stream, but you can treat them all as just "streams". When you read from a network, you do nothing different than when you read from a local file or from user's typing //Reading from console BufferedReader stdin = new BufferedReader(new InputStreamReader( System.in )); -------- ( your console) // Reading from file BufferedReader br=new BufferedReader(new FileReader(“input.txt”)); //Reading from network BufferedReader br = new BufferedReader(new InputStreamReader (s.getInputStream())); ---- “s” is the socket • So you can consider stream as a data path. Data can flow through this path in one direction between specified terminal points (your program and file, console, socket etc.)
  • 86.
    Web Design &Development – CS506 VU © Copyright Virtual University of Pakistan 86 Stream classification based on Functionality Based on functionality streams can be categorized as Node Stream and Filter Stream. Node Streams are those which connect directly with the data source/sick and provide basic functionality to read/write data from that source/sink FileReader fr = new FileReader(“input.txt”); You can see that FileReader is taking a data/source “input.txt” as its argument and hence it is a node stream. FilterStreams sit on top of a node stream or chain with other filter stream and provide some additional functionality e.g. compression, security etc. FilterStreams take other stream as their input. BufferedReader bt = new BufferedReader(fr); BufferedReader makes the IO efficient (enhances the functionality) by buffering the input before delivering. And as you can see that BufferedReader is sitting on top of a node stream which is FileReader. Stream classification based on data
  • 87.
    Web Design &Development – CS506 VU © Copyright Virtual University of Pakistan 87 Two type of classes exists. Classes which contain the word stream in their name are byte oriented and are here since JDK1.0. These streams can be used to read/write data in the form of bytes. Hence classes with the word stream in their name are byte- oriented in nature. Examples of byte oriented streams are FileInputStream, ObjectOutputStream etc. Classes which contain the word Reader/Writer are character oriented and read and write data in the form of characters. Readers and Writers came with JDK1.1. Examples of Reader/Writers are FileReader, PrintWriter etc
  • 88.
    Web Design &Development – CS506 VU © Copyright Virtual University of Pakistan 88 Example Code 8.1: Reading from File The ReadFileEx.java reads text file line by line and prints them on console. Before we move on to the code, first create a text file (input.txt) using notepad and write following text lines inside it. Hello World Text File: input.txt Pakistan is our homeland Web Design and Development // File ReadFileEx.java import java.io.*; public class ReadFileEx { public static void main (String args[ ]) { FileReader fr = null; BufferedReader br = null; try { // attaching node stream with data source fr = new FileReader(“input.txt”); // attatching filter stream over node stream br = new BufferedReader(fr); // reading first line from file String line = br.readLine(); // printing and reading remaining lines while (line != null){ System.out.println(line); line = br.readLine(); } // closing streams br.close(); fr.close(); }catch(IOException ioex){ System.out.println(ioex); } } // end main } // end class
  • 89.
    Web Design &Development – CS506 VU © Copyright Virtual University of Pakistan 89 Example Code 8.2: Writing to File The WriteFileEx.java writes the strings into the text file named “output.txt”. If “output.txt” file does not exist, the java will create it for you. // File WriteFileEx.java import java.io.*; public class WriteFileEx { public static void main (String args[ ]) { FileWriter fw = null; PrintWriter pw = null; try { // attaching node stream with data source // if file does not exist, it automatically creates it fw = new FileWriter (“output.txt”); // attatching filter stream over node stream pw = new PrintWriter(fw); String s1 = “Hello World”; String s2 = “Web Design and Development”; // writing first string to file pw.println(s1); // writing second string to file pw.println(s2); // flushing stream pw.flush(); // closing streams pw.close(); fw.close(); }catch(IOException ioex){ System.out.println(ioex); } } // end main } // end class After executing the program, check the output.txt file. Two lines will be written there. Reference Example code, their explanations and corresponding figures for this handout are taken from the book JAVA A Lab Course by Umair Javed. This material is available just for the use of VU students of the course Web Design and Development and not for any other commercial purpose without the consent of author.
  • 90.
    Web Design &Development – CS506 VU © Copyright Virtual University of Pakistan 90 Lesson 9 Modification of Address Book Code Adding Persistence Functionality Hopefully, your address book you built previously is giving you the required results except one i.e. persistence. You might have noticed that after adding some person records in the address book; if you exit form the program next time on re-executing address book all the previous records are no more available. To overcome the above problem, we will modify our program so that on exiting/starting of address book, all the previously added records are available each time. To achieve this, we have to provide the persistence functionality. Currently, we will accomplish this task by saving person records in some text file. Supporting simple persistence by any application requires handling of two scenarios. These are On start up of application – data (person records ) must be read from file On end/finish up of application – data (person records) must be saved in file To support persistence, we have to handle the above mentioned scenarios Scenario 1 – Start Up Establish a data channel with a file by using streams Start reading data (person records) from file line by line Construct PersonInfo objects from each line you have read Add those PersonInfo objects in arraylist persons. Close the stream with the file Perform these steps while application is loading up We will read records from a text file named persons.txt. The person records will be present in the file in the following format. Ali,defence,9201211 Usman,gulberg,5173940 Salman,LUMS,5272670 persons.txt As you have seen, each person record is on a separate line. Person’s name, address & phone number is separated using comma (,). We will modify our AddressBook.java by adding a new method loadPersons into it. This method will provide the implementation of all the steps. The method is shown below:
  • 91.
    Web Design &Development – CS506 VU © Copyright Virtual University of Pakistan 91 public void loadPersons ( ){ String tokens[] = null; String name, add, ph; try { FileReader fr = new FileReader("persons.txt"); BufferedReader br = new BufferedReader(fr); String line = br.readLine(); while ( line != null ) { tokens = line.split(","); name = tokens[0]; add = tokens[1]; ph = tokens[2]; PersonInfo p = new PersonInfo(name, add, ph); persons.add(p); line = br.readLine(); } br.close(); fr.close(); }catch(IOException ioEx){ System.out.println(ioEx); } } First, we have to connect with the text file in order to read line by line person records from it. This task is accomplished with the following lines of code FileReader fr = new FileReader(“persons.txt”); BufferedReader br = new BufferedReader(fr); FileReader is a character based (node) stream that helps us in reading data in the form of characters. As we are using streams, so we have to import the java.io package in the AddressBook class. We passed the file name persons.txt to the constructor of the FileReader. Next we add BufferedReader (filter stream) on top of the FileReader because BufferedReader facilitates reading data line by line. (As you can recall from the lecture that filter streams are attached on top of node streams). That’s why the constructor of BufferedReader is receiving the fr – the FileReader object. The next line of code will read line from file by using readLine( ) method of BufferedReader and save it in a string variable called line. String line = br.readLine( );
  • 92.
    Web Design &Development – CS506 VU © Copyright Virtual University of Pakistan 92 After that while loop starts. The condition of while loop is used to check whether the file is reached to end (returns null) or not. This loop is used to read whole file till the end. When end comes (null), this loop will finish. while (line != null) Inside loop, the first step we performed is tokenizing the string. For this purpose, we have used split method of String class. This method returns substrings (tokens) according to the regular expression or delimiter passed to it. tokens = line.split(“,”); The return type of this method is array of strings that’s why we have declared tokens as a String array in the beginning of this method as String tokens[]; For example, the line contains the following string Ali,defence,9201211 Now by calling split(“,”) method on this string, this method will return back three substrings ali defence and 9201211 because the delimiter we have passed to it is comma. The delimiter itself is not included in the substrings or tokens. The next three lines of code are simple assignments statements. The tokens[0] contains the name of the person because the name is always in the beginning of the line, tokens[1] contains address of the person and tokens[2] contains the phone number of the person. name = tokens[0]; add = tokens[1]; ph = tokens[2]; The name, add and ph are of type String and are declared in the beginning of this method. After that we have constructed the object of PersonInfo class by using parameterized constructor and passed all these strings to it. PersonInfo p = new PersonInfo(name, add, ph); Afterward the PersonInfo object’s p is added to the arraylist i.e. persons. persons.add(p); The last step we have done inside loop is that we have again read a line form the file by using the readLine() method.
  • 93.
    Web Design &Development – CS506 VU © Copyright Virtual University of Pakistan 93 By summarizing the task of while loop we can conclude that it reads the line from a file, Tokenize that line into three substrings followed by constructing the PersonInfo object by using these tokens. And adding these objects to the arraylist. This process continues till the file reaches its end. The last step for reading information from the file is ordinary one – closing the streams, because files are external resources, so it’s better to close them as soon as possible. Also observe that we used try/catch block because using streams can result in raising exceptions that falls under the checked exceptions category – that needs mandatory handling. The last important step you have to perform is to call this method while loading up. The most appropriate place to call this method is from inside the constructor of AddressBook.java. So the constructor will now look like similar to the one given below: ……………… public AddressBook () { Persons = new ArrayList(); loadPersons(); } ……………… AddressBook.java Scenario 2 – End/Finish Up Establish a datachanel(stream) with a file by using streams Take out PersonInfo objects from ArrayList (persons) Build a string for each PersonInfo object by inserting commas (,) between name & address and address & phone number. Write the constructed string to the file Close the connection with file Perform these steps while exiting from address book. Add another method savePersons into AddressBook.java. This method will provide the implementation of all the above mentioned steps. The method is shown below:
  • 94.
    Web Design &Development – CS506 VU © Copyright Virtual University of Pakistan 94 Public void savePersons ( ){ try { PersonInfo p; String line; FileWriter fw = new FileWriter("persons.txt"); PrintWriter pw = new PrintWriter(fw); for(int i=0; i<persons.size(); i++) { p = (PersonInfo)persons.get(i); line = p.name +","+ p.address +","+ p.phoneNum; // writes line to file (persons.txt) pw.println(line); } pw.flush(); pw.close(); fw.close(); }catch(IOException ioEx){ System.out.println(ioEx); } } As you can see, that we have opened the same file (persons.txt) again by using a set of streams. After that we have started for loop to iterate over arraylist as we did in searchPerson and deletePerson methods. Inside for loop body, we have taken out PersonInfo object and after type casting it we have assigned its reference to a PersonInfo type local variable p. This is achieved by the help of following line of code p = (PersonInfo)persons.get(i); Next we build a string and insert commas between the PersonInfo attributes and assign the newly constructed string to string’s local variable line as shown in the following line of code. line = p.name +","+ p.address +","+ p.phoneNum; Note: Since, we haven’t declare PersonInfo attributes private, therefore we are able to directly access them inside AddressBook.java. The next step is to write the line representing one PersonInfo object’s information, to the file. This is done by using println method of PrintWriter as shown below pw.println(line);
  • 95.
    Web Design &Development – CS506 VU © Copyright Virtual University of Pakistan 95 After writing line to the file, the println method will move the cursor/control to the next line. That’s why each line is going to be written on separate line. The last step for saving information to the file is ordinary one – closing the streams but before that notice the code line that you have not seen/performed while loading persons records from file. That is pw.flush( ); The above line immediately flushes data by writing any buffered output/data to file. This step is necessary to perform or otherwise you will most probably lose some data for the reason that PrintWriter is a Buffered Stream and they have their own internal memory/storage capacity for efficiency reasons. Buffered Streams do not send the data until their memory is full. Also we have written this code inside try-catch block. The last important step you have to perform is to call this method before exiting from the address book. The most appropriate place to call this method is under case 4 (exit scenario) in Test.java. So the case 4 will now look like similar to the one given below: case 4: ab.savePersons(); System.exit(0); Test.java Compile & Execute Now again after compiling all the classes, run the Test class. Initially we are assuming that out persons.txt file is empty, so our arraylist persons will be empty on the first start up of address book. Now add some records into it, perform search or delete operations. Exit from the address book by choosing option 4. Check out the persons.txt file. Don’t get surprised by seeing that it contains all the person records in the format exactly we have seen above. Next time you will run the address book; all the records will be available to you. Perform the search or delete operation to verify that. Finally You have done it !!! References Example code, their explanations and corresponding figures for this handout are taken from the book JAVA A Lab Course by Umair Javed. This material is available just for the use of VU students of the course Web Design and Development and not for any other commercial purpose without the consent of author.
  • 96.
    Web Design &Development – CS506 VU © Copyright Virtual University of Pakistan 96 Abstract Classes and Interfaces Problem and Requirements Before moving on to abstract classes, first examine the following class hierarchy shown below: Circle Square • Suppose that in order to exploit polymorphism, we specify that 2-D objects must be able to compute their area. – All 2-D classes must respond to area() message. • How do we ensure that? – Define area method in class Shape – Force the subclasses of Shape to respond area() message • Java’s provides us two solutions to handle such problem – Abstract Classes – Interfaces Abstract Classes Abstract classes are used to define only part of an implementation. Because, information is not complete therefore an abstract class cannot be instantiate. However, like regular classes, they can also contain instance variables and methods that are full implemented. The class that inherits from abstract class is responsible to provide details. Any class with an abstract method (a method has no implementation similar to pure virtual function in C++) must be declared abstract, yet you can declare a class abstract that has no abstract method. If subclass overrides all abstract methods of the super class, than it becomes a concrete (a class whose object can be instantiate) class otherwise we have to declare it as abstract or we can not compile it.
  • 97.
    Web Design &Development – CS506 VU © Copyright Virtual University of Pakistan 97 The most important aspect of abstract class is that reference of an abstract class can point to the object of concrete classes. Code Example of Abstract Classes The Shape class contains an abstract method calculateArea() with no definition. public abstract class Shape{ public abstract void calculateArea(); } Class Circle extends from abstract Shape class, therefore to become concrete class it must provides the definition of calculateArea() method. public class Circle extends Shape { private int x, y; private int radius; public Circle() { x = 5; y = 5; radius = 10; } // providing definition of abstract method public void calculateArea () { double area = 3.14 * (radius * radius); System.out.println(“Area: ” + area); } }//end of class The Test class contains main method. Inside main, a reference s of abstract Shape class is created. This reference can point to Circle (subclass of abstract class Shape) class object as it is a concrete class. With the help of reference, method calculateArea() can be invoked of Circle class. This is all shown in the form of code below public class Test { public static void main(String args[]){ //can only create references of A.C. Shape s = null; //Shape s1 = new Shape(); //cannot instantiate //abstract class reference can point to concrete subclass s = new Circle(); s.calculateArea(); } }//end of class The compilation and execution of the above program is shown below:
  • 98.
    Web Design &Development – CS506 VU © Copyright Virtual University of Pakistan 98 Interfaces As we seen ne possible java’s solution to problem discussed in start of the tutorial. The second possible java’s solution Interfac are special java type which contains only a set of method prototypes, but doest not provide the implementation for these prototypes. All the methods inside an interface are abstract by default thus an abstract class – a class with zero implementation. Interface can also contains } Classes implement interfaces. Implementing an interface is like signing a contract. A class that implements an interfac definition of all the methods that are present inside an interface. If the class d tions of all methods, the class would not compile. We have to declare it as an abstract class in order to get it compiled. Code Example of Defining & Implementing an Interface The interface Printable contains print() method. o is Interfaces. es interface is tantamount to a pure static final constants Defining an Interface Keyword interface is used instead of class as shown below: public interface Speaker{ public void speak(); Implementing (using) Interface e will have to provide the oes not provide defini Relationship between a class and interface is equivalent to “responds to” while “is a” relationship exists in inheritance.
  • 99.
    Web Design &Development – CS506 VU © Copyright Virtual University of Pakistan 99 public interface Printable{ public void print(); Class . Note the use of keyword implements after the class name. Student class has to provide the definition of print method or we are unable to compile. The cod s is given below: ent implements Printable { private String name; ess; //providing definition of interface’s print method ress"+address); Interface Characteristics ct class, interfaces imposes a design structure on any class that uses the interface. Contrary to inheritance, a class can implement more than one interfaces. To do this separate the interface names with comma. This is java’s way of multiple inheritance. class Circle implements Drawable , Printable { ………. } Objects o f interfaces also cannot be instantiated. Speaker s = new Speaker(); // not compile However, a reference of interface can be created to point any of its implementation class. This is interface based polymorphism. } Student is implementing the interface Printable e snippet of student clas public class Stud private String addr public String toString () { return "name:"+name +" address:"+address; } public void print() { System.out.println("Name:" +name+" add } }//end of class Similar to abstra
  • 100.
    Web Design &Development – CS506 VU © Copyright Virtual University of Pakistan 100 Code Example: Interface based polymorphism Interface Speaker is implemented by three classes Politician, Coach and Lecturer. Code snippets of all these three classes are show below: public class Politician implements Speaker{ public void speak(){ System.out.println(“Politics Talks”); } } public class Coach implements Speaker{ public void speak(){ System.out.println(“Sports Talks”); } } public class Lecturer implements Speaker{ public void speak(){ System.out.println(“Web Design and Development Talks”); } } As usual, Test class contains main method. Inside main, a reference sp is created of Speaker class. Later, this reference is used to point to the objects of Politician, Coach and Lecturer class. On calling speak method with the help of sp, will invoke the method of a class to which sp is pointing. public class Test{ public static void main (String args[ ]) { Speaker sp = null; System.out.println("sp pointing to Politician"); sp = new Politician(); sp.speak(); System.out.println("sp pointing to Coach"); sp = new Coach(); sp.speak(); System.out.println("sp pointing to Lecturer"); sp = new Lecturer(); sp.speak(); } }
  • 101.
    Web Design &Development – CS506 VU © Copyright Virtual University of Pakistan 101 The compilation and execution of the above program is shown below: References Example code, their explanations and corresponding figures for this handout are taken from the book JAVA A Lab Course by Umair Javed. This material is available just for the use of VU students of the course Web Design and Development and not for any other commercial purpose without the consent of author.
  • 102.
    Web Design &Development – CS506 VU © Copyright Virtual University of Pakistan 102 Lesson 10 Graphical User Interfaces A graphical user interface is a visual interface to a program. GUIs are built from GUI components (buttons, menus, labels etc). A GUI component is an object with which the user interacts via the mouse or keyboard. Together, the appearance and how user interacts with the program are known as the program look and feel. Support for GUI in Java The classes that are used to create GUI components are part of the “java.awt” or “javax.swing” package. Both these packages provide rich set of user interface components. GUI classes vs. Non-GUI Support Classes The classes present in the awt and swing packages can be classified into two broad categories. GUI classes & Non-GUI Support classes. The GUI classes as the name indicates are visible and user can interact with them. Examples of these are JButton, JFrame & JRadioButton etc The Non-GUI support classes provide services and perform necessary functions for GUI classes. They do not produce any visual output. Examples of these classes are Layout managers (discussed latter) & Event handling (see handout on it) classes etc. java.awt package AWT stands for “Abstract Windowing Toolkit “contains original GUI components that came with the first release of JDK. These components are tied directly to the local platform’s (Windows, Linux, MAC etc) graphical user interface capabilities. Thus results in a java program executing on different java platforms (windows, Linux, Solaris etc) has a different appearance and sometimes even different user interaction on each platform. AWT components are often called Heavy Weight Components (HWC) as they rely on the local platform’s windowing system to determine their functionality and their look and feel. Every time you create an AWT component it creates a corresponding process on the operating system. As compared to this SWING components are managed through threads and are known as Light Weight Components. This package also provides the classes for robust event handling (see handout on it) and layout managers. javax.swing package These are the newest GUI components. Swing components are written, manipulated and displayed completely in java, therefore also called pure java components. The swing components allow the programmer to specify a uniform look and feel across all platforms.
  • 103.
    Web Design &Development – CS506 VU © Copyright Virtual University of Pakistan 103 Swing components are often referred to as Light Weight Components as they are completely written in java. Several swing components are still HWC. e.g. JFrame etc. A part of the FrameWork Object Component Container JComponent Window AbstractButton JPanel F rame JButton J Frame
  • 104.
    Web Design &Development – CS506 VU © Copyright Virtual University of Pakistan 104 GUI Creation Steps 1. import required packages import java.awt.* and/or javax.swing.* package. 2. Setup the top level containers A container is a collection of related components, which allows other components to be nested inside it. In application with JFrame, we attatch components to the content pane – a container. Two important methods the container class has add and setLayout. The add method is used for adding components to the content pane while setLayout method is used to specify the layout manager. Container are classified into two broad categories that are Top Level containers and General Purpose Containers Top level containers can contain (add) other containers as well as basic components (buttons, labels etc) while general purpose containers are typically used to collect basic components and are added to top level containers. General purpose containers cannot exist alone they must be added to top level containers Examples of top level container are JFrame, Dialog and Applet etc. Our application uses one of these. Examples of general purpose container are JPanel, Toolbar and ScrollPane etc. So, take a top level container and create its instance. Consider the following code of line if JFrame is selected as a top level container JFrame frame = new JFrame();
  • 105.
    Web Design &Development – CS506 VU © Copyright Virtual University of Pakistan 105 3. Get the component area of the top level container Review the hierarchy given above, and observe that JFrame is a frame is a window. So, it can be interpreted as JFrame is a window. Every window has two areas. System Area & Component Area The programmer cannot add/remove components to the System Area. The Component Area often known as Client area is a workable place for the programmer. Components can be added/removed in this area. So, to add components, as you guessed right component area of the JFrame is required. It can be accomplished by the following code of line Conntainer con = frame.getContentPane(); frame is an instance of JFrame and by calling getContentPane() method on it, it returns the component area. This component area is of type container and that is why it is stored in a variable of a Container class. As already discussed, container allows other components to be added / removed. 4. Apply layout to component area The layout (size & position etc. How they appear) of components in a container is usually governed by Layout Managers. The layout manager is responsible for deciding the layout policy and size of its components added to the container. Layout managers are represented in java as classes. (Layout Managers are going to be discussed in detail later in this handout) To set the layout, as already discussed use setLayout method and pass object of layout manager as an argument. con.setLayout( new FlowLayout( ) ); We passed an object of FlowLayout to the setLayout method here. We can also use the following lines of code instead of above. FlowLayout layout = new FlowLayout(); con.setLayout(layout);
  • 106.
    Web Design &Development – CS506 VU © Copyright Virtual University of Pakistan 106 5. Create and Add components Create required components by calling their constructor. JButton button = new JButton ( ); After creating all components your are interested in, the next task is to add these components into the component area of your JFrame (i.e ContentPane, the reference to which is in variable con of type Container) Use add method of the Container to accomplish this and pass it the component to be added. con.add(button); 6. Set size of frame and make it visible A frame must be made visible via a call to setVisible(true) and its size defined via a call setSize(rows in pixel, columns in pixel) to be displayed on the screen. frame.setSize(200, 300) ; frame.setVisible(true) ; Note: By default, all JFrame’s are invisible. To make visible frame visible we have passed true to the setVisible method. frame.setVisible(false) ; Making a Simple GUI The above figured GUI contains one text field and a button. Let’s code it by following the six GUI creation steps we discussed.
  • 107.
    Web Design &Development – CS506 VU © Copyright Virtual University of Pakistan 107 Code for Simple GUI // File GUITest.java //Step 1: import packages import java.awt.*; import javax.swing.*; public class GUITest { JFrame myFrame ; JTextField tf; JButton b; //method used for setting layout of GUI public void initGUI ( ) { //Step 2: setup the top level container myFrame = new JFrame(); //Step 3: Get the component area of top-level container Container c = myFrame.getContentPane(); //Step 4: Apply layouts c.setLayout( new FlowLayout( ) ); //Step 5: create & add components JTextField tf = new JTextField(10); JButton b1 = new JButton("My Button"); c.add(tf); c.add(b1); //Step 6: set size of frame and make it visible myFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); myFrame.setSize(200,150); myFrame.setVisible(true); } //end initGUI method public GUITest () { // default constructor initGUI (); } public static void main (String args[ ]) { GUITest gui = new GUITest(); } } // end of class
  • 108.
    Web Design &Development – CS506 VU © Copyright Virtual University of Pakistan 108 Important Points to Consider main method (from where program execution starts) is written in the same class. The main method can be in a separate class instead of writing in the same class its your choice. Inside main, an object of GUI test class is created that results in calling of constructor of the class and from the constructor, initGUI method is called that is responsible for setting up the GUI. The following line of code is used to exit the program when you close the window myFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); If you delete this line and run your program, the desired GUI would be displayed. However if you close the window by using (X) button on top left corner of your window, you’ll notice that the control doesn’t return back to command prompt. The reason for this is that the java process is still running. How ever if you put this line in your code, when you exit your prompt will return. R eferences: Sun java tutorial: http://java.sun.com/docs/books/tutorial/java Thinking in java by Bruce Eckle Beginning Java2 by Ivor Hortan GUI creation steps are taken from the book Java A Lab Course by Umair Javed
  • 109.
    Web Design &Development – CS506 VU © Copyright Virtual University of Pakistan 109 Graphical User Interfaces - 2 Layout Managers Layout Managers are used to form the appearance of your GUI. They are concerned with the arrangement of components of GUI. A general question is “why we can not place components at our desired location (may be using the x,y coordinate position?” The answer is that you can create your GUI without using Layout Managers and you can also do VB style positioning of components at some x,y co-ordinate in Java, but that is generally not advisable if you desire to run the same program on different platforms The appearance of the GUI also depends on the underlying platform and to keep that same the responsibility of arranging layout is given to the LayoutManagers so they can provide the same look and feel across different platforms Commonly used layout managers are 1. Flow Layout 2. Grid Layout 3. Border Layout 4. Box Layout 5. Card Layout 6. GridBag Layout and so on Let us discuss the top three in detail one by one with code examples. These top three will meet most of your basic needs 1. Flow Layout Position components on line by line basis. Each time a line is filled, a new line is started. The size of the line depends upon the size of your frame. If you stretch your frame while your program is running, your GUI will be disturbed. Example Code // File FlowLayoutTest.java import java.awt.*; import javax.swing.*; public class FlowLayoutTest { JFrame myFrame ; JButton b1, b2, b3, b4, b5; //method used for setting layout of GUI public void initGUI ( ) {
  • 110.
    Web Design &Development – CS506 VU © Copyright Virtual University of Pakistan 110 myFrame = new JFrame(“Flow Layout”); Container c = myFrame.getContentPane(); c.setLayout( new FlowLayout( ) ); b1 = new JButton(“Next Slide”); b2 = new JButton(“Previous Slide”); b3 = new JButton(“Back to Start”); b4 = new JButton(“Last Slide”); b5 = new JButton(“Exit”); c.add(b1); c.add(b2); c.add(b3); c.add(b4); c.add(b5); myFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); myFrame.setSize(300,150); myFrame.setVisible(true); } //end initGUI method public FlowLayoutTest () { // default constructor initGUI (); } public static void main (String args[ ]) { FlowLayoutTest flTest = new FlowLayoutTest(); } } // end of class Output
  • 111.
    Web Design &Development – CS506 VU © Copyright Virtual University of Pakistan 111 2. Grid Layout Splits the panel/window into a grid (cells) with given number of rows and columns. Forces the size of each component to occupy the whole cell. Size of each component is same Components are added row wise. When all the columns of the first row are get filled the components are then added to the next row. Only one component can be added into each cell. Example Code // File GridLayoutTest.java import java.awt.*; import javax.swing.*; public class GridLayoutTest { JFrame myFrame ; JButton b1, b2, b3, b4, b5; //method used for setting layout of GUI public void initGUI ( ) { myFrame = new JFrame(“Grid Layout”); Container c = myFrame.getContentPane(); // rows , cols c.setLayout( new GridLayout( 3 , 2 ) ); b1 = new JButton(“Next Slide”); b2 = new JButton(“Previous Slide”); b3 = new JButton(“Back to Start”); b4 = new JButton(“Last Slide”); b5 = new JButton(“Exit”); c.add(b1); c.add(b2); c.add(b3); c.add(b4); c.add(b5); myFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); myFrame.setSize(300,150); myFrame.setVisible(true); } //end initGUI method
  • 112.
    Web Design &Development – CS506 VU © Copyright Virtual University of Pakistan 112 public GridLayoutTest () { // default constructor initGUI (); } public static void main (String args[ ]) { GridLayoutTest glTest = new GridLayoutTest(); } } // end of class output Modification The grid layout also allows the spacing between cells. To achieve spacing between cells, modify the above program. Pass additional parameters to the constructor of GridLayout, spaces between rows & spaces between columns as shown below c.setLayout( new GridLayout( 3 , 2 , 10 , 20) ); The output is look similar to one given below.
  • 113.
    Web Design &Development – CS506 VU © Copyright Virtual University of Pakistan 113 3. Border Layout Divides the area into five regions. North, South, East, West and Center Components are added to the specified region If any region not filled, the filled regions will occupy the space but the center region will still appear as background if it contains no component. Only one component can be added into each region. NORTH WEST CENTER EAST SOUTH Example Code // File BorderLayoutTest.java import java.awt.*; import javax.swing.*; public class BorderLayoutTest { JFrame myFrame ; JButton b1, b2, b3, b4, b5; //method used for setting layout of GUI public void initGUI ( ) { myFrame = new JFrame(“Border Layout”); Container c = myFrame.getContentPane(); c.setLayout( new BorderLayout( ); b1 = new JButton(“Next Slide”); b2 = new JButton(“Previous Slide”); b3 = new JButton(“Back to Start”); b4 = new JButton(“Last Slide”); b5 = new JButton(“Exit”); c.add( b1 , BorderLayout.NORTH ); c.add( b2 , BorderLayout.SOUTH );
  • 114.
    Web Design &Development – CS506 VU © Copyright Virtual University of Pakistan 114 c.add( b3 , BorderLayout.EAST ); c.add( b4 , BorderLayout.WEST ); c.add( b5 , BorderLayout.CENTER); myFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); myFrame.setSize(300,150); myFrame.setVisible(true); } //end initGUI method public BorderLayoutTest () { // default constructor initGUI (); } public static void main (String args[ ]) { BorderLayoutTest glTest = new BorderLayoutTest(); } } // end of class Points to Remember Revisit the code of adding components, we specify the region in which we want to add component or otherwise they will not be visible. Consider the following segment of code: BorderLayout.NORTH, as you guessed correctly NORTH is a constant (final) defined in BorderLayout class public access modifier. Similarly the other ones are defined. Now you understand, why so much emphasis has been made on following the naming conventions. Output
  • 115.
    Web Design &Development – CS506 VU © Copyright Virtual University of Pakistan 115 Making Complex GUIs From the discussion above it seems that the basic Layout Managers may not help us in constructing complex GUIs, but generally a combination of these basic layouts can do the job. So lets try to create the calculator GUI given below This GUI has 16 different buttons each of same size and text field on the top and a label lator’ on the bottom. So, h w most on compon om has different size. Flow shape. Can we ma a bit tricky business but General Purpose Containers are there to provide the solution. JPanel ‘my calcu o we can make this GUI? If Border Layout is selected, it has five regions (each region can have at e component) but here we have more than five components to add. Lets try Grid Layout, but all the ents in a Grid have same size and the text field at the top and label at the bott Layout cannot be selected because if we stretch our GUI it will destroy its ke this GUI? Yes, we can. Making of such GUI is onents (JButton , JTextField etc even other JPanels) anel has its own layout that can be set while creating JPanel instance Add components by using add method like shown below. e JFrame etc) in order to be visible as they (general purpose It is general purpose container (can’t exist alone, it has to be in some toplevel container) in whichwe can put in different comp JP JPanel myPanel = new JPanel ( new FlowLayout( ) ); myPanel.add (button ); Must be added to a top level container (likcontainers) can’t exist alone.
  • 116.
    Web Design &Development – CS506 VU © Copyright Virtual University of Pakistan 116 Solution To own above, take JFrame (top level container) and set its layout to border. Than take JPa tainer) and set its layout to Grid with 4 rows and 4 columns. Add s they all have equal size and JPanel layout has been set to GridLayout. Afterthat, add n, label to the south region and panel to the center region of the JFrame’s container. The east and west regions are left blank and the center region will be stretched to cover up these. So, n build our calculator GUI. Cod make the calculator GUI shnel (general purpose con buttons to JPanel a text field to the north regio that’s how we ca e for Calculator GUI // Fi import javax.swing.*; public class CalculatorGUI { JButton b1, b2, b3, b4, b5, b6, b7, b8, b9, b0; oint, bEqual, bClear; ut of GUI = new JButton("0"); b1 = new JButton("1"); b2 = new JButton("2"); b3 = new JButton("3"); b4 = new JButton("4"); b5 = new JButton("5"); b6 = new JButton("6"); b7 = new JButton("7"); b8 = new JButton("8"); b9 = new JButton("9"); le CalculatorGUI.java import java.awt.*; JFrame fCalc; JButton bPlus, bMinus, bMul, bP JPanel pButtons; JTextField tfAnswer; JLabel lMyCalc; //method used for setting layo public void initGUI ( ) { fCalc = new JFrame(); b0
  • 117.
    Web Design &Development – CS506 VU © Copyright Virtual University of Pakistan 117 bPlus = new JButton("+"); bMinus = new JButton("-"); bMul = new JButton("*"); bPoint = new JButton("."); bEqual = new JButton("="); bClear = new JButton("C"); tfAnswer = new JTextField(); lMyCalc = new JLabel("My Clacualator"); //creating panel object and setting its layout pButtons = new JPanel (new GridLayout(4,4)); //adding components (buttons) to panel pButtons.add(b1); pButtons.add(b2); pButtons.add(b3); pButtons.add(bClear); pButtons.add(b4); pButtons.add(b5); pButtons.add(b6); pButtons.add(bMul); pButtons.add(b7); pButtons.add(b8); pButtons.add(b9); pButtons.add(bMinus); pButtons.add(b0); pButtons.add(bPoint); pButtons.add(bPlus); pButtons.add(bEqual); // getting componenet area of JFrame Container con = fCalc.getContentPane(); con.setLayout(new BorderLayout()); //adding components to container con.add(tfAnswer, BorderLayout.NORTH); con.add(lMyCalc, BorderLayout.SOUTH); con.add(pButtons, BorderLayout.CENTER); fcalc.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); fCalc.setSize(300, 300); fCalc.setVisible(true); } //end initGUI method public CalculatorGUI () { // default constructor initGUI (); }
  • 118.
    Web Design &Development – CS506 VU © Copyright Virtual University of Pakistan 118 public static void main (String args[ ]) { CalculatorGUI calGUI = new CalculatorGUI (); } } // end of class Reference: Sun java tutorial: http://java.sun.com/docs/books/tutorial/java Thinking in java by Bruce Eckle Beginning Java2 by Ivor Hortan Java A Lab Course by Umair Javed
  • 119.
    Web Design &Development – CS506 VU © Copyright Virtual University of Pakistan 119 Lesson 11 Event Handling One of the most important aspects of most non-trivial applications (especially UI type- apps) is the ability to respond to events that are generated by the various components of the application, both in response to user interactions and other system components such as client-server processing. In this handout we will look at how Java supports event generation and handling and how to create (and process) custom events. GUIs generate events when the user interacts with GUI. For example, — Clicking a button — Moving the mouse — Closing Window etc Both AWT and swing components (not all) generate events — java.awt.event.*; — javax.swing.event.*; In java, events are represented by Objects These objects tells us about event and its source. Examples are: — ActionEvent (Clicking a button) — WindowEvent (Doing something with window e.g. closing , minimizing) Some event classes of java.awt.event are shown in diagram below
  • 120.
    Web Design &Development – CS506 VU © Copyright Virtual University of Pakistan 120 Event Handling Model In Java both AWT and Swing components use Event Delegation Model. – In this model processing of an event is delegated to a particular object (handlers ) in the program – It’s a Publish-Subscribe model. That is, event generating component publish an event and event handling components subscribe for that event. The publisher sends these events to subscribers. Similar to the way that you subscribe for newspaper and you get the newspaper at your home from the publisher. – This model separates UI code from program logic, it means that we can create separate classes for UI components and event handlers and hence business/program logic is separated from GUI components. Event Handling Steps For a programmer the event Handling is a three step process in terms of code – Step 1: Create components which can generate events (Event Generators) – Step 2: Build component (objects) that can handle events (Event Handlers) – Step 3: Register handlers with generators Event Handling Process Step 1: Event Generators The first step is that you create an event generator. You have already seen a lot of event generators like: – Buttons – Mouse – Key – Window etc Most of GUI components can be created by calling their constructors. For example JButton b1 = new JButton(“Hello”); Now b1 can generate events Note: We do not create Mouse/Keys etc as they are system components
  • 121.
    Web Design &Development – CS506 VU © Copyright Virtual University of Pakistan 121 Step 2: Event Handlers/ Event Listener The second step is that you build components that can handle events First Technique - By Implementing Listener Interfaces – Java defines interfaces for every event type – If a class needs to handle an event. It needs to implement the corresponding listener interface – To handle “ActionEvent” a class needs to implement “ActionListener” – To handle “KeyEvent” a class needs to implement “KeyListener” – To handle “MouseEvent” a class needs to implement “MouseListener” and so on – Package java.awt.event contains different event Listener Interfaces which are shown in the following figure
  • 122.
    Web Design &Development – CS506 VU © Copyright Virtual University of Pakistan 122 – Some Example Listeners, the way they are defined in JDK by Sun public interface ActionListener { public void actionPerformed(ActionEvent e); } public interface ItemListener { public void itemStateChanged(ItemEvent e); } public interface ComponentListener { public void componentHidden(ComponentEvent e); public void componentMoved(ComponentEvent e); public void componentResized(ComponentEvent e); public void componentShown(ComponentEvent e); } – By implementing an interface the class agrees to implement all the methods that are present in that interface. Implementing an interface is like signing a contract. – Inside the method the class can do what ever it wants to do with that event – Event Generator and Event Handler can be the same or different classes – To handle events generated by Button. A class needs to implement ActionListener interface and thus needs to provide the definition of actionPerformed() method which is present in this interface. public class Test implements ActionListener{ public void actionPerformed(ActionEvent ae) { // do something } }
  • 123.
    Web Design &Development – CS506 VU © Copyright Virtual University of Pakistan 123 Step 3: Registering Handler with Generator The event generator is told about the object which can handle its events Event Generators have a method — addXXXListener(_reference to the object of Handler class_) For example, if b1 is JButton then — b1.addActionListener(this); // if listener and generator are same class Event Handling Example Clicking the “Hello” button will open up a message dialog shown below. We will take the simplest approach of creating handler and generator in a single class. Button is our event generator and to handle that event our class needs to implement ActionListener Interface and to override its actionPerformed method and in last to do the registration 1. import java.awt.*; 2. import javax.swing.*; 3. import java.awt.event.*; /* Implementing the interface according to the type of the event, i.e. creating event handler (first part of step 2 of our process) */ 4. public class ActionEventTest implements ActionListner{ 5. JFrame frame; 6. JButton hello; // setting layout components 7. public void initGUI ( ) { 8. frame = new JFrame(); 9. Container cont = frame.getContentPane(); 10. cont.setLayout(new FlowLayout()); //Creating event generator step-1 of our process 11. hello = new JButton("Hello");
  • 124.
    Web Design &Development – CS506 VU © Copyright Virtual University of Pakistan 124 /* Registering event handler with event generator. Since event handler is in same object that contains button, we have used this to pass the reference.(step 3 of the process) */ 12. hello.addActionListener(this); 13. cont.add(hello); 14. frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 15. frame.setSize(150, 150); 16. frame.setVisible(true); 17. } //constructor 18. public ActionEventTest ( ) { 19. initGUI(); 20. } /* Override actionPerformed method of ActionListener’s interfacemethod of which will be called when event takes place (second part of step 2 of our process) */ 21. public void actionPerformed(ActionEvent event) { 22. JOptionPane.showMessageDialog(null,"Hello is pressed"); 23. } 24. public static void main(String args[]) { 25. ActionEventTest aeTest = new ActionEventTest(); 26. } 27.} // end class
  • 125.
    Web Design &Development – CS506 VU © Copyright Virtual University of Pakistan 125 How Event Handling Participants interact Behind the Scenes? We have already seen that what a programmer needs to do handle events. Let’s see what takes place behind the scenes, i.e How JVM handles event. Before doing that lets revisit different participants of Event Handling Process and briefly what they do. 1. Event Generator / Source – Swing and awt components – For example, JButton, JTextField, JFrame etc – Generates an event object – Registers listeners with itself 2. Event Object – Encapsulate information about event that occurred and the source of that event – For example, if you click a button, ActionEvent object is created 3. Event Listener/handler – Receives event objects when notified, then responds – Each event source can have multiple listeners registered on it – Conversely, a single listener can register with multiple event sources 4. JVM – Receives an event whenever one is generated – Looks for the listener/handler of that event – If exist, delegate it for processing – If not, discard it (event).
  • 126.
    Web Design &Development – CS506 VU © Copyright Virtual University of Pakistan 126 When button generates an ActionEvent it is sent to JVM which puts it in an event queue. After that when JVM find it appropriate it de-queue the event object and send it to all the listeners that are registered with that button. This is all what we shown in the pictorial form below: (figure from JAVA A Lab Course)
  • 127.
    Web Design &Development – CS506 VU © Copyright Virtual University of Pakistan 127 Making Small Calculator User enters numbers in the provided fields On pressing “+” button, sum would be displayed in the answer field On pressing “*” button, product would be displayed in the answer field
  • 128.
    Web Design &Development – CS506 VU © Copyright Virtual University of Pakistan 128 17. ans = new JTextField (15); 18. plus = new JButton("+"); 19. plus.setPreferredSize(new Dimension(70,25)); 20. mul = new JButton("*"); 21. mul.setPreferredSize(new Dimension(70,25)); 22. Container cont = frame.getContentPane(); 23. cont.setLayout(new FlowLayout()); 24. cont.add(firstOperand); 25. cont.add(op1); 26. cont.add(secondOperand); 27. cont.add(op2); 28. cont.add(plus); 29. cont.add(mul); 30. cont.add(answer); 31. cont.add(ans); 32. plus.addActionListener(this); 33. mul.addActionListener(this); 34. frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 35. frame.setSize(200, 220); 36. frame.setVisible(true); 37. } 38. //constructor 39. public SmallCalcApp ( ) { 40. initGUI(); Example Code: Making Small Calculator 1. import java.awt.*; 2. import javax.swing.*; 3. import java.awt.event.*; 4. public class SmallCalcApp implements ActionListener{ 5. JFrame frame; 6. JLabel firstOperand, secondOperand, answer; 7. JTextField op1, op2, ans; 8. JButton plus, mul; 9. // setting layout 10. public void initGUI ( ) { 11. frame = new JFrame(); 12. firstOperand = new JLabel("First Operand"); 13. secondOperand = new JLabel("Second Operand"); 14. answer = new JLabel("Answer"); 15. op1 = new JTextField (15); 16. op2 = new JTextField (15);
  • 129.
    Web Design &Development – CS506 VU © Copyright Virtual University of Pakistan 129 41. } 42. public void actionPerformed(ActionEvent event) { 43. String oper, result; 44. int num1, num2, res; /* All the information regarding an event is contained inside the event object. Here we are calling the getSource() method on the event object to figure out the button that has generated that event. */ 45. if (event.getSource() == plus) { 46. oper = op1.getText(); 47. num1 = Integer.parseInt(oper); 48. oper = op2.getText(); 49. num2 = Integer.parseInt (oper); 50. res = num1+num2; 51. result = res+""; 52. ans.setText(result); 53. } 54. else if (event.getSource() == mul) { 55. oper = op1.getText(); 56. num1 = Integer.parseInt(oper); 57. oper = op2.getText(); 58. num2 = Integer.parseInt (oper); 59. res = num1*num2; 60. result = res+""; 61. ans.setText(result); 62. } 63. public static void main(String args[]) { 64. SmallCalcApp scApp = new SmallCalcApp(); 65. } 66. }// end class
  • 130.
    Web Design &Development – CS506 VU © Copyright Virtual University of Pakistan 130 Lesson 12 More Examples of Handling Events Handling Mouse Event Mouse events can be trapped for any GUI component that inherits from Component class. For example, JPanel, JFrame & JButton etc. To handle Mouse events, two types of listener interfaces are available. – MouseMotionListener – MouseListener The class that wants to handle mouse event needs to implement the corresponding interface and needs to provide the definition of all the methods in that interface. MouseMotionListener interface – Used for processing mouse motion events – Mouse motion event is generated when mouse is moved or dragged MouseMotionListener interfaces is defined in JDK as follows public interface MouseMotionListener { public void mouseDragged (MouseEvent me); public void mouseMoved (MouseEvent me); } MouseListener interface – Used for processing “interesting” mouse events like when mouse is: ƒ Pressed ƒ Released ƒ Clicked (pressed & released without moving the cursor) ƒ Enter (mouse cursor enters the bounds of component) ƒ Exit (mouse cursor leaves the bounds of component)
  • 131.
    Web Design &Development – CS506 VU © Copyright Virtual University of Pakistan 131 MouseListener interfaces is defined in JDK as follows public interface MouseListener { public void mousePressed (MouseEvent me); public void mouseClicked (MouseEvent me); public void mouseReleased (MouseEvent me); public void mouseEntered (MouseEvent me); public void mouseExited (MouseEvent me); } Example Code: Handling Mouse Events Example to show Mouse Event Handling .Every time mouse is moved, the coordinates for a new place is shown in a label. 1. import java.awt.*; 2. import javax.swing.*; 3. import java.awt.event.*; 4. public class EventsEx implements MouseMotionListener{ 5. JFrame frame; 6. JLabel coordinates; 7. // setting layout 8. public void initGUI ( ) { 9. // creating event generator 10. frame = new JFrame(); 11. Container cont = frame.getContentPane(); 13. coordinates = new JLabel (); 16. frame.addMouseMotionListener(this); 17. frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 19. frame.setVisible(true); 21. //default constructor 12. cont.setLayout(new BorderLayout( ) ); 14. cont.add(coordinates, BorderLayout.NORTH); 15. // registring mouse event handler with generator 18. frame.setSize(350, 350); 20. } // end initGUI method 22. public EventsEx ( ) { 23. initGUI(); 24. }
  • 132.
    Web Design &Development – CS506 VU © Copyright Virtual University of Pakistan 132 // MouseMotionListener event hadler handling dragging 26. int x = me.getX(); 30. public void mouseMoved (MouseEvent me) { 31. int x = me.getX(); 36. EventsEx ex = new EventsEx(); 25. public void mouseDragged (MouseEvent me) { 27. int y = me.getY(); 28. coordinates.setText("Dragged at [" + x + "," + y + "]"); 29. } // MouseMotionListener event handler handling motion 32. int y = me.getY(); 33. coordinates.setText("Moved at [" + x + "," + y + "]"); 34. } 35. public static void main(String args[]) { 37. } 38. } // end class
  • 133.
    Web Design &Development – CS506 VU © Copyright Virtual University of Pakistan 133 Another Example: Handling Window Events Task We want to handle Window Exit event only Why? When window is closed, control should return back to command prompt. But we have already achieved this functionality through following line of code frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); But, what if we want to display some message (Good Bye) befoe exiting? r How? When user closes the window, Message would be displayed After pressing Ok button program will exit “WindowListner” interface contains 7 methods We require only one i.e. WindowListener interface is defined in the JDK as follows public interface WindowListener { public void windowClosed(WindowEvent we); public void windowDeactivated(WindowEvent we); public void windowDeiconified(WindowEvent we); public void windowOpened(WindowEvent we); To handle window events, we need to implement “WindowListner” interface. windowClosing But, We have to provide definitions of all methods to make our class a concrete class public void windowActivated(WindowEvent we); public void windowClosing(WindowEvent we); public void windowIconified(WindowEvent we); } public void windowClosing(WindowEvent we is our required method
  • 134.
    Web Design &Development – CS506 VU © Copyright Virtual University of Pakistan 134 2. import javax.swing.*; 7. public void initGUI ( ) { 13. frame.addMouseMotionListener(this); // registering window handler with generator 15. frame.setSize(350, 350); 17. } // end initGUI method 19. initGUI(); // MouseMotionListener event hadler handling dragging 21. public void mouseDragged (MouseEvent me) { 22. int x = me.getX(); Example Code: WindowExitHandler This example code is modification of the last code example i.e. EventsEx.java 1. import java.awt.*; 3. import java.awt.event.*; 4. public class EventsEx implements MouseMotionListener , WindowListener { 5. JFrame frame; 6. JLabel coordinates; // setting layout // creating event generator 8. frame = new JFrame(); 9. Container cont = frame.getContentPane(); 10. cont.setLayout(new BorderLayout( ) ); 11. coordinates = new JLabel (); 12. cont.add(coordinates, BorderLayout.NORTH); // registring mouse event handler with generator 14. frame.addWindowListener(this); 16. frame.setVisible(true); //default constructor 18. public EventsEx ( ) { 20. } 23. int y = me.getY(); 24. coordinates.setText("Dragged at [" + x + "," + y + "]"); 25. }
  • 135.
    Web Design &Development – CS506 VU © Copyright Virtual University of Pakistan 135 26. public void mouseMoved (MouseEvent me) { 27. int x = me.getX(); 29. 31. } // window listener event handler 37. } 38. public void windowDeactivated (WindowEvent we) { } 42. public static void main(String args[]) { 45. } // end class // MouseMotionListener event handler handling motion 28. int y = me.getY(); 30. coordinates.setText("Moved at [" + x + "," + y + "]"); 32. public void windowActivated (WindowEvent we) { } 33. public void windowClosed (WindowEvent we) { } 34. public void windowClosing (WindowEvent we) { 35. JOptionPane.showMessageDialog(null, “Good Bye”); 36. System.exit(0); 39. public void windowDeiconified (WindowEvent we) { } 40. public void windowIconified (WindowEvent we) { } 41. public void windowOpened (WindowEvent we) { } 43. EventsEx ex = new EventsEx(); 44. }
  • 136.
    Web Design &Development – CS506 VU © Copyright Virtual University of Pakistan 136 Lesson 13 Problem in Last Code Example Problem – We were interested in windowClosing() method only – But have to provide definitions of all the methods, Why? – Because a class implementing an interface has to provide definitions of all methods present in that interface. Solution – To avoid giving implementations of all methods of an interface when we are not using these methods we use Event Adapter classes Adapter Classes – For WindowListener Æ WindowAdapter – and many more • Adapter classes provide definitions for all the methods (empty bodies) of their corresponding Listener interface • It means that WindowAdapter class implements WindowListener interface and provide the definition of all methods inside that Listener interface • Consider the following example of MouseMotionAdapter and its corresponding public void mouseDragged (MouseEvent me) { } • For listener interfaces containing more than one event handling methods, jdk defines adapter classes. Examples are – For MouseMotionListener Æ MouseMotionAdapter MouseMotionListener interface public interface MouseMotionListener { public void mouseDragged (MouseEvent me); public void mouseMoved (MouseEvent me); } public class MouseMotionAdapter implements MouseMotionListener{ public void mouseMoved (MouseEvent me) { } }
  • 137.
    Web Design &Development – CS506 VU © Copyright Virtual University of Pakistan 137 Available Adapter classes How to use Adapter Classes public class EventsEx implements MouseMotionListener{...} Now our handler class will inherit from adapter class Due to inheritance, all the methods of the adapter class will be available inside our handler class Since adapter classes has already provided definitions with empty bodies. Previously handler class need to implement interface Therefore it has to provide definitions of all the methods inside that interface public class EventsEx extends MouseMotionAdapter{...} We do not have to provide implementations of all the methods again We only need to override our method of interest.
  • 138.
    Web Design &Development – CS506 VU © Copyright Virtual University of Pakistan 138 Example Code 13.1: Handling Window Events using Adapter Classes 1. import java.awt.*; 3. import java.awt.event.*; 5. JFrame frame; 12. cont.add(coordinates, BorderLayout.NORTH); // registering window handler with generator 13. frame.addWindowListener(this); 14. frame.setSize(350, 350); 16. } // end initGUI method //default constructor 17. public EventsEx ( ) { 18. initGUI(); 19. } // As you can see that we have only implemented // our required method 21. JOptionPane.showMessageDialog(null, “Good Bye”); 24. public static void main(String args[]) { 25. EventsEx ex = new EventsEx(); 27. } // end class Here we are modifying the window event code in the last example to show the use of WindowAdapter instead of WindowListener. Code related to MouseMotionListener is deleted to avoid cluttering of code. 2. import javax.swing.*; 4. public class EventsEx extends WindowAdapter { 6. JLabel coordinates; // setting layout 7. public void initGUI ( ) { // creating event generator 8. frame = new JFrame(); 9. Container cont = frame.getContentPane(); 10. cont.setLayout(new BorderLayout( ) ); 11. coordinates = new JLabel (); 15. frame.setVisible(true); 20. public void windowClosing (WindowEvent we) { 22. System.exit(0); 23. } 26. }
  • 139.
    Web Design &Development – CS506 VU © Copyright Virtual University of Pakistan 139 Problem in Last Code Example We have inherited from WindowAdapter What if we want to use MouseMotionAdpater as well ? or what if our class already inherited form some other class ? Problem — Java allows single inheritance Solution — Use Inner classes Inner Classes Generally used as a private utility class which does not need to be seen by others classes GUI class (contains GUI creation code) Outer A class defined inside another class Inner class can access the instance variables and members of outer class It can have constructors, instance variables and methods, just like a regular class • tf is a JTextField Class Inner class Handler class • contains event handling code •tf is accessible here
  • 140.
    Web Design &Development – CS506 VU © Copyright Virtual University of Pakistan 140 Example Code13.2: Handling Window Event with Inner Class Here we are modifying the window event code in the last example to show the use of 3. import java.awt.event.*; 5. JFrame frame; 9. frame = new JFrame(); window events and registering it with generator */ 14. WindowHandler handler = new Window Handler (); //default constructor 27. } // end of WindowHandler class WindowAdapter as an inner class. 1. import java.awt.*; 2. import javax.swing.*; 4. public class EventEx { 6. JLabel coordinates; 7. // setting layout 8. public void initGUI ( ) { 10. Container cont = frame.getContentPane(); 11. cont.setLayout(new BorderLayout( )); 12. coordinates = new JLabel (); 13. cont.add(coordinates, BorderLayout.NORTH); /* Creating an object of the class which is handling our 15. frame.addWindowListener(handler); 16. frame.setSize(350, 350); 17. frame.setVisible(true); 18. } // end initGUI 19. public EventEx ( ) { 20. initGUI(); 21. } /* Inner class implementation of window adapter. Outer class is free to inherit from any other class. */ 22. private class WindowHandler extends WindowAdapter { // Event Handler for WindowListener 23. public void windowClosing (WindowEvent we) { 24. JOptionPane.showMessageDialog(null, “Good Bye”); 25. System.exit(0) 26. } 28. public static void main(String args[]) { 29. EventEx e = new EventEx(); 30. } 31. } // end class
  • 141.
    Web Design &Development – CS506 VU © Copyright Virtual University of Pakistan 141 Example Code 13.3: Handling Window and Mouse Events with Inner Class Here we are modifying the window event code of the last example to handle window and mouse events using inner classes. The diagram given below summarizes the approach. 1. import java.awt.*; 3. import java.awt.event.*; 4. public class EventEx { 5. JFrame frame; 8. public void initGUI ( ) { 9. frame = new JFrame(); 11. cont.setLayout(new BorderLayout( ) ); 16. MouseHandler mhandler = new MouseHandler (); Inner class Handling Mouse Events Outer class for GUI and other code Inner class Handling Window 2. import javax.swing.*; 6. JLabel coordinates; 7. // setting layout 10. Container cont = frame.getContentPane(); 12. coordinates = new JLabel (); 13. cont.add(coordinates, BorderLayout.NORTH); /* Creating an object of the class which is handling our window events and registering it with generator */ 14. WindowHandler whandler = new WindowHandler (); 15. frame.addWindowListener(whandler); /* Creating an object of the class which is handling our MouseMotion events & registering it with generator */ 17. frame.addMouseMotionListener(mhandler); 18. frame.setSize(350, 350); 19. frame.setVisible(true); 20. }
  • 142.
    Web Design &Development – CS506 VU © Copyright Virtual University of Pakistan 142 //default constructor 21. public EventEx ( ) { 22. initGUI(); 23. } /* Inner class implementation of WindowAdapter. Outer class 26. JOptionPane.showMessageDialog(null, “Good Bye”); 35. } 36. } // end of MouseHandler 37. public static void main(String args[]) { 39. } 40. } // end class is free to inherit from any other class. */ 24. private class WindowHandler extends WindowAdapter { // Event Handler for WindowListener 25. public void windowClosing (WindowEvent we) { 27. System.exit(0) 28. } 29. } // end of WindowHandler //Inner class implementation of MouseMotionAdapter 30. private class MouseHandler extends MouseMotionAdapter { // Event Handler for mouse motion events 31. public void mouseMoved (MouseEvent me) { 32. int x = me.getX(); 33. int y = me.getY(); 34. coord.setText(“Moved at [" + x + "," + y + "]” ); 38. EventEx e = new EventEx();
  • 143.
    Web Design &Development – CS506 VU © Copyright Virtual University of Pakistan 143 Example Code: Making Small Calculator using Inner classes User enters numbers in the provided fields On pressing “*” button, product would be displayed in the answer field On pressing “+” button, sum would be displayed in the answer field
  • 144.
    Web Design &Development – CS506 VU © Copyright Virtual University of Pakistan 144 1. import java.awt.*; 2. import javax.swing.*; 3. import java.awt.event.*; 4. public class SmallCalcApp implements ActionListener{ 5. JFrame frame; 6. JLabel firstOperand, secondOperand, answer; 7. JTextField op1, op2, ans; 8. JButton plus, mul; 13. secondOperand = new JLabel("Second Operand"); 18. plus = new JButton("+"); 21. mul.setPreferredSize(new Dimension(70,25)); 23. cont.setLayout(new FlowLayout()); 26. cont.add(secondOperand); 29. cont.add(mul); 31. cont.add(ans); /* Creating an object of the class which is handling 9. // setting layout 10. public void initGUI ( ) { 11. frame = new JFrame(); 12. firstOperand = new JLabel("First Operand"); 14. answer = new JLabel("Answer"); 15. op1 = new JTextField (15); 16. op2 = new JTextField (15); 17. ans = new JTextField (15); 19. plus.setPreferredSize(new Dimension(70,25)); 20. mul = new JButton("*"); 22. Container cont = frame.getContentPane(); 24. cont.add(firstOperand); 25. cont.add(op1); 27. cont.add(op2); 28. cont.add(plus); 30. cont.add(answer); button events & registering it with generators */ 32. ButtonHandler bHandler = new ButtonHandler(); 33. plus.addActionListener(bHandler); 34. mul.addActionListener(bHandler); 35. frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 36. frame.setSize(200, 220); 37. frame.setVisible(true); 38. }
  • 145.
    Web Design &Development – CS506 VU © Copyright Virtual University of Pakistan 145 39. //constructor 40. public SmallCalcApp ( ) { 41. initGUI(); //Inner class implementation of ActionListener 54. ans.setText(result); 56. else if (event.getSource() == mul) { 57. oper = op1.getText(); 65. } // end actionPerformed method 69. } 42. } 43. private class ButtonHandler implements ActionListener{ 44. public void actionPerformed(ActionEvent event) { 45. String oper, result; 46. int num1, num2, res; 47. if (event.getSource() == plus) { 48. oper = op1.getText(); 49. num1 = Integer.parseInt(oper); 50. oper = op2.getText(); 51. num2 = Integer.parseInt (oper); 52. res = num1+num2; 53. result = res+""; 55 } 58. num1 = Integer.parseInt(oper); 59. oper = op2.getText(); 60. num2 = Integer.parseInt (oper); 61. res = num1*num2; 62. result = res+""; 63. ans.setText(result); 64 } 66. } // end inner class ButtonHandler 67. public static void main(String args[]) { 68. SmallCalcApp scApp = new SmallCalcApp(); 70. }// end class
  • 146.
    Web Design &Development – CS506 VU © Copyright Virtual University of Pakistan 146 Anonymous Inner Classes Same as inner class in capabilities Named – String s = “hello”; System.out.println(s); We generally use anonymous object when there is just a one time use of a particular object but in case of a repeated use we generally used named objects and use that named reference to use that objects again and again. Has no name much shorter difficult to understand Named vs. Anonymous Objects – “hello” has a named reference s. Anonymous – System.out.println(“hello”);
  • 147.
    Web Design &Development – CS506 VU © Copyright Virtual University of Pakistan 147 Example Code 13.4 Handling Window Event with Anonymous Inner Class Here we are modifying the window event code of 13.3 to show the use of anonymous inner class. 28. import java.awt.*; 29. import javax.swing.*; 30. import java.awt.event.*; 31. public class EventsEx extends WindowAdapter { 32. JFrame frame; 33. JLabel coordinates; // setting layout 34. public void initGUI ( ) { // creating event generator 35. frame = new JFrame(); 36. Container cont = frame.getContentPane(); 37. cont.setLayout(new BorderLayout( ) ); 38. coordinates = new JLabel (); // registering event handler (anonymous inner class) 52. initGUI(); 39. cont.add(coordinates, BorderLayout.NORTH); // with generator by using 40. frame.addWindowListener ( 41. new WindowAdapter ( ) { 42. public void windowClosing (WindowEvent we) { 43. JOptionPane.showMessageDialog(null, “Good Bye”); 44. System.exit(0); 45. } // end window closing 46. } // end WindowAdapter 47. ); // end of addWindowListener 48. frame.setSize(350, 350); 49. frame.setVisible(true); 50. } // end initGUI method //default constructor 51. public EventsEx ( ) { 53. } 54. public static void main(String args[]) { 55. EventsEx ex = new EventsEx(); 56. } 57. } // end class
  • 148.
    Web Design &Development – CS506 VU © Copyright Virtual University of Pakistan 148 Summary of Approaches for Handling Events To implement the above two techniques we can use Same class • putting event handler & generator in one class 1. Outer class • Putting event handlers & generator in two different classes 3. Anonymous Inner classes 1. By implementing Interfaces 2. By extending from Adapter classes Separate class 3. Inner classes R eferences Java A Lab Course by Umair Javed
  • 149.
    Web Design &Development – CS506 VU © Copyright Virtual University of Pakistan 149 Lesson 14 Java Database Connectivity Introduction Java Database Connectivity (JDBC) provides a standard library for accessing databases. The JDBC API contains number of interfaces and classes that are extensively helpful while communicating with a database. The java.sql package The java.sql package contains basic & most of the interfaces and classes. You automatically get this package when you download the J2SE™. You have to import this package whenever you want to interact with a relational database. Connecting With Microsoft Access In this handout, we will learn how to connect & communicate with Microsoft Access Database. We chooses Access because most of you are familiar with it and if not than it is very easy to learn. Create Database In start create a database “PersonInfo” using Microsoft Access. Create one table named “Person”. The schema of the table is shown in the picture. Add the following records into Person table as shown below.
  • 150.
    Web Design &Development – CS506 VU © Copyright Virtual University of Pakistan 150 Save the etup System DSN data base in some folder. (Your database will be saved as an .mdb file) S ƒ After creating database, you have to setup a system Data Source Name (DSN). DSN is a name through which your system recognizes the underlying data source. ƒ Select Start Settings Control Panel Administrative Tools Data Sources (ODBC). ƒ The ODBC Data Source Administrator window would be opened as shown below. Select System DSN tab. (If you are unable to use System DSN tab due to security restrictions on your machine, you can use the User DSN tab) ƒ Press Add… button and choose Microsoft Access Driver (*.mdb) from Create New Data Source window and press Finish button as shown in diagram. ƒ After that, ODBC Microsoft Access Setup window would be opened as shown in following diagram ƒ Enter the Data Source Name personDSN and select the database by pressing Select button. The browsing window would be opened, select the desired folder that contains the database (The database .mdb file you have created in the first step) Press Ok button.
  • 151.
    Web Design &Development – CS506 VU © Copyright Virtual University of Pakistan 151 Basic Steps in U sing JDBC There are eight (8) basic steps that must be followed in order to successfully communicate with a database. Let’s take a detail overview of all these one by one. 1. Imp t ƒ I p data import java.sql.*; or Required Package mort the package java.sql.* that contains useful classes and interfaces to access & work withbase.
  • 152.
    Web Design &Development – CS506 VU © Copyright Virtual University of Pakistan 152 2. Load Driver ƒ Need to load suitable driver for underlying database. ƒ Different drivers & types for different databases are available. ); ƒ ollowing driver. You have to download it explicitly. oracle.jdbc.driver.OracleDriver”); URL atabase (Actually we need to specify the address of the database which is in the form of URL) ƒ and we have loaded a JDBC-ODBC driver. Using d it personDSN. String conURL = “jdbc:odbc:personDSN”; . t ƒ on object. to the getConnection method. Connection con = n below: String u String p Connection con = null;con = DriverManager.getConnection(conURL, usr, pwd); 5. Create Statement Stateme Once yo arious kinds of SQL queries. 6. Execute a Query ƒ The next step is to pass the SQL statements & to execute them. ƒ Two methods are generally used for executing SQL queries. These are: es. the ƒ For MS Access, load following driver available with j2se. Class.forName(“sun.jdbc.odbc.JdbcOdbcDriver” For Oracle, load the f Class.forName(“ 3. Define Connection ƒ To get a connection, we need to specify the URL of a d As we are using Microsoft Access database JDBC-ODBC driver requires a DSN which we have created earlier and nameSo the URL of the database will be 4 Esablish Connection With DataBase Use DriverManagerto get the connecti ƒ The URL of the database is passed DriverManager.getConnection(conURL); ƒ If DataBase requires username & password, you can use the overloaded version of getConnection method as show sr = “umair”; wd = “vu”; ƒ A Statement object is obtained from a Connection object. nt stmt = con.createStatement( ); u have a statement, you can use it for v executeQuery(sql) method ƒ Used for SQL SELECT queri ƒ Returns the ResultSET object that contains the results of the query and can be used to accessquery results.
  • 153.
    Web Design &Development – CS506 VU © Copyright Virtual University of Pakistan 153 ecuteQuery(sql); executeUpdate(sql)method . This method is used for executing an update statement like INSERT, UPDATE or 7. DELETE ƒ Returns an the number of rows updated String sql = “INSERT INTO tablename ” + “(columnNames) Values (values)” ; int count = stmt.executeUpdate(sql); Process Results of the Query ƒ et maintains the data in the form tables (rows & columns) ƒ First row has index 1, not 0. ƒ The next method of ResultSet returns true or false depending upon whether the next row is available (exist) or not and moves the cursor ƒ Always remember to call next() method at-least once ƒ To retrieve the data of the column of the current row you need to use the various getters provided by the ResultSet. ƒ For example, the following code snippet will iterate over the whole ResultSet and illustrates the usage of getters methods while ( rs.next() ){ /by using column name String name = rs.getString(“columnName”); // or by using column indexString name = tString(1); } 8. Close the Connection ƒ An opening connection is expensive, postpone this step if additional database operations are e Example ResultSet String sql = “SELECT * from sometable”;ResultSet rs = stmt.ex Integer value representing ƒ The ResultSet provides various getXXX methods that takes a column index or name and returns the data The ResultS / rs.ge xpected con.close(); Code 14.1: Retrieving Data from The JdbcEx.java demonstrates the usage of all above explained steps. In this code example, we connect with the e we have created earlier, and then execute the simple SQL SELECT query on results. PersonInfo database, the onPerson table, and then process the query
  • 154.
    Web Design &Development – CS506 VU © Copyright Virtual University of Pakistan 154 // File Jd //step 1: import packageimport java.sql.*; public cla publi ng args[ ]) { try { //S driverClass.forName(“sun.jdbc.odbc.JdbcOdbcDriver”); //Step 3: define the connection URL String url = “jdbc:odbc:personDSN”; on ger.getConnection(url); //Step 5: create Statement ement(); //Step 6: preapare & execute the query FROM Person”; ResultSet rs = st.executeQuery(sql); //Step 7: process the results while(rs.next()){ // The row name is “name” in database “PersonInfo,// hence specified in the getString() method. String name = rs.getString(“name”);String add = rs.getString(“address”);String pNum = rs.getString(“phoneNum”); System.out.println(name + “ ” + add + ” ” + pNum);} //Step 8: close the connection con.close(); (Exception sqlEx){ System.out.println(sqlEx); } } // e important thing you must notice that we have put all code inside try block and then handle (in the above example, only printing the name of the exception raised) exception inside catch block. bcEx.java ss JdbcEx { c static void main (Stri tep 2: load //Step 4: establish the connectiConnection con = DriverMana Statement st = con.createStat String sql = “SELECT * }catch end main} // end class Th
  • 155.
    Web Design &Development – CS506 VU © Copyright Virtual University of Pakistan 155 Why? Because we are dealing with an external resource (database). If you can recall all IO related involving external resources in java throw exceptions. These exceptions are checked exceptions and we must need to handle these exceptions. operations Compile & Execute Since the Person table contains only three records, so the following output would be produced on executing the above program. References: . Java – . Java tutori A Lab Course by Umair Javed al by Sun: http://java.sun.com/docs/books/turorial . Beginning Java2 by Ivor Hortan
  • 156.
    Web Design &Development – CS506 VU © Copyright Virtual University of Pakistan 156 Lesson 15 More on JDBC In the pr w to execute SQL statements. In this handout, we’ll learn how to ex ods provided by the JDBC API. Before ju ets take a brief overview of executeUpdate()method that is used for executing DML statements. Useful S evious handout, we have discussed hoecute DML (insert, update, delete) statements as well some useful meth mping on to example, l tatement Methods: o executeUpdate( ) . Us ATE, or DELETE SQL statements. . Th he number of rows that were affected in the database. . . efinition Language) statements CREATE TABLE, DROP TA tc. For example, int num = stmt.executeUpdate(“DELETE from Person WHERE id = 2” ); Example Code 15.1: Executing SQL DML Statements This program will take two command line arguments that are used to update records in the database. executeUpdate( ) method will be used to achieve the purpose stated above. //step 1: import packageimport java.sql.*; public class JdbcDmlEx {public static void main (String args[ ]) { try { //Step 2: load driverClass.forName(“sun.jdbc.odbc.JdbcOdbcDriver”); //Step 3: define the connection URL String url = “jdbc:odbc:personDSN”; //Step 4: establish the connection Connection con = DriverManager.getConnection(url); // assigning first command line argument value String addVar = args[0]; // assigning second command line argument value ed to execute for INSERT, UPDis method returns t Also supports DDL (Data DBLE, and ALERT TABLE e // File JdbcDmlEx.java //Step 5: create Statement Statement st = con.createStatement();
  • 157.
    Web Design &Development – CS506 VU © Copyright Virtual University of Pakistan 157 String nameVar = args[1]; // preparing query – nameVar & addVar strings are embedded // into query within ‘” + string + “’ String sql = “UPDATE Person SET address = ‘”+addVar+”’” + “ WHERE name = ‘”+nameVar+”’ ”; // executing query int num = st.executeUpdate(sql); // Step 7: process the results of the query // printing number of records affected System.out.println(num + “ records updated”); //Step 8: close the connection con.close(); }catch(Exception sqlEx){ System.out.println(sqlEx); } } // end main} // end class ompil Exe Ce &cute The Person table is shown in the following diagram before execution of the program. We want to update first row i.e address of the person ali. The next diagram shows how we have executed our program. We passed it two arguments. The first one is the address (defence) and later one is the name (ali) of the person against whom we want to update the address value.
  • 158.
    Web Design &Development – CS506 VU © Copyright Virtual University of Pakistan 158 The Per n after the execution of the program. Notice that address of the ali is now ch sotable is shown in the following diagramanged to defence. No When w tabase explicitly to mak But in the above code, you have never seen such act that java will implicitly commit the changes. However, we can change this java behavior to manual commit. We will cover these in some la Useful t.): te e execute DML statements (insert, update, delete) we have to commit it in the da e the changes permanent or otherwise we can rollback the previously executed statements. a statement. This is due to the f ter handout. Statement Methods (con . Used for determines the number of rows a ResultSet may contain . are unlimited (return value is 0), or by using setMaxRows(int), the number of rows can be specified. o tQueryTimeOut (int) . Retrieves the number of seconds the driver will wait for a Statement object to execute. seconds, zero means there is no limit . If the limit is exceeded, a SQLException is thrown if o getMaxRows / setMaxRows(int) By default, the number of rows getQueryTimeOut / se . The current query time out limit in Dferent Types of Statements . n the previous handout that through Statement objects, SQL queries are sent to the databases. . Three types of Statement objects are available. These are; As we have discussed i
  • 159.
    Web Design &Development – CS506 VU © Copyright Virtual University of Pakistan 159 1. Statement -The Statement objects are used for executing simple SQL statements. -We have already seen its usage in the code examples. ent for executing precompiled SQL statements and passing in different parameters to it. about it in detail shortly. 3. C - procedures. - ava tutorial on it if you are interested in learning it. Prepared 2. PreparedStatem -The PrepaeredStatement are used - We will talk allableStatement Theses are used for executing storedWe are not covering this topic; See the J Statements ƒ What if we want to execute same query multiple times by only changing parameters. ƒ PreparedStatement object differs from Statement object as that it is used to create a statement in standard form that is sent to database for compilation, before actually being used. ƒ Each time you use it, you simply replace some of the marked parameters (?) using some setter methods. ƒ W nnection class. T is pa Prepa ” ); ƒ Notices that we used marked parameters (?) in query. We will replace them later on by using various setter methods. ƒ If we want to replace first ? with String value, we use setString method and to replace second ? with i his is shown in the following code snippet. pStmt.setString (1 , stringValue); pStmt.setInt (2 , intValue) Note . Next, call executeUpdate (for INSERT, UPDATE or ETE queries) or executeQuery (for simp pStmt.executeUpdate(); e can create PreparedStatement object by using prepareStatementmethod of the cohe SQL query ssed to this method as an argument as shown below. redStatement pStmt = con.prepareStatement (“UPDATE tableName SET columnName = ? ” + “WHERE columnName = ? nt value, we use setInt method. T : The first market parameter has index 1. we can DELle SELECT query) method.
  • 160.
    Web Design &Development – CS506 VU © Copyright Virtual University of Pakistan 160 Modify E This exam the last example code (JdbcDmlEx.java).The modifications are highlighte // File JdbcDmlEx.java //step 1 l.*; public s JdbcDmlEx {public static void main (String args[ ]) { try { //Step 2: load driverClass.forName(“sun.jdbc.odbc.JdbcOdbcDriver”); //Step 3: define the connection URL String url = “jdbc:odbc:personDSN”; l, ””, ””); // make query and place ? where values are to //be inserted later String sql = “UPDATE Person SET address = ? “ + “ WHERE name // assigning first command line argument valueString addVar = args[0]; // assigning second command line argument valueString nameVar = args[1]; // setting first marked parameter (?) by using setString()// method to address. pStmt.setString(1 , addVar); // setting second marked parameter(?) by using setString()// method to name pStmt.setString(2 , nameVar); // suppose address is “defence” & name is “ali” // by setting both marked parameters, the query will look // like: // sql = “UPDATE Person SET address = “defence” // WHERE name = “ali” ” // executing update statemnt int num = pStmt.executeUpdate(); xample Code 15.1: Executing SQL DML using Prepared Statements ple code is modification to d as bold face. : import packageimport java.sqclas //Step 4: establish the connection Connection con = DriverManager.getConnection(ur = ? ”; // creating statement using Connection object and passing // sql statement as parameter PreparedStatement pStmt = con.prepareStatement(sql);
  • 161.
    Web Design &Development – CS506 VU © Copyright Virtual University of Pakistan 161 // Step 7: process the results of the query// printing number of records affectedSystem.out.println(num + “ re ”); //Step 8: close the connection con.close(); }catch(Exception sqlEx){ System.out.println(sqlEx); } } // ompile & Execute cords updated end main} // end class C Execute this code in a similar way as we showed you in execution of the last program. Don’t forget to pass the address & name values as the command line arguments. References: Entire material for this handout is taken from the book JAVA A Lab Course by Umair Javed. This mat Web Design and Development and not for any other commercial purpose without the consent of author. eri al is available just for the use of VU students of the course
  • 162.
    Web Design &Development – CS506 VU © Copyright Virtual University of Pakistan 162 Lesson 16 Result Set This handout will familiarize you with another technique of inserting, updating & deleting rows. Before moving on, first we look at ResultSet. ResultSet – A Represented by a table with rows and columns First row has index 1 ResultSet contains the results of the SQL query Maintains a cursor pointing to its current row of data. Initially the cursor positioned before the row (0). Default ResultSet . A default ResultSet object is not updatable and has a cursor that moves forward only. . You can iterate over through it only once and only from the first row to last row. U . For a quick overview, here how we create a default ResultSet object. ; PreparedStatement pStmt = con.prepareStatement(sql); ResultSet rs = pStmt.executeQuery( ); Useful ResultSet’s Methods . ntil now, we have worked & used it in various examples. String sql = “SELECT * FROM Person” Following methods are used often to wor et object. We already seen and used some of them in code examples. k with default ResultS
  • 163.
    Web Design &Development – CS506 VU © Copyright Virtual University of Pakistan 163 ƒ next( ) -Attempts to move to the next row in the ResultSet, if available -The next() method returns true or false depending upon whether the next row is available (exist) or not. initially tioned before first row. ƒ getters -To retrieve the data of the column of the current row you need to use the various getters provided by the ResultSet -These getters return the value from the column by specifying column name or column index. -For example, if the column name is “Name” and this column has index 3 in the ResultSet object, then we can retrieve the values by using one of the following methods: e = rs.getString(“Name”);String name = ); -These gett her types like getInt( ),getDouble( ) etc. Consult the Java API documentation for more references. No dex 1, NOT zero (0). ƒ -Used to release the JDBC and database resources -The ResultSet is implicitly closed when the associated Statement object executes a new query or closed Updatable and/or Scrollable ResultSet -Before retrieving any data from ResultSet, always remember to call next()at least once because cursor is posi String namrs.getString(3 er methods are also available for ot te: Remember that first column has an in close( ) by method call. ƒ It is possible to produce ResultSet objects that are scrollable and/or updatable (since JDK 1.2) ƒ p of such ResultSet, it is possible to move forward as well as backward with in ƒ Another advantage is, rows can be inserted, updated or deleted by using updatable ResultSet object. esultSet The following code fragment, illustrates how to make a ResultSet object that is scrollable and updatable. With the hel RestultSetobject. Creating Updatable & Scrollable R
  • 164.
    Web Design &Development – CS506 VU © Copyright Virtual University of Pakistan 164 String sql = “SELECT * FROM Person”; tSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR _UPDATABLE); eQuery( ); constants have been used of ResultSet class for producing a ResultSet rs that is scrollable, will not show changes made by others and will be updatable Useful ResultSet’s Methods (cont.) PreparedStatement pStmt = con.prepareStatement(sql,Resul ResultSet rs = pStmt.execut Two The methods discussed in this section can only be used with updatable/scrollable ResultSet object. . previous( ) -Moves the cursor to the previous row in the ResultSet object, if available -Returns true if cursor is on a valid row, false it is off the result set. -Throws exception if result type is TYPE_FORWARD_ONLY. Example Code 16.1: Use of previous( ), next( ) & various getters methods The ResultSetEx.java shows the use of previous, next and getters methods. We are using the same Person table of PersonInfo database, the one we had created earlier in this example and later on. 1 // File ResultSetEx.java 2 import java.sql.*; 3 public class ResultSetEx { 4 public static void main (String args[ ]) { 5 try { 6 7 8 9 10 //Step 4: establish the connection 11 Connection con = DriverManager.getConnection(url); 12 //Step 5: creating PrepareStatement by passing sql and 13 //ResultSet’s constants so that the ResultSet that will 14 15 //scrollable & updatable 16 ”; 17 PreparedStatement pStmt = con.prepareStatement(sql, 18 ResultSet.TYPE_SCROLL_INSENSITIVE, 19 ResultSet.CONCUR_UPDATABLE); 20 21 //Step 2: load driver Class.forName(“sun.jdbc.odbc.JdbcOdbcDriver”); //Step 3: define the connection URL String url = “jdbc:odbc:personDSN”; //produce as a result of executing query will be String sql = “SELECT * FROM Person //Step 6: execute the query ResultSet rs = pStmt.executeQuery();
  • 165.
    Web Design &Development – CS506 VU © Copyright Virtual University of Pakistan 165 22 23 rs.next( ); 24 current row (first) 25 rward”); 26 String name = rs.getString(“Name”); 27 System.out.println(name); 28 // moving cursor forward i.e. on to second row 29 rs.next( ); 30 // moving cursor ba 31 rs.previous( ); 32 // printing column “name” value of current row (first) 33 System.out.println(“moving cursor forward”); 34 name = rs.getString(“Name”); 35 System.out.println(name); 36 //Step 8: close the connection 37 con.close(); 38 }catch(Exception sqlEx){ 39 System.out.println(sqlEx); 40 } 41 } // end main 42 43 } // end class Compile & Execute: : // moving cursor forward i.e. first row // printing column “name” value of System.out.println(“moving cursor fo ckward i.e to first row The sample output is given below Useful ResultSet’s Methods (cont.) ƒ -Moves the cursor to the given row number in the ResultSetobject. -If g ves the cursor forward with respect to beginning of the result set. -If t , the cursor moves to the absolute row position with respect to the absolute(int) iven row number is positive, mo he given row number is negative end of the result set.
  • 166.
    Web Design &Development – CS506 VU © Copyright Virtual University of Pakistan 166 -For example, calling absolute(-1) positions the cursor on the last row; calling absolute(-2) moves the -last row, and so on. -Throws Exception if ResultSet type is TYPE_FORWARD_ONLY ƒ updaters (for primitives, String and Object) -Used to update the column values in the current row or in insert row (discuss later) -Do not update the underlying database -Each update method is overloaded; one that takes column name while other takes column index. For example String updater are available as: updateString(String columnName, String value) updateString(String columnIndex, String value) ƒ updateRow( ) -Updates the underlying database with new contents of the current row of this ResultSetobject Example Code 16.2: Updating values in existing rows cursor to next-t o The following code example updates the Name column in the second row of the ResultSet object rs and then uses the method updateRow to update the Person table in database. This code is the modification of the last one. Changes made are shown in bold face. 1 // File ResultSetEx.java 2 import java.sql.*; 3 public class ResultSetEx { 4 public static void main (String args[ ]) { 5 try { 6 //Step 2: load driver 7 Class.forName(“sun.jdbc.odbc.JdbcOdbcDriver”); 8 //Step 3: define the connection URL 9 String url = “jdbc:odbc:personDSN”; 10 //Step 4: establish the connection 11 Connection con = DriverManager.getConnection(url); 12 //Step 5: create PrepareStatement by passing sql and 13 // ResultSet appropriate fields 14 String sql = “SELECT * FROM Person”; 15 PreparedStatement pStmt = con.prepareStatement(sql, 16 ResultSet.TYPE_SCROLL_INSENSITIVE, 17 ResultSet.CONCUR_UPDATABLE); 18 //Step 6: execute the query 19 ResultSet rs = pStmt.executeQuery();
  • 167.
    Web Design &Development – CS506 VU © Copyright Virtual University of Pakistan 167 20 // moving cursor to second row 21 rs.absolute(2); 22 lumn of 2nd row in rs 23 24 25 26 27 28 tion sqlEx){ 29 System.out.println(sqlEx); 30 31 } // end main 32 } // end class Compile & Execute Given below are two states of Person table. Notice that address of 2nd row is updated. Person table: Before execution // update address co rs.updateString(“Address”, “model town”); // update the row in database rs.updateRow( ); //Step 8: close the connection con.close(); }catch(Excep } Person table: After execution
  • 168.
    Web Design &Development – CS506 VU © Copyright Virtual University of Pakistan 168 Useful ResultSet’s Methods (cont.) . moveToInsertRow(int) -An updatable resultset object has a special row associate with it i.e. insert row -Insert row – a buffer, where a new row may be constructed by calling updater methods. -Doesn’t insert the row into a result set or into a databse. -For example, initially cursor is positioned on the first row as shown in the diagram. -Bng moveToInsertRow( ), the cursor is m y calli oved to insert row as shown below. Now by calling various updates, we can insert values into the columns of insert row as shown nser the current row into this ResultSet object and into the database too. belo w. . insertRow ( ) -Its the contents of
  • 169.
    Web Design &Development – CS506 VU © Copyright Virtual University of Pakistan 169 -Moves the cursor back to the position where it was before calling moveToInsertRow() given below diagram Note: The cursor must be on the insert row before calling this method or exception would be raised. Example Code 16.3: Inserting new row -This is shown in the The following code example illustrates how to add/insert new row into the ResultSet as well into the database. This code is the modification of the last one. Changes made are shown in bold face. 1 // File ResultSetEx.java 2 import java.sql.*; 3 public class ResultSetEx { 4 public static void main (String args[ ]) { 5 try { 6 d driver 7 Class.forName(“sun.jdbc.odbc.JdbcOdbcDriver”); 8 9 String url = “jdbc:odbc:personDSN”; 10 11 nection(url); 12 //Step 5: create PrepareStatement by passing sql and 13 ultSet appropriate fields 14 String sql = “SELECT * FROM Person”; 15 PreparedStatement pStmt = con.prepateStatement(sql, 16 ResultSet.TYPE_SCROLL_INSENSITIVE, 17 ResultSet.CONCUR_UPDATABLE); 18 //Step 6: execute the query 19 ResultSet rs = pStmt.executeQuery(); 20 // moving cursor to insert row 21 22 23 rs.updateString( “Name” , “imitiaz” ); 24 rs.updateString( “Address” , “cantt” ); 25 rs.updateString( “phoneNum” , “9201211” ); //Step 2: loa //Step 3: define the connection URL //Step 4: establish the connection Connection con = DriverManager.getCon // Res rs.moveToInsertRow(); // updating values in insert row
  • 170.
    Web Design &Development – CS506 VU © Copyright Virtual University of Pakistan 170 26 // inserting row in resultset & into database 27 rs.insertRow( ); 29 con.close(); 32 } ven b er executing program, a newly added row is sent. tion 28 //Step 8: close the connection 30 }catch(Exception sqlEx){ 31 System.out.println(sqlEx); 33} // end main 34 } // end class Compile & Execute Gielow are two states o f Person table. Note that aft pre Person table: Before execu Person table: After execution
  • 171.
    Web Design &Development – CS506 VU © Copyright Virtual University of Pakistan 171 Useful ResultSet’s Methods (cont.) . last( ) & first( ) -Moves the cursor to the last & first row of the ResultSetobject respectively. -Throws exception if the ResultSet is TYPE_FORWARD_ONLY . getRow( ) -Returns the current row number -As mentioned earlier, the first row has index 1 and so on. . deleteRow( ) row from this ResultSet object and from the underlying database. -Throws exception if the cursor is on the insert row. Example Code 16.4: Deleting existing row -Deletes the current The given below example code shows the usage of last( ), getRow( ) and deleteRow( ) method. This code is also the modification of the last one. Changes made are shown in bold face. 1 // File ResultSetEx.java 2 import java.sql.*; 3 public class ResultSetEx { 4 public static void main (String args[ ]) { 5 try { 6 //Step 2: load driver 7 Class.forName(“sun.jdbc.odbc.JdbcOdbcDriver”); 8 //Step 3: define the connection URL 9 String url = “jdbc:odbc:personDSN”; 10 //Step 4: establish the connection 11 Connection con = DriverManager.getConnection(url); 12 //Step 5: create PrepareStatement by passing sql and 13 // ResultSet appropriate fields 14 String sql = “SELECT * FROM Person”; 15 PreparedStatement pStmt = con.prepateStatement(sql, 16 ResultSet.TYPE_SCROLL_INSENSITIVE, 17 ResultSet.CONCUR_UPDATABLE); 18 //Step 6: execute the query 19 ResultSet rs = pStmt.executeQuery(); 20 // moves to last row of the resultset 21 rs.last(); 22 // retrieving the current row number 23 int rNo = rs.getRow();
  • 172.
    Web Design &Development – CS506 VU © Copyright Virtual University of Pakistan 172 24 System.out.println(“current 25 // delete current row from rs & db i.e. 4 because 26 // previously we have called last() method 27 rs.deleteRow( ); 28 //Step 8: close the connection 29 con.close(); 30 }catch(Exception sqlEx){ 31 System.out.println(sqlEx); 32 } 33 } // end main 34 } // end class ompile & Execute he first diagram shows the Person table before execution. Person table: Before execution row number” + rNo); C T Execution program from command prompt will result in displaying current row number on console. This can be confirmed from following diagram. After execution, the last row (4) is deleted from ResultSet as well as from database. The Person table is shown after execution
  • 173.
    Web Design &Development – CS506 VU © Copyright Virtual University of Pakistan 173 Person table: After execution References: Entire material for this handout is taken from the book JAVA A Lab Course by Umair Javed. This material is available just for the use of VU students of the course Web Design and Development and not . for any other commercial purpose without the consent of author
  • 174.
    Web Design &Development – CS506 VU © Copyright Virtual University of Pakistan 174 Lesson 17 Meta Data rmation) about data. The actual data has no meaning without tenc are listed some numeric values In simple terms, Meta Data is data (info exise of Meta data. To clarify this, let’s look at an example. Given below What this information about? We cannot state accurately. These values might be representing some one’s salaries, price, tax payable & utility bill etc. But if we specify Meta data about this data like shown below: Now, just casting a glance on these values, you can conclude that it’s all about some ones salaries. ResultSet Meta data ResultSet Meta Data will help you in answering such questions -Ho columns are in the ResultSet? -Wh -Ar -Wh n? -Wh -Ca m a ry() ), derive a ResultSetMetaData object by calling eta pet (here rsis a valid ResultSetobject): etaData(); w many at is the name of given column? e the column name case sensitive? at is the data type of a specific colum at is the maximum character size of a column? n you search on a given column? Creating ResultSetMetaData object FroResultSet (the return type of executeQue getMData() method as shown in the given code snip ResultSetMetaData rsmd = rs.getM Now, rsmd can be used to look up number, names & types of columns
  • 175.
    Web Design &Development – CS506 VU © Copyright Virtual University of Pakistan 175 Useful ResultSetMetaData methods . getColumnCount ( ) – Returns the number of columns in the result set ColumnDisplaySize (int) olumn in characters getColumnLabel (int) ame of the column – The getColumnLabel() method returns the suggested column label for printouts (int) Ret he column to compare against types in java.sql.Types mp ultSetMetaData . get – Returns the maximum width of the specified c . getColumnName(int) / – The getColumnName() method returns the database n . getColumnType – urns the SQL type for t Exale Code 17.1: Using R es The MetaDataEx.java will print the am column names by using ResultSetMetaData object and column values ons ple of the scenario where we have no idea about the column names in ance te: F for the coming ones, we are using the same database (PersonInfo) the one created e anges are shown in bold face //Step 2: load driver “sun.jdbc.odbc.JdbcOdbcDriver”); the connection 11 Connection con = null; 12 con = DriverManager.getConnection(url, “”, “”); 13 //Step 5: create PrepareStatement by passing sql and 14 // ResultSet appropriate fields 15 String sql = “SELECT * FROM Person”; 16 PreparedStatement pStmt = con.prepateStatement(sql, 17 ResultSet.TYPE_SCROLL_INSENSITIVE, 18 ResultSet.CONCUR_UPDATABLE); 19 //Step 6: execute the query 20 ResultSet rs = pStmt.executeQuery(); 21 // get ResultSetMetaData object from rs 22 ResultSetMetaData rsmd = rs.getMetaData( ); 23 // printing no. of column contained by rs 24 int numColumns = rsmd.getColumnCount(); 25 System.out.println(“Number of Columns:” + numColumns); 26 // printing all column names by using for loop 27 String cName; on cole. This is an excellent ex adv Noor this example code andarlier and repeatedly used. Ch we 1 // File MetaD ataEx.java 2 import java.sql.*; 3 public class MetaDataEx { 4 pub lic static void main (String args[ ]) { 5 try { 6 7 Class.forName( 8 //Step 3: define the connection URL 9 String url = “jdbc:odbc:personDSN”; 10 //Step 4: establish
  • 176.
    Web Design &Development – CS506 VU © Copyright Virtual University of Pakistan 176 28 for(int i=1; i<= numColumns; i++) { 29 cName = rsmd.getColumnName(i); 30 System.out.println(cName); 31 System.out.println(“t”); 32 } 33 // changing line or printing an empty string 34 System.out.println(“ ”); 35 // printing all values of ResultSet by iterating over it 36 String id, name, add, ph; 37 while( rs.next() ) 38 { 39 id = rs.getString(1); 40 name = rs.getString(2); 41 add = rs.getString(3); 42 ph = rs.getString(4); 43 System.out.println(id); 44 System.out.println(“t”); 47 System.out.println(add); 48 49 50 51 52 3 con.close(); 55 System.out.println(sqlEx); C T on of this program. The database and the output are shown below: 45 System.out.println(name); 46 System.out.println(“t”); System.out.println(“t”); System.out.println(ph); System.out.println(“ ”); } //Step 8: close the connection 5 54 }catch(Exception sqlEx){ 56 } 57 } // end main101.} // end class ompile & Execute: he database contains the following values at the time of executi
  • 177.
    Web Design &Development – CS506 VU © Copyright Virtual University of Pakistan 177 DataB aseMetaData DataBa ng such questions ƒ uct? i be derived. The following code snippet n ataBaseMetaDataobject. n , usr, pwd); ta ata(); y the database. u f the database’s product name u is database product u he name of the JDBC driver used to established the connection a – Retri s database is in read-only mode u s true if so, false otherwise se Meta Data will help you in answeri ƒ What SQL types are supported by DBMS to create table? What is the name of a database prod ƒ What is the version number of this database product? ƒ What is the name of the JDBC driver that is used? ƒ Is the database in a read-only mode? Creat ng DataBaseMetaData object From a Connection object, a DataBaseMetaData object can demo strates how to get D Con ection con= DriverManager.getConnection(url Da BaseMetaData dbMetaData = con.getMeataD Now, ou can use the dbMetaData to gain information about Usefu l ResultSetMetaData methods . getD atabaseProductName( ) – Ret rns the name o . getD atabaseProductVersion( ) – Ret rns the version number of thrName( ) . getD– Ret riverns t . isRe dOnly( ) eves whether thi – Ret rn
  • 178.
    Web Design &Development – CS506 VU © Copyright Virtual University of Pakistan 178 Example Code 17.2: using DataBaseMetaData This code is modification of the example code 17.1. Changes made are shown in bold face. 102.// File MetaDataEx.java 103.import java.sql.*; 104.public class MetaDataEx { 105. public static void main (String args[ ]) { 106. try { 107. //Step 2: load driver 108. Class.forName(“sun.jdbc.odbc.JdbcOdbcDriver”); 109 110. 11. e connection 12. Connection con = null; 113. n(url, “”, “”); 114. 115. DataBaseMetaData dbMetaData = con.getMetaData(); 116. // printing database product name 117. eProductName(); 118. System.out.println(“DataBase: ” + pName); 119. // printing database product version abaseProductVersion(); 122. // printing driver name used to establish connection & 123. // to retrieve data ta.getDriverName(); 125. System.out.println(“Driver: ” + dName); 126. 127. b 128. S 129. // you can create & execute statements and can 130. // process results over here if needed 131. //Step 8: close the connection 132. con.close(); 133. }catch(Exception sqlEx){ 134. System.out.println(sqlEx); 135. } 136. } // end main 137. } // end class . //Step 3: define the connection URL String url = “jdbc:odbc:personDSN”; 11 //Step 4: establish th con = DriverManager.getConnectio// getting DataBaseMetaDat object Sring pName = dbMetaData.getDatabas 120. Sring pVer = dbMetaData.getDat121. System.out.println(“Version: ” + pVer); 124. Sring dName = dbMetaDa // printing whether database is read-only or not oolean rOnly = dbMetaData.isReadOnly(); ystem.out.println(“Read-Only: ” + rOnly);
  • 179.
    Web Design &Development – CS506 VU © Copyright Virtual University of Pakistan 179 Compile & Execute On executing the above program, the following output will produce: JDBC Driver Types ƒ JDBC Driver Types are divided into four types or levels. ƒ Each type defines a JDBC driver implementation with increasingly higher level of platform Type – 1: JDBC – ODBC Bridge Type 2: Native – API/partly Java driver Type 3: Net – protocol/all–Java driver Type 4: Native – protocol/all–Java driver Now, let’s look at each type in more detail them to the ODBC Driver - independence, performance, deployment and administration. The four types are: Type – 1: JDBC – ODBC Bridge -Translates all JDBC calls into ODBC (Open Database Connectivity) calls and send Generally used for Microsoft database. -Performance is degraded
  • 180.
    Web Design &Development – CS506 VU © Copyright Virtual University of Pakistan 180 4. Type – 2: Native – API/partly Java driver -Converts JDBC calls into database-specific calls such as SQL Server, Informix, Oracle or Sybase. -Partly-Java drivers communicate with database-specific API (which may be in C/C++) using the Java Native Interface. -Significantly better Performance than the JDBC-ODBC bridge 4. Type – 3: Net – protocol/all–Java driver -Follows a three-tiered approach whereby the JDBC database requests ()are passed through the network to the middle-tier server -Pure Java client to server drivers which send requests that are not database-specific to a server that translates them into a database-specific protocol. . -If the middle-tier server is written in java, it can use a type 1or type 2JDBC driver to do this
  • 181.
    Web Design &Development – CS506 VU © Copyright Virtual University of Pakistan 181 4. Type – 4: Native – protocol / all – java driver -Converts JDBC calls into the vendor-specific DBMS protocol so that client application can communicate directly with the database server plemented in Java to achieve platform independence and eliminate deployment issues. -Per m -Completely im forance is typically very good
  • 182.
    Web Design &Development – CS506 VU © Copyright Virtual University of Pakistan 182 On – Line Resources • Sun’s JDBC Site http://java.sun.com/products/jdbc/ • JDBC Tutorial tp://java.sun.com/docs/books/tutorial/jdbc/ ht • List of available JDBC Drivers http://industry.java.sun.com/products/jdbc/drivers/ • RowSet Tutorial http://java.sun.com/developer/Books/JDBCTutorial/chapter5.html • JDBC RowSets Implementation Tutorial http://java.sun.com/developer/onlineTraining/ Database/jdbcrowsets.pdf References: • Java API documentation 5.0 • Java – A Lab Course by Umair Javed • JDBC drivers in the wild http://www.javaworld.com/javaworld/jw-07-2000/jw-0707-jdbc_p.html
  • 183.
    Web Design &Development – CS506 VU © Copyright Virtual University of Pakistan 183 Lesson 18 Java Graphics Painting Window is like a painter’s canvas. All window paints on the same surface. More importantly, windows don’t remember what is under them. There is a need to repaint when portions are newly exposed. Java components are also able to paint themselves. Most of time, painting is done automatically. However sometimes you need to do drawing by yourself. Anything else is programmer responsibility How painting works? Let’s take windows example. Consider the following diagram in which the blue area is representing the desktop. The one frame (myApp) is opened in front of desktop with some custom painting as shown below. myApp consist of a JPanel. The JPanel contains a JButton. Two rectangles, a circle & a lines are also drawn on the JPanel.
  • 184.
    Web Design &Development – CS506 VU © Copyright Virtual University of Pakistan 184 After opening notepad and windows explorer window, diagram will look like this: Lets shuts off the windows explorer, the repaint event is sent to desktop first and then to myApp. The figure shown below describes the situation after desktop repaint event get executed. Here you can clearly see that only desktop repaints itself and window explorer remaining part is still opened in front of myApp.
  • 185.
    Web Design &Development – CS506 VU © Copyright Virtual University of Pakistan 185 The following figure shows the situation when myApp’s JPanel calls its repaint method. Notice that some t repaint event is sent to it. Next, JPanel forwards repaint event to JButton that causes the button to be displayed in its original form. portion of window explorer is still remains in front of JButton because yet no
  • 186.
    Web Design &Development – CS506 VU © Copyright Virtual University of Pakistan 186 This is all done automatically and we cannot feel this process cause of stunning speed of modern compthat performs all these steps in flash of eye. uters Painting a Swing Component Three methods are at the heart of painting a swing component like JPanel etc. For instance, paint() gets called when it's time to render -- then Swing further factors the paint() call into three separate methods, which are invoked in the following order: — protected void paintComponent(Graphics g) — protected void paintBorder(Graphics g) — protected void paintChildren(Graphics g) ) to paint. Lets look at these methods in order in which they get executed paomponet( ) intC — it is a main method for painting — By default, it first paints the background — After that, it performs custom painting (drawing circle, rectangles etc.) paintBorder( ) Tells the components border (if any — — It is suggested that you do not override or invoke this method paintChildern( ) — Tells any components contained by this component to paint themselves — It is suggested that you do not override or invoke this method too.
  • 187.
    Web Design &Development – CS506 VU © Copyright Virtual University of Pakistan 187 ing methods calls Example: Understand Consider the following figure The figure above illustrates ich each component that inherits from JC e background and performing custom painting is perfor In Figure 3 – paintBorder is get called And finally in figure 4 – paintChildern is called that causes the JButto important thing to note here is for JButton (since it is a JComponent), all thes metho Yo the order in wh omponent paint itself. Figure 1 to 2 --painting th med by the paintComponent method n to render itself. Note: The e ds are also called in the same order. ur Painting Strategy You must follow the three steps in order to perform painting. Subclass JPanel – class MyPanel extends JPanel – Doing so MyPanel also becomes a JPanle due to inheritance Override the paintComponent(Graphics g) method – Inside method using graphics object, do whatever drawing you want to do Install that JPanel inside a JFrame – When frame becomes visible through the paintChildren() method your panel become visible – To become visible your panel will call paintComponent() method which will do your custom drawing
  • 188.
    Web Design &Development – CS506 VU © Copyright Virtual University of Pakistan 188 Example Code 18.1: Suppose, we want to draw one circle & rectangle and a string “Hello World”. The first step is building a cl anel. The following class MyPanel is fulfilling this requirement. p o override in this class. The sample code is given below // importing requ port java.awt.*; // extending class from JPanelpu { // overriding p public void pa g){ // erasing r all the// previous painting super.paintComponent(g); // Down cas DGraphics2D g2 = (Graphics2D)g; // drawing rectanle g2.drawRe 0); // changin g2.setColo // drawing filled oval with // draw }// end pain } // end MyPan ass that inherits from JPaintComponent( ) method is als ired packagesimport javax.swing.*;im blic class MyPanel extends JPanelaintComponent method intComponent(Graphicsbehaviour – this will clea ting Graphics object to Graphics2 ct(20,20,20,2 g the color to blue r(Color.blue); color i.e. blueg2.fillOval(50,50,20,20); ing stringg2.drawString("Hello World", 120, 50); tComponent el class
  • 189.
    Web Design &Development – CS506 VU © Copyright Virtual University of Pakistan 189 The Test class that contains the main method as well uses MyPainel (previously built) class is given below // importing required packages import javax.swing.*; import java.awt.*; public class Test { JFrame f; // declaring Reference of MyPanel class MyPanel p; // parameter less constructor public Test(){ f = new JFrame(); Container c = f.getContentPane(); c.setLayout(new BorderLayout()); // instantiating reference p = new MyPanel(); // adding MyPanel into container c.add(p); f.setSize(400,400); f.setVisible(true); f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); } // end constructor // main method public static void main(String args[ ]){ Test t = new Test(); }
  • 190.
    Web Design &Development – CS506 VU © Copyright Virtual University of Pakistan 190 Note: Here we have used only some methods (drawRect( ) & fillOval( ) etc. ) of Graphics class. F complete list, see the Java API documentation or a
  • 191.
    Web Design &Development – CS506 VU © Copyright Virtual University of Pakistan 191 Lesson 19 How to Animate? If we want to animate something like ball, moving from one place to another, we constantly need to call paintComponent( ) method and to draw the shape (ball etc.) at new place means at new coordinates. Painting is managed by system, so calling paintComponent() directly is not recommended at all. Similarly calling paint( ) method is also not recommended. Why? Because such code may be invoked at times when it is not appropriate to paint -- for instance, before the component is visible or has access to a valid Graphics object. Java gives us a solution in the from of repaint( ) method. Whenever we need to repaint, we call this method that in fact makes a call to paint( ) method at appropriate time. Problem & Solution present in example code 18.1 (last example) when a mouse is dragged ƒ When a mouse is clicked find the co-ordinates of that place and paint Rectangle at that place by ead of Hard-coding the position of co-ordinates uses some variables. For example mx, my tangle by passing hard-coded values like 20 0); at a new ƒ nis game (during lecture). Now, what to do code the paddle ƒ le. We are doing it using mouse, try it using mouse. Exam Th oduced when mouse is dragged from one location to anther ƒ What to do to move the shapes ƒ First time painting is what we already have done requesting, using repaint() call ƒ Here inst – In the last example code, we draw a recg.drawRect(20,20,20,2 – Now, we’ll use variables so that change in a variable value causes to display a rectangle location g.drawRect(mx,my,20,20; Similarly, you have seen a tenmovement. In the coming up examp ple Code 19.1 e following outputs were pr
  • 192.
    Web Design &Development – CS506 VU © Copyright Virtual University of Pakistan 192 First we examine the MyPanel.java class that is drawing a filled rectangle. import jav t.*; // exten // variables used to draw rectangles at different//locations int m int m // overriding paintComponent method public void paintComponent(Graphics g){ // erasing behaviour – this the// previous painting super.paintComponent(g); // Down casting Graphics object to Graphics2D // changing the color to blue stance variablesg2.fillRect(mX,mY,20,20); }// en The Test // importing required packagesimport javax.swing.*;import java.awt.*; public cla ax.swing.*;import java.awding class from JPanelpublic class MyPanel extends JPanel { X = 20; Y = 20; will clear all Graphics2D g2 = (Graphics2D)g; g2.setColor(Color.blue); // drawing filled oval with color i.e. blue// using in d paintComponent class is given below. Additionally this class also contains the code for handling mouse events. ss Test {
  • 193.
    Web Design &Development – CS506 VU © Copyright Virtual University of Pakistan 193 JFra MyPanel class MyPanel p; // parameter less constructor C ntPane(); c.setLayout(new BorderLayout()); // instantiating reference // adding MyPanel into container f.setSize f.setVisi // creating inner class object Handler h = new Handler(); // registering MyPanel to handle events p.addMouseMotionListner(h); } // end constructor // inner class used for handling events public class Handler extends MouseMotionAdapter{ // capturing mouse dagged events public void mouseDragged(MouseEvent me){ // getting the X-Position of mouse and assigning// value to instance variable mX of MyPanel class p.mX = me.getX(); // getting the Y-Position of mouse and assigning// value to instance variable mX of MyPanel class p.mY = me.getY(); // call to repaint causes rectangle to be drawn on// new location me f; // declaring Reference of public Test(){ f = new JFrame(); ontainer c = f.getConte p = new MyPanel(); c.add(p); (400,400); ble(true); f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  • 194.
    Web Design &Development – CS506 VU © Copyright Virtual University of Pakistan 194 p.repaint() ; } // end mouseDragged } // end Handler class // main method public static void main(String args[ ]){ Test t = new Test(); } } // end MyPanel class On executing this program, when you drag mouse from one location to another, rectangle is also in sink with the movement of mouse. Notice that previously drawn rectangle is erased first. If we exclude or comment out the following line from MyPanel class sup Dragging a mouse will produce a similar kind of output shown next er.paintComponent(g);
  • 195.
    Web Design &Development – CS506 VU © Copyright Virtual University of Pakistan 195 Example Code 19.2: Ball Animation The ball is continuously moving freely inside the corner of the frames. The sample outputs are shown below: First we examine the MyPanel.java class that is drawing a filled oval. import j va.awt.*; // extending blic class MyPanel extends JPanel { // va oval at different locations int m int m // overriding paintComponent method publ / s painting super.paintComponent(g); / G Graphics2D)g; // changing the color to blue g2.setColor(Color.blue); // drawing filled oval with blue color // using instance variables g2.fillOval(mX,mY,20,20); } } end of MyP avax.swing.*;import jaclass from JPanelpu riables used to drawX = 200; Y = 0; ic void paintComponent(Graphics g){ / erasing behaviour – this will clear all the// previou/ Down casting Graphics object to Graphics2D raphics2D g2 = ( // end paintComponent anel class
  • 196.
    Web Design &Development – CS506 VU © Copyright Virtual University of Pakistan 196 The T nts. // importing required packagesimport javax.swing.*;import java.awt.*;Import java.awt.event.*; pu { JFrame f; MyPa public AnimTest(){ f = new JFrame(); x = 5; ultCloseOperation(JFrame.EXIT_ON_CLOSE); Timer class object, used for firing er a specified delay ires time in // milliseconds and object of class that handles Timer t = new Timer (5, this); // starts the timer, causing it to start sending// action events to listeners t.start(); } // end constructor // event handler method public void actionPerformed(ActionEvent ae){ est class is given below. Additionally this class also contains the code for handling mouse eve blic class AnimTest implements ActionListener nel p; // used to control the direction of ball int x, y; Container c = f.getContentPane(); c.setLayout(new BorderLayout()); y = 3; p = new MyPanel(); c.add(p); f.setSize(400,400); f.setVisible(true); f.setDefa // creating a // one or more action events aft// Timer class constructor requ // action events
  • 197.
    Web Design &Development – CS506 VU © Copyright Virtual University of Pakistan 197 // if ball reached to maximum width of frame minus// 40 since diameter of ball is 40 then change the// X-direction of ball i x = -5; // if ball reached to maximum height of frame // minus 40 then change the Y-direction of ball if (f.getHeight()-40 == p.mY) y = -3; // if ball reached to min. of width of frame, // change the X-direction of ball if (p.mX == 0 ) x = 5; // if ball reached to min. of height of frame, // change the Y-direction of ball if (p.mY == 0 ) y = 3; // Assign x,y direction to MyPanel’s mX & mY p.mX += x; p.mY += y; // call to repaint() method so that ball is drawn on// new locations p.repaint(); } // end actionPerformed() method // main method public static void main(String args[ ]){ AnimTest at = new AnimTest(); } } // end of AnimTest class f (f.getWidth()-40 == p.mX)
  • 198.
    Web Design &Development – CS506 VU © Copyright Virtual University of Pakistan 198 References: ƒ Java, A Lab Course by Umair Javed ƒ Painting in AWT & Swing http://java.sun.com/products/jfc/tsc/ar ting/index.html ticles/pain ƒ Performing Custom Painting g/index.html http://java.sun.com/docs/books/tutorial/uiswing/14paintin
  • 199.
    Web Design &Development – CS506 VU © Copyright Virtual University of Pakistan 199 Lesson 20 Applets d included in a HTML page. ating system on which it runs ƒ An applet is a Panel that allows interaction with a Java program ƒ A ƒ Y ƒ For security reasons, applets run in a sandbox: they have no access to the client’s file system Applets Support ƒ Most modern browsers support Java 1.4 if they have the appropriate plugin ƒ Sun provides an application appletviewerto view applets without using browser. ƒ In general you should try to write applets that can be run with any browser What an App ƒ You w extending the class Appletor JApplet ƒ Applet is just a class like any other; you can even use it in applications if you want ƒ When ou write an applet, you are only writing part of a program ƒ The browser supplies the main method The genealogy o The following figure shows the inheritance hierarchy of the JApplet class. This hierarchy determines much of what an applet can do and how, as you'll see on the next few pages. bject | +----java.awt.Component | +----java.awt.Container|+----java.awt.Panel | +----java.applet.Applet|+----javax.swing.JApplet ƒ A small program written in Java an ƒ It is independent of the oper applet is typically embedded in a Web page and can be run from a browser ou need special HTML in the Web page to tell the browser about the applet let is? rite an applet by y f Applet java.lang.O Example Code 20.1: Writing a Simple Applet Below is the source code for an applet called HelloApplet. This displays a “Hello World” string. Note that no main method has been provided. // File HelloApplet.java
  • 200.
    Web Design &Development – CS506 VU © Copyright Virtual University of Pakistan 200 //step 1 kagesimport java.awt.*;import javax.swing.*; ss also becomes an//appletpublic class HelloApplet extends JApplet { // overriding paint method public void paint(Graphics g) { // write code here u want to display & draw by using// Graphics objectg.drawString(“Hello World”, 30 , 30); After defining the HelloApplet.java, the next step is to write .html file. Below is the source code of Tes m tains the ordinary html code except one. <title> Simple <body> <!-- providing the class name of applet with width &height--!> <applet code="HelloApplet.class” width=150 height=100> </applet> </body> </html> Compile & Execute By simply double clicking on Test.html file, you can view the applet in your browser. However, you can also use the appletviewer java program for executing or running applets. The applet viewer is invoked from the command line by the command appletviewer htmlfile where htmlfile is the name of the file that contains the html document. For our example, the command e this: : importing required pac // extending class from JApplet so that our cla } } // end class t.htl file. The Test.html con <html> <head> Applet </title> </head> looks lik
  • 201.
    Web Design &Development – CS506 VU © Copyright Virtual University of Pakistan 201 appletviewer Test.html As a s reult, you will see the following output Applet Life Cycle Methods When an applet is loaded, an instance of the applet's controlling class (an Applet subclass) is created. After that an applet passes through some stages or methods, each of them are build for specific purpose An applet can react to major events in the following ways: ƒ It can initialize itself. op running. ƒ It can perform a final cleanup, in preparation for being unloaded lled in the specific order shown below. Not every applet needs to ƒ It can start running. ƒ It can st The applet’s life cycle methods are caoverride every one of these methods.
  • 202.
    Web Design &Development – CS506 VU © Copyright Virtual University of Pakistan 202 Let’s t each method in detail and find out what they do init( ) ƒ Is ca ƒ The t each time it's loaded (or reloaded). ƒ You can on ƒ For example, n the applet's loaded or when the user revisits a page that contains the applet alled whenever the browser is maximized paint( ) ƒ paint( ) is called for the first time when the applet becomes visible ƒ Whenever applet needs to be repainted, paint( ) is called again ƒ Do all your painting in paint( ), or in a method that is called from paint( ) the user leaves the applet's page or quits the browser. ƒ stop( ) is also called whenever the browser is minimized estroy( ) ƒ Is called only once. ƒ To perform a final cleanup in preparation for unloading xample Code 20.2: Understanding Applet Life Cycle Methods ake a look on lled only once. purpose of init( ) is to initialize the apple think of it as a constructor start( ) ƒ To start the applet's executi whe ƒ start( ) is also c stop( ) ƒ To stop the applet's execution, such as when d E The following code example helps you in understanding the calling sequence of applet’s life cycle methods.
  • 203.
    Web Design &Development – CS506 VU © Copyright Virtual University of Pakistan 203 These methods are only displaying debugging statements on the console. / File AppletDemo.java //step 1: importing required packagesimport java.awt.*;import javax.swing.*; ss also becomes an//appletpublic clas p alled"); } // overriding start method p li } // overriding paint method public void paint(Graphics g){ System.out.println("paint() called"); // overriding stop method public void stop(){ println("stop() called"); } // overriding destroy method public void destroy(){ tln("destroy() called"); // end class The DemoTest.html file is using this applet. The code snippet of it given below: <html> <head> <title> Applet Life Cycle Methods </ / // extending class from JApplet so that our cla s ApletDemo extends JApplet { // overriding init method public void init ( ) { System.out.println("init() c ubc void start ( ){ System.out.println("start() called"); } System.out. System.out.prin} } title></head> <body>
  • 204.
    Web Design &Development – CS506 VU © Copyright Virtual University of Pakistan 204 <!-- providing the class name of applet with width &height--!> <applet code="AppletDemo.class” width=150 height=100> </applet></body></html> Compile & Execute To u cycle methods, you have to execute it by using appletvi zing, minimizing the applet, bringing another window in fro utput. Example Code 20.3: Animated Java Word Sample Output nderstand the calling sequence of applet life ewer command. Do experiments like maximint of applet and keep an eye on console o The b elow: Design Process The Progr method ƒ Draws string “java” on 40 random locations ƒ F ndom font out of 4 different fonts ƒ For every drawing, it selects random color out of 256 * 256 * 256 RGB colors Repaint is called after every 1000 ms. After 10 calls to repaint, screen is cleared Generating Random Numbers ƒ Use static method random of Math class Mat ƒ less than 1.0. ƒ Multiply the number with appropriate scaling factor to increase the range and type cast it, if needed. int i = (int)( Math.random() * 5 );// will generate random numbers between 0 & 4. rowser output of the program is given b am in a single call of paint or every drawing, it selects ra h.random() ; Returns positive double value greater than or equal to 0.0 or
  • 205.
    Web Design &Development – CS506 VU © Copyright Virtual University of Pakistan 205 Progra The pr ny custom methods. Let’s discuss each of them one by one that will help in unders overall logic of the program. . drawJava( ) As name indicates, this method will be used to write String “java” on random locations. The code is given below: // m public void drawJava(Graphics2D g2) { // generate first number randomly. The panel width is 1000int x = (int) (Math.random() * 1000); // generate second number randomly. The panel height is 700 int y = (int) (Math.random() * 700); // draw String on these randomly select . chooseC This method will choose color randomly out of 256 * 256 * 256 possible colors. The code snippet is given below: // method c public Color // choosing red color value randomly int r = (int) (Math.random() * 255); // choosing green color value randomly int g = (int) (Math.random() * 255); // choosing blue color value randomly r by providing R-G-B valuesColor c = new Color(r, g, b); // returning color return c; m’s Modules ogram is build using matanding the ethod drawJava ed numebrsg2.drawString("java", x, y); } olor( ) hooseColor chooseColor() { int b = (int) (Math.random() * 255); // constructing a colo
  • 206.
    Web Design &Development – CS506 VU © Copyright Virtual University of Pakistan 206 } . chooseFont( ) This method will choose a Font for text (java) to be displayed out of 4 available fonts. The code snippet is given below: dom value that helps in choosing a fontint fontChoice = (int) ) + 1; for selecting font Font("Serif", Font.BOLD + Font.ITALIC, 20);break; case 2: f = new Font("SansSerif", Font.PLAIN, 17);break; ca , Font.ITALIC, 23);break; case 4: f = new Font("Dialog", Font.ITALIC, 30);break; } // end switch // returns Font object return f; . p The last method to be discussed here is paint( ). By overriding this method, we will print string “java” on 40 random locations. For every drawing, it selects random font out of 4 different fonts & random color out of 256 * 256 * 256 RGB colors. Let’s see, how it happens: / overriding method paint public void paint(Graphics g) { counter variable. clearCounter++; // method chooseFont public Font chooseFont() { // generating a ran(Math.random() * 4// declaring font reference Font f = null; // using switch based logicswitch (fontChoice) { case 1: f = new se 3: f = new Font("Monospaced" } //end chooseFont aint( ) / // incrementing clear
  • 207.
    Web Design &Development – CS506 VU © Copyright Virtual University of Pakistan 207 // printing 40 “java” strings on different locations by// selcting random font & colorfor (int i = 1; i <= 40; i++) { // choosing random color by calling chooseColor() method Color c = chooseColor(); // setting color g2.setColor(c); // choosing random Font by calling chooseColor() method Font f = chooseFont(); g2.setFont(f); va” by calling drawJava() method drawJava(g2); g2 = (Graphics2D) g; paint is called 10 times then clears the// screen and set counter again to zero if , 0, 1000, 700);clearCounter = 0; } } // end paint method // drawing string “ja } // end for loop Graphics2D// checking if (clearCounter == 10) { g2.clearRect(0
  • 208.
    Web Design &Development – CS506 VU © Copyright Virtual University of Pakistan 208 Merging Pieces By ins the program will look like one given below. Notice that it con me extra code with which you are already familiar. / /step 1: importing required packages import java.awt.*; import java.awt.event.*; x.swing.*; public class JavaAnim extends JApplet implements ActionListener { // used to count how many times paint is called clearCounter; Timer reference publ ) { setBackground(Color.black); clearCounter = 0; Timer t = new Timer(1000, this); } // overriding paint method – discussed above phics g) { if (clearCounter == 10) { g2 cle } for (int i = 1; i <= 40; i++) { Color c = chooseColor(); g2.setColor(c); Font f = chooseFont(); erting all method inside JavaAnim.java class, tains methods discussed above with so / File JavaAnim.java / import java int// declaring Timer t; // overriding init method, used to initialize variables ic void init( t.start(); public void paint(Gra clearCounter++; Graphics2D g2 = (Graphics2D) g; .clearRect(0, 0, 1000, 700); arCounter = 0;
  • 209.
    Web Design &Development – CS506 VU © Copyright Virtual University of Pakistan 209 g2.setFont(f); drawJava(g2); } } // o r pub v repaint(); } // chooseColor method – discussed above public Color chooseColor() { in i int b ndom() * 255); Cr r } // ch public Font chooseFont() { int fontChoice = (int) (Math.random() * 4) + 1; Font f = null; switch (fontChoice) { case 1: f = new Font("Serif", Font.BOLD + Font.ITALIC, 20);break; case 2: f = new Font("SansSerif", Font.PLAIN, 17);break; case 3: f = new Font("Monospaced", Font.ITALIC, 23);break; case 4: f = new Font("Dialog", Font.ITALIC, 30);break; } return f; } veriding actionPerformed()of ActionListener interface// called by Timer object licoid actionPerformed(ActionEvent ae) { t r= (int) (Math.random() * 255); nt g= (int) (Math.random() * 255); = (int) (Math.ra olor c = new Color(r, g, b); etun c; ooseFont method – discussed above
  • 210.
    Web Design &Development – CS506 VU © Copyright Virtual University of Pakistan 210 // drawJava() method – discussed above public void drawJava(Graphics2D g2) { int x = (int) (Math.random() * 1000); int y = (int) (Math.random() * 700); g2.drawString("java", x, y); } } / : <html> <head> <title> Animated Java Word </title> </head> <applet code="JavaAnim.class" width=1000 height=700> </applet> </b l> Compile & Execute You can cute it directly us you can use “your name” instead of “java” References: . Java, A Lab Course by Umair Javed . W s . http://java.sun.com/docs/books/tutorial/applet/ / end class The AnimTest.html file is using this applet. The code snippet of it given below body ody /htm exe ing browser or by using appletviewer application. For having fun, and watch it in different colors ☺ riting Applet
  • 211.
    Web Design Development – CS506 VU © Copyright Virtual University of Pakistan 211 Lesson 21 Socket Programming Socket ƒ A socket is one endpoint of a two-way communication link between two programs running generally on a network. ƒ A socket is a bi-directional communication channel between hosts. A computer on a network often termed as host. Socket ƒ at file is an abstraction of your hard drive. Similarly you can think of a socket as an abstraction of the network. ƒ wired up to the other ƒ cs of receive data to and from network through socket, without actually going into underlying mechanics. ƒ You read and write data from/to a file using streams. To read and write data to socket, you will also What is protocols available to communicate such as TCP and UDP. We will use TCP for programming in this handout. ƒ There are 64k ports available for available for UDP, so at least n 128k simultaneous connections. ƒ There are well-known ports w o below 1024 o provides standard services o Some well-known ports are: -FTP works on port 21 -HTTP works on port 80 -TELNET works on port 23 etc. How Client – Server Communicate Dynamics As you have already worked with files, you know th Each end has input stream (to send data) and output stream (to receive data) host. You store and retrieve data through files from hard drive, without knowing the actual dynamithe hard drive. Similarly you send and use streams. Port? ƒ It is a transport address to which processes can listen for connections request. ƒ There are different TCP sockets and 64k ports theoretically we can ope hich are ƒ Normally, a server runs on a specific computer and has a socket that is bound to a specific port number. ƒ The server just waits, listening to the socket for a client to make a connection request. ƒ On the client side: The client knows the hostname of the machine on which the server is running and the port number to which the server is connected. ƒ On the server side, if the connection is accepted, a socket is successfully created and the client can use the socket to communicate with the server. ƒ Note that the socket on the client side is not bound to the port number used to make contact with the server. Rather, the client is assigned a port number local to the machine on which the client is running. ƒ The client and server can now communicate by writing to or reading from their sockets
  • 212.
    Web Design Development – CS506 VU © Copyright Virtual University of Pakistan 212 . As soon as client creates a socket that socket attempts to connect to the specified server. . The server listens through a special kind of socket, which is named as server socket. . The sole purpose of the server socket is to listen for incoming request; it is not used for communication. . I n . The (and consequently a different port number) so that it can continue to listen through the original server socket for connection requests while tending to the c f every thing goes well, the server accepts the connection. Upon acceptance, the server gets a ew socket, a communication socket, bound to a different port number. server needs a new socket needs of the connected client. This scheme is helpful when two or more clients try to onnect to a server simultaneously (a very common scenario). Steps – To Make a Simple Client To make a client, process can be split into 5 steps. These are: 1. Import required package You have to import two packages . java.net.*; . java.io.*; Server serverName : Name or address of the server you wanted to connect such as e.com or 172.2.4.98 etc. For testing if you are running client and server on the same machine then you can specify “localhost” as the name of server . serverPort : Port number you want to connect to 2. Connect / Open a Socket with Create a client socket (communication socket) Socket s = new Socket(“serverName”, serverPort) ; http://www.googl
  • 213.
    Web Design Development – CS506 VU © Copyright Virtual University of Pakistan 213 The scheme is very similar to our home address and then phone number. 3. Get I/O Streams of Socket Get input output streams connected to your socket . For reading data from socket As stated above, a socket has input stream attached to it. InputStream is = s.getInputStream(); // now to convert byte oriented sstream that helps in achieving abo tream into character oriented buffered reader // we use intermediary ve stated purpose InputStreamReader isr= new InputStreamReader(is); BufferedReader br = new BufferedReader(isr); . For writing data to socket A socket has also output stream attached to it. Therefore, OutputStream os = s.getOutputStream(); // now to convert byte oriented stream into character oriented print writer // here we will not use any intermediary stream because PrintWriter constructor // directly accepts an object of OutputStream PrintWriter pw = new PrintWriter(os, true); Here notice that true is also passed to so that output buffer will flush. 4. Send / Receive Message Once you have the streams, sending or receiving messages isn’t a big task. It’s very much similar to the way you did with files . To send messages pw.println(“hello world”); . To read messages ne(); 5. Close Socket Don’t forget to close the socket, when you finished your work s.c String recMsg = br.readLi lose();
  • 214.
    Web Design Development – CS506 VU © Copyright Virtual University of Pakistan 214 Steps – To M ake a Simple Server To make a server, process can be split into 7 steps. Most of these are similar to steps used in making a client. These are: 1. Import req You need the similar set of packages you have used in making of client . java.net.*; . java.io.*; 2. Create a Server Socket In order t for client requests. ServerSocket ss = new ServerSocket(serverPort) ; . serv uired package o create a server socket, you will need to specify port no eventually on which server will listen erPort: port local to the server i.e. a free port on the server machine. This is the same port number that is given in the client socket constructor 3. Wait f nnections The job of the server socket is to listen for the incoming connections. This listening part is done th d. Socket s = ss.accept(); The server program blocks ( stops ) at the accept method and waits for the incoming client connection for connection comes it opens a new communication socket (s) and use this socket to 4. Get I/O Streams of Socket Once you have the communication socket, getting I/O streams from communication socket is similar or Incoming Co rough the accept metho when a request communicate with the client. to the way did in making a client 1. For reading data from socket InputStream is = s.getInputStream(); InputStreamReader isr= new ader br = new BufferedReader(isr); 2. For writi InputStreamReader(is); BufferedRe ng data to socket OutputStream os = s.getOutputStream(); Pr 5. Send / Receive Message Sending and receivi nt T pw.println(“hello world”); . T intWriter pw = new PrintWriter(os, true); ng messages is very similar as discussed in making of clieo send messages: o read messages String recMsg = br.readLine();
  • 215.
    Web Design Development – CS506 VU © Copyright Virtual University of Pakistan 215 6. Close Socket s.close Example Code 21.1: Echo Server Echo Client (); The c append “hello” with the name send by the client. After that, server will send back the name with appended “hello”. EchoServ Let’s first see the code for the server import java.net.*; import java.io.*; import javax.swing.*; public class EchoServer { public static void main(String args[]) { try { //step 2: create a server socket ServerSocket ss = new ServerSocket(2222); System.out.println(Server /* Loop back to the accept method of the serversocket and wait for a new connection request. Soserver will continuously listen for requests */ while(true) { // step 3: wait for incoming connection Socket s = ss.accept(); System.out.println(connection request recieved); // step 4: Get I/O streams InputStream is = s.getInputStream();InputStreamReader isr= new InputStreamReader(is);BufferedReader br = new BufferedReader(isr); OutputStream os = s.getO lient will send its name to the server and server will er.java // step 1: importing required package started...); utputStream();
  • 216.
    Web Design Development – CS506 VU © Copyright Virtual University of Pakistan 216 PrintWriter pw = new PrintWriter(os,true); // reading name sent by clientString name = br.readLine(); // appending “hello” with the received name String msg = Hello + name + from Server; // sending back to client pw.println(msg); // closing communication sockeys.close(); } // end while }catch(Exception ex){ System.out.println(ex); } } } // end class EchoClient.java The code of the client is given below // step 1: importing required package import java.net.*;import java.io.*;import javax.swing.*; public class EchoClient{ public static void main(String args[]){ try { //step 2: create a communication socket // if your server will run on the same machine thenyou can pass “localhost” as server address */ /* Notice that port no is similar to one passedwhile creating server socket */server Socket s = new Socket(“localhost”, 2222); // step 3: Get I/O streams InputStream is = s.getInputStream();InputStreamReader isr= new InputStreamReader(is);BufferedReader br = new BufferedReader(isr); OutputStream os = s.getOutputStream();PrintWriter pw = new PrintWriter(os,true); // step 4: Send / Receive message // asking use to enter his/her name String msg = JOptionPane.showInputDialog(Enter your name); // sending name to server pw.println(msg); // step 5: Send / Receive message
  • 217.
    Web Design Development – CS506 VU © Copyright Virtual University of Pakistan 217 // reading message (name appended with hello) from// servermsg = br.readLine(); // displaying received messageJOptionPane.showMessageDialog(null , msg); // closing communication sockets.close(); }catch(Exception ex){ System.out.println(ex); } } } Com il After compiling both files, run EchoServer.java first, from the command prompt window. You’ll see a as shown in the figure below. Also notice that cursor is continuously blinking since server is waiting for client request // end class pe Execute message of “server started” Now, open another command prompt window and run EchoClient.java from it. Look at EchoServer window; you’ll see ask you to enter name in input dial me press ok button, with in no time, a message dialog box will pop up containing your name with appended “hello” from server. This whole process is illustrated below in pictorial form: the message of “request received”. Sooner, the EchoClient program willog box. After entering na
  • 218.
    Web Design Development – CS506 VU © Copyright Virtual University of Pakistan 218 sending name to server response from server Notice that server is still running, you can run again EchoClient.java as many times untill server is running. r on a different computer and client on a different. But before doing that find the IP of the computer machine on which your EchoServer will eventually run. Replace “localhost” with the new IP and start conversion over network ☺ References To have more fun, run the serve Entire material for this handout is taken from the book JAVA A Lab Course by Umair Javed. This material is available just for the use of VU students of the course Web Design and Development and not for any other co the consent of author. mmercial purpose without
  • 219.
    Web Design Development – CS506 VU © Copyright Virtual University of Pakistan 219 Lesson 22 Serialization . You want to send an object to a stream. Motivati ƒ A boring conversion from a file to memory ƒ As you might recall that AddressBook program reads data from file and then parses it ƒ This is a common problem Revisiting A We read rec amed persons.txt. The person record was present in the file in the following format. T s used to construct Person objects after reading information from the file is given below. Here only the part of code is shown, for complete listing, see AddressBook code in your earlier handout. FileReader fr = new FileReader(persons.txt);BufferedReader br = while ( line != null ) { tokens = line.split(,); add = tokens[1]; ph = tokens[2]; / you can add p into arraylist, if } As you have rsing code is required for converting a line into PersonInfo objects. Serialization mechanism ving all above in a very simple way. What? on lot of code involves ddressBook ord from a text file n persons.txt he code that wa new BufferedReader(fr); String line = br.readLine(); name = tokens[0]; PersonInfo p = new PersonInfo(name, add, ph); / needed line = br.readLine(); seen a lot of paeases developer’s life by achie
  • 220.
    Web Design Development – CS506 VU © Copyright Virtual University of Pakistan 220 Serialization in Java ƒ Java provides an extensive support for serialization ƒ Object knows how to read or write themselves to streams : ƒ Problem bjects have some state ƒ You need to save and restore that state. ƒ The good news is that java serialization takes care of it automatically Serializable Interface ƒ By implementing this interface a class declares that it is willing to be read/written by automatic serialization machinery ƒ Found in java.iopackage ƒ Tagging interface – has no methods and serves only to identify the semantics of being serializable Automa ƒ System knows how to recursively write out the state of an object to stream ƒ If an object has the reference of another object, the java serialization mechanism takes care of it a Automa ƒ System knows object in memory ƒ T nto a Serializ ƒ of PersonInfo, ObejctOutputStream and its method writeObject( ) will be used PersonInfo p = new PersonInfo( ); ObejctOutputStream out; // writing PersonInfo’s object p out.writeObject(p); ƒ To read that object back, ObejctInputStream and its method readObject()will be used ObejctInputStream in; // reading PersonInfo’s object. Remember type casting// is required PersonInfo obj = (PersonInfo)in.readObject( ); Example Code 22.1: Reading / Writing PersonInfo objects ƒ As you know, objects get created on heap and have some values therefore Oin memory tic Writing nd writes it too. tic Reading how to read the data from Stream and re-create he recreated object is of type “Object” therefore Down-casting is required to convert it ictual type. ation: How it worTo write an object ks? We wato send PersonInfo object to stream. You have alr nt eady seen this class number of times before. Here it will also implement serializable interface.
  • 221.
    Web Design Development – CS506 VU © Copyright Virtual University of Pakistan 221 PersonInfo.java import javax.swing.*; String name; String address; String phoneNum; (String n, String a, String p) { phoneNm = p; g person record on GUIpublic void printPersonInfo( ) { JOptionPane.showMessageDialog(null , “name: ” + name + “address:” +address + phone no:” + phoneNum); } } // end class WriteEx.java The fo sonInfo object to a file impor public public static void main(String args[ ]){ ew PersonInfo(ali, defence, 9201211); tput stream with “ali.dat” FileOutputStream fos =new FileOutputStream(ali.dat); // attaching ObjectOutput stream over FileOutput// stream tputStream out =new ObjectOutputStream(fos); //serialization // writing object to ‘ali.dat’ out.writeObject(pWrite); out.close(); fos.close(); } catch (Exception ex){ System.out.println(ex) import java.io.* class PersonInfo implements Serializable{ //parameterized constructorpublic PresonInfoname = n; address = a; } //method for displayin “ llowing class will serialize Per t java.io*; class WriteEx{ PersonInfo pWrite =ntry { // attaching FileOuObjectOu // closing streams
  • 222.
    Web Design Development – CS506 VU © Copyright Virtual University of Pakistan 222 } } // end class ReadEx.java The following class will read serialized object of PersonInfo from file i.e “ali.data” import java.io*; public class ReadEx{ public static void main(String args[ ]){ try { // attaching FileInput stream with “ali.dat” FileInputStream fin = new FileInputStream(ali.dat); tStream in = new ObjectInputStream(fis); li.dat’ adObject( ); intPersonInfo method to confirm that// object contains same set of values before// serializatoion // closing streams } } // en Compile Execute After compilation, first run the WriteEx.java file and visit the “ali.dat” file. Then run ReadEx.java from different command or same command prompt. Object Serialization Network // attaching FileInput stream over ObjectInput stream ObjectInpu//de-serializa tion // reading object from ‘a PersonInfo pRead = (PersoInfo)in.Re // calling pr pRead.printPersonInfo(); in.close(); fis.close(); catch (Exception ex){ System.out.println(ex) } d class . You can read / write to a network using sockets . All you need to do is attach your stream with socket rather than file . The class version should be same on both sides (client network) of the network
  • 223.
    Web Design Development – CS506 VU © Copyright Virtual University of Pakistan 223 Example Code 22.2: Sending/Reading Objects to/from Network We are going to use same PersonInfo class listed in example code 22.1. An object of PersonInfo class will be sent by client on network using sockets and then be read by server from network. Sending Objects over Network The following class ClientWriteNetEx.java will send an object on network imp j java w in(Str sonIn ”); // create a communication socket Socket s = new Socket(“localhost”, 2222); treams OutputStream is = s.getOutputStream(); tOutput stream over Input stream ObjectOutputStream oos= new ObjectOutputStream(is); // writing object to network oo // closing communication socket s.close(); }cat System.out.println( } } }// end class Reading Objects over Network The following class ServerReadNetEx.java will read an object of PersonInfo sent by client. import java.net.*;import java.io.*;import javax.swing.*; ortava.net.*;import java.io.*;import x.sing.*; public class ClientWriteNetEx { public static void maing args[]){ try { Pers onInfo p = new Perfo(“ali”, “defence”, “9201211 // Get I/O s // attaching Objec s.write(p); ch(Exception ex){ ex);
  • 224.
    Web Design Development – CS506 VU © Copyright Virtual University of Pakistan 224 public class ServerReadNetEx{ public static void main(String rgs[]) // create a server socket ServerSocket ss = new ServerSocket(2222); { ing connection Socket s = ss.accept(); request recieved); // Get I/O streams InputStr tInputStream(); // attaching ObjectOutput stream over Input stream ObjectIn new ObjectInputStream(is); // read PersonInfo object from network Pers p.printPersonInfo(); // closing communication socket s.close(); } // end while }catch(Exception ex){ System.out.println(ex); } } } // end class { try { System.out.println(Server started...); /* Loop back to the accept method of the serversocket and wait for a new connection request. Soserver will continuously listen for requests */ while(true) / wait for incom / System.out.println(connection eam is = s.ge putStream ois = onInfo p = (PersonInfo)ois.read( );
  • 225.
    Web Design Development – CS506 VU © Copyright Virtual University of Pakistan 225 Compile Execute After compiling both files, run ServerReadNetEx.java first, from the command prompt window. Open .java will send an Object of PersonInfo to ServerReadNetEx.java that displays that object values in dialog box after reading it from network. Preventing Serialization another command prompt window and run ClientWriteNetEx.javafrom it. The ClientWriteNetEx ƒ Often there is no need to serialize sockets, streams DB connections etc because they do no represent the state of object, rather connections to external resources ƒ To do so, transient keyword is used to mark a field that should not be serialized o transient OutputStream os; o transient Connecction con; ƒ Transient fields are returned as nullon reading Example Code 22 . 3: transient ƒ So we can mark them as, o transient Socket s; Assume that we do not want to serialize phoneNum attribute of PersonInfo class, this can be done as shown below PersonInfo.java import javax.swing.*; import java.io.* class PersonInfo implements Serializable{ String name; String address; transient String phoneNum; public PresonInfo(String n, String a, String p) { name = n;address = a;phoneNm = p; } public void printPersonInfo( ) { JOptionPane.showMessageDialog(null , “name: ” + name + “address:” +address + “phone no:” + phoneNum); } } // end class References Entire material for this handout is taken from the book JAVA A Lab Course by Umair Javed. This material is available just for the use of VU students of the course Web Design and Development and not for any other commercial purpose without the consent of author.
  • 226.
    Web Design Development – CS506 VU © Copyright Virtual University of Pakistan 226 Lesson 23 Multithreading odu Intrction Multithreading is the ability to do multiple things at once wnular ith in the same application. It provides finer reads ess. A . mul require more complex chro arvation. graity of concurrency. A thread — sometimes called an execution context or a lightweight process — is a single sequential flow of control within a program. Th are light weight as compared to processes because they take fewer resources then a procthread is easy to create and destroy. Threads share the same address space i.etiple threads can share the memory variables directly, and therefore may synnization logic to avoid deadlocks and st Sequential Execution vs Multithreading Every program has atleast one thread. Programs without multithreading executes sequentially. That is, after executing one instruction the next instruction in sequence is executed. If a function is called then until the mplet executed. Similarly if there is a loop then instructions er loo ets completed. Consider the following java program having ree loops in it. // F T public class ThreeLoopTest { //first loop // sec for (in rintln(“second ” + j); d ” + k); } // end main} // end class coion of the function the next instruction is not aftp only gets executed when the loop g th ilehreeLoopTest.java public static void main (String args[ ]) { for (int i=1; i= 5; i++)System.out.println(“first ” +i); ond loop t j=1; j= 5; j++)System.out.p // third loop for (int k=1; k= 5; k++)System.out.println(“thir Note: Each loop has 5 iterations in the ThreeLoopTest program.
  • 227.
    Web Design Development – CS506 VU © Copyright Virtual University of Pakistan 227 Note: Each loop has 10 iterations in the ThreadTest program. Your output can be different from the one given above. Notice th e between the outputs of the two programs. In ThreeLoopTest each loop generated a sequentia ile in ThreadTest the output of the loops got intermingled i.e. concurrency took place and ly Let us code our first multithreaded program and try to learn how Java supports multithreading. support for threading. While other languages have threads bolted-on to an existing f the original language but latter came into existence as the need aros All w e days support multithreading. JVM transparently maps Java Threads to the ating system i.e. OS Threads. JVM allows threads in Java to take advantage of ha d operating system level advancements. It keeps track of threads and schedules them to get CPU . Scheduling may be pre-emptive or cooperative. So it is the job of JVM to manage different tasks of thread. Let’s see how we can create threads? e differencl output wh loops executed simultaneous Java includes built-in structure. i.e. threads were not the part o e. ell known operating systems thesir counter-parts in the operrdware antime
  • 228.
    Web Design Development – CS506 VU © Copyright Virtual University of Pakistan 228 Creating Threads in Java There are two approaches to create threads in Java. Using Interface Using Inheritance Foll sing Interface: 1 Create a class where you want to put some code that can run in parallel with some other code and ethod therefore provide the implementation for the run() in parallel here Runnable object in constructor are the steps to create threads by using Intheritance: herit a class from java.lang.Thread class ethod in the subclass t of the subclass ments Runnable • Step 2 - Provide an Implementation of run() method public void run( ){// write thread behavior// code that will be executed by the thread • Step 3 - Instant nnable object in the constructor Worker Thread • Step 4 – Start thread by calling start() method owing are the steps to create threads by u let that class implement the Runnable interface 2 Runnable interface has the run() mmethod and put your code that you want to run3 Instantiate Thread class object by passing4 Start thread by calling start() method Following1 In2 Override the run() m3 Instantiate the objec 4 Start thread by calling start() method To write a multithreaded program using Runnable interface, follow these steps: • Step 1 - Implement the Runnable Interface class Worker imple iate Thread class object by passing Ruw = new Worker(“first”); t = new Thread (w); t.start(); Threads Creation Steps Using Inheritance To write a multithreaded program using inheritance from Thread class, follow these steps: Step 1 – Inherit from T class Wo Step 2 - Override run() method public void run( ){ // write thread behavior // code that will execute by thread Step 3 - Instantiate subclass object Step 4 – Start thread by calling start() method ƒ Two ways to write multithreaded Java programs hread Class rker extends Thread Worker w = new Worker(“first”); t.start(); So far we have explored: ƒ What is multithreading? ƒ What are Java Threads?
  • 229.
    Web Design Development – CS506 VU © Copyright Virtual University of Pakistan 229 Now we will re-write the ThreeLoopTest program by using Java Threads. At first we will use the Iapproach and then we will use Inheritance. Code Example using Interface // File Worker.java public class Worker implements Runnable { nterface private String job ; //Constructor of Worker class public Worker (String j ){ job = j; } //Implement run() method of Runnable interface public void run ( ) { for(int i=1; i= 10; i++)System.out.println(job + = + i); } } // end class // File ThreadTest.java public class ThreadTest{ public static void main (String args[ ]){ //instantiate three objects Worker first = new Worker (“first job”); Worker second = new Worker (“second job”); Worker third = new Worker (“third job”); //create three objects of Thread class passing worker //(runnable) to them Thread t1 = new Thread (first ); Thread t2 = new Thread (second); Thread t3 = new Thread (third); //start threads to execute }//end main} // end class Following code is similar to the code given above, but uses Inheritance instead of interface // File Worker.java public cla ead{ priva //C public Worker (String j ){ job } //Override run() method of Thread class public void run ( ) {for(int i=1; i= 10; i++)System.out.println(job + = + i); } t1.start(); t2.start(); t3.start(); ss Worker extends Thrte String job ; onstructor of Worker class = j;
  • 230.
    Web Design Development – CS506 VU © Copyright Virtual University of Pakistan 230 } // end class / File ThreadTest.java public class ThreadTest{ public static void main (String args[ ]) { //instantiate three objects of Worker (Worker class is now //becomes a Thread because it is inheriting from it)class Worker third = new Worker (“third job”); //start threads to execute t1.st .s hreads provide a way to write concurrent programs. But on a single CPU, all the threads do not run eously. JVM assigns threads to the CPU based on thread priorities. Threads with higher priority are executed in preference to threads with lower priority. A thread’s default priority is same as that of the creating A Thre and 10. We can also use the following predefined constants to assign priorities. Thread.MAX_PRIORITY (typically 10) Thread.NORM_PRIORITY (typically 5) Thread.MIN_PRIORITY (typically 1) To change the priority of a thread, we can use the following method setPriority(int priority) It changes the priority of this thread to integer value that is passed. It throws an IllegalArgumentException if the priority is not in the range MIN_PRIORITY to MAX_PRIORITY i.e. (1–10). For example, we can write the following code to change a thread’s priority. Thread t = new Thread (RunnableObject); // by using predefined constantt.setPriority (Thread.MAX_PRIORITY); // by using integer constantt.setPriority (7); Thread Priority Scheduling / Worker first = new Worker (“first job”); Worker second = new Worker (“second job”); art(); tart(); t2 t3.start(); }//end main} // end class Tsimultan thread i.e. parent thread. ad’s priority can be any integer between 1 The Java runtime environment supports a very simple, deterministic scheduling algorithm called fixed-priority scheduling. This algorithm schedules threads on the basis of their priority relative to other Runnable threads. At any given time, when multiple threads are ready to be executed, the runtime system chooses for execution the Runnable thread that has the highest priority. Only when that thread stops, yields (will be explained later), or becomes Not Runnable will a lower-priority thread start executing. If two threads of the same priority are waiting for the CPU, the scheduler arbitrarily chooses one of them to run. The chosen thread runs until one of the following conditions becomes true: ƒ A higher priority thread becomes Runnable. ƒ It yields, or its run() method exits. ƒ On systems that support time-slicing, its time allotment has expired.
  • 231.
    Web Design Development – CS506 VU © Copyright Virtual University of Pakistan 231 Then the second thread is given a chance to run, and so on, until the interpreter exits. Consider t following figure in which threads of various priorities are represented by capital alphabets A, B, …, K. A and B have same priority (highest in this iority (lowest in this case). JVM start executing with A and B, and divides CPU time between these two threads arbitrarily. When both A and B comes to an end, it chooses the next thread C to execute. he case). J and K have same pr Code Example: Thread Properties Try following example to understand how JVM executes threads based on their priorities. // File PriorityEx.java public class PriorityEx{ public static void main (String args[ ]){ //instantiate two objects Worker first = new Worker (“first job”); Worker second = new Worker (“second job”); //create two objects Thread t1 = new Thread (first ); Thread t2 = new Thread (second); IN_PRIORITY); t2.setPriority (Thread.MAX_PRIORITY); hreads to execute //set thread priorities t1.setPriority (Thread.M //start tstart(); t1. t2.start();
  • 232.
    Web Design Development – CS506 VU © Copyright Virtual University of Pakistan 232 }//end main} // end class Ou tput rities Problems with Thr ead Prio Ho hreads, remember the following two issues: First ities of the underlying OS. It is because of dif lying OS. For example ƒ ƒ Windows NT has only 7 user priority levels Second, starvation can occur for lower-priority threads if the higher-priority threads never terminate, sleep, or wait for I/O indefinitely. Refe ƒ ractical Guide by Umair Javed ƒ Java How to Program by Deitel and Deitel ƒ CS193j handouts on Stanford wever, when using priorities with Java T a Java thread priority may map differently to the thread priorference in priority levels of JVM and under Solaris has 232–1 priority levels rences: Java, A P
  • 233.
    Web Design Development – CS506 VU © Copyright Virtual University of Pakistan 233 Lesson 24 More on Multithreading In this handout, we’ll cover different aspects of multithreading. Some examples are given to make you understand the topic of multithreading. First we will start with an example that reads data from two text files simultaneously. Example Code: Reading Two Files Simultaneously The task is to read data from file “first.txt” “second.txt” simultaneously. Suppose that files contains the following data as shown below first.txt second.txt Follo is the code for ReadFile.java that implements Runable interface. The file reading code will be writte inside the run( ) method. // File ReadFile.java import java.io.*; public class ReadFile implements Runnable{ wingn
  • 234.
    Web Design Development – CS506 VU © Copyright Virtual University of Pakistan 234 //attribute used for name of file String fileName; public ReadFile(String fn){ // o ains the code for file reading pub try { // connecting FileReader with attribute fileNameFileReader fr = new FileReader(fileName);BufferedReader br = new BufferedReader(fr); String line = ; // reading line by line data from file// and displaying it on console line = br.readLine(); while(line != null) { System.out.println(line); line = br.readLine(); } ose(); lose(); }catch (Exception e){ System.out.println(e); } } // end run() method } // File Test.java ublic class Test { public static void main (String args[]){ // creating ReadFile objects by passing file names to them ReadFile first = new ReadFile(first.txt); ReadFile second = new ReadFile(second.txt); // Instantiating thread objects and passing // runnable (ReadFile) objects to them Thread t1 = new Thread(first); Thread t2 = new Thread(second); // starting threads that cause threads to read data from // two different files simultaneously t1.start(); t2.start(); } } // param constructor fileName = fn; } verriding run method// this method contlic void run ( ){ fr.clbr.c p
  • 235.
    Web Design Development – CS506 VU © Copyright Virtual University of Pakistan 235 Output On executing Test class, following kind output would be generated: Now let’s discuss some useful thread class methods. . sle ep(int time) method -Causes the currently executing thread to wait for the time (milliseconds) specified -Waiting is efficient equivalent to non-busy. The waiting thread will not occupy the processor -T hen the specified time interval expires or when interrupted by some -T ming out of sleep may go to the running or ready state depending upon the availability of the The different states of threads will be discussed later -High priority threads should execute sleep method after some time to give low priority threads a -sl sed for delay purpose i.e. anyone cal call Thread.sleep()method -N hrow InterruptedException. So, you need try-catch block Example Code: Demonstrating sleep ( ) usage t we used in the previous handout. // File Worker.javapublic class Worker implements Runnable { ; public Worker (String j ){ job = j; } Runnable interface try { Thread.sleep(100); // go to sleep for 100 hreads come out of the sleep wother thread hread coprocessor. chance to run otherwise starvation may occur eep() method can be uote that sleep() method can t Below the modified code of Worker.java is given tha private String job //Constructor of Worker class () method of //Implement runpublic void run ( ) { for(int i=1; i= 10; i++) {
  • 236.
    Web Design Development – CS506 VU © Copyright Virtual University of Pakistan 236 ms}catch (Exception ex){System.out.println(ex);} } // end for} // en // File public class SleepEx { public static void main (String args[ ]){ // Creating Worker objects Worker first = new Worker (“first job”); Worker second = new Worker (“second job”); tiating thread class objects Thread t1 = new Thread (first ); Thread t2 = new Thread (second); // starting thread t1.start(); t2.start(); } } // end class Output On executing SleepEx.java, the output will be produced with exact alternations between first thread second thread. On starting threads, first thread will go to sleep for 100 ms. It gives a chance to second thread to execute. Later this thread will also go to sleep for 100 ms. In the mean time the first thread will come out of sleep and got a chance on processor. It will print job on console and again enters into sleep state and this cycle goes on until both threads finished the run() method System.out.println(job + = + i); d run } // end class SleepEx.java // Instan Before jumping on to example code, lets reveal another aspect about main() method. When you run a Java program, the VM creates a new thread and then sends the main(String[] args) message to the class to be run! Therefore, there is always at least one running thread in existence. However, we can create more threads
  • 237.
    Web Design Development – CS506 VU © Copyright Virtual University of Pakistan 237 which can run concurrently with the existing default thread. void main (String args[ ]){ System.out.println(“main thread going to sleep”); try { // the main thread will go to sleep causing delay Thread.sleep(100); }catch (Exception ex){ System.out.println(ex); } System.out.println(“main thread coming out of sleep”); } // end main() } // end class Output On executing DelayEx class, you will experience a delay after the first statement displayed. The second statement will print when the time interval expired. This has been show below in the following two diagrams: sleep() method can be used for delay purpose. This is demonstrated in the DelayEx.java given below // File DelayEx.java public class DelayEx { public static . yield( ) method -Allows any other threads of the same priority to execute (moves itself to the end of the priority queue) -If all waiting threads have a lower priority, then the yielding thread resumes execution on the CPU -Generally used in cooperative scheduling schemes Example Code: Demonstrating yield ( ) usage Below the modified code of Worker.javais given // File Worker.javapublic class Worker implements Runnable { private String job ; //Constructor of Worker class
  • 238.
    Web Design Development – CS506 VU © Copyright Virtual University of Pakistan 238 public Worker (String j ){ 1; i= 10; i++) { // g Thread.yield( ); System.out.println(job + = + i); } // end for } // end run } // end class // File YieldEx.java Worker second = new Worker (“second job”); g thread class objects t2.start(); job = j; } //Implem ent run() method of Runnable interface public void run ( ) { for(int i= iving chance to a thread to execute of same priority public class YieldEx { public static void main (String args[ ]){ // Creating Worker objects Worker first = new Worker (“first job”); // Instantiatin Thread t1 = new Thread (first ); Thre ad t2 = new Thread (second); // starting thread t1.start(); } } // end class
  • 239.
    Web Design Development – CS506 VU © Copyright Virtual University of Pakistan 239 Output Since both threads have the same priority (until we change the priority of some thread explicitly). Therefore both threads will execute on alternate basis. This can be confirmed from the output given below: A thread can be in different states during its lifecycle as shown in the figure.
  • 240.
    Web Design Development – CS506 VU © Copyright Virtual University of Pakistan 240 Some Important states are . New state -When a thread is just created . Ready state -Thread’s start() method invoked -Thread can now execute -Put it into the Ready Queue of the scheduler . Running state -Thread is assigned a processor and now is running . Dead state -Thread has completed or exited -Eventually disposed off by system Thread’s Joining -Used when a thread wants to wait fo ethod -For example, if thread2 sent the thread2.join() message, it causes the currently executing thread to block efficiently until thread2 finishes its run() method public class Worker implements Runnable { private String job ; public Worker (String j ){ job = j;} public void run ( ) {for(int i=1; i= 10; i++) { System.out.println(job + = + i); } // end for} // end run} // end class The class JoinEx will demonstrate how current running (main) blocks until the remaining threads finished their run( ) // File JoinEx.java public class JoinEx { public static void main (String args[ ]){ Worker first = new Worker (first job);Worker second = new Worker (second job); System.out.println(Starting...); // starting threads t1.start(); t2.start(); }catch (Exception ex) {System.out.println(ex);} System.out.println } // end main} r another thread to complete its run( ) m -Calling join method can throw InterruptedException, so you must use try-catch block to handle it Example Code: Demonstrating join( ) usage Below the modified code of Worker.java is given. It only prints the job of the worker // File Worker.java Thread t1 = new Thread (first ); Thread t2 = new Thread (second); // The current running thread (main) blocks until both //workers have finished try { t1.join(); t2.join(); (All done );
  • 241.
    Web Design Development – CS506 VU © Copyright Virtual University of Pakistan 241 Ou On exec . Since main thread do not finish until both threads have finished their run( ). Therefore “All done” will be print on last. tput uting JoinEx, notice that “Starting” is printed first followed by printing workers jobs References: ed ƒ Java, A Practical Guide by Umair Jav ƒ Java tutorial by Sun : http://java.sun.com/docs/books/tutorial/ ƒ CS193j handouts on Stanford
  • 242.
    Web Design Development – CS506 VU © Copyright Virtual University of Pakistan 242 Lesson 25 Web Application Development Introduction Because of the re becoming vital part of IT infrastructure of ance management systems are used by orga hand online course registration and examination systems can allow students to study while staying at their homes. Web Applic o wide spread use of internet, web based applications a large organizations. For example web based employee perform nizations for weekly or monthly reviews of employees. On the other atins In general a we connected to w se ommunication ent (usually a web-browser) sends b application is a piece of code running at the server which facilitates a remote user eb server through HTTP protocol. HTTP protocol follows stateless Request-Responmodel. Cli c Figure 1: A typical web application A web server is software which provides users, access to the services that are present on the internet. These servers can provide support for many protocols used over internet or intranet like HTTP, FTP, telnet etc HTTP Basics A protocol defines the method and way of communication between two parties. For example when we talk to our teacher we use a certain way which is different from the way that we adopt with our fiends or parents. Similarly there are many different protocols used by computers to communicate with each other depending on applications. Figure 2: HTTP communication model -HTTP is as request-response oriented protocol. -It is a stateless protocol since there is no built-in state management between successive requests. We will discuss state later.
  • 243.
    Web Design Development – CS506 VU © Copyright Virtual University of Pakistan 243 Par f ts o an HTTP request -Request Method: It tells the server the type of action that a client wants to perform -URI: Uniform Resource Indictor specifies the address of required document or resource -Header Fields: Optional headers can be used by client to tell server extra Figure 3: HTTP request example -Body: Contains data sent by client to the server -Other request headers like FROM (email of the person responsible for request) and VIA (used by gateways and proxies to show intermediate sites the request passes) can also be used. 1. In URL as query string e.g. http://www.gmail.com/register?name=alistate=punjab 2. As part of request body (see Figure 3) Parts of HTTP response Request Parameters ƒ Request can also contain addition information in form of request parameters Result Code: A numeric status code and its description. -Header Fields: Servers use these fields to tell client about server information like configurations and software etc. -Body: Data sent by server as part of response that is finally seen by the user.
  • 244.
    Web Design Development – CS506 VU © Copyright Virtual University of Pakistan 244 Figure 4: HTTP response example HTTP Response Codes ƒ An HTTP Response code tell the client about the state of the response i.e. whether it’s a valid response or some error has occurred etc. HTTP Response codes fall into five general categories • 100-199 Codes in ld respond with some other action. 100: Continue with partial request. • 200-299 Values in the 200s signify that the request was successful. 200: Means every thing is fine. • 300-399 Values in the 300s are used for files that have moved and usually include a Location header indicating the new address. 300: Document requested can be found several places; they'll be listed in the returned document. • 400-499 Values in the 400s indicate an error by the client. 404: Indicates that the requested resource is not available. 401: Indicates that the request requires HTTP authentication. 403: Indicates that access to the requested resource has been denied. • 500-599 Codes in the 500s signify an error by the server. 503: Indicates that the HTTP server is temporarily overloaded and unable to handle the request. the 100s are informational, indicating that the client shou
  • 245.
    Web Design Development – CS506 VU © Copyright Virtual University of Pakistan 245 ƒ 404: indicates that the requested resource is not available ƒ 401: Indicates that request requires HTTP authentication Server Side Programming Web server pages can be either static pages or dynamic pages. A static web page is a simple HTML (Hyper Text Transfer Language) file. When a client requests an HTML page the server simple sends back response with the required page.
  • 246.
    Web Design Development – CS506 VU © Copyright Virtual University of Pakistan 246 Figure 5: Static web page request and response An example of static web page is given below While in case of dynamic web pages server executes an application which generates HTML web pages according to specific requests coming from client. These dynamically generated web pages are sent back to client with the response. Figure 6: Dynamic web page request and response
  • 247.
    Web Design Development – CS506 VU © Copyright Virtual University of Pakistan 247 Why build Pages Dynamically? Wr confirmation pages at on line stores. ] e need to create dynamic web pages when the content of site changes frequently and client specific esponse is required. Some of the scenarios are listed below -The web page is based on data submitted by the user. e.g. results page from search engines and order Web page is derived from data that changes frequently. e.g. a weather report or news headline The s page.
  • 248.
    Web Design Development – CS506 VU © Copyright Virtual University of Pakistan 248 The Web page uses information from databases or other server-side resources. e.g. an e-commerce site could use a ser Web page that lists the current price and availability of each item that is for sale. vlet to build a -Using technologies for developing web pages that include dynamic content. -Developing web based applications which can produce web pages that contain information that is connection-dependent or time-dependent. Dyn Dynamic web content development technologies have evolved through time in speed, security, ease of use te based technologies like plex web pages. Sun Java vlets and JSP that provided more speed and security as well as better tools for web page amic Web Content Technologies Evolution and complexity. Initially C based CGI programs were on the server Then templaASP and PHP were then introduced which allowed ease of use for designing com introduced Ser creation. Figure 7: Dynamic web content technologies evolution
  • 249.
    Web Design Development – CS506 VU © Copyright Virtual University of Pakistan 249 Layers and Web Application ally web applications are partitioned into logical layers. Each layer performs a specific ixed with other layers. Layers are isolated from each other upling between them but they provide interfaces to communicate with each other. Norm functionality which should not be m to reduce co Figure 8: Simplified view of a web application and its layers user interface for client to interact with application. This is the only part of application visible to client. -Business Layer The business or service layer implements the actual business logic or functionality of the application. This layer consists of objects that represent real-world business objects such as an Order, OrderLineItem, Product, and so on. ere ar nologies available for web application development which includes Java Servlets, -Presentation Layer: Provides a For example in case of online shopping systems this layer handles transaction management. -Data Layer The several Java tech JavaServer Pages, JavaServer Faces etc. Figure 9: Java web application technologies (presentation/web tier) References: ƒ Java, A Practical Guide by Umair Javed ƒ Java tutorial by Sun: http://java.sun.com/docs/books/tutorial/
  • 250.
    Web Design Development – CS506 VU © Copyright Virtual University of Pakistan 250 Lesson 26 Java Servlets Servlets are java technology’s answer to CGI programming. CGI was widely used for generating dynamic content before Servlets arrived. They were programs written mostly in C,C++ that run on a web server and a servlet, servlet generates dynamic content, mostly in the form of HTML pages, and returns it back to the server, which sends it back to the client. Hence we can say that servlet is extending the functionality of the webserver (The job of the earlier servers was to respond only to request, by may be sending the required html file back to the client, and generally no processing was performed on the server) used to build web pages. As you can see in the figure below, a client sends a request to web server, server forwards that request to What Servlets can do? ƒ Servlets can do anything that a java class can do. For example, connecting with database, reading/writing data to/from file etc. ƒ Handles requests sent by the user (clients) and generates response dynamically (normally HTML pages). ƒ The dynamically generated content is send back to the user through a webserver (client) Servlets vs. other SSP technologies The java’s servlet technology has following advantage over their counter parts: Convenient Servlets can use the whole java API e.g. JDBC. So if you already know java, why learn Perl or C. Servlets have an extensive infrastructure for automatically parsing and decoding HTML form data, reading and sending HTTP headers, handling cookies and tracking session etc and many more utilities Efficient With traditional CGI, a new process is started for each request while with servlets each request is handled by a lightweight java thread, not a heavy weight operating system process. (more on this later) Powerful Java servlets let you easily do several things that are difficult or impossible with regular CGI. For example, servlets can also share data among each other
  • 251.
    Web Design Development – CS506 VU © Copyright Virtual University of Pakistan 251 Portable Since java is portable and servlets is a java based technology therefore they are generally portable across web servers Inexpensive There are numbers of free or inexpensive web servers available that are good for personal use or low volume web sites. For example Apache is a commercial grade webserver that is absolutely free. However some very high end web and application servers are quite expensive e.g BEA weblogic. We’ll also use Apache in this course Software Requirements To use java servlets will be needed ƒ J2SE ƒ Additional J2EE based libraries for servlets such as servlet-api.jar and jsp-api.jar. Since these libraries are not part of J2SE, you can download these APIs separately. However these APIs are also available with the web server you’ll be using. ƒ A capable servlet web engine (webserver) Jakarta Servlet Engine (Tomcat) Jakarta is an Apache project and tomcat subprojects. Apache Tomcat is an open source web server, which is used as an official reference implementation of Java Servlets and Java Server Pages technologies. Tomcat is developed in an open and participatory environment and released under the Apache software license Environment Setup is one of its To work with servlets and JSP technologies, you first need to set up the environment. Tomcat installation can be performed in two different ways (a) using .zip file (b) using .exe file. This setup process is broken down into the following steps: 1 Download the Apache Tomcat Server 2 Install Tomcat 3 Set the JAVA_HOME variable 4 Set the CATALINA_HOME variable 5 Set the CLASSPATH variable 6 Test the Server Environment Setup Using .zip File Let’s take a detail look on each step and get some hands on experience of environment setup. 1. Download the Apache Tomcat Server From the http://tomcat.apache.org, download the zip file for the current release (e.g. jakarta-tomcat- 5.5.9.zip or any latest version) on your C: drive. There are different releases available on site. Select to dow a ote: J2SE 5.0 must be installed prior to use the 5.5.9 version of tomcat. nlod .zip file from the Binary Distributions Æ core section. N
  • 252.
    Web Design Development – CS506 VU © Copyright Virtual University of Pakistan 252 2. Installing Tomcat using .zip file -Unzip the file into a location (e.g. C:). (Rightclick on the zip file and select unziphere option ) hen the zip file will unzipped a directory structure will be created on your computer such as: -W -Th : or CATALINA_HOME No s create their own directory and unzip the file there such as C:jakarta-tomcat-5.5.9jakarta-tomcat- 5.5.9.This causes problems while giving path information 3. Set ƒ JAVA_HOME indicates the root directory of your jdk. Set the JAVA_HOME environment bin r icon. Select the advanced tab, a System Properties window n below. Select the Environment Variables button to proceed. ƒ On clicking Environment Variable button, the Environment Variables window will open as shown next ƒ Create a new User variable by clicking New button as shown above, the New User Variable window will appear ƒ Set name of variable JAVA_HOME ƒ The value is the installation directory of JDK (for example C:ProgramFilesj2sdk_nbj2sdk1.4.2). This is shown below in the picture. Please note that bin folder is not included in the path. ƒ Press Ok button to finish e Cjakarta-tomcat-5.5.9 folder is generally referred as root directory te: After extraction, make sure C:jakarta-tomcat-5.5.9 contains a bin subdirectory. Sometimesstudent theJAVA_HOME variable variable to tell Tomcat, where to find java ase JDK installation directory, not the subdirectory ƒ This variable should list the b ƒ To set it, right click on My Co mputewill appear in front of you like show
  • 253.
    Web Design Development – CS506 VU © Copyright Virtual University of Pakistan 253
  • 254.
    Web Design Development – CS506 VU © Copyright Virtual University of Pakistan 254 4. Set the CATALINA_HOME variable CATALINA_HOME is used to tell the system about the root directory of the TOMCAT. There are various files (classes, exe etc) needed by the system to run. CATALINA_HOME is used to tell your system (in this case your web server Tomcat) where the required files are. ƒ To Set the CATALINA_HOME environment variable, create another User Variable. ƒ Type CATALINA_HOME as the name of the environment variable. ƒ Its value should be the path till your top-level Tomcat directory. If you have unzipped the Tomcat in C drive. It should be C:jakarta-tomcat-5.5.9.This is shown below: ƒ Press Ok button to finish Note: To run Tomcat (web server) you need to set only the two environment variables NA_HOME f the Java 2 platform, standard edition, you have to identify the servlet classes to the compiler. The server already knows about the servlet classes, but the compiler (i.e., r compiling source files of servlet does not. So if you don't set your CLASSPATH, any ƒ To Set the CLASSPATH environment variable, create another User Variable. ƒ Type CLASSPATH as the name of the environment variable. ƒ Its value should be the path for servlet-api.jar and jsp-api.jar. These file can be found on following path: commonlibjsp-api.jar • Both these api’s are specified as values with semicolon between them. Remember to add semicolon dot semicolon (;.;) at the end too. For example and these are JAVA_HOME CATALI 5. Set the CLASSPATH variable Since servlets and JSP are not part o javac) you use fo attempt to compile servlets, tag libraries, or other classes t hat use the servlet API will fail with error messages about unknown classes. • C:jakarta-tomcat-5.5.9commonlibservlet-api.jar • C:jakarta-tomcat-5.5.9
  • 255.
    Web Design Development – CS506 VU © Copyright Virtual University of Pakistan 255 Classpath = C:jakarta-tomcat-5.5.9commonlibservlet-api.jar;C:jakarta-tomcat 5.5.9commonlibjsp-api.jar;.; This is also shown in the figure below — Press OK button to finish the setting of CLASSPATH variable 6. Test the server Before making your own servlets and JSP, verify that the server is working properly. Follow these steps in order to do that: ƒ Open the C:jakarta-tomcat-5.5.9bin folder and locate the startup.batfile. ƒ Double clicking on this file will open up a DOS window, which will disappear, and another DOS window will appear, the second window will stay there. If it does not your paths are not correctly set. ƒ Now to check whether your server is working or not, open up a browser window and type http://localhost:8080. This should open the default page of Tomcat as shown in next diagram: Note: If default page doesn’t displayed, open up an internet explorer window, move on to Tools Æ Internet Options Æ Connections LAN Settings. Make sure that option of “Bypass proxy server for local addresses” is unchecked.
  • 256.
    Web Design Development – CS506 VU © Copyright Virtual University of Pakistan 256 There is another easier way to carry out the environment setup using .exe file. However, it is strongly recommended that you must complete the environment setup using .zip file to know the essential fundamentals. t Setup Using .exe File Environmen Let’s look at the steps involved to accomplish the environment setup using .exefile. Download the Apache Tomcat Server Fro 1. m the http://tomcat.apache.org, download the .exe file for the current release (e.g. jakarta-tomcat- ) on your C: drive. There are differen 5.5.9.zip t releases available on site. Select to download Windows executable (.exe) file from Binary Distributions Core section. Note: J 5.9 version of tomcat. 2. I uble clicking on it. -Moving forward in setup, you will reach to the following window -Select install type “Full” and press Next button to proceed. 2SE 5.0 must be installed to use the 5. nstalling Tomcat using .exe file -Run the .exefile by do
  • 257.
    Web Design Development – CS506 VU © Copyright Virtual University of Pakistan 257 -Choose the folder in which you want to install Apache Tomcat and press Next to proceed. The configuration window will be opened. Leave the port unchanged (since by default web servers run on port 8080, you can change it if you really want to). Specify the user name password in the specified coming next: - fields and press Next button to move forward. This is also shown in the diagram
  • 258.
    Web Design Development – CS506 VU © Copyright Virtual University of Pakistan 258 -The setup will automatically select the Java Virtual Machine path. Click Install button to move ahead. -Fin Run Apache Tomcat option selected. It will cause the tomcat server to run in quick launch bar as shown in diagram below. The Apache Tomcat shortcuts will also added to ish the setup with the Programs menu. -Double clicking on this button will open up Apache Tomcat Properties window. From here you can start s configure many options if you want to. This properties window below: or top your web server. You can also is shown 3C . Se E variable 5. Set the CLASSPATH variable Same as step 5 of .zip installation mode 6. Test the server If tomcat installation is made using .exe file, follow these steps t the JAVA_HOM hoosing .exe mode does not require completing this step. 4. Set the CATALINA_HOME variable Choosing .exe mode does not require completing this step.
  • 259.
    Web Design Development – CS506 VU © Copyright Virtual University of Pakistan 259 -Open the Apache Tomcat properties window by clicking on the Apache Tomcat button from Quick Launch. -Start the tomcat server if it is not running by clicking on Start button. /localhost:8080 -Open up a browser window and type http:/ . This should open the default page of Note: If default page doesn’t displayed, open up an internet explorer window, move on to Tools Æ Internet Options Æ Connections LAN Settings. Make sure that option of “Bypass proxy server for local addresses” is unchecked. Tomcat as shown in the next diagram: References: . Java, A Lab Course by Umair Javed . Jav e a Srvlet JSP tutotrial http://www.apl.jhu.edu/~hall/java/Servlet-Tutorial/
  • 260.
    Web Design Development – CS506 VU © Copyright Virtual University of Pakistan 260 Lesson 27 Creating a Simple Web Application in Tomcat iscuss the standard tomcat directory structure, a pre-requisite for building any web d bolts of Servlets will also be discussed. In the later part of this handout, we’ll pplication using servlet. ion web a be used ƒ Unp g development ƒ Pac o Known as Web Archive (WAR) file The web s folder is the t n the server. Each app In this handout, we’ll dapplication. Different nuts ana lso learn how to make a simple web a Standard Directory Structure of a J2EE Web ApplicatA pplication is defined as a hierarchy of directories and files in a standard layout. Such hierarchies can in two forms ack o Where each directory file exists in the file system separately o Used mostly durin k o Mostly used to deploy web applications app op-level Tomcat directory that contains all the web applications deployed olication is deployed in a separate folder often referred as “context”. To make a new application e.g myapp in tomcat you need a specific folder hierarchy. -Create a folder named myapp in C:jakarta-tomcat-5.5.9webapps folder. This name will also appear in /localhost:8080/myapp/index.html the URL for your application. For example http:/ -All JSP and n folder (C:jakartatomcat-5.5.9webappsmyapp) -Create another folder inside myapp folder and change its name to WEB-INF. Remember WEB-INF is case sensitive html files will be kept in main applicatio and it is not WEB_INF
  • 261.
    Web Design Development – CS506 VU © Copyright Virtual University of Pakistan 261 -Configuration EB-INF folder (C:jakarta-tomcat- B-INF folder and change its name to classes. Remember classes name is also case sensitive. files such as web.xml will go in W 5.5.9webappsmyappWEB-INF) -Create another folder inside WE -Servlets and Java Beans will go in classes folder (C:jakarta-tomcat5.5.9webappsmyappWEB- INFclasses) That’s the minimum directory structure required in order to get started. This is also shown in the figure below: n hierarchy, make a simple html file e.g. index.html file. W -To test applicatio rite some basic HTML code into it and save it in main application directory i.e. C:jakarta-tomcat-5.5.9webappsmyapp -Restart the server and access it by using the URL http://localhost:8080/myapp/index.html -A more detailed view of the Tomcat standard directory structure is given below.
  • 262.
    Web Design Development – CS506 VU © Copyright Virtual University of Pakistan 262 -Here you can see some other folders like lib tags under the WEB-INF. -The lib folder is required if you want to use some achieve files (.jar). For example an API in jar format that can help generating .pdf files. -Similarly tags folder is helpful for building custom tags or for using .tagfiles. Note: Restart Tomcat every time you create a new directory structure, a servlet or a java bean so that it can recognize it. For JSP and html files you don’t have to restart the server. Writing Servlets Servlet or HttpServlet ilable in javax.servlet package ailable in javax.servlet.http package ƒ Extends from GenericServletclass Servlet Types -Servlet related classes are included in two main packages javax.servletand javax.servlet.http. -Every servlet must implement the javax.servlet.Servlet interface, it contains the servlet’s life cycle methods etc. (Life cycle methods will be discussed in next handout) - o Inrder to write your own servlet, you can subclass from Gerneric GenericServlet class ƒ Ava ƒ Implements javax.servlet.Servlet ƒ Extend your class from this class if you are interested in writing protocol independent servlets HttpServlet class ƒ Av
  • 263.
    Web Design Development – CS506 VU © Copyright Virtual University of Pakistan 263 ƒ Adds functionality for writing HTTP specific servlets as compared to GernericServlet ƒ Extend your class from HttpServlet, if you want to write HTTP based servlets Servlet Class Hierarchy The Servlet class hierarchy is given below. Like all java classes GenericServletalso inherits from Object class. Apart from GenericServlet and HttpServlet classes, ServletRequest, HttpServletRequest, ServeltResponse and HttpServletResponse are also helpful in writing a servlet. As you can guess ServletRequest ServletResponse are used in conjunction with GenericServlet. These classes are used for processing protocol independent requests and generating protocol independent responses respectively. javax.servlet.http HttpServletRequest HttpServletRespose are used for processing HTTP protocol specific requests and generating HTTP specific response. Obviously these classes will be used in conjunction with HttpServet class, which means you are making a HTTP protocol specific servlet. Types of HTTP requests HTTP supports different types of request to be sent over to server. Each request has some specific purpose. The most important ones are get post. Given below a brief overview of each request type is given. You can refer to RFC of HTTP for further details. -GET: Requests a page from the server. This is the normal request used when browsing web pages. -POST: This request is used to pass information to the server. Its most common use is with HTML forms. -PUT: Used to put a new web page on a server. -DELETE: Used to delete a web page from the server. -OPTIONS: Intended for use with the web server, listing the supported options.
  • 264.
    Web Design Development – CS506 VU © Copyright Virtual University of Pakistan 264 -TRACE: Used to trace servers -Attribute-Value pair is attached with requested URL after ‘?’. xample if attribute is ‘name’ and value is ‘ali’ then the request will be http://www.gmail.com/register?name=ali . POST -Attribute-Value pair attached within the request body. For your reference HTTP request diagram is GET POST, HTTP request types Some details on GET and POST HTTP request types are given below. . GET -For e -For HTTP based servlet, override doGet() methods of HttpServlet class to handle these type of requests. given below again: -Override doPost() method of HttpServlet class to handle POST type requests. Steps for making a Hello World Servlet To get started we will make a customary “HelloWorldServlet”. Let’s see what are the steps involved in writing a servlet that will produce “Hello World” 1. Create a directory structure for your application (i.e. helloapp). This is a one time process for any application 2. Create a HelloWorldServlet source file by extending this class from HttpServlet and overriding your desired method. For example doGet() or doPost(). 3. Compile it (If get error of not having required packages, check your class path) 4. Place the class file of HelloWorldServlet in the classes folder of your web application (i.e. myapp). Note: If you are using packages then create a complete structure under classes folder 5. Create a deployment descriptor (web.xml) and put it inside WEB-INF folder 6. Restart your server if already running 7. Access it using Web browser
  • 265.
    Web Design Development – CS506 VU © Copyright Virtual University of Pakistan 265 Example Code: HelloWorldServlet.java ages import java.io.*; import javax.servlet.*; import javax.servlet.http.*; // extending class from HttpServelt public class HelloWorldServlet extends HttpServlet { /* overriding doGet() method because writing a URL in the browserby default generate request of GET type As you can see, HttpServletRequest andHttpServletResponse are passed to this method. Theseobjects will help in processing of HTTP request andgenerating response for HTTP This method can throw ServletException or IOException, so wemention these exception types after method signature */ public void doGet(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException etWriter method on it As mentioned, for generating response, we will World in the browser using PrintWriter object. You can also write HTML like out.println(“h1 Hello World /h1”) */ Xtensible Markup Language (xml) contains custom defined tags which convey information about the ontent. To learn more about XML visit http schools.com //File HelloWorldServlet.java // importing required pack { /* getting output stream i.e PrintWriter from responseobject by calling g useHttpServletResponse object*/ PrintWriter out = response.getWriter(); /* printing Hello out.println(“Hello World! ”); } // end doGet() } // end HelloWorldServlet xample Code: web.xml E ec ://ww.w3 . ?xml version=1.0 encoding=ISO-8859-1? w Inside web.xml, the web-app is the root ta g representing the web application. All other tags come inside of it. eb-app servlet servlet-name HelloWorldServlet /servlet-name servlet-class HelloWorldServlet /servlet-class /servlet servlet-mappingservlet-name HelloWorldServlet
  • 266.
    Web Design Development – CS506 VU © Copyright Virtual University of Pakistan 266 /servlet-nameurl-pattern /myfirstservlet /url- The class. To specify the name of servlet, servlet-name tag is used. Similarly to specify the class name of servlet (it is the same name you used for making a No This name is used for referring to servlet in later part of web.xml. You can think of it as your id assigned to your university while you have actually different name (like servlet-class). ext w g using servlet-name tag and then you will define the URL pattern using url-pecifying the url. You can specify any name of ation. url-pattern /myfirstservlet /url-pattern Now you can access HelloWorldServelt (if it is placed in myapp application) by giving the following url in ote: Save this web.xml file by placing double quotes(“web.xml”) around it as you did to save .java files. Compiling and Invoking Servlets -Compile HelloWorldServlet.java using javac command. -Put HelloWorldServlet.class in C:jakarta-tomcat5.5.9/webapps/myapp/WEB-INF/classes folder -Put web.xml file in C:jakarta-tomcat5.5.9/webapps/myapp/WEB-INF folder -Invoke your servlet by writing following URL in web browser. Don’t forget to restart your tomcat server if already running http://localhost:8080/myapp/myfirstservlet Note: By using IDEs like netBeans® 4.1, you don’t have to write web.xml by yourself or even to worry about creating directory structure and to copy files in appropriate locations. However manually undergoing this process will strengthen your concepts and will help you to understand the underlying mechanics☺. References: pattern/servlet-mapping /web-app servlet tag represents one’s servlet name and its servlet), servlet-classtag is used. te: It is important to note here that you can specify any name for a servlet inside servlet-name tag. you by N e will define the servlet mapping. By defining servlet mapping we are specifying URL to access a servlet. servlet-mapping tag is used for this purpose. Inside servlet-mapping tag, first you will write the name of the servlet for which you want to specify the URL mappin pattern tag. Notice the forward slash (/ ) is used before sURL. The forward slash indicates the root of your applic the browser http://localhost:8080/myapp/myfirstservlet N Entire material for this handout is taken from the book JAVA A Lab Course by Umair Javed. This material is available just for the use of VU students of the course Web Design and Development and not for any other commercial purpose without the consent of author.
  • 267.
    Web Design Development – CS506 VU © Copyright Virtual University of Pakistan 267 Lesson 28 Servlets Lifecycle en how to write a simple servlet. In this handout we will look more ed. What different set of method are invoked during the fecycle reading HTML form data through servlet technology. This will be explored in etail using code example e e passage of time a servlet passes through these stages one after another. In the last handout, we have sespecifically on how servlets get created and destroy li of a typical servlet. The second part consists on d Stages of Servlet Lifecycl A servlet passes through the following stages in its life. 1 Initialize 2 Service 3Destroy As you can conclude from the diagram below, that with th 1. Initialize When the servlet is first created, it is in the initialization stage. The webserver invokes he init() method of the servlet in this stage. It should be noted here that init() is only called once and is not called for each requ t. itialization ng ge The service() method is the engine of the servlet, which actually processes the client’s request. On every request from the client, the server spawns a new thread and calls the service() method as shown in the figure below. This makes it more efficient as compared to the technologies that use single thread to respond to es Since there is no constructor available in Servlet so this urges its use for one time in of resources, setting of parameters etc) just as the init() method of applet. (loadiIn itialize stage has the following characteristics and usa ƒ Executed once, when the servlet gets loaded for the first time ƒ Not called for each client request ƒ The above two points make it an ideal place to perform the startup tasks which are done in constructor in a normal class. 2. Service requests.
  • 268.
    Web Design Development – CS506 VU © Copyright Virtual University of Pakistan 268 The figur am, we assum let. (Remember, GenericServlet is used for constructing protocol independent servlets.). To provide the desired functionality, service() method is to the web server; a new thread is created to serve this request service() method. Finally a response is prepared and sent back to the user according e below show both versions of the implementation of service cycle. In the upper part of diagr e that servlet is made by sub-classing from GenericServ overridden. The client sends a request followed by calling the to the request. The second part of the figure illustrates a situation in which servlet is made using HttpServlet class. Now, this servlet can only serves the HTTP type requests. In these servlets doGet() and doPost() are overridden provide desired behaviors. When a request is sent to the web server, the web server after creating a thread, passes on this request to service() method. The service() method checks the HTTP requests type (GET, POST etc) and calls the doGet() or doPost() method depending on how the request is originally sent. st() method, the response is sent back to the service() erver. to After forming the response by doGet() or doPomethod that is finally sent to the user by the web s
  • 269.
    Web Design Development – CS506 VU © Copyright Virtual University of Pakistan 269 3. Destroy The web server may decide to remove a previously loaded servlet instance, perhaps because it is explicitly sked to do so by the server administrator, or perhaps servlet container shuts down or the servlet is idle for e, or may be the server is overloaded. Before it does, however it calls the servlets destroy() method. This makes it a perfect spot for releasing the acquired resources. Summary ƒ is constructed and initialized. The initialization can be performed inside of init() method. ƒ e() method that may decide to call further methods depending upon t ype (Generi TTP specific) ƒ s down, Servlet is destroyed and garbage is collected The following figure can help to summarize the life cycle of the Servlet a a long tim A Servlet Servlet services zero or more requests by calling serviche Servlet tc or H Server shut The web sever creates a servlet instance. After successful creation, the servlet enters into initialization phase. Here, init() method is invoked for once. In case web server fails in previous two stages, the servlet instance is unloaded from the server. After initialization stage, the Servlet becomes available to serve the clients requests and to generate response accordingly. Finally, the servlet is destroyed and unloaded from web server. Reading HTML Form Data Using Servlets In the second part, the required concepts and servlet technology is explored in order to read HTML form data. To begin with, let’s first identify in how many ways a client can send data
  • 270.
    Web Design Development – CS506 VU © Copyright Virtual University of Pakistan 270 HTML Servlets Generally HTML is used as a Graphic a Servlet. In the figure below, HTML form is ents. s User Interface for being used as a GUI interface for MyServlet. The data entered by the user in HTML form is transmitted to the MyServlet that can process this data once it read out. Response may be generated to fulfil the application requirem Types of Data send to Web Server When a user submits a browser request to a web server, it sends two categories of data: HTML form. For example: registration information provided . HTTP Request Header Data Data, which is automatically, appended to the HTTP Request from the client for example, cookies, browser type, and browser IP address. Based on our understanding of HTML, we now know how to create user forms. We also know how to gather user data via all the form controls: text, pass checkbox, radio buttons, etc. Now, the question arises: if I submit form data to a Servlet, h w do I extract this form data from servlet? Figuring Reading HTML Form Data from Servlet Now let see how we can read data from “HTML form” using Servlet. The HttpServletRequest object contains three main methods for extracting form data submitted by the user: . getParameter(String name) -Used to retrieve a single form parameter and returns String corresponding to name specified. -Empty String is returned in the case when user does not enter any thing in the specified form field. -If the name specified to retrieve the value does not exist, it returns null. Note: You should only use this method when you are sure that the parameter has only one value. If the parameter might have more than one value, use getParamterValues(). . Form Data Data, that the user explicitly type into anfor creating a new email account. word, select, o this out, provides the basis for creating interactive web applications that respond to user requests.
  • 271.
    Web Design Development – CS506 VU © Copyright Virtual University of Pakistan 271 . getParameterValues(String name) er names, this method will be helpful s of the parameters that come with the -If meration. ote: All these methods discussed above work the same way regardless of the request type(GET or “userName” is not the same as the e html), one servlet (MyServlet.java) and one xml file (we eters: firstName and surName. The Servlet extracts thes e browser after appending “Hello”. Note: The example given below and examples later i coming handouts are built using netBeans®4.1. It’s important to note that tomcat server bundled with netBeans® runs on 8084 port by default. -Returns an array of Strings objects containing all of the given values of the given request parameter. -If the name specified does not exist, null is returned . getParameterNames() -If you are unsure about the paramet -It returns Enumeration of String objects containing the namerequest. the request has no parameters, the method returns an empty Enu N POST). Also remember that form elements are case sensitive for example, “usrname.” E xample Code: Reading Form Data using Servlet This example consists of one HTML page (inde. x b.xml) file. The HTML page contains two form parame specific parameters and echoes them back to th n index.html
  • 272.
    Web Design Development – CS506 VU © Copyright Virtual University of Pakistan 272 Let’s struct the above page. html title Reading Two Parameters /title body H2 Pleas FORM OD=GET ACTION=http://localhost:8084/paramapp/formservletNAME=myform BR Firstname: INPUT TYPE = “text” NAME=firstName BR Surname: NPUT TYPE = “text” NAME=surName t Form INPUT TYPE=reset /body /html Let’s discuss the code of above HTML form. As you can see in the FORM tag, the attribute ME to “GET”. The possible values for this attribute can be GET and POST. Now what do the od attribite to “GET” means that we want to send the HTTP request using the the doGet() method of the servlet. In the GET method the information in the input fields entered by the user, merges with the URL as the query string and are visible to the user. ƒ s the entered information from the user as this mes the part of request body and activates doPost() method of the servlet. Attribute ACTION of FROM tag is set to http://localhost:8084/paramapp/formservlet. The form nsmitted to this URL. paramapp is the name of web application created using netBeans. alue of url-pattern defined in th web.xml. The code of web.xml is given at the end. The NAME attribute is set to “myform” that helps when the same page has more than one forms. However, here it is used only for demonstration purpose. To create the text fields where user can enter data, following lines of code come into play INPUT TYPE = “text” NAME=firstName INPUT TYPE = “text” NAME=surName Each text field is distinguished on the basis of name assigned to them. Later these names also help in extracting the values entered into these text fields. have a look on the HTML code used to con head /head e fill out this form: /H2 METH I BR INPUT TYPE=submit value=Submi value=Reset /FORM THODis set se values mean? ƒ Setting the methGET method which will evantually activate Setting METHOD value to “POST” hideinformation beco data will be traformservlet is the v e
  • 273.
    Web Design Development – CS506 VU © Copyright Virtual University of Pakistan 273 MyServlet.java Now lets take a look at the servlet code to which HTML form data is submitted. ervlet extends HttpServlet{ public void doGet(HttpServletRequest req, HttpServletResponse res)throws ServletException, // reading first name parameter/textfield etParameter(“firstName”); // gettting stream from HttpServletResponse objectPrintWriter out = res.getWriter(); out.println(Hello: + fName + “ “ +sName ); out.close(); }// d We started the code with importing three packages. import java.io.*, import javax.servlet.*; import javax.servlet.http.*; These packages are imported to have the access on PrintWriter, HttpServlet, HttpServletRequest, Htt he s alue of mehtod attribute was set to “GET”. So in this case, we only need to override doGet()Method. Entering inside doGet() method brings the crux of the code. These are: String fName = req.getParameter(“firstName”); r(“surName”); t” NAME=firstName INPUT TYPE = “text” NAME=surName In the last part of the code, we get the object of PrintWriter stream from the object of import java.io.*;import javax.servlet.*;import javax.servlet.http.*; public class MyS IOException{ String fName = req.g // reading surname parameter/textfield String sName = req.getParameter(“surName”); } en FormServlet pServletResponse, ServletException and IOException classes. THTML code (index.html) discussed above, the v clas MySevlet extends from HttpServlet to inherit the HTTP specific functionality. If you recall String sName = req.getParamete Two String variables fName and sName are declared that receive String values returned by getParameter() method. As discussed earlier, this method returns Stringcorresponds to the form parameter. Note that the values of name attributes of input tags used in index.html have same case with the ones passed to getParameter() methods as parameters. The part of HTML code is reproduced over here again: INPUT TYPE = “tex
  • 274.
    Web Design Development – CS506 VU © Copyright Virtual University of Pakistan 274 HttpServletResponse. This object will be used to send data back the response. Using PrintWriter object (out s are printed with appended “Hello” that becomes visible in the browser. web.xml ?xml version=1.0 encoding=ISO-8859-1? web-app serv /s servlet-mapping servlet-name FormServlet /servlet-name url-pattern /formservlet /url-pattern mapping /web-app The servlet-mapping tag contains two tags servlet-name and urlpatteren containing name and pattern of the URL respectively. Recall the value of action attribute of the form element in the HTML ost:8084/paramapp/formservlet Re ), the name let servlet-name FormServlet /servlet-name servlet-class MyServlet /servlet-class ervlet /servlet- page. You can see it is exactly the same as mentioned in url-pattern tag. http://localh ferences: ƒ JAVA a Lab Course by Umair Javed ƒ Java API documentation ervlets and JSP by Marty Hall ƒ Core S
  • 275.
    Web Design Development – CS506 VU © Copyright Virtual University of Pakistan 275 Lesson 29 More on Servlets The objective of this handout is to learn about the use and implementation of initialization parameters for a Servlet. M and forwarding or including requests also discussed in detail. Initializat Some times at the time of starting up the application we need to provide some initial information e,g, name of the file where server can store logging information, DSN for database etc. Initial configuration can be defined for a Servlet by defining some string parameters in web.xml. This allows a Servlet to have initial parameters from outside. This is similar to providing command line parameters to a standard console based application. init-param //defining param 1 param-name param1 /param-name param-value value1 /param-value init-param //defining param 2 param-param In the above code, it is shown that for each parameter we need to define separate initparam tag that have two sub tags param-name and param-value, which contain the name and values of the parameter respectively. ServletConfig h it as shown in the fig. below. It contains levant mation about the Servlet like initialization parameters defined in web.xml oreover different ways of redirecting response ion Parameters Example: setting init parameters in web.xml Let’s have a look on the way of defining these parameters in web.xml /init-param name param2 /param-name -value value2 /param-value Every Servlet has an object called ServletConfig associated witre infor
  • 276.
    Web Design Development – CS506 VU © Copyright Virtual University of Pakistan 276 Reading Initialization Parameters t’s see tParameter()of r, matches it with param-name One way is to override init() method as shown in the code below. The ServletConfig object can then be used to read init public void init(ServletConfig config) throws ServletException { String nam etInitParameter(“paramName”); other way to read initialization parameters out side the init () method is ƒ Call getServletConfig() to obtain the ServletConfig object ƒ Use getInitParameter() of ServletConfig to read initialization parameters thod() // defined inside servlet{ ServletConfig config = getServletConfig(); String name = config.getInitParameter(“param_name); } Example Code: Reading init parameters MyServlet.java will read the init parameter (log file name) defined inside web.xml. The code is given below: import java.io.*; import java.net.*; import javax.servlet.*; import javax.servlet.http.*; public class MyServlet extends HttpServlet { // attribute used to store init-parameter value String fileName; // overriding init() method public void init(ServletConfig config) throws ServletException{ super.init(config); // reading init-parameter “logfilename” stored in web.xmlfileName = config.getInitParameter(logfilename); } /* Both doGet() doPost() methods are override over here.processRequest() is called from both rvlet to handle both POST and GET requestsidentically. */ // Handles the HTTP GET request type ServletRequest request, est, response); } Now le, how we can access init parameters inside the Servlet. The method getIniServletConfig is usually used to access init parameters. It takes a String as paramete tag under all init-param tags and returns param-value from the web.xml ialization parameter. e = config.g } An public void anyMe these methods. This makespossible for a se protected void doGet(Http HttpServletResponse response)throws ServletException, IOException{ processRequest(requ
  • 277.
    Web Design Development – CS506 VU © Copyright Virtual University of Pakistan 277 // Handles the HTTP POST request type pr quest request, st() protected void processRequest(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException{ PrintWriter out = response.getWriter(); // writing init-parameter value that is store in fileNameout.println(fileName); out.close(); } web.xml ?xml version=1.0 encoding=UTF-8?web-app servlet servlet-name MyServlet /servlet-name servlet-class MyServlet /servlet-class init-param param-name logfilename /param-name param-value logoutput.txt /param-value /init-param /servlet servlet-mapping /web-app otected void doPost(HttpServletRe HttpServletResponse response)throws ServletException, IOException{ processRequest(request, response); } // called from doGet() doPo servlet-name MyServlet /servlet-name url-pattern /myservlet /url-pattern /servlet-mapping
  • 278.
    Web Design Development – CS506 VU © Copyright Virtual University of Pakistan 278 Response Redirection We can redirect the response of the Servlet to another application resource (another Servlet, an HTML page or a JSP) but the resource (URL) must be available to the calling Servlet, in the same Servlet context (discussed later). There are two forms of response redirection that can be possible: ƒ Sending a standard redirect ƒ Sending a redirect to an error page Sending a standard Redirect let will not have access to the original request object. For example, if the request is redirected from servlet1 to servlet2, then servlet2 would not bject of servlet1. ƒ Sending a redirect to an error page Instead o This me class (lis cond the appropriate error message. The steps to redirect the user to an error page are: ƒ An error code is sent as a parameter of response.sendError(int, msg)method ƒ The error page is displayed with the msg passed to method r numbers are predefined constants of the HttpServletResponse class. For example: _NOT_FOUND (404) -SC_NO_CONTENT (204) -SC_REQUEST_TIMEOUT (408) xample Code: Response Redirection n leads to welcome page or otherwise to a registration page. This example consists of login.html, welcome.html, register.html and MyServlet.java files. Let’s examine these one after another. login.html This page contains two text fields; one for entering username and another for password. The data from this page is submitted to MyServlet.java. ƒ Using response.sendRedirect(“myHtml.html”) method, a new request is generated which redirects the user to the specified URL. ƒ If the URL is of another Servlet, that second Serv be able to access the request o To have access to the original request object, you must use the request dispatching technique (discussed later) instead of redirect. f using response.sendRedirect(), we can use response.sendEorror() to show user an error page. thods takes two parameters, first the error number that is a predefined constant of the response ted below) and se ƒ The erro -SC E The example given below demonstrates a typical sign on example in which a user is asked to provide login/password, providing correct informatio
  • 279.
    Web Design Development – CS506 VU © Copyright Virtual University of Pakistan 279 html h2 Please provide login details/h2 FROM METHOD=POST ACTION=http://localhost:8084/redirectionex/myservletNAME=myFor m name=userid/ BR Password: INPUT TYPE=password name=pwd/ BR BR input type=submit value=Submit Form/ ome.html displays a successfully logged-in message to the user. html bod h2 Y ed in /h2 /body /body /html register.html The use n/password information. The user can enter user id, address and phone number here to register. Note: T the user. It does not register user as no such function html bo FORM METHOD=POST ACTION= NAME=myForm BR Name: body BR User Id: INPUT TYPE=text /form /body /html welc The user is directed to this page only if user provides correct login / password. This page only y ou have successfully logg r is redirected to this page in case of providing incorrect logi he code given below will only show fields to ality is added into this small example. dy h2Your login is incorrect. Please register yourself/h2
  • 280.
    Web Design Development – CS506 VU © Copyright Virtual University of Pakistan 280 INPUT TYPE=text NAME=userid/ BR Address: INPUT TYPE=text NAME=address/ BR Phone No: INPUT TYPE=text NAME=phoneno/ BR BR input type=submit value=Register/ /form /body /html MyServ MyServl m login.html and redirects the user to welcome.html or register.html based o me password provided. Username password are compared with fix values in this exam ou can verify these from database or from a text file etc. import java.io.*; import jav port javax.servlet.*; port javax.servlet.http.*; // Handles the HTTP GET request type protected void doGet(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOExc processRequest(request, response); } // Handles the HTTP POST request type equest request, HttpServletResponse response)throws ServletException, IOException{ processRequest(request, } ServletRequest request, HttpServletResponse response)throws ception, IOException{ g id = request.getParameter(userid);String pwd = request.getParameter(pwd); // comparing id password with fix values if(id.equals(ali) pwd.equals(vu)) { // redirectign user to welcome.html response.sendRedirect(welcome.html); le.java et.java accepts requests fro n the verification of usernaple, however y a.net.*; im im public class MyServlet extends HttpServlet { eption{ protected void doPost(HttpServletR response); protected void processRequest(Http ServletEx Strin
  • 281.
    Web Design Development – CS506 VU © Copyright Virtual University of Pakistan 281 else {// redirecting user to register.htmlresponse.sendRedirect(register.html); /* if you want to display an error message to theuser, you can use the following method response.sendError(response.SC_PROXY_AUTHENTICATION_REQUIRED,Send Error Demo );*/ e } ServletContext ServletC sed for sharing resources among servlets As initiali onfig, ServetContext can store initializa ation. These parameters are also called context attributes or the lifetime of the application. The following figure illustrates the sharing of context attributes mong all the servlets of a web application. }// end els } ontext belongs to one web application. Therefore it can be uin the same web application. zation parameters, for a single servlet are stored in ServletC tion parameters for the entire web applic and exist fa Note: ServletContextper web application ) of ServletContext returns a RequestDispatcher object associated with the ƒ There is a single ƒ Different Sevlets will get the same ServletContext object, when calling getServletContext()during different sessions Request Dispatcher RequestDispatcher provides a way to forward or include data from another source. The method getRequestDispatcher(String path
  • 282.
    Web Design Development – CS506 VU © Copyright Virtual University of Pakistan 282 resource at the given path passed as a parameter. wo important methods of RequestDispatcher are: sponse resp) sponse resp) RequestDispatcher: forward Charact rward methods are: ƒ It allows esource (Servlet, JSP or HTML file) in the same Se ƒ Forward res.sendRedirect(String location). You can not see the chang ƒ ct is available to the called resource. In other words, it remains in scope. ƒ arding request to another source, headers or status codes can be set, but tent cannot be added. To clarify the co User initates the request to servlet1. servlet1 forwards the request to servlet2 by calling forward(request,response). Finally a response is returned back to rvlet2. T ƒ forward(ServletRequest req, ServletRe ƒ include(ServletRequest req, ServletRe eristics of fo a Servlet to forward the request to another rrvlet context. ing remains transparent to the client unlike es in the URL. Request Obje Before forwoutput con ncepts, lets take the help from following figure. the user by se RequestDispatcher: include It allows a Servlet to include the results of another resource in its response. The two major differences from forward are: ƒ Data can be written to the response before an include ƒ The first Servlet which receive the request, is the one which finishes the response It will be more cleared from the following figure. User sends a HTTPRequest to Servlet1. Serlet2 is called by Servlet1 by using include(request, response) method. The response generated by Servlet2 sends back to
  • 283.
    Web Design Development – CS506 VU © Copyright Virtual University of Pakistan 283 Servlet1. Servlet1 can also add its own response content and finally send it back to user. References: ƒ Java A Lab Course by Um ƒ Core Servlets an ƒ Java API docum air Javed d JSP by Marty Hall entation
  • 284.
    Web Design Development – CS506 VU © Copyright Virtual University of Pakistan 284 Lesson 30 ests In this handout st dispatching techniques and give some examples related to that. Further more some method HttpRequestwill also be discussed. Finally, this handout will be concluded by discussing the importance of session tracking. Before starting, let’s take a look at the summery of the Recap In the previous lecture we had some discussion about Response Redirection and Request Dispatcher. We said that Respon Servlet to another application resource. This resource m . Two forms of Resp . Sending a Using res od, a new request is generated which redirects ther servlet, that second servlet will not be able to a . Redirection to an error page: An err rror(int, msg) method lar error page in case of occurrence of specified error. Similarly request ility to forward the request processing to another servlet, or to include the output of another resource (servlet, JSP or HTML etc) in the response. Unlike Response Redirection, request object of calling resource is available to called resource. The two ways of Request ispatching are: . Fo ssing to another resource. . In Allows a servlet to include the results of another resource in its response. So unlike forward, the first servlet to receive the request is the on Example Code: Request Dispatching – Include Lets sta ow a Servlet includes the output of another resource in its respo eServlet, who’s output will be included in the calling Servlet. The code of MyServlet.java servlet is given below. Dispatching Requ we will start with reque s of HttpResponse and previous lecture. se Redirection was used to redirect response of the ight be another Servlet or any JSP pageonse redirection were discussed. These were: standard request: ponse.sendRedirect(“path of resource”) meth the user to the given URL. If the URL is of ano ccess the original request object. or code is passed as a parameter along with message to response.sendE . This method redirects the user to the particu dispatching provides us the fac D rward: Forwards the responsibility of request proce clude: e which finishes the response. rt with the example of include. We will see h nse. The following example includes a calling Servlet MyServlet and Servlet Includ
  • 285.
    Web Design Development – CS506 VU © Copyright Virtual University of Pakistan 285 MyServlet.java import java.io.*; t.*; p.*; ublic class MyServlet extends HttpServlet { /* this method is being called by both doGet() and doPost().We usually type of incoming request to the servlet. So the ac processing is be */ rotected void processRequest(HttpServletRequest request, HttpServletResponse response) ception { response.setContentType(text/html); PrintWr out.prin (html); out.prin out.prin equest /h1); out.flush // gettin ed to // obtai ispacther ServletC letContext(); // gettin ispatcher by passing the path // of in meter Request udeservlet); import java.net.*; import javax.servle import javax.servlet.htt p follow this practice, when we are not sure about the tual ing done in the processRequest(). p throws ServletException, IOEx iter out = response.getWriter(); tln tln(body); tln(h1Start of include r (); g the object of ServletContext, that will be us n the object of RequestD ontext context = getServ g the object of RequestD cluded resource as a para Dispatcher rd = context.getRequestDispatcher(/incl
  • 286.
    Web Design Development – CS506 VU © Copyright Virtual University of Pakistan 286 // calling include method of RequestDispatcher by passing // requ parameters. This will execute //the se ut in the first servlet rd.includ sponse); er including the out.println(h1End o out.prin t.println(/html); out.close(); } This method only calls processRequest() rotected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // This method only calls processRequest() protected void d tResponse response) ption, IOException { est(request, response); } // end est and response objects as cond servlet and include its outp e(request, re /* the statements below will be executed aft output of the /includeservlet */ f tln(/body); ou // closing PrintWriter stream // p processRequest(request, response); } oPost(HttpServletRequest request, HttpServle throws ServletExce processRequ } MyServlet
  • 287.
    Web Design Development – CS506 VU © Copyright Virtual University of Pakistan 287 Include Now lets take a look import java.io.*; import j port javax.servlet.*; import j public class Inclu // this method is being called by both doGet() and doPost() sRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // Obtaining the object of PrintWriter, this will return the ct we have in MyServlet // Including a HTML tag using PrintWriter throws ServletException, IOException { processRequest(request, response); ServletResponse response) throws ServletException, IOException { the processRequest(), firstly we get the PrintWriter stream from the HttpServletResponse object. Then tag to the output of the calling servlet. One thing that must be considered is that sed again in the calling servlet. Servlet at the code of IncludeServlet.java ava.net.*; im avax.servlet.http.*; deServlet extends HttpServlet { protected void proces // same PrintWriter obje PrintWriter out = response.getWriter(); out.println(h1 marqueeI am included /marquee/h1); } protected void doGet(HttpServletRequest request, HttpServletResponse response) } protected void doPost(HttpServletRequest request, Http } } // end IncludeServlet In we include an HTML P rintWriter stream is not closed in the end, because it is the same stream that is being used in the calling servlet and this stream may also be used in the calling servlet again. So, if it is closed over here, it can not be u
  • 288.
    Web Design Development – CS506 VU © Copyright Virtual University of Pakistan 288 web.xml ?xml version=1.0 encoding=UTF-8? web-app servlet servlet-nameMyServlet/servlet-name me vlet-classIncludeServlet/servlet-class url-pattern/myservlet/url-pattern servlet-mapping servlet-nameIncludeServlet/servlet-name /servlet-mapping servlet-classMyServlet/servlet-class /servlet servlet servlet-nameIncludeServlet/servlet-na ser /servlet servlet-mapping servlet-nameMyServlet/servlet-name /servlet-mapping url-pattern/includeservlet/url-pattern /web-app
  • 289.
    Web Design Development – CS506 VU © Copyright Virtual University of Pakistan 289 Code Example: Request Dispatcher - forward As discussed earlier, we can forward the request pro o another resource using forward method of form method=POST ACTION = “firstservlet NAME=myForm h2 Enter your name/h2 INPUT TYPE=text name=name/ br/ h2 Salary/h2 INPUT TYPE=text name=salary/ BR/BR/ INPUT type=submit value=Submit/ /form /html import java.net.*; import javax.servlet.*; import javax.servlet.http.*; public class FirstServlet extends HttpServlet { // this method is being called by both doGet() and doPost() protected void processRequest(HttpServletRequest request, HttpServletResponse response) sthrows ServletException, IOException { // getting value of salary text filed of the HTML form String salary = request.getParameter(salary); cessing t request dispatcher. In this example, the user enters his/her name and salary on the index.html and submits the form to FirstServlet, which calculates the tax on salary and forwards the request to another servlet for further processing i.e. SecondServlet. index.html html body FirstServlet.java import java.io.*;
  • 290.
    Web Design Development – CS506 VU © Copyright Virtual University of Pakistan 290 // converting int sal = Integer.parseInt(salary); 5); // converting tax into string String taxValue = tax + ; alues in key-value form, later it // can be retrieved by using getAttribute() method request.setAttribute(tax, taxValue); // getting object of servletContext ServletContext sContext = getServletContext(); // getting object of request dispatcher RequestDispatcher rd = sContext.getRequestDispatcher(/secondservlet); // calling forward method of request dispatcher rd.forward(request, response); } // This method is calling processRequest() protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { processRequest(request, response); } // This method is calling processRequest() protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { processRequest(request, response); } } Note: It the case of Forward, it is illegal to make the reference of PrintWriter stream in the calling Servlet. Only the called resource can use PrintWriter stream to generate response it to the integer. // calculating 15% tax int tax = (int)(sal * 0.1 // request object can store v
  • 291.
    Web Design Development – CS506 VU © Copyright Virtual University of Pakistan 291 SecondServlet.java ublic class SecondServlet extends HttpServlet { // this method is being called by both doGet() and doPost() Request(HttpServletRequest request, HttpServletResponse response) // obtaining values of name and salary text fields of index.html /* getting attribute value that has been set by the calling servlet i.e. FirstServlet */ String tax = (String)request.getAttribute(tax); using PrintWriter out.println(html); out.println(head); out.println(titleSecondServlet/title); body); tln(h1 Welcome + name+ /h1); out.println(h3 Salary + salary+ /h3); import java.io.*; import java.net.*; import javax.servlet.*; import javax.servlet.http.*; p protected void process throws ServletException, IOException { response.setContentType(text/html); PrintWriter out = response.getWriter(); String name = request.getParameter(name); String salary = request.getParameter(salary); // generating HTML tags out.println(/head); out.println( out.prin
  • 292.
    Web Design Development – CS506 VU © Copyright Virtual University of Pakistan 292 out.println(h3 Tax + tax+ /h3 ); out.println(/body); throws ServletException, IOException { } // This method is calling processRequest() p te tResponse response) } } web.xml TF-8? web-app servlet-nameFirstServlet/servlet-name servlet-classSecondServlet/servlet-class /servlet out.println(/html); out.close(); } // This method is calling processRequest() protected void doGet(HttpServletRequest request, HttpServletResponse response) processRequest(request, response); rocted void doPost(HttpServletRequest request, HttpServle throws ServletException, IOException { processRequest(request, response); ?xml version=1.0 encoding=U servlet servlet-classFirstServlet/servlet-class /servlet servlet servlet-nameSecondServlet/servlet-name
  • 293.
    Web Design Development – CS506 VU © Copyright Virtual University of Pakistan 293 servlet-mapping firstservlet/url-pattern /w Http Let’s discuss some methods of HttpServletRequestclass s We c attrib Disp been illustrated in the above example. These attributes are available every where in the same web application so th cess them by using getAttribute() method. getA Th in th in the co getMethod() This method returns the name of HTTP method which was used to send the request. The two possible returning values could be, get or post. getRequestURL() It can be used to track the source of Request. It returns the part of the request’s URL with out query string. servlet-nameFirstServlet/servlet-name url-pattern/ /servlet-mapping servlet-mapping servlet-nameSecondServlet/servlet-name url-pattern/secondservlet/url-pattern /servlet-mapping eb-app ServletRequest Methods etAttribute(String, Object) an put any object to the context using setAttribute() method in the key-value pair form.. These utes are also set or reset between requests. These are often used in conjunction with Request atcher. This has also at any other Servlet or JSP resource can ac ttribute(String) e objects set by the setAttribute() method can be accessed using getAttribute() method. Passing the key e form of string as a parameter to this method will return the object associated with that particular key ntext. Cast the object into its appropriate type.
  • 294.
    Web Design Development – CS506 VU © Copyright Virtual University of Pakistan 294 getProtocol( It returns the name and version of the protocol used. getHeaderName It returns the enum t are contained in the request. getHearderName() It takes a String parameter ts the header name and returns that appropriate header. Null value is returned if there is no header exists with the specified name. HttpServletRe Let’s discuss some methods of HttpServletResponse class ore getting the PrintWriter Stream. It is used to set the on the client’s browser. This method is used to set the content length. It takes length as an integer parameter. e header. It takes a Cookie object as a parameter and ad kies in the session tracking part. se T cepts the relative URL. It takes U ) s() eration of all available header names tha that represen sponse Methods setContentType() Almost every Servlet uses this header. It is used bef Content Type that the PrintWriter is going to use. Usually we set “text/html”, when we want to send text output or generate HTML tags setContentLength( ) addCookie() This method is used to add a value to the Set-Cooki ds it to the Cookie-header. We will talk more about CoondRedirect() his method redirects the user to the specific URL. This method also acRL strser to that resource. ing as parameter and redirects the u
  • 295.
    Web Design Development – CS506 VU © Copyright Virtual University of Pakistan 295 Many applications require a series of requests from the same client to be associated with one another. For exam s the state of a user's shopping cart across multiple requests. Web-based applications are responsible for maintaining such state, because HTTP protocol is stateless. To supp ate, Java Servlet technology provides an API for managing sessions and allows several mechan Befo tracking mechanism lets see the limitation of HTTP protocol to get the real p an happen with out maintaining the session. Con nuity problem- user’s point of view Session Tracking ple, any online shopping application save ort applications that need to maintain stisms for implementing sessions. re looking inside the sessionicture of problems that cti Suppose a user logs on t t. He enters his billing address a fin as it is stateless in nature and user thinks that the choices made on page1 are remembered on page3 o the online bookshop, selects some books and adds them to his carally submits the order. HTTP cannot track session nd
  • 296.
    Web Design Development – CS506 VU © Copyright Virtual University of Pakistan 296 Continuity problem- Server’s point of view The server has a very different point of view. It considers each request independent from other even if the requests are made by the same client. References ƒ Java A Lab Course by Umair Javed ƒ Core Servlet and JSP by Marty Hall
  • 297.
    Web Design Development – CS506 VU © Copyright Virtual University of Pakistan 297 Lesson 31 the Store State Somewhere To maintain the conversational state, the straightforward approach is to store the state. But where? These states either can be stored on server or on client. However, both options have their merits and demerits. Let’s cast a glance on these options: Storing state on server side makes server really complicated as states needed to be stored for each client. Some one can imagine how much space and processing is required in this scenario as some web servers are hit more than hundred times in a second. E.g. Google, Yahoo etc. What if states are stored on client side in order to maintain a conversation? Do all the clients permit you doing that? What if client (user) wiped out these states from the machine? Concluding this discussion, state is stored neither completely on server side nor on client. States are maintained by the mutual cooperation of both client server. Generally modern servers give the capability to store state on the server side and some information (e.g. client ID/state ID) passed from the client will relate each client with its corresponding state. Post–Notes In order to maintain the conversational state, server puts little notes (some text, values etc) on the client slide. When client submits the next form, it also unknowingly submits these little notes. Server reads these notes and able to recall who the client is. Three Typical Solutions Session Tracking We have discussed the importance of session tracking in the previous handout. Now, we’ll discover basic techniques used for session tracking. Cookies are one of these techniques and remain our focus in this handout. Cookies can be used to put small information on the client’s machine and can be used for various other purposes besides session tracking. An example of simple “Online Book Store”, using cookies, will also be surveyed. As mentioned elsewhere, HTTP is a stateless protocol. Every request is considered independent of every other request. But many applications need to maintain a conversational state with the client. A shopping cart is a classical example of such conversational state. Three typical solutions come across to accomplish session tracking. These are: 1 Cookies 2 URL Rewriting 3 Hidden Fields
  • 298.
    Web Design Development – CS506 VU © Copyright Virtual University of Pakistan 298 Cookies ing off. In fact, in computer terminology, “a cookie is a piece hard disk”. Cookies allow the ent machine and later retrieve it. The pieces of inform value pair on the client. Later while reconnecting to the same site (or same doma depending upon the cookie settings), client returns the same name-value pair to the server. Cook To reve ample. We are assuming here that the web application we ar ƒ wser sends a request for that web page e www.amazon.com What a cookie is? Don’t be tempted? These are not, what you might be think of text that a web server can store on a client’s (user) web sites to store information on a cliation are stored as name- in ie’s Voyage al the mechanism of cookies, let’s take an exe using will set some cookies If you type URL of a Web site into your browser, your bro o For example, when you typ a request is send to the Amazon’s server ƒ Before sending a request, browser looks for cookie files that amazon has set o If browser finds one or more cookie files related to amazon, it will send it along with the ent with the request ƒ Amazaon web server receives the request and examines the request for cookies hat you have not visited before or the cookies that were previously set got expired. eader of HTTP Response ed on the client machine. os or cons is arguable. However, cookies are helpful in the following For example, this book is added into shopping cart s are saved on your machine mail-inbox in a different look form others. This sort e used to format e, a web site can store information in the form of cookies about the or. request o If not, no cookie data will be s o If cookies are received, amazon can use them o If no cookie is received, amazon knows t o Server creates a new cookie and send to your browser in the h so that it can be sav Potential Uses of Cookies Whether cookies have more pr situations ƒ Identifying a user during an e-commerce session. by this client. ƒ Avoiding username an d password as cookie ƒ Customizing a site. For example, you might like e of information can be stored in the form of cookies on your machine and latter can binbox according to your choice. ƒ Focused Advertising. For examplkinds of books, you mostly hunt f
  • 299.
    Web Design Development – CS506 VU © Copyright Virtual University of Pakistan 299 Send Follo ookie to a browser (client). 1 ie constructor, which takes two strings: the cookie Cookie c = new Cookie (“name”, “value”); 2 Before adding the cookie to outgoing headers (response), various characteristics of the cookie can be ie persists on the disk or not. If yes then how long. urrent user session (i.e. until the user quits the session) and before the ne hour 3. Place the Cookie into HTTP response attributes, the most important and unforgettable step is to add this onse. If you forget this step, no cookie will be sent to the browser. e.addCookie(c); owing steps are generally followed. okies t of the HttpServeltRequest by calling following method s[] = request.getCookies(); T 2 ies, you can iterate over it. Two important methods of Cookie class are () getValue(). These are used to retrieve cookie name and value respectively. ing Cookies to Browser wing are some basic steps to send a c . Create a Cookie Object A cookie object can be created by calling the Cookname and the cookie value. . Setting Cookie Attributes set. For example, whether a cook A cooki es by default, lasts only for the c will not be stored on the disk. Using setMaxAge(int lifetime) method indicates how much time (in seconds) should elapse cookie expires. c.setMaxAge(60); // expired after o After making changes to cookiecurrently created cookie into resp respons Reading Cookies from the Client To read the cookies that come back from the client, foll1. Reading incoming co To read incoming cookies, get them from the request objec Cookie cookie This call returns an array of Cookies object corresponding to the name values that came in the HTP request header. . Looping down Cookies Array Once you have an array of cookgetName
  • 300.
    Web Design Development – CS506 VU © Copyright Virtual University of Pakistan 300 // looping down the whole cookies array ookie c = cookies[i]; ar cookie someName”) { n do something with cookieor with the help of cookie. her, loop canalso be stopped using break */ } Exam In the exam a unique cookie, named “repeat”. If the cookie is present, servlet disp ndicates that the user is visiting this site for the first time thus serv rd”. This exa code snippet of web Not sing netBeans4.1. This IDE will write web.xml for you. How ose only, or for those which are not using any IDE to strengthen their concepts RepeatVisitorServlet.java import java.io.*;import java.net.*;import javax.servlet.*;import javax.servlet.http.*; publi VisitorServlet extends HttpServlet { tion, IOException{ // Handles od. protected v HttpServletResponse response)throws ServletException, IOException{ processRequest(request, response); // called from both doGet() doPost() for(int i=0; icookies.length; i++) { // getting each cookie from the arrayC // in search for particulif( c.getName().equals(“ /* if found, you ca If don’t want to process furtstatement } // end for ple Code1: Repeat Visitor ple below, servlet checks for lays “Welcome Back”. Absence of cookie ilet displays a message “Welcome Aboa mple contains only one servlet “RepeatVisitorServlet.java” and its code is given below. A .xml is also accompanied. e: As a reminder, all these examples are built uever, here it is given for your reference purp c class Repeat // Handles the HTTP codeGET/code me thod. protected void doGet(HttpServletRequest request, HttpServletResponse response)throws ServletExcep processRequest(request, response); } the Hde meth TTP codePOST/co oid doPost(HttpServletRequest request, } protected void processRequest(HttpServletRequest request,
  • 301.
    Web Design Development – CS506 VU © Copyright Virtual University of Pakistan 301 H response)throws ServletException, IOException{ respo boolean repeatVisitor = false; okie[] cookies = request.getCookies(); t object Cookie c = cookies[i]; okie firming if cookie name equals “repeat” and // value equals “yes” if( name.equals(repeat) val.equals(yes)) { k;repeatVisitor = true;break; // if no cookie with name “repeat” is foundif (repeatVisitor == false){ // create a new cookie Cookie c1 = new Cookie(repeat, yes); // setting time after which cookies expires c1.setMaxAge(60); // adding cookie to the response response.addCookie(c1); msg = Welcome Aboard; } ttpServletResponse nse.setContentType(text/html); PrintWriter out = response.getWriter(); // writing html out.println(html); out.println(body); out.println(h2Cookie Example /h2); String msg = ; // reading cookies Co cookies are returned from reques // if if (cookies != null) {//search for cookie -- repeatfor (int i = 0; i cookies.length; i++) { // retrieving one cookie out of array // retrieving name value of the coString name = c.getName(); String val = c.getValue(); // con msg= Welcome Bac } } // end for } // end if
  • 302.
    Web Design Development – CS506 VU © Copyright Virtual University of Pakistan 302 // displaying message value out.println(h2 + msg + / ervlet-class RepeatVisitorServlet /servlet-c /servlet servlet-map /servlet-nameurl-pattern /repeatexample /url-pattern Ou On first time visiting this URL, an output similar to the one given below would be displayed h2); out.println(/body); out.println(/html); out.close();}}// end RepeatVisitorServlet web.xml ?xml version=1.0 encoding=UTF-8? web-app servlet servlet-name RepeatVisitorServlet /servlet-names lass pingservlet-name RepeatVisitorServlet /servlet-mapping /web-app tpu t On r mins), following utp should refeshing this page or revisiting it within an hour (since the age of cookie was set to 60ut be expected. o
  • 303.
    Web Design Development – CS506 VU © Copyright Virtual University of Pakistan 303 Example Code2: Online Book Store using cookies A sc f online book store is goin aledown version ontain the session. g to be built using cookies. For the first time, cookies will be used to mai Three b g with check boxes. User can select any check box to add the boo art of the application is, it remembers the books previously selected by the user. “Yo a were added to cart one after another. The important thing is server that remembers the previously added books by the same user and thus maintains the session. Session managem ooks will be displayed to the user alon k in the shopping cart. The he The following figure will help you understand the theme of this example. Books displayed under the heading of u hve selected the following books” ent is accomplished using cookies. Online Bo es around one ShoppingCartServlet.java. This Servlet has one global HashM . This (sessio ores the books selected by the user. What’s e part of cookies? Cookie (named JSESSIONID, with unique value) is used to keep the unique sessionID associated with each user. This sessionID is passed back and forth between user and the server and is used to retrieve the HashMap (sessionInfo) of the user from the global HashMap at the server. It should be noted here that, HashMaps of individual users are stored in a global HashMap against a sessionID. ok Store example revolv ap (globalMap) in which HashMap of individual user (sessionInfo) are going to be stored nInfo) HashMap st th
  • 304.
    Web Design Development – CS506 VU © Copyright Virtual University of Pakistan 304 ShoppingC import java.io.*;import java.net.*;import javax.servlet.*;import javax.servlet.http.*; public class ShoppingCartServlet extends HttpServlet { ap(); ion, IOException{ se); } hod. t(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException{ / HttpServletResponse response) throw response.setContentType(text/html;charset=UTF-8); hMap s used to determine whether browser// has send any cookie named JSESSIONID is visiting the site for the first time. // make a unique string sID = makeUniqueString(); artServlet.java // used to generate a unique value w hich is // used as a cookie value public static int S_ID = 1; // used to store HashMaps of indiviual users public static HashMap globalMap = new HashM// Handles the HTTP GET method. protected void doGet(HttpServletRequest request, HttpServletResponse response)throws ServletExceptprocessRequest(request, respon // Handles the HTTP codePOST/code metprotected void doPos processRequest(request, response); } / called from both doGet() doPost() protected void processRequest(HttpServletRequest request, s ServletException, IOException { // declaring user's HasHashMap sessionInfo = null;String sID = ; // method findCookie i Cookie c = findCookie(request); // if no cookies named JSESSIONID is recieved, means that// userif (c == null) {
  • 305.
    Web Design Development – CS506 VU © Copyright Virtual University of Pakistan 305 // creating a HashMap where books selected by the// user will be stored ; // add the user's HashMap (sessionInfo) into the// globalMap against unique string i.e. sID // create a cookie named JSESSIONID alongwith Cookie sessionCookie = new Cookie(JSESSIONID, sID); respon } else { / retrieve a HashMap from the globalMap against// cookie value i.e. unique string which is your//sessionID alMap.get( c.getValue() ); } PrintWriter out = response.getWriter(); u // user will submit the fr out.println(form action= + url + +h3input type=checkbox name=firstCB value=firstCB / + java core servlts/h3 +br+ “h3input type=checkbox name=secondCB value=secondCB / + java how to program/h3 + br+ h3input type=checkbox name=thirdCB value=thirdCB / + java complete reference/h3 + br+ input type=submit value=Add to Cart / + /from ); out.println(br/); out.println(h1You have selected followig books/h1); out.println(br/); sessionInfo = new HashMap() globalMap.put(sID, sessionInfo); // value of sID i.e. unique string // add the cookie to the response se.addCookie(sessionCookie); // if cookie is found named JSESSIONID,/ sessionInfo = (HashMap) glob out.println(html); out.println(head); out .println(titleShooping Cart Example/title); t.println(/head); oo ut.println(body); out.println(h1Online Book Store/h 1); String url =http://localhost:8084/cookiesessionex/shoppingcartex; om to the same servlet
  • 306.
    Web Design Development – CS506 VU © Copyright Virtual University of Pakistan 306 //reteriving params of check boxes ook = request.getParameter(firstCB); if ( fBook != null fBook.equals(firstCB) ) { sessionInfo.put(firstCB, java core servlets); } rogram);} // user's HashMap i.e. sessionInfo if (tBook != null tBook.equals(thirdCB)){sessionInfo.put(thirdCB, java // the user's HashMap i.e. sessionInfo out.close(); } // end processRequest() // method used to generate a unique string public String makeUniqueString(){return ABC + S_ID++;} // returns a reference global HashMap. public static HashMap findTableStoringSessions(){return globalMap;} / method used to find a cookie named JSESSIONID ttpServletRequest request){ me().equals(JSESSIONID)){// doSomethingWith cookiereturn } // used to print the books currently stored in// user's HashMap. i.e. sessionInfo String fB String sBook = request.getParameter(secondCB); String tBook = request.getParameter(thirdCB); // if first book is selected then add it to // user's HashMap i.e. sessionInfo // if second book is selected then add it to // user's HashMap i.e. sessionInfo if (sBook != null sBook.equals(secondCB)){sessionInfo.put(secondCB, java how to p// if third book is selected then add it to complete reference);} // used to display the books currently stored in printSessionInfo(out, sessionInfo); out.println(/body); out.println(/html); / public Cookie findCookie(H Cookie[] cookies = request.getCookies(); if (cookies != null) { for(int i=0; icookies.length; i++) { Cookie c = cookies[i]; if (c.getNa c; } } } return null;
  • 307.
    Web Design Development – CS506 VU © Copyright Virtual University of Pakistan 307 public void printSessionInfo(PrintWriter out,HashMap sessionInfo){ String title = ; title= (String)sessionInfo.get(firstCB); if (title != null){ out.println(h3 + title +/h3); } title= (String)sessionInfo.get(secondCB); out.println(h3 + title +/h3); onInfo.get(thirdCB);if (title != null){out.println(h3 + title +/h3);}} web.xml ?x we servlet s /se servlet-mapping servlet-name ShoppingCart /servlet-name References: if (title != null){ } title= (String)sessi } // end ShoppingCartServlet ml version=1.0 encoding=UTF-8? b-app ervlet-name ShoppingCart /servlet-nameservlet-class ShoppingCartServlet /servlet- cla ss rvlet url-pattern /shoppingcartex /url-pattern /servlet-mapping /web-app ƒ Java A Lab Course by Umair Javed lets and JSP by Marty Hall ƒ Stanford Course – Internet Technologies mentation ƒ Core Serv ƒ Java API docu
  • 308.
    Web Design Development – CS506 VU © Copyright Virtual University of Pakistan 308 Lesson 32 In the last handout we have discussed the solutions for session tracking and talked about one important mechan ient machine and later retrieve it. Now we will see acility to maintain a session between user’s requests. These are URL R we will discuss a session tracking API provided by java. URL Rewriting URL rewriting provides king. With URL rewriting, the parameter that we want to pass bac een the server and client is appended to the URL. This appended information can be retrieve by parsing the URL. This information can be in the form of: . Added parameters, or Note: Due to limited space available in r s usually limited to a unique session ID. The following URLs have been rewritten to pass the session ID 123 . Original – . Extra path i ://server: port/servlet/rewrite/123 . Added parameters – http://server: port/servlet/rewrite?id=123 . Custom change – rewrite;$id$123 Disadvantages of URL rewriting The following D are considerable: - ƒ What if the user bookm e if server is not assigning a unique session ƒ Every URL on a page, which needs the session information, must be rewritten each time page is served, which can cause o o ƒ Unlike c ƒ This mechani Example Code: OnlineBookStore using URL Rewriting This is the mod y, however you can add in on your own) that is built using cookies in the last handout. Another important difference is books are displayed in the form of hyperlin to maintain session information. How to make Query String Before jumping on to example, one important technique is needed to be learned i.e. making on query string. If you ever noticed the URL of a servlet in a browser that is receiving some HTML form values, also contains the HTML fields name with . Now, if you want to pass some attribute and values along with URL, you can use the technique of query string. Session Tracking 2 ism cookies in detail. We said cookies allow the server to store information on a cl two more mechanisms that provide us fewriting and Hidden Form Fields. After that another way for session trac k and forth betw . Extra path information, . Some custom, server-specific URL change ewriting a URL, the extra information i http://server: port/servlet /rewrite nformation – http http://server: port/servlet/ isadvantages of URL rewriting, arks the page and the problem get worsid. Computationally expensive Can increase communication overhead ookies, state information stored in the URL is not persistent sm limits the client interaction with the server to HTTP GET request. ified version of online book store (selling two books onl k instead of check boxes. URL rewriting mechanism is used values entered/selected by the user
  • 309.
    Web Design Development – CS506 VU © Copyright Virtual University of Pakistan 309 Attribute names lues are written in pair form after the ?. For example, if you want to send attribute “name” and its value “ali”, the URL will look like ƒ Original URL http://server:por ƒ After adding parameters http://server:port/servletex/register ?name=ali If you want to add more t equent parameters are separated by sign. For example ƒ Adding two parameters – http://server:port/servletex/register ?name=aliaddress=gulberg URLRewriteServlet.java port java.io.*;import java.net.*;import javax.servlet.*;import javax.servlet.http.*; public class URL // used to gener ch is // used as public stat // used to users public static HashMap globalMap = new HashMap(); // Handles protected void doGet(HttpServletRequest request, HttpServletRespons proce } // Handles protected voi HttpServletResponse response)throws ServletException, IOException{ processRequest(reques } // called from both doGet() doPost()protected void pro ttpServletRequest request,HttpServletResponse response)throws ServletException, IOException { g user's HashMap null; g sessionId String sID = request.getParameter(“JSESSIONID”); /* if parameter JSESSIONID is received, means that user isvisiting the site for the first time. */ if (sID == null) { ue string and va t/servletex /register han one parameter, all subs im RewriteServlet extends HttpServlet { ate a unique value whia cookie value ic int S_ID = 1; store HashMaps of indiviual the HTTP GET method. e response)throws ServletException, IOException{ ssRequest(request, response); the HTTP codePOST/code method. d doPost(HttpServletRequest request, t, response); cessRequest(H // declarin HashMap sessionInfo = // readin // make a uniq
  • 310.
    Web Design Development – CS506 VU © Copyright Virtual University of Pakistan 310 sID = makeUniqueString(); // creating a HashMap where books selected by the // user will be stored sessionInfo = new HashMap(); d the user's HashMap (sessionInfo) into the // globalMap against unique string i.e. sID ap.put(sID, sessionInfo); }else { eve a HashMap from the globalMap against unique string which is your sessionID ashMap)globalMap.get(sID); } resp -8); Prin riter out = response.getWriter(); html); out.println(head); out.println(titleShopping Cart Example/title); l =http://localhost:8084/urlbookstore/urlrewriteservlet?JSESSIONID= + String s ookstore/urlrewriteservlet?JSESSIONID= out.p re servlts /a /h3 +br+ h3a href= + secondurl + + java how to program /a /h3 + br+ ); out.println(br/); out.println(h1You have selected following books/h1); out.println(br/); //retrieving params that are emebded in URLs String fBook = request.getParameter(firstCB);String sBook = request.getParameter(secondCB); // ad globalM // if parameter JSESSIONID has some value // retri // sID i.e. sessionInfo = (H onse.setContentType(text/html;charset=UTFtW out.println( out.println(/head); out.println(body); out.println(h1Online Book Store/h1); // Making three URLS by using query string mechanism// The attributes/parameters are JSSESSIONID and book name (like// firstCB) along with values sID and book name respectively String firstur sID + firstCB=firstCB; econdurl =http://localhost:8084/urlb +sID + secondCB=secondCB; rintln(h3a href= + firsturl + + java co
  • 311.
    Web Design Development – CS506 VU © Copyright Virtual University of Pakistan 311 // if first book is selected then add it to // user's HashMap i.e. sessionInfo if ( fBook != null fBook.equals(firstCB) ) { sessionInfo.put(firstCB, java core servlets); } / s if (sBook != null sBook.equals(secondCB)){ // used to display the books currently stored in // the user's HashMap i.e. sessionInfo printSessionInfo(out, sessionInfo); out.p out.cl used to generate a unique string + S_ID++;} // retur public st Sessions(){return globalMap;} / used to print the books currently stored in// user's HashMap. i.e. sessionInfo ionInfo){ String title = ; title= (String)sessionInfo.get(firstCB); out.println(h3 + title +/h3); t(secondCB); } // // if second book is selected then add it to / uer's HashMap i.e. sessionInfo sessionInfo.put(secondCB, java how to program); } out.println(/body); rintln(/html); ose(); } // end processRequest() // methodpubli c String makeUniqueString(){return ABC ns a reference global HashMap. atic HashMap findTableStoring / public void printSessionInfo(PrintWriter out,HashMap sess if (title != null){ } title= (String)sessionInfo.geif (title != null){ out.println(h3 + title +/h3); } end URLRewriteServlet
  • 312.
    Web Design Development – CS506 VU © Copyright Virtual University of Pakistan 312 web.xml ?xml version=1.0 encoding=UTF-8? web-app s Servlet / serv meurl-pattern /u /se /web-app Hidden HTML nt that looks like the following: INP 123 / Hidden appearance of HTML page. They actually contain the information that is neede Thus, hidden fields can also be used to store information (like sessionid) in order to ervlet servlet-name URLRewriteServlet /servlet-nameservlet-class URLRewrite/servlet-class servlet let-mappingservlet-name URLRewriteServlet /servlet-na rlrewriteservlet /url-pattern rvlet-mapping Form Fields forms can have an elemeUT TYPE=HIDDEN NAME=sessionid VALUE= Forms Fields do not affect the d to send to the server. maintain session. In the above figure you can see the use of Hidden form fields for storing particular information. Java Solution for Session Tracking lent solution to all the problems that occurred in tracking a session. The Servlet API ndle session tracking. In other words, servlets king. t. HttpSession tacking API built on top of URL rewriting and ism is hidden and most application server uses cookies but ookies are unsupported or explicitly disabled. Using ervlets is straightforward and involves looking up the session object associated with the curr ssion, Java provides an excelprovides several methods and classes specifically designed to hahave built in session tracSessions are r epresented by an HttpSession objeccookies. All cookies and URL rewriting mechan automatically revert to URL rewriting when c HttpSessionAPI in s ent request, creating new session object when necessary, looking up information associated with a se
  • 313.
    Web Design Development – CS506 VU © Copyright Virtual University of Pakistan 313 storing information in a session, and discarding completed or abandoned sessions. Wor Let’s 1. Ge To ge t, we call the getSession() method of HttpServeltRequestthat returns the obje HttpSession sess = request.getSession(true); If true is passed to the getSession() method, this method returns the current session associated with this request, or, if the request does not have a session, it creates a new one. We can confirm whether this sess eturned by using isNew() method of HttpSession. In case of passing false, null is returned if the session doesn’t exist. 2. Stori ion in a Session ion object (sess), we use setAttribute() method of HttpSession class. Session ou can store number of a Session To retrieve back the stored information from session object, getAttribute()method of HttpSession class is used. For example, Note: -getAttribute() method returns Object 4. Terminat , session gets terminated automatically. We can see its maximum activation time eInterval() method of HttpSession class. However, we can also terminate any For this, we need to call invalidate() method of HttpSessionclass as shown below. sess.invalidate() xample Code: Showing Session Information To understand HttpSession API properly we need to have a look on an example. In this example, we will get ject and check whether it is a new user or not. If the user is visiting for the first time, we will print “Welcome” Moreover, we will print the session inf im import java.net.*; king with HttpSession have a look on HttpSession working step by step. t ting the user’s session object t the user’s session objec ct of HttpSession ion object (sess) is newly created or r ng informat To store information in Sess object works like a HashMap, so it is able to store any java object against key. So ykeys and their values in pair form. For example, sess.setAttribute(“sessionid”, ”123”); 3. Looking up information associated with String sid=(String)sess.getAttribute(“sessionid”); type, so typecast is required. ing a Session am After theount of timeby using getMaxInactiv existing session manually. E the session ob and if we find the old one, we’ll print “Welcome Back”. he number of access ormation and count tes for every user ; port java.io.*
  • 314.
    Web Design Development – CS506 VU © Copyright Virtual University of Pakistan 314 im im ; wSessionServlet extends HttpServlet { // Handles the HTTP codeGET/code method. protected void doGet(HttpServletRequest request, HttpServletResponse response) ws ServletException, IOException { processRequest(request, response); d doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException processRequest(request, response); } ServletRequest request, HttpServletResponse response) throws ServletException, IOException { // used for displaying message (like Welcomem, Newcomer) to user private String heading; response.setContentType(text/html); // Getting session object HttpSession session = request.getSession(true); /* Getting stored information using getAttribute() method */ port javax.servlet.*; port javax.servlet.http.* public class Sho thro } // Handles the HTTP codePOST/code method. protected voi { // called from both doGet() doPost() protected void processRequest(Http
  • 315.
    Web Design Development – CS506 VU © Copyright Virtual University of Pakistan 315 Integer accessCount = (Integer)session.getAttribute(sessionCount); /* If user comes for the first ti ill be assigned null, so we can guess easily that this a new user */ if (accessCount == null) { { heading = Welcome Back; // Incrementing the value accessCount = new Integer(accessCount.intValue() + 1); } /* Storing the new value of accessCount in the session using ute() method */ Getting the PrintWriter PrintWriter out = response.getWriter(); H3 Session ID: + session.getId() + /H3 + me, accessCount w accessCount = new Integer(1); heading = Welcome, Newcomer; } else setAttrib session.setAttribute(sessionCount, accessCount); // /*Generating HTML tags using PrintWriter to print session info and no of times this user has accessed this page */ out.println(HTML + BODY + h1Session Tracking Example/h1 + H2Information on Your Session:/H2n +
  • 316.
    Web Design Development – CS506 VU © Copyright Virtual University of Pakistan 316 H3Number of Previous Accesses: + accessCount + /BODY + /HTML ); } // d eb.xml ing=UTF-8? s e ShowSession /servlet-nameservlet-class ShowSessionServlet /servlet-apping e ShowSession /servlet-name url-pattern /showsession /url-pattern tpSession – Behind the scenes method, there is a lot going on behind the scenes. For every user, a unique session is assigned automatically. As the server deals with lot of users at a time, this ID is used to distinguish one ƒ Option 1: If the browser supports cookies, the Servlet will automatically creates a session cookie and store the session ID within that cookie. et /H3 + //Closing the PrintWriter stream out.close(); } // end processRequest en ShowSessionServlet class w ?xml version=1.0 encodweb -app ervlet servlet-namclass /servlet servlet-m servlet-nam /servlet-mapping /web-app Ht When we call getSession() ID user from another. Now here is the question, how this ID sends to the user? Answer is, there are two options ƒ Option 2: If the first option fails because of browser that does not support cookies then the Servlwill try to extract the session ID from the URL
  • 317.
    Web Design Development – CS506 VU © Copyright Virtual University of Pakistan 317 Encoding URLs sent to Client Servlet will automatically switch to URL rewriting when cookies are not supported or disabled by the clienWhen Session Tracking is based on URL rewriting, it requires additional help from the Servlets. Forto support session tracking via URL rewriting, it has to rewrite (encode) every local URL before sending ithe client. Now see how this encoding work t. a Servlet t to s perform encoding ƒ String encodeURL(String URL) Cookies are disabled, both methods encode (rewrite) the specific URL to include the session ID and returns new URL. However, if cookies are enabled, the URL is returned unchanged. Difference between encodeURL() and encodeRedirectURL() encodeURL() is used for URLs that are embedded in the webpage, that the servlet generates. For example, let/sessiontracker”; String eURL = response.encodeURL(URL); ” ” + eURL + ” ” …… /A”); Whereas ers yours site is in sendRedirect() call. For example, String URL = ”/servlet/sessiontracker”; String eURL = response.encodeRedirectURL(URL); Respons Redirect(eURL); Example Code: OnlineB This book store is mod rewriting mechanism. Here, HttpSession will be used to maintain session. ShoppingCartServlet.java import java.io.*;import ja javax.servlet.*;import javax.servlet.http.*; public class ShoppingCartServlet extends HttpServlet { // Handles the HTT protected void doG HttpServletResponse response)throws ServletException, IOException{ processRequest(request, response); } // Handles the HTTP codePOST/code method. protected void doPost(HttpServletRequest request, HttpServletResponse respon HttpServletResponse provides two methods to ƒ String encodeRedirectURL(String URL) If the String URL = ”/serv out.println(“A HREF= encodeRedirectURL() is used for URLs that ref e.send ookStore using HttpSession ified version of last one, which is built using URL va.net.*;import P GET method. et(HttpServletRequest request, se)throws ServletException, IOException{
  • 318.
    Web Design Development – CS506 VU © Copyright Virtual University of Pakistan 318 processRequest(request, response); } // called from both doGet() doPost()protected void processRe est request,HttpServletResponse response)throws ServletException, IOException { response.setContentType(text/html;charset=UTF-8); HttpSession session = request.getSession(true); PrintWriter out = response.getWriter(); out.println(html); out.println(head); out.println(titleShopping Cart Example/title); out.println(/head); out.println(body); out.println(h1Online Book Store/h1); // Second URL built using query string, representing second book// Note that parameter name is still book, so t parameter String secondURL =http://localhost:8084/urlrewritebookstore/shoppingcart?book=second // c String eURL1 = response.encodeURL( firstURL );String eURL2 = RL ); out.println(h3a href= + eURL1 + + java core servlets /a /h3 +br+ h3a href= + eURL2 + + o Program /a /h3 ); out.println(br/); out.println(h1You have selected following books/h1); out.println(br/); //retrieving params that are emebded in URLs String fBook = sBook = request.getParameter(secondCB); out.println( out.println(h1You have selected following books/h1); out.println(br/); //retrieving param that is embedded into URL String book = request.getParameter(book); if (book != null){ // if firstURL, value of first hyperlink is clicked// then storing the book into session object against quest(HttpServletRequ // First URL built using query string, representing first book String firstURL =http://localhost:8084/urlrewritebookstore/shoppingcart?book=first hat later we need // to read only this Enoding URLs response.encodeURL( secondU java How t request.getParameter(firstCB);String br/);
  • 319.
    Web Design Development – CS506 VU © Copyright Virtual University of Pakistan 319 fBook if (book.equals(first)){session.setAttribute(fBook, java core servlets);} // if secondURL, value of second hyperlink is clicked// then storing the book into session object against sBook else if(book.equals(second)){session.setAttribute(sBook, java how to program);} }//outer if ends // used to display the books currently stored in // the HttpSession object i.e. session printSessionInfo(out, session); out.println(/body); out.println(/html); out.close(); } // end processRequest() if (title != null){ out.println(h3 + title +/h3); e against key sBook from session,// if exist displays it title= (Stri ttribute(sBook); tle +/h3); } } // end printSessionInfo web.xml ?xml web- servlet servlet-name ShoppingCartServlet /servlet-name servlet-class /s // used to display values stored in HttpSession object public void printSessionInfo(PrintWriter out,HttpSession session){ String title = ; // reading value against key fBook from session,// if exist displays it title= (String)session.getAttribute(fBook); } // reading valung)session.getA if (title != null){ println(h3 + ti out. } // end ShoppingCartServlet version=1.0 encoding=UTF-8? app ShoppingCartServlet /servlet-class ervlet
  • 320.
    Web Design Development – CS506 VU © Copyright Virtual University of Pakistan 320 servlet-mappingservlet-name ShoppingCartServlet /servlet-name art /url-pattern /s /web-app Some Now let’s explore some methods of HttpSessionclass . setAttr . getAttribute(String) d value from a session object. It returns nullif no value is associated with the . re d removes values associated with the name . getId( ) This method returns the unique identifier of this session . getCreationTime( ) This method returns time at which session was first created . getMaxInactiveInterval( ) , setMaxInactiveInterval(int) To get or s nvalidated. References: url-pattern /shoppingcervlet-mapping Methods of HttpSession ibute(String, Object) This method associates a value with a name. Extracts previously storegiven name moveAttribute(String) This metho et the amount of time session should go without access before being i ƒ Java A Lab Course by Umair Javed ƒ Core Servlets and JSP by Marty Hall ƒ Stanford Course – Internet Technologies ƒ Java Tutorial on Servlets http://java.sun.com/j2ee/tutorial/1_3-fcs/doc/Servlets11.html ƒ Java API documentation
  • 321.
    Web Design Development – CS506 VU © Copyright Virtual University of Pakistan 321 Lesson 33 AddressBook Case Study Using Sevlets Design Process In this handout, we will discuss the design process of a simple address book. A step by step procedure of creating a simple address book is given below. Layers Web Application As discussed previously, normally web applications are partitioned into logical layers. Each layer performs a specific functionality which should not be mixed with other layers. For example data access layer is used to interact with database and we do not make any direct calls to database from the presentation layer. Layers are isolated from each other to reduce coupling between them but they provide interfaces to communicate with each other. Simplified view of a web application and its layers -Presentation Layer Provides a user interface for client to interact with application. This is the only part of application visible to client. -Business Layer The business or service layer implements the actual business logic or functionality of the application. For example in case of online shopping systems this layer handles transaction management. - Data Layer This layer consists of objects that represent real-world business objects such as an Order, OrderLineItem, Product, and so on. It also encapsulates classes which are used to interact with the data providing services such as databases, other web services etc. In our case study of address book, we will also try to make use of the layered architecture. We will create a separate layer for working with data, and our presentation and business logic will be merged into servlets. It means that we will not have separate layers for presentation and business rather one layer (formed by servlets) will do the job of both presentation and business logic. The extent to which you divide your application into layers depends upon the size of the application and some other factors such as scalability, portability etc.
  • 322.
    Web Design Development – CS506 VU © Copyright Virtual University of Pakistan 322 Step 1 ƒ Create a database (AddressBook) ƒ Make a table named Person according to the figure shown below. It has columns name, address, phomeNum Step 2 The next step is to create a class that can hold the information of a single person. Remember we have stored the information in the database, now when we extract this information from the database as a result of some search, we will require some object to store the data for that particular person. The PersonInfo class will be used at that point to store the retrieved data and transport it to presentation layer. Also we extend this application and add the functionality of “AddingNewContacts” in the database. The PersonInfo class can be used to transport data from front end to the database. ƒ Make a PersonInfo class with the following consideration ƒ It has three three attributes: name, address, ph. No. ƒ It has a parameterized constructor which takes in the above mentioned parameters ƒ Override the toString() method //File: PersnInfo.java String name; s; pub g pn) { nam n; public String toString( ){ public class PersonInfo { String addres String phoneNum; lic PersonInfo(String n, String a, Strin e = address = a; phoneNum = pn; }
  • 323.
    Web Design Development – CS506 VU © Copyright Virtual University of Pakistan 323 return Name: + name + Address: + address + Phone No: + phoneNum; } }// end class PersonInfo Note: To keep the code simple, attributes (name, address phoneNum) are not declared as private, which is indeed not a good programming approach. Step 3 Now we will create a class that will be used to interact with the database for the search, insert, update and delete operations. We will call it PersonDAO where DAO stands for the “data access object”. The PersonDAO along with the PersonInfo class forms the data layer of our application. As you can see that these two classes do not contain any code related to presentation or business logic (There is not much of business logic in this application anyway). So PersonDAO along with PersonInfo is used to retrieve and store data in this application. If at some stage we choose to use some other way of storing data (e.g. files) only the PersonDAO class will change and nothing else, which is a sign of better design as compared to a design in which we put every thing in a single class. ass which contains: eturns PersonInfo object after searching the information of the specified person from the database. //File: PersonDAO.java // method searchPerson public PersonInfo searchPerson(String sName){ PersonInfo person = null; try { Class.forName(sun.jdbc.odbc.JdbcOdbcDriver); String url = jdbc:odbc:AddressBookDSN; Connection con = DriverManager.getConnection(url); String sql = SELECT * FROM Person WHERE name = ?; PreparedStatement pStmt = con.prepareStatement(sql); So, Make a PersonDAOcl ƒ a searchPerson(String name) method that first establishes a connection to the database and r import java.sql.*; public class PersonDAO {
  • 324.
    Web Design Development – CS506 VU © Copyright Virtual University of Pakistan 324 pStmt.setString(1 String add = rs.getString(address); um = rs.getString(phoneNum); Num); ch(E System.out.println(ex); } Step 4 an interface through which he/she can enter the input. The Sear s job for us, It will collect the data from the user and submit that data to another class. The SearchPersonServlet forms the part of our presentation layer. As you can see that it is bein form to the user and collect input. ƒ Write Se hPersonS to search in address book //File: Searc Pe Serv port java.io.*; import java.net.*; import javax.servlet.*; import javax.servlet.http.*; , sName); ResultSet rs = pStmt.executeQuery(); if (rs.next( ) ) { String name = rs.getString(name); String pN person = new PersonInfo(name, add, p } con.close(); }catxception ex){ return person; }// end method } To find what user wants to search, we need to give user chPesonServlet.java will do thi g used to present a arcervlet.java ƒ Will take input for name ƒ Subitsrequ m the est to ShowPersonServlet hrsonlet.java im
  • 325.
    Web Design Development – CS506 VU © Copyright Virtual University of Pakistan 325 public class SearchPersonServlet extends HttpServlet { xt/html); PrintWriter out = response.getWriter(); out.println(html + body +h1 Address Book /h1 +form action=showperson n of // ShowPersonServleth2 Enter name to pName / br/ +input n / +/form +/body +/html out.close(); } // Handles the HTTP GET method.protected void (HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException { // Handles the HTTP POST method protected void doPost(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException { proc sR } } Step 5 The data submitted by the SearchPersonServlet will be submitted to another servlet i.e. ShowPersonServlet, which will interact with the DataLayer(Business logic processing) collects the output and show it to the user. The ShowPersonServlet forms the part of our presentation layer and business layer. As you can see that it is being used to do processing on the incoming data and giving it to data layer (business layer) and present data/output to the user (presentation layer) . Write ShowPersonServlet.java . Receives request from SearchPersonServlet . Instantiate objects of PersonInfo and PersonDAO class . Call searchPerson() method of PersonDAOclass . Show results //File : ShowPersonServlet.java import java.io.*; import java.net.*; import javax.servlet.*; import javax.servlet.http.*; protected void processRequest(HttpServletRequest request,HttpServletResponse esponse) throws ServletException, IOException { response.setContentType(te + // showperson is alias or // url patter search /h2 br/ +inputpe=submit value=Search Perso type=text name= ty); doGet processRequest(request, response);} esequest(request, response);
  • 326.
    Web Design Development – CS506 VU © Copyright Virtual University of Pakistan 326 public class ShowPersonServlet extends HttpServlet { protected void processRequest(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException { response.setContentType(text/html); PrintWriter out = response.getWriter(); String name = request.getParameter(pName); // creating PersonDAO object, and calling searchPerson() method PersonDAO personDAO = new PersonDAO(); PersonInfo person = personDAO.searchPerson(name); out.println(html); out.println(body); out.println(h1Search Results/h1); if (person != null){ out.println(h3+ person.toString() +/h3 ); } else{ out.println(h3Sorry! No records found/h3 ); out.close(); } response)throws ServletException, IOException {processRequest(request, response);} // Handles the HTTP POST method.protected void doPost(HttpServletRequest request,HttpServletResponse response)throws ServletException, IOException } out.println(/body); out.println(/html); // Handles the HTTP GET method.protected void doGet(HttpServletRequest request,HttpServletResponse {processRequest(request, response); } } // end ShowPersonServlet
  • 327.
    Web Design Development – CS506 VU © Copyright Virtual University of Pakistan 327 Sequence Diagram: Address Book (search use case)
  • 328.
    Web Design Development – CS506 VU © Copyright Virtual University of Pakistan 328 Package is put all java files to one k, easy and harmless. However if our small project gets bigger, and es into the same directory would be a nightmare for us. In java we can avoid this sort of problem by using Packages. What is a package? organized for convenience in the same directory to avoid the name es according to packaging is the Many times when we get a chance to work on a small project, one thing we intend to do toin single directory (folder). It is quic the number of files is increasing, putting all these fil In simple terms, a set of Java classes collisions. Packages are nothing more than the way we organize files into different directoritheir functionality, usability as well as category they should belong to. An obvious example of JDK package from SUN (java.xxx.yyy) as shown below: Figure. Basic structure of JDK package Basically, file in e dire nality from those of another directory. For example, files in java.i t files in java.net package give us the way to deal with t e Network. Packaging al h s us t ollision when we use the same class name as that of others. For example, if we have a class s name would crash with the ArrayList class from JDK. Howeve ens because JDK use java.util as a package name for the ArrayList class (java.util.ArrayList). So our ArrayList class can be named as ArrayList or we can put it into another package like com.mycompany.ArrayList without fighting with a ne. The benefits of using package reflect the ease of maintenance, organization, and increase collaboration among developers. Understanding the concept of package will also help us manage and use files stored in jar files in more efficient ways. How to create a package Suppose we have a file called HelloWorld.java, and we want to put this file in a package world. First thing we have to do is to specify the keyword package with the name of the package we want to use (world in our case) on top of our source file, before the code that defines the real classes in the package, as shown in our HelloWorld class below: // only comment can be here s onctory (or package) would have different functio o package do something related to I/O, buh soelpo avoid class name c name called ArrayList, it r, this never happ nyo
  • 329.
    Web Design Development – CS506 VU © Copyright Virtual University of Pakistan 329 package world; System.out.println(Hello World);} } One thi ate nested subdirectories to represent package hierarchy of the class. In our case, we have the world package, which requires only one directory. So, we create a directory (folder) world and put it. public class HelloWorld { public static void main(String[] args) { ng you must do after creating a package for the class is to cre our HelloWorld.java into Figure: HelloWorld in world package (C:worldHelloWorld.java) package package can be imported. For example, // we can use any public classes inside world package import world.*; // import all public classes from java.util package import java.util.*; // import only ArrayList class (not all classes in // java.util package) rt java.util.ArrayList; ote: hile w folders (packages) and to place classes at right cation Many orms this job on your behalf. How to use By using import keyword, all class files reside only in that impoNWorking with IDEs, You don’t have to createlos.IDEs (like netBeans® 4.1) perf
  • 330.
    Web Design Development – CS506 VU © Copyright Virtual University of Pakistan 330 JavaServer Pages (JSP) Like Servlets, JSP is also a specification. JSP technology enables Web developers and designers to rapidly ges that leverage existing business systems. As part of the Java technology family, JSP technology enables rapid development of Web-based applications that are platform independent. JSP technology separates the user interface from content generation, enabling designers to change the overall page layout without altering the underlying dynamic content. The Need for JSP ƒ With servlets, it is easy to Read form data est headers headers — Use cookies and session tracking vlets een requests Get fun, high-paying jobs ƒ Bu — Use those println()statements to generate HTML tain that HTML The JSP Framework Use regular HTML for most of the pages tags ed ent to produce a JSP file. develop and easily maintain, information-rich, dynamic Web pa — — Read HTTP requ — Set HTTP status codes and response — Share data among ser — Remember data betw — t, it sure is a pain to — Main — — Mark servlet code with special — Entire JSP page gets translated into a servlet (once), and servlet is what actually gets invok(for each request) — The Java Server Pages technology combine with Java code and HTML tags in the same docum AagSP over Competing Technologies dvant es of J ƒ e for dynamic part i.e. java ltiple servers and operating systems ƒ ƒ Versus pure servlets — JSPs provide more convenient way to create HTML — JSPs can use standard front end tools (e.g., UltraDev) — JSPs divide and conquer the problem of presentation and business logic. Versus ASP or ColdFusion — JSPs offer better languag — JSPs are portable to muVersus PHP — JSPs offer better language for dynamic part — JSPs offer better tool support
  • 331.
    Web Design Development – CS506 VU © Copyright Virtual University of Pakistan 331 Setting Up Your Environment In order to create a web-application that entirely consists of JSP pages and Html based pages, the setup is fairly simple as compared to a servlet based webapplication. ƒ Set your CLASSPATH. No. ompile your code. No. ƒ Use packages to avoid name conflicts. No. ƒ e WEB-INF for servlets No. o tomcat_install_dir/webapps/ROOT run_install_dir/servers/default/default-app ƒ ƒ However o If you want to use java based classes in an application along with JSPs, previous rules about apply to regular classes used by JSP Refe ƒ air Javed ƒ http l ƒ Java .html ƒ C Put JSP page in special directory, lik o j Use special URL to invoke JSP page. No CLASSPATH, install dirs, etc, still rences: Java A Lab Course by Um Java Package Tutorial by Patrick Bouklee ://jarticles.com/package/package_eng.htm Server Pages Overview http://java.sun.com/products/jsp/overview
  • 332.
    Web Design Development – CS506 VU © Copyright Virtual University of Pakistan 332 Lesson 34 Java Server Pages g either static or dynamic content to a client’s browser. Static content and dynamic content can be intermixed. The examples of static content are HTML, XML Text etc. Java code, displaying properties of JavaBeans and invoking dynamic content. es a JSP passed through before displaying result. As we concluded in our discussion on JSP, JSP is a text based document capable of returnin business logic defined in custom tags are all examples of First run of a JSP Figure below shows what phas The web browser makes a request to JSP source code. This code is bifurcated into HTML and java code by the ler resulting in producing a servlet equivalent displayed to the user. It is important to note voked for the first time or when the changes have been made to JSP. Any later call to JSP does not undergo of compilation phase. Benefits of JSP Convenient • We alre nothing new to be learned to work with JSP. Like gets converted into a servlet), provides an • extensive infrastructure for Tracking sessions Reading and sending HTML headers Parsing and decoding HTML form data Every request for a JSP is handled by a simple JSP java thread as JSP gets converted into a servlet. Hence, the te a JSP document is not dominated by starting a process. Portable Like Servlets, JSP is also a specification and follows a well standardized API. The JVM which is used to execute JSP ile JSP parser. The java source code is compiled by the Java compicode of a JSP. The servlet code is intermixed with HTML and that a JSP only passes through all these phases when it is in ady know java and HTML. So • servlets (as seen, ultimately a JSP time to execu a f is supported on many architectures and operating systems.
  • 333.
    Web Design Development – CS506 VU © Copyright Virtual University of Pakistan 333 Inexpensive There are number of free or inexpensive are good for commercial quality websites JSP vs. Servlet of so there are no signs of doGet(), doPost(). %@ page import=“java.util.*” % h Current Date is:%= new Date()% /h3 /b /html Now, compare the JSP code above with the Servlet code given below that is also displaying the current date. //File: SearchPersonServlet.java import java.net.*; import javax.servlet.*; ttp.*; public cl rvlet extends HttpServlet { prot ocessRequest(HttpServletRequest request,HttpServletResponse response)throws response PrintWriter out = response.getWriter(); out.p tln( ); Web Servers that Let’s compare JSP and Servlet technology by taking an example that simply plays current date. First have a look on JSP that is displaying a current date. This page more looks like a HTML page except two strangely written lines of codes. Al html body 3 ody import java.io.*; import avax.servlet.h import java.util.*; ass SearchPersonSe ec ted void pr ServletException, IOException { .setContentType(text/html); rin “html” + “body” + “h3” + “Current Date is:“ + new Date() + “/h3” + “/body” + “/html”
  • 334.
    Web Design Development – CS506 VU © Copyright Virtual University of Pakistan 334 // Handles the HTTP GET method. st,HttpServletResponse response)throws processRequest(request, response); } protected void doPost(HttpServletRequest request,HttpServletResponse response)throws ServletException, IOException { processRequest(request, response); } } Clearly, a lot of code is needed to be written in the case of servlet example to perform a basic job. ing elements. Directive Elements – Provides global control of JSP ……..…………….. %@ % ƒ Scripting Elements P comments ……………………………………... %----% – declarations ……………………………………... %! % ce variables methods – expressions ……………………………………... %= % • A java code fragment which returns String – scriptlets ……………………………………... % % Blocks of java code ƒ – Special JSP tags ……..…………………………….. jsp: .…. / We’ll discuss in detail all the ingredients of JSP. This handout will cover only scripting elements, remaining ones will be discussed in next handouts. protected void doGet(HttpServletRequest reque ServletException, IOException { // Handles the HTTP POST method. Besides HTML, a JSP may contain the follow ƒ – JS • Used to declare instan • Action Elements
  • 335.
    Web Design Development – CS506 VU © Copyright Virtual University of Pakistan 335 Scripting Elements Comments Comments are ignored by JSP-to-servlet translator. Two types of comments are possibly used in JSP. HTML comment: These comments are shown in browser, means on taking view source of the web page; these sorts of comments can be read. Format of HTML comments is like to: !-- comment text-- – JSP comment: These comments are not displayed in browser and have format like: %-- comment text --% Expressions The format of writing a Java expression is: %= Java expression % These express ML page at the place it occurred in JSP page Examples of writing Expressions are: – will print current data time after converting it to String – /h2 will print the name attribute The format of writing a scriptlet is: %= Java code % After ening up the sc de can be written inside it. This code is inserted verbatim into corresponding servlet. ptlet is: String n = request.getParameter(“name”); out.println(“welcome ” + n); % iptlet reads the name attribute and prints it after appending “welcome” – ions are evaluated, after converted to strings placed into HT h2 Time: %= new java.util.Date() % /h2 h2 Welcome: %= request.getParameter(“name”)% Scriptlets opriptlet tag, any kind of java co Example of writing a scri % The above scr
  • 336.
    Web Design Development – CS506 VU © Copyright Virtual University of Pakistan 336 Declarations laration tag is: %! Java code % This tag is used to declare variables and methods at class level. The code written inside this tag is inserted verbat into servlet’s ) variable is: – %! % Example of declaring a class level method is: – %! public void someMethod ( …… ) { ……………. } xample: Using scripting elements The next example code consists on two JSP pages namely first.jsp and second.jsp. The user will enter two nd after pressing the calculate sum button, able to see the sum of entered numbers on sec nd.jsp first.jsp numbers along with a button. html body eir sum/h1 !—the form values will be posted to second.jsp -- form name = myForm action=second.jsp h3 First Number /h3 e=text name=num1 / h3 Second Number /h3 pe=text name=num2 /br/br/ input type=submit value=Calculate Sum / /form /body /html The format of writing a dec imclass definition. Example of declaring a class level (attribute private int someField = 5; % Code E numbers on the first.jsp a o This page only displays the two text fields to enter h2Enter two numbers to see th input typ input ty
  • 337.
    Web Design Development – CS506 VU © Copyright Virtual University of Pakistan 337 secon This nverting the numbers into integers, displays their sum. html o numbers -- %-- Declaration--% %! public int sum(int op1, int op2) { return op1 + op2; } % %-- Scripltet--% % String op1 = request.getParameter(num1);String op2 = er(num2); int secondNum = Integer.parseInt(op2); // calling method sum(), declared above in declartion tag res = sum(firstNum, secondNum); % %-- expression used to display sum --% h3Sum is: %=res% /h3 /body /html Writing JSP scripting Elements in XML Now days, the preferred way for composing a JSP pages is using XML. Although writing JSP pages in old style is still heavily used as we had shown you in the last example. Equivalent XML tags for writing scripting elements are given below: ƒ Comments: No equivalent tag is defined ƒ Declaration: jsp:declartion /jsp:declaration ƒ Expression: jsp:expression /jsp:expression ƒ Scriptlet: jsp:scriptlet /jsp:scriptlet It’s important to note that every opening tag also have a closing tag too. The second.jsp of last example is given below in XML style. d.jsp page retrieves the values posted by first.jsp. After co body !-- JSP to sum tw // declaring a variable to store sum int res; // method helps in calculating the sum request.getParametint firstNum = Integer.parseInt(op1);
  • 338.
    Web Design Development – CS506 VU © Copyright Virtual University of Pakistan 338 ? xml version=1.0 encoding=UTF-8? jsp:direc t=UTF-8/ ere, e.g.: -- jsp:element name=text jsp:decl on public int sum(int op1, int op2) { n jsp:scri tParameter(num1); ); int firstNum = Integer.parseInt(op1); m, secondNum); /jsp:scriptlet jsp:text Sum is: /jsp:text jsp:expression res /jsp:expression /jsp:body /jsp:element /jsp:root References ƒ Java A Lab Course by Umair Javed ƒ Core Servlets and JSP by Marty Hall jsp:root xmlns:jsp=http://java.sun.com/JSP/Page version=2.0 !-- to change the content type or response encoding change thefollowing line-- tive.page contentType=text/xml;charse !-- any content can be specified h jsp:body arati int res; retu rn op1 + op2; } /jsp:declaratio ptlet String op1 = request.ge String op2 = request.getParameter(num2 int secondNum = Integer.parseInt(op2); res = sum(firstNu
  • 339.
    Web Design Development – CS506 VU © Copyright Virtual University of Pakistan 339 Lesson 35 e have started JSP journey in the last handout and thoroughly discussed the JSP scripting elements. JSP ements and implicit objects will be discussed in this handout. Let’s review JSP journey again to find at part we have already covered. ƒ Directive Elements – Provides global control of JSP ……..…………….. %@ % – JSP comments ……………………………………... %----% – declarations ……………………………………... %! % • Used to declare instance variables methods – JavaServer Pages W directive elout wh ƒ Scripting Elements • A java code fragment which returns String . Action Elements – Special JSP tags ……..…………………………….. jsp: .…. / We start our discussion from implicit objects. Let’s find out what these are? Implicit Objects To simplify code in JSP expressions and scriptlets, you are supplied with eight automatically defined variables, sometimes called implicit objects. The three most important variables are request, response out. Details of these are given below: – request This variable is of type HttpServletRequest, associated with the request. It gives you access to the request parameters, the request type (e.g. GET or POST), and the incoming HTTP request headers (e.g. cookies etc). – response This variable is of type HttpServletResponse, associated with the response to client. By using it, you can set HTTP status codes, content type and response headers etc.
  • 340.
    Web Design Development – CS506 VU © Copyright Virtual University of Pakistan 340 –out This is the object of JspWriterused to send output to the client. Code Example: Use of Implicit Objects The following example constitutes of 4 JSP pages. These are index.jsp, controller.jsp, web.jsp and java.jsp. The user will select either the option of “java” or “web” from index.jsp, displayed in the form of radio buttons and sed on the selection made by the user, controller.jsp will redirect the user to respective pages (web.jsp or java.jsp). shown below in the pictorial form. submits the request to controller.jsp. Ba The flow of the example is The code of these entire pages is given below. index.jsp html h2 input type=radio name = page value=web/ Web Design Develoment /h3 br h3 input type=radio name = page value=java/ body Select the page you want to visit/h2 form name=myForm action=controller.jsp h3
  • 341.
    Web Design Development – CS506 VU © Copyright Virtual University of Pakistan 341 Java /h3 br /html controller. html body !-- scri , name of radio button using // implicit object request String pageName = request.getParameter(page); // deciding which page to move on based on “page” value // redirecting user by using response implicit object if (pageName.equals(web)) { response.sendRedirect(web.jsp); } else if (pageName.equals(java) ) { response.sendRedirect(java.jsp); } % /body /html input type=submit value=Submit / /form /body jsp ptlet -- // reading parameter “page” %
  • 342.
    Web Design Development – CS506 VU © Copyright Virtual University of Pakistan 342 web.jsp html body // use of out implicit object, to generate HTML % out.println( h2 + Welcome to Web Design Development Page + /h2 ); % /body /html java.jsp html body // use of out implicit object, to generate HTML % out.println( h2 + Welcome to Java Page + /h2 ); % /body /html
  • 343.
    Web Design Development – CS506 VU © Copyright Virtual University of Pakistan 343 Th t. ƒ application configuration options e.g. init-parameters etc. ƒ pageContext This variable is of type javax.servlet.jsp.PageContext, to give a single point of access to many of the page attributes. This object is used to stores the object values associated with this object. ƒ exception This variable is of type java.lang.Throwable. Represents the exception that is passed to JSP error page. ƒ page This variable is of type java.lang.Object. It is synonym for this. e details of remaining 5 implicit objects are given below: ƒ session This variable is of type HttpSession, used to work with session objec This variable is of type ServletContext. Allows to store values in key-value pair form that are shared by all servlets in same web application ƒ config This variable is of type ServletConfig. Represents the JSP
  • 344.
    Web Design Development – CS506 VU © Copyright Virtual University of Pakistan 344 JSP Directives JSP processing information about the page to JSP container. It affects the ov programmer to: from other resources specify custom-tag libraries Fo %@ directive {attribute=”val”}* % In JSP, there are three types of directives: page, include taglib. The formats of using these are: –page: %@ page {attribute=”val”}* % – include: %@ include {attribute=”val”}* % %@ taglib {attribute=”val”}* % JSP page Directive Gi about servlet that will result from JSP page. It can be used anywhere in the do rted – What MI – How multit n session pected errors etc. Th lists of attributes that can be used with page directive are: language = “java” extends = “package.class” import = “package.*,package.class,…” Info = “text” eType” isThreadSafe = “true | false” isErrorPage = “true | false” Some exam e uses like java.util %@page import=“java.util.*” info=“using util package” % – To declare this page as an error page rPage = “true” % ead sheet page contentType = “application/vnd.ms-excel” % directives are used to convey special erall structure of the servlet that results from the JSP page. It enables – Specify page settings – To Include content – To rmat – taglib: ve high level information cument. It can control – Which classes are impo– What class the servlet extends ME type is generated hreading is handled – If the participates i– Which page handles unex e session = “true | false” contentType = “mim errorPage = “relativeURL” pl are: – To import package %@ page isErro– To generate the excel spr %@
  • 345.
    Web Design Development – CS506 VU © Copyright Virtual University of Pakistan 345 JS Lets you include (reuse) navigation bars, tables and other elements in JSP page. You can include files at – Translation Time (by using include directive) – Request Time (by using Action elements, discussed in next handouts) Fo % Purpose To i t. It may contain JSP code that affects the main page such as response page header settings etc. Ex e This example contains three JSP pages. These are index.jsp, header.jsp footer.jsp. The header.jsp will display the text of “web design and development” along with current date. The footer.jsp will display only “virtual university”. The outputs of both these pages will be included in index.jsp by using JSP include directive. header.jsp % .*% html Development /h3 h3%=new Date()%/h3 /marquee /body /html P include Directive rmat @include file=“relativeURL”% nclude a file in a JSP document at the time document is translated into a servle ample Code: using include directiv @page import=java.util body marquee h3 Web Desing
  • 346.
    Web Design Development – CS506 VU © Copyright Virtual University of Pakistan 346 footer.jsp html body marquee h3 Virtual University /h3 /marquee /body /html index.jsp html body TABLE BORDER=1 TRTH/THTHApplesTHOranges TRTHFirst QuarterTD2307TD4706 TRTHSecond QuarterTD2982TD5104 5TD5287 /TABLE // includes the output of footer.jsp %@include file=footer.jsp % // includes the output of header.jsp %@include file=header.jsp % TRTHThird QuarterTD3011TD5220 TRTHFourth QuarterTD305 /body /html
  • 347.
    Web Design Development – CS506 VU © Copyright Virtual University of Pakistan 347 Example Code: setting content type to generate excel spread sheet In d to generate excel spread sheet of the last example. The change is shown in bo in // %@page contentType=application/vnd.ms-excel % html body // includes the output of header.jsp %@include file=header.jsp % HTHApplesTHOranges irst QuarterTD2307TD4706 econd QuarterTD2982TD5104 TRTHThird QuarterTD3011TD5220 TRTHFourth QuarterTD3055TD5287 /TABLE // includes the output of footer.jsp %@include file=footer.jsp % /body / this example, index.jsp is modifield face. dex.jsp setting content type to generate excel sheet using page directive TABLE BORDER=1TRTH/T TRTHFTRTHS html
  • 348.
    Web Design Development – CS506 VU © Copyright Virtual University of Pakistan 348 JS Life C Th JSP are jspInit(), _jspService() and jspDesroy(). On receiving each request, _jspService() me Pycle Methods e life cycle methods ofthod is invoked that generates the response as well. Re ƒ Java A Lab Course by Umair Javed ƒ Co e Servle ferences: rts and JSP by Marty Hall
  • 349.
    Web Design Development – CS506 VU © Copyright Virtual University of Pakistan 349 Lesson 36 Java Server Pages 3 irectives and the use of implicit objects. In this s and what affect they produce. Before learning JavaBeans, let’s start with nd the impact of using JavaBeans. Outline his example is actually the modification of the last one we had discussed in previous handout. User will select ld be . The In the last handout, we learned how to work with JSP d handout, we’ll learn about JavaBeanan example that helps us to understa Code Example: Displaying Course T either course “web design and development” or “java”. On submitting request, course outline woudisplayed of the selected course in tabular format. This course outline actually loaded from databaseschema of the database used for this example is given below: The flow of this example is shown below: This page is used to display the course options to the user in the radio button form. html body h2Select the page you want to visit/h2 ent index.jsp form name=myForm action=controller.jsp h3 input type=radio name = page value=web/ Web Design Develom /h3 br
  • 350.
    Web Design Development – CS506 VU © Copyright Virtual University of Pakistan 350 h3 input type=radio name = page value=java/Java /h3br it value=Submit / / controller.jsp on made by the user, this page will redirect the user to respective pages. Those are web.jspand java.jsp body !-- scriptlet -- // reading parameter named page String pageName = request.getParameter(page); ing user based on selection made if (pageName.equals(web)) { response.sendRedirect(web.jsp); } else if (pageName.equals(java) ) { endRedirect(java.jsp); } % input type=subm /form /body html Based upon the selecti html % // redirect response.s
  • 351.
    Web Design Development – CS506 VU © Copyright Virtual University of Pakistan 351 /body /html web.jsp course outline of “web design and development” in a tabular format after reading them from database. The code is: %@page import=java.sql.*% body b Design Development Page /h2 line/h3 TABLE BORDER=1 TH THAssignments/TH /TR % // establishing conection Class.forName(sun.jdbc.odbc.JdbcOdbcDriver); String conUrl = jdbc:odbc:CourseDSN; Connection con = DriverManager.getConnection(conUrl); This page is used to display // importing java.sql package using page directive, to work with database html center h2 Welcome to We h3 Course Out TR THSession No./TH THTopics/ %-- start of scriptlet --%
  • 352.
    Web Design Development – CS506 VU © Copyright Virtual University of Pakistan 352 // preparing query u sing join statements String sql = SELECT sessionNo, topic, assignment + FROM Course, SessionDetail + WHERE courseName = ? + e.courseId = SessionDetail.courseID; PreparedStatement pStmt = con.prepareStatement(sql); parameter value ”web”.pStmt.setString( 1 , web); ResultSet rs = pStmt.executeQuery(); String sessionNo; String topic; assignment; // iterating over resultset o = rs.getString(sessionNo); topic = rs.getString( c); assignment = rs.getString(assignment); if (assignment == null){ assignment = ; %-- end of scriptlet --% are displayed in tabular format usingexpressions, however it can also be done usingout.println(sessionNo) like statements --% AND Cours // setting String while (rs.next()) { sessionN topi } % %-- The values
  • 353.
    Web Design Development – CS506 VU © Copyright Virtual University of Pakistan 353 TR TD %=topic% /TD TD %=assignment% /TD java.jsp The code of this page is very much alike of “web.jsp”. The only change is in making of query. Here the value is set “java” instead of “web” / imp ith database %@page impor html body come o Java Outline/ TABLE BORDER=1 THSession No./TH THTopics/TH /TR TD %=sessionNo% /TD /TR % } // end while % /TABLE /center /body /html /orting java.sql package using page directive, to work w t=java.sql.*% center h2 Wel tPage /h2 h3 Course h3 TR THAssignments/TH
  • 354.
    Web Design Development – CS506 VU © Copyright Virtual University of Pakistan 354 %-- start of scriptlet --% % // establishing connection Calss.forName(“sun.jdbc.odbc.JdbcOdbcDriver”); String conUrl = jdbc:odbc:CourseDSN; Connection con = DriverManager.getConnection(conUrl); // preparing query using join statements , topic, assignment + = ? + AND Course.courseId = SessionDetail.courseID; pareStatement(sql); String topic; String assignment; o); getString(topic); assignment = rs.getString(assignment); String sql = SELECT sessionNo FROM Course, SessionDetail + WHERE courseName PreparedStatement pStmt = con.pre // setting parameter value ”web”.pStmt.setString( 1 , java); ResultSet rs = pStmt.executeQuery(); String sessionNo; // iterating over resultset while (rs.next()) { sessionNo = rs.getString(sessionN topic = rs. if (assignment == null)
  • 355.
    Web Design Development – CS506 VU © Copyright Virtual University of Pakistan 355 { assignment = ; % %-- end of scriptlet --% %-- The values are displayed in tabular format usingexpressions, however it can also be done usingout.println(sessionNo) like statements --% TR %=sessionNo% /TD TD %=topic% /TD TD %=assignment% /TD /TR % } // end while % /TABLE /center /body /html and java.jsp. This makes it very difficult to understand (probably you enced it by yourself) and to make changes/enhancements. A single page is doing everything that is really a bad approach while making of web applications. The tasks ts (Presentation logic) atabase (DB connectivity logic) g (Business Logic) answer lies in the use of JavaBeans technology. } TD Issues with Last Example Too much cluttered code in web.jsp experi performed by web.jspor java.jspare: ƒ Displaying conten ƒ Connecting with d ƒ Results Processin Can we simplify it? Yes, the
  • 356.
    Web Design Development – CS506 VU © Copyright Virtual University of Pakistan 356 JavaBeans A java class that can be easily reused and composed togethercertain design conventions can be a JavaBean. in an application. Any java class that follows JavaBeans Design Conventions These conventions are: ƒ A bean class must have a zero argument constructor ƒ A bean class should not have any public instance variables/attributes (fields) ƒ ld be accessed through setters/getters For boolean data types, use boolean isXXX( ) setXXX(boolean) ust be serializable A Sample JavaBean that satisfies all the conventions described above. The e; // zero argument constructor pub name = “”; ame(String n) { n; } ublic String getName( ) { return name; } ny other method public void print( ) { me is: ” + name); } // end Bean class Private values shou ƒ A bean class m The code snippet of very basic JavaBean is given belowMyBean.java class has only one instance variable. public class MyBean implements Serializable { private String nam lic MyBean( ){ } // standard setter public void setNname = // standard getter p // a System.out.println(“Na }
  • 357.
    Web Design Development – CS506 VU © Copyright Virtual University of Pakistan 357 Example Code: Displaying course outline by incorporating JavaBeans his exa Two JavaBeans are included in this example code. These are CourseOutlineBean CourseDAO. The CourseOutlineBean is used to represent one row of the table. It contains the following attributes: ƒ sessionNo ƒ topic ƒ assignment e DAO stands of Data Acess Object) bean encapsulates database connectivity and Beans. The code of these and the JSPs used in this example are CourseOutlineBean.java package vu; tlineBean implements Serializable{ private int sessionNo; private String topic; private String assignment; // no argument constructor assignment = ; } // setters public void setTopic(String t){ Tmple is made by making more enhancements to the last one. The CourseDAO (wherresult processing logic. The web.jsp and java.jsp will use both these Javagiven below. import java.io.*; public class CourseOu public CourseOutlineBean() { sessionNo = 0; topic = ; public void setSessionNo(int s){ sessionNo = s; } topic = t; }
  • 358.
    Web Design Development – CS506 VU © Copyright Virtual University of Pakistan 358 public void setAssignment(String a){ assignment = a; } lic No( ){ nNo; public String getTopic( ){ return topic; public String getAssignment( ){ } // end class CourseDAO.java import java.util.*; public class CourseDAO implements Serializable{ private Connection con; public CourseDAO() { establishConnection(); // getterspub int getSession return sessio } } return assignment; } package vu; import java.io.*; import java.sql.*;
  • 359.
    Web Design Development – CS506 VU © Copyright Virtual University of Pakistan 359 } //********** establishConnection method ************* method used to make connection with databaseprivate void establishConnection(){ // establishing conection N; con = DriverManager.getConnection(conUrl); }catch(Exception ex){ System.out.println(ex); } //*********** retrieveCourseList method ******************** ng cName){ t courseList = new ArrayList(); ic, assignment + FROM Course, SessionDetail + WHERE courseName = ? + AND Course.courseId = SessionDetail.courseID ; PreparedStatement pStmt = con.prepareStatement(sql); pStmt.setString(1, cName); ResultSet rs = pStmt.executeQuery(); try{ Class.forName(sun.jdbc.odbc.JdbcOdbcDriver); String conUrl = jdbc:odbc:CourseDS } public ArrayList retrieveCourseList(Stri ArrayLis try{ String sql = SELECT sessionNo, top
  • 360.
    Web Design Development – CS506 VU © Copyright Virtual University of Pakistan 360 int sNo; String topic; String assignment; while ( rs.next() ) { sNo = rs.getInt(sessionNo); topic = rs.get tring(topic); rs.getString(assignment); if (assignment == null) { assignment = ; } // creating a CourseOutlineBean object CourseOutlineBean cBean = new CourseOutlineBean(); cBean.setSessionNo(sNo); cBean.setTopic(topic);cBean.setAssignment(assignment); // adding a bean to arraylist courseList.add(cBean); } }catch(Exception ex){ System.out.println(ex); } finally { // to close connection releaseResources(); } // returning ArrayList object return courseList; } // end retrieveCourseOutline S assignment =
  • 361.
    Web Design Development – CS506 VU © Copyright Virtual University of Pakistan 361 //********** releaseResources method ******************** private void releaseResources(){ if(con }catc System.out.println(); }//end ourseDAO index.jsp This page is used to display the course options to the user in the radio button form. html body e you want to visit/h2 form name=myForm action=controller.jsp e=radio name = page value=web/ /h3 page value=java/Java input submit value=Submit / /html try{ != null ){ con.close(); } h(Exception ex){ } } // end releaseResources C h2Select the pag h3 input typ Web Design Develoment br h3 input type=radio name = /h3br type = /form /body
  • 362.
    Web Design Development – CS506 VU © Copyright Virtual University of Pakistan 362 controller.jsp Based on user selection, redirects the user to desired page. !-- scriptlet -- sponse.sendRedirect(java.jsp); % /body /html e also uses the JavaBeans (CourseOutlineBean CourseDAO). center html body % equest.getParameter(page); String pageName = r if (pageName.equals(web)) { response.sendRedirect(web.jsp); } else if (pageName.equals(java) ) { re } web.jsp This page is used to display course outline of “web design and development” in a tabular format after reading them from database. Moreover, this pag %@page import=java.util.* % %-- importing vu package that contains the JavaBeans--% %@page import=vu.* % html body
  • 363.
    Web Design Development – CS506 VU © Copyright Virtual University of Pakistan 363 h2 Welcome to Web Design Development Course /h2 TABLE BORDER=1 TR THSession No./TH THTopics/TH THAssignments/TH /TR %-- start of scriptlet --% % // creating CourseDAO object CourseDAO courseDAO = new CourseDAO(); // calling retrieveCourseList() of CourseDAO class and // passing “web” as value. This method returns ArrayListArrayList courseList = courseDAO.retrieveCourseList(web); CourseOutlineBean webBean = null; for(int i=0; icourseList.size(); i++){ ean = (CourseOutlineBean)courseList.get(i); tlet --% T TD %= webBean.getSessionNo()% /TD TD %= webBean.getTopic()% /TD h3 Course Outline/h3 // iterating over ArrayList to display course outline webB% %-- end of scripR
  • 364.
    Web Design Development – CS506 VU © Copyright Virtual University of Pakistan 364 TD % /TAB /center java.js The code contains by this page is almost same of web.jsp. Here, “java” is passed to retieveCourseList( ) ethod. This is shown in boldface. %@page import=java.util.* % %-- importing vu package that contains the JavaBeans--%%@page import=vu.* % html body center h2 W h3 C tline/h3 E BORDER=1 TR THSession No./TH THTopics/TH THAssignments/TH /TR %= webBean.getAssignment()% /TD / TR % } // end for LE /body /html p m elcome to Java Course /h2 ourse Ou TABL
  • 365.
    Web Design Development – CS506 VU © Copyright Virtual University of Pakistan 365 %-- start of scriptlet --% % // creating CourseDAO object CourseDAO courseDAO = new CourseDAO(); // calling retrieveCourseList() of CourseDAO class and thod returns ArrayList etrieveCourseList(java); CourseOutlineBean javaBean = null; // iterati to display course outline % %-- end of scriptlet --% TR TD %= javaBean.getSessionNo()% /TD .getTopic()% /TD TD %= javaBean.getAssignment()% /TD /TR % } // end for % /TABLE // passing “java” as value. This meArrayList courseList = courseDAO.r ng over ArrayList for(int i=0; icourseList.size(); i++){ javaBean = (CourseOutlineBean)courseList.get(i); TD %= javaBean
  • 366.
    Web Design Development – CS506 VU © Copyright Virtual University of Pakistan 366 /center /body /html for this handout is taken from the book JAVA A Lab Course by Umair Javed. This material is ava le r the use of VU students of the course Web Design and Development and not for any other commercial purpose without the consent of author. References: Entir m eaterialilab just fo
  • 367.
    Web Design Development – CS506 VU © Copyright Virtual University of Pakistan 367 Lesson 37 JSP Action Elements and Scope T wc Let’s first quic n the JSP journey to find out where we have reached. ƒ Directive Elements – Provides global control of JSP ……..…………….. %@ % ƒ Scripting Elements – JSP comments ……………………………………... %----% – declarations ……………………………………... %! % ƒ Used to declare instance variables methods ƒ Action Elements – Special JSP tags ……..…………………………….. jsp: .…. / JSP Action Elements JSP action elements allow us to work with JavaBeans, to include pages at request time and to forward requests to other resources etc. dy body -Closing tag /jsp:actionElement Some JSP Action Elements ƒ To work with JavaBeans -jsp:useBean / he journey we had started of JSP is very much covered except of JSP action elements. In this handout, e’ll study the use of JSP action elements. Further also learn how and where to store JavaBean objects that an be shared among JSP pages. kly look o Format Expressed using XML syntax -Opening tag jsp:actionElement attribute=”value” ….. -Bo Empty tags (without body) can also be used like jsp:actionElement attribute=”value” ….. -jsp:setProperty / -jsp:getProperty / ƒ To include resources at request time -jsp:include / ƒ To forward request to another JSP or Servlet
  • 368.
    Web Design Development – CS506 VU © Copyright Virtual University of Pakistan 368 -jsp:forward / applets -jsp:plugin / Working with JavaBeans using JSP Action Elements The three action elements are used to work with JavaBeans. These are discussed in detail below. JSP useBean Action Element It is used to obtain a reference to an existing JavaBean object by specifying id(name of object) and scope in which bean is stored. If a reference is not found, the bean is instantiated. The format of this action element is: jsp:useBean id = “name” scope = “page|request|session|application” class=“package.Class ” / The id attribute specifies the name of the JavaBean object that is also used for later references. The scope attribute can have one possible value out of page, request, session and application. If this attribute is omitted, the default value of scope attribute is page. We’ll discuss in detail about scope shortly. The class attribute specifies the type of object is going to be created. jsp:useBean is being equivalent to building an object in scriptlet. For example to build an object of MyBeanusing scriptlet is: % MyBean m = new MyBean( );% Achieving above functionality using jsp:useBean action element will look like this: jsp:useBean id = “m” scope = “page” class=“vu.MyBean” / In the above code snippet, we are assuming that MyBean lies in vu package. JSP setProperty Action Element To set or change the property value of the specified bean. String values are converted to types of properties by using the related conversion methods. The format of this action element is: jsp:setProperty name = “beanName or id” property = “name”value =“value” / The name attribute should match the id given in jsp:useBean. The propertyattribute specifies the name of the property to change and the value attribute specifies the new value. jsp:setProperty is being equivalent to following code of scriptlet. For example to change the name property of m (instance of MyBean) using scriptlet is: % m.setProperty(“ali”); % Achieving above functionality using jsp:setProperty action element will look like this: jsp:setProperty name = “m” property = “name” value = “ali” / ƒ To work with
  • 369.
    Web Design Development – CS506 VU © Copyright Virtual University of Pakistan 369 JSP getProperty Action Element Use to retrieves the value of property, converts it to String and writes it to output stream. The format of this action element is: jsp:getProperty name = “beanName or id” property = “name” / jsp:getProperty is being equivalent to following code of scriptlet. For example to retrieve the name property of m (instance of MyBean) followed by writing it to output stream, scriptlet code will look like: % String name = m.getName( ); out.println(name); % chieving above functionality using jsp:getProperty action element will look like this: jsp:getProperty name = “m” property = “name” / ndex.jsp and result.jsp and one JavaBean i.e. SumBean. User will enter two numbers on be displayed on result.jsp. Let’s examine these one after another SumBean.java The SumBean has following attributes nd secondNumbers are “write-only” properties means for these only setters would be efined. Whereas sum is a “read-only” property as only getter would be defined for it. The SumBean also contain one additional method for calculating sum i.e. calulateSum(). After performing import java.io.*; public class SumBean implements Serializable{ private int firstNumber; private int secondNumber; private int sum; // no argument constructor public SumBean() { firstNumber = 0; secondNumber = 0; sum = 0; } A Example Code: Calculating sum of two numbers by using action elements and JavaBean his example contains i Tindex.jsp and their sum will – firstNumber – secondNumber – sum The firstNumber a d addition of firstNumber with secondNumber, this method will assign the result to sum attribute. package vu;
  • 370.
    Web Design Development – CS506 VU © Copyright Virtual University of Pakistan 370 // firstNumber secondNumber are writeonly properties// setterspublic void setFirstNumber(int n){ firstNumber = n; } public void setSecondNumber(int n){ secondNumber = n; } // no setter for sum // sum is a read only property public int getSum( ){ return sum; } // method to calculate sum public void calculateSum() { sum = firstNumber + secondNumber; } } index.jsp This page will display two text fields to enter number into them. html body h2Enter two numbers to calculate their sum/h2 form name=myForm action=result.jsp input type=text name=num2 / br/ input type=submit value=Calculate Sum / /h3 /form /body /html h3 Enter first numebr input type=text name=num1 /br/ Enter second numebr
  • 371.
    Web Design Development – CS506 VU © Copyright Virtual University of Pakistan 371 result.jsp This page will calculate the sum of two entered numbers by the user and displays the sum back to user. The ddition is performed using SumBean %-- importing vu package that contains the SumBean -- %%@page import=vu.*% html body element -- % n id=sBean class=vu.SumBean scope=page/ %-- setting firstNumber property of sBean using action elements -- % %-- implicit conversion from string to int as num1 is of typeString and firstNumber is of type int--% %--//Servlet equivalent code of setProperty for num1int no = Integer.parseInt(request.getParameter(num1));sBean.setFirstNumber(no); --% 1 / %--//Servlet equivalent code of setProperty for num2int no = property=secondNumber param=num2 / // calling calculateSum() method that will set the value of// sum attribute sBean.calculateSum(); % ying sumint res = sBean.getSum();out.println(res); jsp:getProperty name=sBean property=sum / /h2 /body /html a h2The sum is: %-- instantiating bean using action //Servlet equivalent code of useBean SumBean sBean = new SumBean(); --% jsp:useBea jsp:setProperty name=sBeanproperty=firstNumber param=num Integer.parseInt(request.getParameter(num2));sBean.setSecondNumber(no); --% jsp:setProperty name=sBean % %--// servlet equivalent code of displa--%
  • 372.
    Web Design Development – CS506 VU © Copyright Virtual University of Pakistan 372 Sharing Beans Object Scopes So far, we have learned the following techniques to create objects. -Implicitly through JSP di -Explicitly through actions -Directly using scripting code Although the beans are indeed bound to local variables, that is not the only behavior. They are also stored in four different locations, depending on the value of the optional scope attribute of jsp:useBean. The scope attribute has the following possible values: page, request, sessionand application. Let’s discover what impact these scopes can produce on JavaBeans objects which are stored in one of these This is the default value of scope attribute, if omitted. It indicates, in addition to being bound to local variable, the bean object should be placed in the pageContextobject. The bean’s values are only available and persist on JSP in which bean is created. of following diagram: rectives scopes. ƒ page In practice, beans created with page scope are always accessed (their values) by jsp:getProperty, jsp:setProperty, scriptlets or expressions later in the same page. This will be more cleared with the help PageContext In the diagram above, first.jsp generates a request “request 1” that is submitted to second.jsp. Now, second.jsp creates an object m of MyBeanby calling its default constructor and stores a value “ali” for the name property by making a call to appropriate setter method. Since, the scope specified in this example is t of MyBean is instantiated using jsp:useBean action element. Therefore, object (m) of MyBeanis stored in PageContext. st 2), e ag “page”when the objec Whether, second.jsp forwards the same request (request 1) to third.jsp or generates a new request (requeat third.jsp, values (e.g. ali) stored in MyBean object m, are not available. Hence, specifying scop “pe” results in using the object on the same page where they are created.
  • 373.
    Web Design Development – CS506 VU © Copyright Virtual University of Pakistan 373 ƒ request This value signifies that, in addition to being bound to local variable, the bean object should be placed in Serv e duration of the current request. In other words, until you continue to forw r JSP/servlet, the beans values are available. This has been illustrated in the foll letRequest object for thard the request to anothe owing diagram. In the diagram above, MyBean is instantiated by specifying scope = “request”that results in storing object in second.jsp forwards the same request (request 1) to third.jsp, since scope of m (object of MyBean) is request, as a result third.jsp can access the values(e.g. ali) stored in m. According to the figure, third.jsp generates a new request (request 2) and submits it to fourth.jsp. Since a new q t erefore values stored in object m (e.g. ali) are not available to fourth.jsp. This value means that, in addition to being bound to local variable, the bean object will be stored in the HttpSession object associated with the current request. As you already know, object’s value stored n understanding this concept. ServletRequest. A value “ali” is also stored in m using setter method. re ues is generated th ƒ session in HttpSession persists for whole user’s session. The figure below helps i
  • 374.
    Web Design Development – CS506 VU © Copyright Virtual University of Pakistan 374 HttpSession In t is instantiated by specifying scope = “session”that results in storing object in HttpSession. A value “ali” is also stored in m using setter method. Irre uest forwarding or new request generation from second.jsp to other resources, the valu s stored sion is ended. ƒ application This very useful value means that, in addition to being bound to local variable, the bean object will be stored in ServletContext. The bean objects stored in ServletContext is shared by all JSPs/servlets in the same web application. The diagram given below illustrates this scenario: he diagram above, MyBean spective of reqe in HttpSession remains available until user’s ses ServletContext
  • 375.
    Web Design Development – CS506 VU © Copyright Virtual University of Pakistan 375 Summary of Object’s Scopes Let’s take another view of session, request page scopes in the next figure that helps us to understand the und b er eneath things.
  • 376.
    Web Design Development – CS506 VU © Copyright Virtual University of Pakistan 376 The figure shows four JavaServer Pages. Each page has its own page scope. Therefore objects stored in page scope are only available to same pages on which they are created. Suppose page1 forwards the request to page2. Objects stored in request scope remains available to page1 as well to page 2. Similar case is true for page 3 page 4. If user makes a visit to all these pages in one session, object’s values stored in session scope remains available To d er the following figure: on all these pages. unerstand the difference between sessions application scope, consid As you can conclude from the figure, for each user (client), objects are stored in different sessions. However, in the case of application scope, all users stores objects in single place.
  • 377.
    Web Design Development – CS506 VU © Copyright Virtual University of Pakistan 377 More JSP Action Elements Let’s talk about two important action elements. These are include forward. JSP include action Element It is used to include files at request time. For example, to reuse HTML, JSP or plain text content. It’s important to note that JSP content cannot affect main page (in which output is included); only output of included JSP is used. It also allows updating of the included content without changing the main JSP. The jsp:include action element requires two attributes: page flush. -page: a relative URL of the file to be in “true” jsp:include page = “relative URL” flush = “true” / jsp:in owing code of scriptlet. For example to include the output of one.jsp , scriptl % = request.getRequestDispatcher(“one.jsp”);rd.include(request, response); % unctionality using jsp:include action element will look like this: jsp:include page = JSP forward action Element rce. The format of jsp:forward action is: jsp:forward page = “one.jsp” / uivalent to following code of scriptlet. For example to forward the request to one.jsp , scriptlet code will l % RequestD References: cluded. -flush:must have the value clude is being equivalent to follet code will look like: RequestDispatcher rd Achieving above f “one.jsp” flush = “true” / It is used to forward request to another resou jsp:forward is being eqook like: ispatcher rd = request.getRequestDispatcher(“one.jsp”); rd(request, response); rd.forwa% . Java A Lab Course by Umair Javed. rver Pages by Marty Hall . Core Servlets and JavaSe
  • 378.
    W VU ©Copyright Virtual University of Pakistan eb Design Development – CS506 378 Lesson 38 JSP Custom Tags To begin with, let’s review our last code example of lecture 36 i.e. Displaying course outline. We incorporated JavaBeans to minimi P. But still, we have to write some lines of java code inside java SPs are built for presentation purpose only, so all the other code that involves business and database logic must be shifted else where like we used JavaBeans for such purpose. There is also another problem attached to it. Generally web page designers which have enough knowledge to work me scripting language, faced lot of difficulties in writing some simple lines of java code. ues, java provides us the mechanism of custom tags. Motivation ppet we used in JSP of the course outline t for your reference to give you a hint. % CourseDAO courseDAO = new CourseDAO(); ist for (…………………… ) { …………………… …………………… // displaying courseoutline } ……………… Can we replace all the above code with one single line? Yes, by using custom tag we can write like this: By only g will display the course outline in tabular format. Now, you must ha anges custom tags can bring on. ƒ In simplistic terms, “a user defined component that is used to perform certain action”. This action could be as simple as displaying “hello world” or it can be as complex as displaying course outline of selected course after reading it form database. ƒ It provides mechanism for encapsulating complex functionality for use in JSPs. Thus facilitates the non-java coders. ze the database logic from the JS.jsp web.jsp. As discussed earlier, J with HTML and soTo overcome these iss To give you an inspiration, first have a glance over the code sniexample of last lecture. Of course, not all code is given here; it’s jus ……………… // iterating over ArrayL % mytag:coursetag pageName=“java” / specifying the course/page name, this tave realized how significant ch What is a Custom Tag?
  • 379.
    Web Design Development – CS506 VU © Copyright Virtual University of Pakistan 379 ƒ We already seen used many built in tags like: - jsp:useBean …… / - jsp:include …… / Why Build Custom Tag? ƒ seBean and JavaBeans to incorporate complex, encapsulated ƒ H s cannot manipulate JSP content and Web page designers must have some kn aBeans in a page ƒ With page designers to use complex functionality without knowing any java Advantages ustom Tags ƒ rocessing logic and presentation, than JavaBeans. ƒ all JSP implicit objects like out, request etc. ƒ an be customized by specifying attributes. Types of Tags Three types of can be constructed. These are: 1 Simple Tag 2 Tag with Attribute 3 Tag wit 1. Simple Tag A simple tag has the following characteristics: -Start and End of tag -No body is specified within tag -No attributes -For example - jsp:forward …… / etc. We introduced action jsp:ufunctionality in a JSP. owever, JavaBeanowledge to use JavCustom tags, it is possible for web of using CProvides cleaner separation of pHave access toC h Body
  • 380.
    Web Design Development – CS506 VU © Copyright Virtual University of Pakistan 380 2. Tag with Attributes ith attributes has the following characteristics: -Start and End of tag -Attributes within tag -For example mytag:hello attribute = “value” / 3. Tag with Body A : -Start and End of tag -M -Body enclosed within tag -For example mytag:hello optional_attributes ………… some body / mytag:hello A tag w -No body enclosed tag with body has the following characteristics ay be attributes
  • 381.
    Web Design Development – CS506 VU © Copyright Virtual University of Pakistan 381 Building Cu So far, we have used many built-in tags. Now the time has come to build your own one. Custom tags can be built either by using JSP 1.2 specification or JSP 2.0 (latest) specification. To develop custom tags u me (too difficult for James Gossling also☺). However, JSP 2.0 brings lots of goodies like ƒ Simple tag extensions to build custom tags ƒ Integrated Expression Language (will be discussed in coming lecture) ƒ Also provides an alternate mechanism for building custom tags using tag files (.tag) ƒ Improved XML syntax etc. Steps for Building The following steps are used in order to develop your own custom tag. These are: 1 Develop the Tag Handler class 2 Write Tag library Descriptor (.tld) file 3 Deployment 1. De s ƒ Tag Handler is also a java class that is implicitly called when the associated tag is encountered in the JSP. ƒ Must implement SimpleTaginterface ƒ Usually extend from SimpleTagSupport class that has already implemented SimpleTag interface. ƒ For example, public class MyTagHandler extends SimpelTagSupport { ……………………… ……………………… } ƒ doTag() method • By default does nothing • Need to implement / override to code/write functionality of tag • Invoked when the end element of the tag encountered. ƒ JSP implicit obje (e.g. out etc) are available to tag handler class through pageContextobject. ƒ pageContextobje n be obtained using getJspContext() method. ƒ For example to get the reference of implicit outobject, we write. PageContext pc = (PageContext) getJspContext(); JspWriter out = pc.getOut(); 2. Write Tag Library Discriptor (.tld) file • It is a XML based document. • Specifies information required by the JSP container such as: stom Tags sing JSP 1.2 involves lot of cumberso Custom Tags velop the Tag Handler clas cts ct ca
  • 382.
    Web Design Development – CS506 VU © Copyright Virtual University of Pakistan 382 -Tag library version te names etc. Note: If you are using any IDE (like netBeans® 4.1, in order to build custom tags, the IDE will • Place Tag Handler class in myapp/WEB-INF/classes folder of web application. • Place .tld file in myapp/WEB-INF/tldsfolder of web application. Note: Any good IDE will also perform this step on your behalf Use taglib directive in JSP to lib uri=”TLD file name” prefix=“mytag” % The next step is to call the tag by its name as defined in TLD. For example, if tag name is hello then we write: mytag:hello / where mytag is the name of prefix specified in taglibdirective. What actu propriate tag handler class. After that, Example Code: Building simple tag that displays “Hello World” h we have talked about what are custom tags, their types. Now, it is a time to build a custom tag that ays “Hello World”. Approach • Extend Tag Handler class from SimpleTagSupport class and override doTag() method • Build TLD file • Deploy Note: As mentioned earlier, if you are using any IDE (like netBeans® 4.1), the last two steps will be performed by the IDE. WelcomeTagHandler.java package vu; // importing required packages im import jav -JSP version -Tag name -Tag Handler class name -Attribu write .tldfile for you. 3. Deployment refer to the tag library. For example %@ tag ally happened behind the scenes? Container calls the doTag() method of apTag Handler will write the appropriate response back to the page. Enougdispl port javax.servlet.jsp.*; ax.servlet.jsp.tagext.*;
  • 383.
    Web Design Development – CS506 VU © Copyright Virtual University of Pakistan 383 // ov public void d // ob ntext)getJspContext();JspWriter out = pageContext.getOut(); ); } catch (java.io.IOException ex) {throw new JspException(ex.getMessage());} } // end doTag() method } end W custom If using IDE, this file will be written automatically. In this file you specify the tag name along with Tag Handler class. ?xm /java.sun.com/xml/ns/j2eexmlns:xsi=http://www.w3.org/2001/XM LSchema-instancexsi:schemaLocation=http://java.sun.com/xml/ns/j2ee web- short-namemytag/short-name used in JSP to refer to this tld -- !— Specifying the tag name and tag class. Also mentioning thatthis tag has no body tag-classvu.WelcomeTagHandler/tag-class body-contentempty/body-content erriding doTag() method oTag() throws JspException { taining the reference of out implicit object PageContext pageContext = (PageCotry { out.println( Hello World elcomeTagHandler class tags.tld l version=1.0 encoding=UTF-8? sion=2.0 taglib verxmlns=http:/ jsptaglibrary_2_0.xsd tlib-version1.0/tlib-version !—the value of uri will be uri/WEB-INF/tlds/customtags/uri -- tag namewelcome/name ag /t /taglib
  • 384.
    Web Design Development – CS506 VU © Copyright Virtual University of Pakistan 384 %-- taglib directive, specifying the tld file namethe%@taglib uri=/WEB-INF/tlds/customtags. html bod using as well asprefix. Note that you you use any value for prefix attribtute --% tld prefix=mytag % y h2A Simple Tag Example/h2 h3 %-- calling welcome tag with the help of prefix --%mytag:welcome / /h3 /body/html Building tags with attributes If you w ld a tag that can also take attributes, for example mytag: ello attribute=”value” / To handle attribu • Instance • Corresponding setter methods Behind the scenes, contai attribute as an argument. In this example, we will modify our course outline example to incorporate tags. Based on attribute value, the tag will displ pective course outline in tabular format. Approach • Extend Tag ass from SimpleTagSupport class -Add instance variable of type String -Write setter method for this attribute verride doTag() method • Build TLD file • Deploy ant to bui h tes, you need to add s and variablener will call these setter methods implicitly and pass the value of the custom tag ay the res Handler cl -O
  • 385.
    Web Design Development – CS506 VU © Copyright Virtual University of Pakistan 385 CourseOutlineBean.java This is the same file used in the last example package vubean; a.io.*; public cl Bean implements Serializable{ pr t sessionNo; private String topic; private Stri // no argument con public CourseOutlin sessionNo = 0; topic = ; assignment = } etters public void setSessionNo(int s){ sessionNo = s; public void setTopic(String t){ } public void setAssignment(String a){ assignment = a; // getter public S tTopic( ){return topic;} public S } } // end class import jav ass CourseOutline ivate in ng assignment; structor eBean() { ; // s } topic = t; } spublic int getSessionNo( ){return sessionNo;} tring ge tring getAssignment( ){return assignment;
  • 386.
    Web Design Development – CS506 VU © Copyright Virtual University of Pakistan 386 CourseDAO.java a.io.*;import java.sql.*;import java.util. public class Cou private Con public C ) { est onnection(); } //********** establishConnection method ********************// method used to make connection with da e void establishConnection(){ try{// establishing conectionClass.forName(sun.jdbc.odbc.JdbcOdbcDriver); String conUrl = jdbc:odbc:CourseDSN;con = DriverManager.getConnection(conUrl); } } ArrayList courseList = new ArrayList(); try{ String sql = SELECT sessionNo, topic, assignment + FROM Course, SessionDetail + WHERE courseName = ? + AND Course.courseId = SessionDetail.courseID ; PreparedStatement pStmt = con.prepareStatement(sql);pStmt.setString(1, cName); ResultSet rs = pStmt.executeQuery(); int sNo; String topic; String assignment; No changes are made to this file too. package vu; import jav *; rseDAO implements Serializable{ nection con; ourseDAO( ablishC tabaseprivat }catch(Exception ex){ System.out.println(ex);
  • 387.
    Web Design Development – CS506 VU © Copyright Virtual University of Pakistan 387 while ( rs.next() ) { sNo = rs.getInt(sessionNo);topic = rs.getString(topic); ng(assignment); rseOutlineBean cBean = new CourseOutlineBean(); n.setAssignment(assignment); // adding a bean to arraylist // to close connection releaseResources(); rn courseList; } // end retrieveCourseOutline try{ if(con != null){ con.close(); } }catch(Exception ex){ System.out.println(); } } // end releaseResources }// end CourseDAO assignment = rs.getStri if (assignment == null){assignment = ;} // creating a CourseOutlineBean objectCou cBean.setSessionNo(sNo);cBean.setTopic(topic);cBea courseList.add(cBean); } }catch(Exception ex){ System.out.println(ex); } finally { } // returning ArrayList object retu
  • 388.
    Web Design Development – CS506 VU © Copyright Virtual University of Pakistan 388 MyTagHandler.java The tag handler class uses JavaBeans (CourseOutlineBean.java CourseDAO.java), and includes the logic / importing package that contains the JavaBeansimport vubean.*; import javax.servlet.jsp.tagext.*;import javax.servlet.jsp.*;import java.util.*; public class MyTagHandler extends SimpleTagSupport { */ g pageName; pu Tag() throws JspException { CourseDAO courseDAO = new CourseDAO(); ourseList = courseDAO.retrieveCourseList(pageName); course outline in tabular form, this method is// used – define below display(courseList); /** * Sette */ public void setPageName(java.lang.String value) {this.pageName = value; } /** * display method used to print courseoutline in tabular form */ ist courseList)throws JspException{ Page JspW t of displaying course outline in tabular format. package vutag; / /** * Declaration of pageName property. private Strin blic void do ArrayList c // to display } r for the pageName attri bute. private void display(ArrayL Context pc = (PageContext)getJspContext(); riter out = pc.getOut(); ry{
  • 389.
    Web Design Development – CS506 VU © Copyright Virtual University of Pakistan 389 // displaying table headers ou ou out.print(TH Session No /TH); out.print(TH Topic /TH); TH Assignment /TH); /TR); t for (int i=0; icourseList.size(); i++){ CourseOutlineBean courseBean = (CourseOutlineBean)courseList.get(i); // displaying one row out.print(TR); out.print(TD + courseBean.getSessionNo() + /TD); out.print(TD + courseBean.getTopic() + /TD); out.print(TD + courseBean.getAssignment() + /TD); out.print(/TR); } out.print(/TABLE); }catch(java.io.IOException ex){throw new :xsi=http://www.w3.org/2001/XM LSchema-instancexsi:schemaLocation=http://java.sun.com/xml/ns/j2ee web-jsptaglibrary_ 2_0.xsd tlib-version1.0/tlib-version short-namemytaglibrary/short-name !—the value of uri will be used in JSP to refer to this tld -- uri/WEB-INF/tlds/mytaglibrary/uri !— Specifying the tag name and tag class. Also mentioning thatthis tag has no body -- tag namecoursetag/name tag-classvutag.MyTagHandler/tag-class body-contentempty/body-content t.print(TABLE BORDER=1 ); t.print(TR); out.print( out.print( // loop to iterate over courseLis JspException(ex.getMessage());}} } // end clas MyTagHandler.java ?xml version=1.0 encoding=UTF-8? taglib version=2.0 xmlns=http://java.sun.com/xml/ns/j2eexmlns
  • 390.
    Web Design Development – CS506 VU © Copyright Virtual University of Pakistan 390 !— Specifying the attribute name and its type ribute na epageName/name java.lang.String/type /tag This course options to the user in the radio button form. html ou want to visit/h2 myForm action=controller.jsp h3 input type=radio name = page value=web/Web Design Develoment /h3 r name = page value=java/Java submit value=Submit / /form /html -- att m type /attribute /taglib index.jsp page is used to display the body h2Select the page yform name= b h3 input type=radio /h3 br input type= /body
  • 391.
    Web Design Development – CS506 VU © Copyright Virtual University of Pakistan 391 controller.jsp Based upon the selection made by the user, this page will redirect the user to respective pages. Those are web.jspand java.jsp html body % String pageName = request.getParameter(page); if (pageName.equals(web)) { response.sendRedirect(web.jsp); response.sendRedirect(java.jsp);}% %-- using taglib directive, specifying the tld file and prefix --% %@taglib uri=/WEB-INF/tlds/mytaglibrary.tld prefix=mytag% html center h2 Welcome to Java Learning Center /h2h3 Course Outline/h3 --% rsetag pageName=java / /center !-- scriptlet -- } else if (pageName.equals(java) ) { /body /html java.jsp body %--calling coursetag and specifying java as attribute value mytag:cou /body /html
  • 392.
    Web Design Development – CS506 VU © Copyright Virtual University of Pakistan 392 web.jsp %@taglib uri=/WEB-INF/tlds/mytaglibrary.tld prefix=mytag% elcome to Java Learning Center /h2h3 Course Outline/h3 ute value ag pageName=java / /center urse by Umair Javed. and JavaServer Pages by Marty Hall %-- using taglib directive, specifying the tld file and prefix --% html body center h2 W%--calling coursetag and specifying java as attrib --% mytag:courset /body /html References • Java A Lab Co• Core Servlets
  • 393.
    Web Design Development – CS506 VU © Copyright Virtual University of Pakistan 393 Lesson 39 e Study Ps in detail. Now, the time has come to learn e sake of web development. These architectures e components best fit in. In this handout, we’ll cover the most widely View Controller (MVC). also part of this handout that is based on MVC Model 1. Before oving on to MVC, let’s see what error pages are and how they are used? ages enables you to customize error messages. You can even hide them from the user's view makes possible to maintain a consistent look and feel throughout an application, even when those dreaded error messages are thrown. By means of page directive, a JSP can be given the responsibility of an Error page. An Error JSP is called by This exception is passed as an instance of r JSP (also accessible via implicit exception object). Defining and Using Error Pages • isErrorPage attribute of a page directive is used to declare a JSP as an error page. • JSP pages are informed about the error page by setting errorPage attribute of page directive In the figure below, error.jsp is defined as JSP Error page and index.jsp is informed to call error.jsp if any uncaught exception rose. This is done by setting attributes errorPage and isErrorPage of the page index.jsp error.jsp MVC + Cas We have covered an adequate amount of Servlets and JSdifferent architectures that are most commonly used for th also help us to understand where thesused/popular architecture i.e. Model A small case study “Address Book” ism Error Page Error P entirely, if you want. This also the web server when an uncaught exception gets occurred. java.lang.Throwable to Erro directive on these JSPs.
  • 394.
    Web Design Development – CS506 VU © Copyright Virtual University of Pakistan 394 Case Study – Address Book What we have learned is going to be implemented in this Address Book example. Here MS-Access is being sed as DBMS. This database will have only one table, Person with following attributes u Ingredients of Address Book rver Pages and Error Page that are being used in this Address Book example are: - . Java B . Perso Has following attributes: – n – address – phoneNum . Pers – En database logic. – The nfo data. . Java Server P . addperso – Used to collect new person info that will be saved in database. . saveper – Re n info from addperson.jsp – Saves it to database . searchperson.jsp oviding name Java B eans, Java Seeans nInfo– ame onDAO capsulates refore, it will be used to save and retrieve PersonI ages n.jsp son.jsp ceives perso – Used to provide search criteria to search Person’s info by pr
  • 395.
    Web Design Development – CS506 VU © Copyright Virtual University of Pakistan 395 . showpe – This page receive person’s name from searchperson.jsp to search in database – Retriev son record found against person name Error Page . the type of exception. ition to that, it also displays the message associated with the received exception to the user. P w N scuss the flow of program. Assume that the system has been deployed on a JSP compatible Web Server ke Tomcat and has been ready to use for clients. The following figure helps to understand the program flow of this small example. rson.jsp es and displays per addbookerror.jsp – This p– In add age is declared as an error page and used to identify rogram Flo ow let’s di li addperson.jsp takes person’s information from the user and sends it to saveperson.jsp. After receiving request, saveperson.jsp makes an object of PersonInfo using received information and saves it into the database using PersonDAOJava bean. Similarly, searchperson.jsp takes search criteria (name) from the user and passes it to showperson.jsp that searches the record in database using PersonDAO and shows the results to the user. If any uncaught exception is generated on these JSP, addbookerror.jsp is called implicitly, which displays an appropriate message to the user after identifying the exception type.
  • 396.
    Web Design Development – CS506 VU © Copyright Virtual University of Pakistan 396 Code for the Case Study PersonInfo represents the record of one person and its objects are used to interrupt the information about persons. package vu; port java.io.*; ublic class PersonInfo implements Serializable{ private String name; private String address; private int phoneNum; phoneNum = 0; setters public void setName(String n){ public void setAddress(String a){ } public void setPhoneNum(int pNo){ phoneNum = pNo; } // getters public String getName( ){ return name; Let’s have a look on the code of each component used in the case study; first start from JavaBeans. PersonInfo im p // no argument constructor public PersonInfo() { name = ; address = ; } // name = n; } address = a; } public String getAddress( ){ return address;
  • 397.
    Web Design Development – CS506 VU © Copyright Virtual University of Pakistan 397 } public int getPhoneNum( ){ return phoneNum; } // end class PersonInfo Pers This elp in retrieving and storing person’s records in database. The code is given below: packa im *; import jav public class PersonDAO{ private Connection con; public PersonDAO() throws ClassNotFoundException , SQLException { establishConnection(); } // method used to establish connection with db private void establishConnection() throws ClassNotFoundException , SQLException { // establishing conection Class.forName(sun.jdbc.odbc.JdbcOdbcDriver); String conUrl = jdbc:odbc:PersonDSN; con = DriverManager.getConnection(conUrl); } onDAO class will h ge vu; port java.util. a.sql.*; // default constructor
  • 398.
    Web Design Development – CS506 VU © Copyright Virtual University of Pakistan 398 } // used to search the person records against name and returns ly those PersonInfo objects // which matches the search criteria i.e. name publi trievePersonList(String Name) throws SQLException { ArrayLis ); // preparing query String PreparedStatement pStmt = con.prepareStatement(sql); pStmt.setS // executing quer ResultSet rs = pStm y(); String name; String add; int pNo; while ( rs.next() ) { name = rs.getStrin add = rs.getS ); pNo = rs.getI ber); // creating a CourseOutlineBean object PersonI nBean = new PersonInfo(); person me(nam personBean.setAddress(add); pe (pNo); // adding a bean to arraylist personList.add(personBean); } // end while return personList; // the ArrayList that contains on c ArrayList ret personList = new ArrayList( sql = SELECT * FROM Person WHERE name = ?; tring( 1, pName); y t.executeQuer g(name) tring(address nt(phoneNum ; nfo perso Bean.setNa e); rsonBean.setPhoneNum
  • 399.
    Web Design Development – CS506 VU © Copyright Virtual University of Pakistan 399 } // end retrievePersonList PreparedStatement pStmt = con.prepareStatement(sql); String name = person.getName(); String add = person.getAddress(); o = person.getPhoneNum(); pStmt.setString( 1 , name ); iding finalize method to release acquired resources try{ if(con ! con.close(); } }catch( System.ou } } // end finalize } // end PersonDAO class // this method accepts an object of PersonInfo, and stores it into // the database public void addPerson(PersonInfo person) throws SQLException{ String sql = INSERT INTO Person VALUES (?, ?, ?); int pN pStmt.setString( 2 , add ); pStmt.setInt( 3 , pNo ); pStmt.executeUpdate(); } // end addPerson // overr public void finalize( ) { = null){ SQtion sqlex){ LExcept.println(sqlex);
  • 400.
    Web Design Development – CS506 VU © Copyright Virtual University of Pakistan 400 Now let’s t pages addperson. This SP the user. It contains three Input ields for name, address and phone number as shown in the diagram. This page sends this information to p for further processing, ake a look at the code for JSP jsp J page gets person record’s information from Fsaveperson.js The code that is used to generate the above page is given below: %-- Although there are no chances of exception to arise on this page, for consistency, error page is defined on top of all JSPs --% %@page errorPage=addbookerror.jsp % html body center h2 Address Book /h2 h3 Add New Person/h3 %-- Form that contains Text input fields and sending it to saveperson.jsp --% form name =register action=saveperson.jsp /
  • 401.
    Web Design Development – CS506 VU © Copyright Virtual University of Pakistan 401 TABLE BORDER=1 TR input type=text name=name / /TR /h4 /TD TD input type=tex name=address / /TD TR TD h4Phone Number/h4 /TD TD input type=text name=phoneNum / /TD /TR TR TD COLSPAN=2 ALIGN=CENTER input type=submit value=save /input type=reset value=clear / /TD /TR LE h4 %-- A a href hperson.jsp Search Person /a /h4 /center /body /html TD h4 Name /h4 /TD TD /TD TR TD h4 Adt dress /TR /TAB/form link to searchperson.jsp --% =searc
  • 402.
    Web Design Development – CS506 VU © Copyright Virtual University of Pakistan 402 saveperso This JSP p ata from the addperson.jsp, makes an object of PersonInfo and saves it to the database using PersonDA also disp ys an informative message to the user if new person record is saved hyperlinks to navigate on to the desired pages as shown in the following diagram: The code e is given below: error page --% errorPage=addbookerror.jsp % %@ page import=java.sql.* % body %-- creating PersonDAO object and storing in page scope --% jsp:useBean id=pDAO class=vu.PersonDAO scope=page / %-- creating PersonBean object and storing in page scope --% jsp:useBean id=personBean class=vu.PersonInfo scope = page / %-- setting all properties of personBean object with input parameters using * --% jsp:setProperty name=personBean property=* / %-- to save Person record into the database, calling addperson n.jsp age gets d O class. Apart from these, it lasuccessfully into the database and two of this pag %-- defining %@page html
  • 403.
    Web Design Development – CS506 VU © Copyright Virtual University of Pakistan 403 method of PersonDAO --% % pDAO.addPerson(personBean); % h4 a href=addperson.jsp Add Person /a a href=searchperson.jsp Search Person /a /h4 /center /html sea It g d sends it to showperson.jsp to display the search results. he outlook of the page is given below: center h3 New Person Record is saved successfully!/h3 /h4 h4 /body rchperson.jsp ets search criteria from the user (i.e. name) an T
  • 404.
    Web Design Development – CS506 VU © Copyright Virtual University of Pakistan 404 The code used to generate the above page given page is: %@page errorPage=addbookerror.jsp % center h2 Address Book /h2 h3 Search Person/h3 TABLE BORDER=1 h4 Name/h4 /TD TD input type=text name=name / /TD it value=search /input type=reset /TD /TR /TABLE /form h4 on.jsp Add Person /a /center/body /html %-- defining error page --% html body %-- Form that contains Text input field and sending it to showperson.jsp --% form name =search action=showperson.jsp / TR TD /TR TR TD COLSPAN=2 ALIGN=CENTER input type=subm value=clear / a href=addpers /h4
  • 405.
    Web Design Development – CS506 VU © Copyright Virtual University of Pakistan 405 showperson.jsp showperson.jsp receives search criteria on.jsp, that is entered by the user to find the matching record. This page retrieves the complete list of matching records from the database using t, when person named “saad” is searched. (i.e. name) from the searchpers PersonDAO, and shows them to the user. This following figure gives you the sigh Below, the code of showperson.jsp is given: %@page errorPage=addbookerror.jsp % vu.* % html body center h2 Address Book /h2 h3 Following results meet your search criteria/h3 TABLE BORDER=1 TH Name /TH %-- defining error page --% %-- importing required packages --% %@page import=java.util.* % %@page import= TR TH Address /TH TH PhoneNum /TH /TR
  • 406.
    Web Design Development – CS506 VU © Copyright Virtual University of Pakistan 406 DAO class=vu.PersonDAO scope=page / the Database using // retrievePersonList() method of PersonDAO rsonDAO.retrievePersonList(pName); PersonInfo person = null; % /TD TD %= person.getAddress()% /TD % } // end for % /TABLE a href=addperson.jsp Add Person /a a href=searchperson.jsp Search Person /a /center /body /html jsp:useBean id=p % // getting search criteria sent by searchperson.jsp String pName = request.getParameter(name); // retrieving matching records from ArrayList personList = pe // Showing all matching records by iterating over ArrayList for(int i=0; ipersonList.size(); i++) { person = (PersonInfo)personList.get(i); TR TD %= person.getName()% TD %= person.getPhoneNum()% /TD /TR
  • 407.
    Web Design Development – CS506 VU © Copyright Virtual University of Pakistan 407 addbookerror.jsp This JSP error page is called implicitly by all other JSP pages whenever any uncaught / unhandled exception ccurs. It also finds out the type of the exception that is generated, and shows an appropriate message to e user: %-- indicating that this is an error page --% % a %-- importing class --% html head titleError/title /head body h2 Error Page /h2 h3 %-- scriptlet to determine exception type --% % if (exception instanceof SQLException) { % An SQL Exception % } else if (exception instanceof ClassNotFoundException){ % } else { % %-- end scriptlet to determine exception type --% occured while interacting with the database oth @pge isErrorPage=true % %@page import = java.sql.SQLException % % A Class Not Found Exception A Exception % } // end if-else %
  • 408.
    Web Design Development – CS506 VU © Copyright Virtual University of Pakistan 408 /h3 The Error Message was %= exception.getMessage() % /h3 h ter! /h3 eturn back to addperson.jsp or searchperson.sjp --% a href=controller.jsp?action=addperson Add Person /a a href=controller.jsp?action=searchperson Search Person /a /h3 /body /html Model Now, more t plications need to support multiple types of users with multiple types of interfaces. Fo xample, an online store may require an HTML front for Web customers, a WML front for wireless customers, a JavaTM (JFC) / Swing interface for administrators, and an XML-based Web service for supplier h3 3 Please Try Again La%-- hyperlinks to r h3 View Controller (MVC) han ever, enterprise apr e s
  • 409.
    Web Design Development – CS506 VU © Copyright Virtual University of Pakistan 409 Also, several problems can arise when applications contain a mixture of data access code, business logic code, and presentation code. Such applications are difficult to maintain, because interdependencies between oupling makes classes difficult or impossible to reuse because they depend on so many other classes. Adding new ata views often requires re-implementing or cutting and pasting business logic code, which then requires n multiple places. Data access code suffers from the same problem, being cut and pasted among business logic methods. The Model-View-Controller architecture solves these problems by decoupling data access, business logic, and data presentation and user interaction. Such separation allows multiple views to share the same enterprise data model, which makes supporting multiple clients easier to implement, test, and maintain. Partici The in (model, view controller) is given below: The model represents the state of the component (i.e. its data and the methods required to manipulate it) in ed. View ers the contents of a model and specifies how that data should be presented. There can be multiple views for the same model within single applications or model may have different views in different applications or operating systems. . Controller The the model. In a web app HTTP requests. The actions performed by the model include activating business processes or changing the state of the model. Based on the user interactions and the outcome of the model actions, the controller responds by selecting an appropriate view. Evolution of MVC Architecture In the beginning, we used no MVC. Then we had MVC Model 1 and MVC Model 2 architectures. And peop uch as Apache Struts based on Model 2 archi ndard web based application framework i.e. JavaServer Faces (JSF). In this handout, we’ll only talk about MVC Model 1. all of the components cause strong ripple effects whenever a change is made anywhere. High c d maintenance i pants and Responsibilities dividual’s responsibility of three participants . Model dependent of how the component is viewed or render . The view rend controller translates interactions with the view into actions to be performed by lication, they appear as GET and POST le came up with so called web application frameworks s tecture. And finally we have a sta
  • 410.
    Web Design Development – CS506 VU © Copyright Virtual University of Pakistan 410 MVC A M ecture consists of a Web browser directly accessing Web-tier JSP pages. The JSP pages access JavaBeans that represent the application model. And the next view to di let, HTML page, and so on) is determined either by hyperlinks selected in the source document or by request parameters. Model 1 odel 1 archit splay (JSP page, serv In M is decentralized, because the current page being displayed deter age to display. In addition, each JSP page or servlet processes its own inputs (parameters from GET or POST). And this is hard to maintain, for example, if you have to change the view selection, then several JSP pages need to be changed. In some Model 1 architectures, choosing the next page riptlet code, but this usage is considered poor form. In MVC Model 1 architecture, the JSP page alone is responsible for processing the incoming request and rom content, because all data access is performed using JavaBeans. lthough the Model 1 architecture should be perfectly suitable for simple applications, it may not be cture usually leads to a significant nt of scriptlets or Java code embedded within the JSP page, especially if there is a significant amount f re em to be much of a problem for Java devel d maintained by designers which are only aware Note nking about the case study discussed earlier in this handout. Indee ecture. References: ƒ ƒ http://java.sun.com/blueprints/patterns/MVC-detailed.html odel 1 architecture, view selection mines the next p to display occurs in sc replying back to the client. There is still separation of presentation f A desirable for complex implementations. Random usage of this archite amouo quest processing to be performed. While this may not seopers, it is certainly an issue if your JSP pages are created an of HTML and some scripting language. : Probably some of you must be thid, it is based on MVC Model 1 archit Java A Lab Course by Umair Javed Java BluePrints - J2EE Patterns ƒ Exploring the MVC Design Pattern .html http://www.javaworld.com/javaworld/jw-12-1999/jw-12-ssj-jspmvc
  • 411.
    Web Design Development – CS506 VU © Copyright Virtual University of Pakistan 411 Lesson 40 MVC Model 2 Architecture ch and page-with-bean approach until now. You must be wondering n w ad covered these. Probably these buzz words are new one for you but we already covered these ics. L s review these once again. e-C that is collection of JSPs. Generally this approach is followed to get started with plications. This approach is represented in the following diagram: We have studied page-centric approa whee htopet’ Pagentric Approach A web applicationdeveloping web ap The page-centric approach has lot of draw backs such as the code becomes a mixture of presentation, e. Page-with-Bean Approach (MVC Model1) This approach is different from page-centric approach in a way that all the business logic goes into JavaBeans. Therefore, the web application is a collection of JSPs and JavaBeans. But still this approach is ogics. We have made an address book example in the last handout MVC Model 2 Architecture This architecture introduces a controller. This controller can be implemented using JSP or servlet. Introducing a controller gives the following advantages: ƒ It centralizes the logic for dispatching requests to the next view based on: -The Request URL business and data access logic. The maintenance and up-gradation of the application becomes a nightmarScaling of such kind of application is also difficult and lots of code is also get duplicated. insufficient to separate different kind of l using this approach.
  • 412.
    Web Design Development – CS506 VU © Copyright Virtual University of Pakistan 412 -Input Parameters -Application state ƒ It gives the single point of control to perform security checks and to record ƒ It also encaps a form that is usable by the back-end MVC model. We’ll discuss it with the help of an example. The following n that is built using MVC Mod logging information ulates the incoming data into figure will help you to understand the architecture and functioning of the applicatioel 2 architecture. The client (browser) sends all the requests to the ccharge of the request processing and creation oJSoas and there is notre ontroller. Servlet/JSP acts as the Controller and is in f any beans or objects (Models) used by the JSP. P is w rking View much processing logic within the JSP page itself, it is simply sponsible for retrieving objects and/or beans, created by the Servlet, extracting dynamic content from them and put them into the static templates. Case Study Address Bo k usin The address book example that is built using page-with-bean approach will be modified to incorporate controller. We’ to implement controller using JSP as well as with servlet. Let’s first incorporate controller : og MVC Model 2 ll show you how using JSP.
  • 413.
    Web Design Development – CS506 VU © Copyright Virtual University of Pakistan 413 Introducing a JSP as Controller r JSP (controller.jsp) that ƒ Acts as a controller ƒ Recieves requests form addperson.jsp searchperson.jsp ƒ Identifies the page which initiates the request ƒ Uses JavaBeans to save or search persons to/from database ƒ Forwards or redirects the request to appropriate (saveperson.jsp or showperson.jsp) page. The program flow of this example is shown in the following diagram: Add anothe As you can see in the diagram that all the requests are submitted to controller which uses the JavaBeans and forwards/redirects the user to another view (JSP)? If any exception arises on controller or JSPs, the control would automatically be transferred to addbookerror.jsp to display an appropriate message. How controller differentiates between requests? Most likely, you must be thinking about it. The simplest solution lies in using the consistent name (e.g. action) of the submit button across all the pages but with different and unique values. The same rule applies to hyperlinks that send the action parameter along with value by using query string technique. This eases the controller’s job to identify which page is actually generated the request and what to do next. The controller simply retrieves the value of action parameter using request.getParameter() method. Now, if-else structure can be used to compare the possible values of action to act upon the requested task. Now, let’s first see the code of JavaBean that is used in this example.
  • 414.
    Web Design Development – CS506 VU © Copyright Virtual University of Pakistan 414 PersonInfo This JavaBean is used to represent one person record. The code is given below: package vu; import java.io.*; public class PersonInfo implements Serializable{ private String name; private String address; private int phoneNum; // no argument constructor public PersonInfo() { name = ; address = ; phoneNum = 0; } // setters public void setName(String n){ public void setAddress(String a){ address = a; } setPhoneNum(int pNo){ eNum = pNo; // getters return address; } public int getPhoneNum( ){ retu } } // end class PersonInfo name = n; } public void phon } public String getName( ){ return name; } public String getAddress( ){ rn phoneNum;
  • 415.
    Web Design Development – CS506 VU © Copyright Virtual University of Pakistan 415 PersonDAO This class will help in retrieving and storing person’s records in database. The code is given below: package vu; import java.util.*; import java.sql.*; ublic class PersonDAO{ private Connection con; // default constructor public PersonDAO() throws ClassNotFoundException , SQLException { establishConnection(); } // method used to establish connection with db priv te throws ClassNotFoundException , SQLException { // establishing conection sun.jdbc.odbc.JdbcOdbcDriver); String con = tion(conUrl); } // used to search the person records against name and returns the ArrayList that contains only nfo objects which matches the search criteria i.e. name public ArrayList retrievePersonList(String pName) throws SQLException { ArrayList personList = new ArrayList(); // preparing query String sql = SELECT * FROM Person WHERE name = ?; PreparedStatement pStmt = con.prepareStatement(sql); pStmt.setString( 1, pName); // executing query ResultSet rs = pStmt.executeQuery(); p avoid establishConnection() Class.forName( conUrl = jdbc:odbc:PersonDSN; DriverManager.getConnec // those PersonI
  • 416.
    Web Design Development – CS506 VU © Copyright Virtual University of Pakistan 416 String name; String add; name = rs.getString(name); pNo = rs.getInt(phoneNumber); PersonInfo personBean = new PersonInfo(); personBean.setName(name); personBean.setAddress(add); personBean.setPhoneNum(pNo); // adding a bean to arraylist } // end while d retrievePersonList // this method accepts an object of PersonInfo, and stores it into // the database public void addPerson(PersonInfo person) throws SQLException{ ES (?, ?, ?); PreparedStatement pStmt = con.prepareStatement(sql); String name = person.getName(); Str int pNo = person.getPhoneNum(); pStmt.setString( 1 , name ); pSt pSt pSt } // end addPerson // overriding finalize method to release acquired resources int pNo; while ( rs.next() ) { add = rs.getString(address); // creating a CourseOutlineBean object personList.add(personBean); return personList; } // en String sql = INSERT INTO Person VALU ing add = person.getAddress(); mt.setString( 2 , add ); mt.setInt( 3 , pNo ); mt.executeUpdate();
  • 417.
    Web Design Development – CS506 VU © Copyright Virtual University of Pakistan 417 con.close(); }catch(SQLException sqlex){ System.out.println(sqlex); } } // e } // en addperson.jsp This page is u tabase. Note that a hyperlink is also given at the bott the page that takes the user to searchperson.jsp. Note: Since we are following MVC model 2 architecture, so all the hyperlinks will also sends the request to controller first which redirects the user to requested page. public void finalize( ) { try{ } nd finalize d PersonDAO class sed for entering a new person record into the daom of The code of above page is given below:
  • 418.
    Web Design Development – CS506 VU © Copyright Virtual University of Pakistan 418 %-- Although there are no chances of exception to arise on this page, for consistency, error page is defined on top of all JSPs %@page errorPage=addbookerror.jsp % html body center h3 Add New Person/h3 %-- As mentioned in MVC2, all the requests are submitted to controller, that’s why action’s ns the value of “controller.jsp” form name =register action=controller.jsp / TABLE BORDER=1 TR TD h4 Name /h4 /TD TD input type=text name=name / /TD /TR TR TD h4 Address /h4 /TD TD input type=text name=address / /TD TR TD h4Phone Number/h4 /TD TD input type=text name=phoneNum / /TD /TR TR TD COLSPAN=2 ALIGN=CENTER %-- As described above the technique to differentiate between the requests, “save”. --% input type=submit name =action value=save / input type=reset value=clear / /TD /TR --% h2 Address Book /h2 contai --% /TR the name of the button is “action” with value
  • 419.
    Web Design Development – CS506 VU © Copyright Virtual University of Pakistan 419 /TABLE /form h4 %- The hyperlink will also sends the request to controller Note the action parameter with its value are also part of hyperlink using the query string technique. --% a href=controller.jsp?action=searchperson Search Person /a /h4 /body /html /center
  • 420.
    Web Design Development – CS506 VU © Copyright Virtual University of Pakistan 420 searchperson.jsp This JSP is used to sear n at the bottom of add ch the person record against name given in the text field. A hyperlink is also given.jsp. perso The code that is used to generate that above page is given below: %-- defining error page --% %@page errorPage=addbookerror.jsp % html body center h2 Address Book /h2 h3 Search Person/h3 form name =search action=controller.jsp / TABLE BORDER=1 TR TD h4 Name /h4 /TD TD input type=text name=name / /TD /TR TR TD COLSPAN=2 ALIGN=CENTER
  • 421.
    Web Design Development – CS506 VU © Copyright Virtual University of Pakistan 421 %- The name of the button is still “action” but with different value “search”. tion value=search / input type=reset value=clear / /TR /TABLE /form h4 %- The action parameter with different value “addperson” are part of hyperlink here as --% Add Person /a /center /body /html --% input type=submit name =ac /TD well. a href=controller.jsp?action=addperson/h4
  • 422.
    Web Design Development – CS506 VU © Copyright Virtual University of Pakistan 422 controller.jsp As mentio that controller.jsp identifies the page which initiates the request and use JavaBeans to save/searc to/from database. Also its job list includes redirecting the user to appropriate page. Since this JSP is available. Let’s check it out its code: %-- defining error page --% %@page errorPage=addbookerror.jsp % %-- impor avaBeans --% %@page import =java.util.* % %@page import = html body %-- declaring PersonDAO object--% jsp:useBean id=pDAO class=vu.PersonDAO scope=page / %- scriptlet to identify JSP for redirection purpose if request comes from hyperlinks % // Remember that “action” is the name of buttons as well // it is used in hyperlinks in making of query string String action = request.getParameter(action); // if Add Person hyperlink is clicked if (action.equals(addperson) ){ response.sendRedirect(addperson.jsp); // if Search Person hyperlink is clicked } else if (action.equals(searchperson)){ response.sendRedirect(searchperson.jsp); // if save button is clicked of addperson.jsp }else if (action.equals(save)) { % ned earlier h persons doing only processing therefore no view ting required packages. package vu contains J vu.* % --% // retrieving action parameter value
  • 423.
    Web Design Development – CS506 VU © Copyright Virtual University of Pakistan 423 // declaring PersonInfo obeject jsp:useBean id=personBean class=vu.PersonInfo scope=page/ %-- --% jsp:setProperty name=personBean property=* / %-- to insert record into database--% ean); // redirecting user to saveperson.jsp response.sendRedirect(saveperson.jsp); %-- if search button is clicked on searchperson.jsp --% % // storing personList(contains PersonInfo objects) into // request hashmap List); % - forwarding request to showperson.jsp to retrievestored arraylist (“list”) person.jsp / % ch % /body /html setting all properties of personBean object with input parameters using * % pDAO.addPerson(personB % }else if (action.equals(search) ) { String pName = request.getParameter(name); ArrayList personList = pDAO.retrievePersonList(pName); request.setAttribute(list, person %- --% jsp:forward page=show } // end if page == sear
  • 424.
    Web Design Development – CS506 VU saveperson.jsp This page displays a successful message indicating that person record is saved. Its also give the options to the user to move on to addperson.jsp or searchperson.jsp through hyperlinks. Note that these hyperlinks also first take the user to controller.jsp then on to requested page. The code of saveperson.jspis given below: %-- defining error page --% %@page errorPage=addbookerror.jsp % body center sfully!/h3 a href=controller.jsp?action=addperson Add Person /a /h4 hperson Search /center /body /html html h3 New Person Record is saved succes h4 /h4 a href=controller.jsp?action=searc Person /a /h4 © Copyright Virtual University of Pakistan 424
  • 425.
    Web Design Development – CS506 VU © Copyright Virtual University of Pakistan 425 showperson.jsp aad” is searched. T his following figure gives you the view when name “s Below, the code of showperson.jsp is given: ng error page --% %@page errorPage=addbookerror.jsp % %-- importing required packages --% %@ %@page impo html body center h3 Following results meet your search criteria/h3 TR TH Name /TH /TR on controller.jsp to display PersonInfo objects %-- defini page import=java.util.* % rt=vu.* % h2 Address Book /h2 TABLE BORDER=1 TH Address /TH TH PhoneNum /TH % // retrieving arraylist stored
  • 426.
    Web Design Development – CS506 VU © Copyright Virtual University of Pakistan 426 ArrayList personList = (ArrayList)request.getAttribute(list); PersonInfo person = null; { %-- displaying PersonInfo details--% TR TD %= person.getName()% /TD TD %= /TD TD %= person.getPhoneNum()% /TR % } // end for h4 a href=controller.jsp?action=addperson Add Person /a a href=controller.jsp?action=searchpersonSearch Person/a /h4 /c enter /body /h for(int i=0; ipersonList.size(); i++) person = (PersonInfo)personList.get(i); % person.getAddress()% /TD % /TABLE tml
  • 427.
    Web Design Development – CS506 VU © Copyright Virtual University of Pakistan 427 addbookerror.jsp User will view this page only when any sort of exception is generated. The code of this page is given below: %-- indicating that this is an error page --% %@ %-- im %@page import = java.sql.SQLException % html head titleError/titl body h2 h3 %-- scriptlet to determine exception type --% % if (exception instanceof SQLException) { L Exception % } else if (exception instanceof ClassNotFoundException){ % A Class Not Found Exception % } else { % A Exception %-- end scriptlet to determine exception type --% page isErrorPage=true % porting class --% e /head Error Page /h2 % An SQ % } // end if-else %
  • 428.
    Web Design Development – CS506 VU © Copyright Virtual University of Pakistan 428 occured while interacting with the database /h3 h3 The Error Message was %= exception.getMessage() % /h3 %-- hyperlinks to return back to adperson.jsp orsearchperson.sjp --% h3 a href=controller.jsp?action=addperso n Add Person /a a href=controller.jsp?action=searchperso n Search Person /a /h3 /body /html JSP is the Right Choice as a Controller? Since JSP that is performing the job of controller is doing only processing and there is no view available of it. It includes the logic of selecting JSP and to retrieve/store records from/to dataset using JavaBeans. But remember the reason for introducing JSPs? JavaServer Pages are built for presentation (view) only so JSP is really not a good place for such kind of logic. Concluding, what’s the option we have? The answer is, use Servlets as controller. Introducing a Servlet as Controller Remove the controller.jsp from the previous example code and add ControllerServlet.java (a servlet) into this example. This ControllerServlet.java performs the same job that was previously performed by controller.jsp. Besides adding ControllerServlet.java, you have to modify all the addresses which are previously pointing to controller.jsp. For example the value of action attribute of form tag the address of hyperlink in all /h3 h3 Please Try Again Later!
  • 429.
    Web Design Development – CS506 VU © Copyright Virtual University of Pakistan 429 concerned pages. If controller is defined in web.xml as an alias of ControllerServlet.java, consider the following fragment of code which shows the value of action attribute of form tag before and after introducing change. form name =register action=controller / When controller.jsp is acting as a controller Search Person /a When ControllerServlet.java is acting as a controller a href=controller?action=searchperson Search Person /a For example, the following code snippet is taken from ControllerServlet.java to demonstrate how to pass SQLExceptionto addbookerror.jsp … ……………… }catch (SQLException sqlex){ // setting SQLException instance request.getRequestDispatcher(addbookerror.jsp); rd.forward(request, response); } // end catch When controller.jsp is acting as a controller form name =register action=controller.jsp / When ControllerServlet.java is acting as a controller then value of action attribute becomes: Similarly, the following comparison shows the code of hyperlinks used in the previous example before and after making changes a href=controller.jsp?action=searchperson Passing Exceptions to an Error JSP from a Servlet Servlet can use existing error pages (like addbookerror.jsp) to pass on the exceptions. Set the request attribute to javax.servlet.jsp.JspExcpetion with the exception object you want to pass. After that forwards the request to error page. …………… request.setAttribute(javax.servlet.jsp.JspException , sqlex); RequestDispatcher rd =
  • 430.
    Web Design Development – CS506 VU C © Copyright Virtual University of Pakistan 430 otrollerServlet.java The following code is of servlet that is acting as a controller ackage controller; import vu.*; import java.io.*;import java.net.*; extends HttpServlet { // This method only calls processRequest() protected void doGet(HttpServletRequest request, HttpServletResponse response) throws xception { processRequest(request, response); } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { } equest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // retrieving value of action parameter String userAction = request.getParameter(action); // if request comes to move to addperson.jsp from hyperlink if (userAction.equals(addperson) ) { response.sendRedirect(addperson.jsp); // if request comes to move to searchperson.jsp from hyperlink } else if (userAction.equals(searchperson)) { response.sendRedirect(searchperson.jsp); p import java.sql.*; import java.util.*; import javax.servlet.*; import javax.servlet.http.*; public class ControllerServlet ServletException, IOE // This method only calls processRequest() processRequest(request, response); protected void processR
  • 431.
    Web Design Development – CS506 VU // if “save” button clicked on addperson.jsp to add new record } if (userAction.equals(save)) { // this method defined below addPerson(request,response); // if “search” button clicked on searchperson.jsp for search searchPerson(request,response); } // end processRequest() // if request comes to add/save person private void addPerson(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { try { // creating P PersonDAO w PersonDAO(); // creating PersonInfo object PersonInfo person = new PersonInfo(); // setting properties of Person object // setting name property String pName = request.getParameter(name); person.setName(pName); ess(add); // setting phoneNumb property String pNo = request.getParameter(phoneNum); on(person); // redirecting page to saveperson.jsp response.sendRedirect(saveperson.jsp); } else if (userAction.equals(search)) { // this method defined below } ersonDAO object pDAO = ne // setting address propertyt String add = request.getParameter(address); person.setAddr int phoneNum = Integer.parseInt(pNo); person.setPhoneNum(phoneNum); // calling PersonDAO method to save data into database pDAO.addPers © Copyright Virtual University of Pakistan 431
  • 432.
    Web Design Development – CS506 VU © Copyright Virtual University of Pakistan 432 }catch (SQLException sqlex){ request.setAttribute(javax.servlet.jsp.JspException , sqlex); RequestDispatcher rd = request.getRequestDispatcher(addbookerror.jsp); catch (ClassNotFoundException cnfe){ // setting ClassNotFoundException instance request.setAttribute(javax.servlet.jsp.JspException , cnfe); RequestDispatcher rd = request.getRequestDispatcher(add bookerror.jsp); rd.forward(request, response); } }// end addperson() // if request comes to search person record from database private void searchPerson(HttpServletRequest request, tion, IOException { try { String pName = request.getParameter(name); // calling DAO method to retrieve personlist from database // against name ArrayList personList = pDAO.retrievePersonList(pName); request.setAttribute(list, personList); // setting SQLException instance rd.forward(request, response); } HttpServletResponse response) throws ServletExcep // creating PersonDAO object PersonDAO pDAO = new PersonDAO();
  • 433.
    Web Design Development – CS506 VU © Copyright Virtual University of Pakistan 433 // forwarding request to showpeson, so it can render personlist RequestDispatcher rd = request.getRequestDispatcher(showperson.jsp); rd.forward(request, response); request.setAttribute(javax.servlet.jsp.JspException , sqlex); RequestDispatcher rd = request.getRequestDispatcher(add bookerror.jsp); rd.forward(request, response); ClassNotFoundException instance request.setAttribute(javax.servlet.jsp.JspException , cnfe); RequestDispatcher rd = request.getRequestDispatcher(addbookerror.jsp); rd.forward(request, response); }// end searchPerson() } // end ControllerServlet web.xml As you already familiar, for accessing a servlet, you need to define a URL pattern in web.xml. This is shown below: ?xml version=1.0 encoding=UTF-8? web-app servlet servlet-name ControllerServlet /servlet-name servlet-class controller.ControllerServlet /servlet-class /servlet }catch (SQLException sqlex){ // setting SQLException instance }catch (ClassNotFoundException cnfe){ // setting }
  • 434.
    Web Design Development – CS506 VU © Copyright Virtual University of Pakistan 434 servlet-mapping servlet-name ControllerServlet /servlet-name /controller /url-pattern /servlet-mapping References: urse by Umair Javed. . Java E-commerce course at Stanford url-pattern /web-app . Java A Lab Co
  • 435.
    Web Design Development – CS506 VU Lesson 41 Layers and Tiers How do you structure an application to support such operational requirements as maintainability, reusability, scalability and robustness? The answer lies in using Layers and Tiers? What different technologies Java provides to support layered or tiered architectures. The answer to these questions will remain our focus in this handout. A small case study will also be used to comprehend the concept of layers. Layers are merely logical grouping of the software components that make up the application or service, whereas Tiers refer to the physical residence of those layers. In general, . Layers – represents the logical view of application . Tiers – represents physical view of application However, both terms are used intractably very often. You must be confused what does logical physical view mean? Let’s elaborate layers and tiers further in detail to differentiate between them. Layers The partitioning of a system into layers such that each layer performs a specific type of functionality and communicates with the layer that adjoin it. The separation of concerns minimizes the impact of adding services/features to an application. The application developed in layers also enables tiered distribution (discussed later). Furthermore easier maintenance, reuse of code, high cohesion loose coupling sort of additional benefits are also enjoyed by the use of tiered architecture. To begin with, layered architecture based on three layers. These are ƒ Presentation Layer ƒ Business Layer ƒ Data Layer Note: However, there is no upper limit of number of layers an application can have. Each layer can also be further break down into several layers depending upon the requirement and size of the application. Layers vs. Tiers © Copyright Virtual University of Pakistan 435
  • 436.
    Web Design Development – CS506 VU The figure given below shows a simplified view of an application and its layers. As you can see in the figure, users can only interact with the presentation layer. The presentation layer passe he user request to the business layer, which further passes the request to the data layer. The data layer com ces (like Database etc.) or other external services in order to accomplish Let’s discu nsibility in detail: Presentation Layer It prov nt/user to interact with the application. This is the only part of the application visible to client. Its job lis input, validating user’s input (on client side using JavaScript like technologies OR on server side), presenting the results of the request made by the user and controlling the screen flow (which page/view will be visible to the user). Business La Also called application layer, it is only concerned with the application specific functionality. It is used to implement business rules and to perform business tasks. For example, in a banking system, this layer will provide the functionality of banking functions such as opening an account, transferring of balance from one account to another, Calculation of taxes etc. s tmunicates with the data sour the user request. ss each layer’s respo ides a user interface to the clie t includes collecting user’s yer © Copyright Virtual University of Pakistan 436
  • 437.
    Web Design Development – CS506 VU © Copyright Virtual University of Pakistan 437 Data Layer is concerned with the management of the data data sources of the system. Data sources can be database, XML, web services, flat file etc. Encapsulates data retrieval storage logic For example, the address book application needs to retrieve all person records from a database to display them to the user. Tiers As mentioned, layers help in building a tiered architecture. Like layers, there is no restriction on using er of tiers. An application can be based on Single-tier, Two-tier, Three-tier or N-Tier (application hich have more than three tiers). The choice of using a tiered architecture is contingent to the business requirements and the size of the application etc. Tiers are physically separated from each other. Layers are spread across tiers to build up an application. Two or more layers can reside on one tier. The following figure presents a three-tier architectural view of an application. The client tier represents the client machine where actually web browser is running and usually displays HTML. You can think of a Presentation as of two parts; one is on client side, for example, HTML. There is lso a presentation layer that is used to generate the client presentation often called server presentation. We’ll discuss about it later. The server machine can consist on a single server machine or more. Therefore, it is possible web server is running on one server machine while application server on another. Web server is used to execute web pages The client tier represents the client mThe database server is often running on a separate tier, i.e. DB machine often called Enterprise information tier. It numbw Presentation Layer EIS Layer a like JSPs whereas application server is used to run special business objects like Enterprise JavaBeans (discussed later). The web layer and applications server can be on two separate machines or they can be on same tier as shown in the diagram
  • 438.
    Web Design Development – CS506 VU © Copyright Virtual University of Pakistan 438 Layers Support in Java Th iding specific technology for each layer. This not only e nt by freeing the programmer for caring operational features but only reduces the production time of the software. In the foll on is bifurcated into two layers. These are Client Presentation layer and Server Presentation Layer. What client sees in a browser forms client presentation layer while server p s the Java technology components? (JSP and Servlets etc.) that are used to generate the client presentation. Layers Java/J2EE Technology e secret of wide spread use of Java lies in provases the developme owing figure, Presentati resentation layer include On business layer, JavaBeans (also referred as Plain Old Java Objects (POJO) ) can be used. While moving tow hitecture, the J2EE hat fits in business layer i.e. Enterprise Ja EJ sed to encapsulate business logic. They provide additional benefits in building up an application such as scalability, robustness, scalability etc. On data layer, Data Access Objects (DAO) can be used. Similarly you can use connectors. There are other different specialized components provided in java that ease the development of data layer. ards a bigger arcprovides the special class tvaBean (EJB). Bs are special java classes that are u
  • 439.
    Web Design Development – CS506 VU © Copyright Virtual University of Pakistan 439 J2EE Multi-Tiered Applications In a ing based application or a web based. As you can see in the following figure, clients can access the web server from behind the firewall as well. Supp web server. JSP at can be used in a web server. However, there are some Frameworks such as JSF etc that can be used in a web server. The classes which form the prese eb server and of course controllers are also used over here. typical J2EE Multi-Tiered application, a client can either be a sw ose, our client is HTML based. Client does some processing on HTML and transports it to and Servlets are possible technologies th ntation layer reside on w I wants to perform some business process, it usually gets help from some business layer components. The business layer component can be a simple JavaBean (POJO) but in a typical J2EE architecture, EJBs are used. Enterprise JavaBeans interacts with the database or information system to store and retrieve data. EJBs a ks in two different servers. As you already know, JSP and Servlets runs in a web s application server. But, generally application server contains the web server as well. Application server including web server generally resides on a single tier (machine), which is often called m retrieves data from the Enterprise Information Tier (EIS) which is a separate tier. The response sends back to the client by the middle tier can be HTML, XML etc. This response can be seen on the separate tier know as client tier. f web server, nd JSP/Servlets worerver where as EJBs requires an iddle tier. This tier stores and
  • 440.
    Web Design Development – CS506 VU © Copyright Virtual University of Pakistan 440 Case Study: Matrix Multiplication using Layers Proble as well as shown to the user. rmat . Inpu -inpu where 4,2 represents entries of the first row . Display format . Storage format for DB the order of the matrix -The following figure shows the table design that will be used to store the results. m Statement . Calculate product of two m atrices of order 2 * 2 . Result of multiplication should be stored in DB Fo t format t will be in 4,2,6,5 format separated by commas -Displays the matrix as a square -Matrix will be stored as a string in the database along with Layer by Layer View A picture’s worth than thousand words. Therefore, before jumping on to code, let’s put a glance over layers that tionality irst, loo the whole story. will be used in this small case study. The classes that will be used on each layer and what func each class will perform will also be discussed. Fk on the following picture that will describe
  • 441.
    Web Design Development – CS506 VU The data layer has a class MatrixDAO that is used to save the matrix result into database. As mentioned in MatrixDAO called by the MatrixMultiplier, a business layer class. The functionality list of MatrixMultiplier ƒ Converting the user input string (e.g.2, 3, 4, 1) into a proper object i.e. a matrix ƒ Helps in g product of two matrices Controller layer’s class ControllerServlet calls the MatrixMultiplier. This layer calls the various business methods (like multiplication of two matrices) of business layer class and got the resultant matrix. Furthe nds the ou from ri atrixBean representing matrix data structure, as you can see in the figure is used across several layers. act, t o o irst, loo the problem statement, that resultant matrix should be saved in the database. So, MatrixDAOis used toaccomplish that. includes: ƒ data structure. calculatin rmore, ControllerServlet setput to the matrixresult.jsp and receives the input xin matput.jsp. The M In fhe object formed by MatrixMultiplier from a user input string is f MatrixBean type. It is used ttransfer data from one layer to another. Fk on the MatrixBean code given below: © Copyright Virtual University of Pakistan 441
  • 442.
    Web Design Development – CS506 VU © Copyright Virtual University of Pakistan 442 MatrixBean package bo; import java.io.*; public class MatrixBean implements Serializable{ // a 2D array representing matrix public int matrix[ // construc matrix = new int[2][2]; matrix[0][1] = 0; matrix[1][0] = 0; matrix[1][1] = 0; } // setter tha to array public void t y, int z) { matrix[1][0] = y; matrix[1][1] = z; } turning a 2D array { return m } rt 2D array into string toString(){ return matrix[0][0] + , + , + matrix[1][0] + , +matrix[1][1] ; } } // end MatrixBean ][ ] ; tor public MatrixBean() { matrix[0][0] = 0; t takes 4 int values and assigns these setMatrix(int w, int x, in matrix[0][0] = w; matrix[0][1] = x; // getter re public int[ ][ ] getMatrix() atrix; // used to conve public String matrix[0][1] +
  • 443.
    Web Design Development – CS506 VU matrixinput.jsp T of string such as 2,3,5,8. The data will be s this page. /h2 h3 %-- “controller” is an alias/URL pattern of ControllerServlet -% for ller First Matrix: input type=text name = firstMatrix / E.g. 2,3,4,1 br/ Matrix / br/ input type = submit value = Calculate Product / /form /h3 /body /html ControllerServlet This servlet acting as a controller receives the input from matrixinput.jsp. Furthermore, it will interact with the business layer class MatrixMultiplier to convert the string into a MatrixBean object, and to multiply two matrices. his JSP is used to collect the input for two matrices in the form ubmitted to ControllerServlet from html body h2 Enter Two Matrices of order 2 * 2 to compute Product m name=matrixInput action=contro Second Matrix: input type=text name = second © Copyright Virtual University of Pakistan 443
  • 444.
    Web Design Development – CS506 VU package © Copyright Virtual University of Pakistan 444 controller; import bl.*; import bo.* ; o.*; import java.net.*; import javax.servlet.*; import javax.servlet.http.*; ontrollerServlet extends HttpServlet { nly calls processRequest() prote HttpServletResponse response) throws OException { processRequest(request, response); } // This method only calls processRequest() prote tRequest request, HttpServletResponse response) throws ServletException, IOException { processRequest(request, response); } protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // retrieving values from input fields of matrixinput.jsp String sMatrix1 = req.getParameter(firstMatrix); String sMatrix2 = req.getParameter(secondMatrix); // Creating MatrixMultipler object MatrixMultiplier mm = new MatrixMultiplier(); // Passing Strings to convertToObject() method of MatrixMultiplier // convertToObject() is used to convert strings into MatrixBean import java.i public class C // This method octed void doGet(HttpServletRequest request, ServletException, I cted void doPost(HttpServle
  • 445.
    Web Design Development – CS506 VU © Copyright Virtual University of Pakistan 445 MatrixBean fMatrix = mm.convertToObject(sMatrix1); MatrixBean sMatrix = mm.convertToObject(sMatrix2); // passing MatrixBean’s objects to multiply() method of // MatrixMultiplier and receiving the product matrix in the form // of MatrixBean MatrixBean rMatrix = mm.multiply(fMatrix, sMatrix); // saving results in database mm.saveResult(rMatrix); // storing the product of matrices into request, so that it can be // retrieved on matrixresult.jsp req.setAttribute(product, rMatrix); // forwarding request to matrixresult.jsp RequestDispatcher rd = req.getRequestDispatcher(matrixresult.jsp); rd.forward(req, res); } // end processRequest() } // end ControllerServlet MatrixMultiplier The business layer class that’s primary job is to calculate product of tow matrices given in the form of MatrixBean. This class also has a method convertToObject that takes a String and returns back a MatrixBean object. MatrixMultiplier will also interact with the data layer class MatrixDAOto store results in the database. package bl; import bo.*; import dal.*; public class MatrixMultiplier { //constructor public MatrixMultiplier( ) { } // used to convert a String (like 2,3,4,5) into a MatrixBean object public MatrixBean convertToObject(String sMatrix){
  • 446.
    Web Design Development – CS506 VU © Copyright Virtual University of Pakistan 446 //splitting received string into tokens by passing “,” as delimeter String tokens[] = sMatrix.split(,); //creating MatrixBean object MatrixBean matrixBO = new MatrixBean( // converting tokens into integers int w = Integer.parseInt(tokens[0]); int x = Integer.parseInt(tokens[1]); int y = Integer.parseInt(tokens[2]); int z = Integer.parseInt(tokens[3]); matrixBO.setMatrix(w , x , y, z); return matrixBO; ixBean objects form of MatrixBean as well an sMatrix){ // creating MatrixBean object where product of the matrices will be tored MatrixBean resultMatrix = new MatrixBean(); // r eans object to // perform multipication trix(); trix(); ; // code to multiply two matrices for (int i=0; i2; i++) { ] += (matrixA[i][k] * matrixB[k][j]); } } // storing the product from 2d array to MatrixBean object by // calling setter ); // setting values into MatrixBean object by calling setter } // end convertToObject() // used to multiply two matrices , receives two Matr // and returns the product in the public MatrixBean multiply(MatrixBean fMatrix , MatrixBe retieving two dimensional arrays from MatrixB int matrixA[ ][ ] = fMatrix.getMaintmatrixB[ ][ ] = sMatrix.getMa int matrixC[ ][ ] = resultMatrix.getMatrix() for (int j=0; j2; j++) { for (int k=0; k2; k++){ matrixC[i][j }
  • 447.
    Web Design Development – CS506 VU © Copyright Virtual University of Pakistan 447 re xC[0][0], matrixC[0][1], matrixC[1][0], matrixC[1][1] ); } // end MatrixMulitplier } // end multiply() // save results (MatrixBean containg product of two matrices) into // database using DAO public void saveResult( MatrixBean resultMatrix ) atrixDAO dao = new MatrixDAO(); dao.saveMatrix(resultMatrix); } // end MatrixMu As class name depicts, it is used to store product results into database. Let’s look on the code to see how it is accomplished. import java.util.*; import java.sql.*; import bo.*; public class MatrixDAO{ private Connection con; // constructor public MatrixDAO() throws ClassNotFoundException , SQLException { ablishConnection(); } method used to estab lishConnection() throws ClassNotFoundException , SQLException { // establishing conection Class.forName(sun.jdbc.odbc.JdbcOdbcDriver); ng conUrl = jdbc:odbc:MatrixDSN; con = DriverManager.getConnection(conUrl); } sultMatrix.setMatrix( matri return resultMatrix; { M } litplier MatrixDAO package dal; est // lish connection with db private void estab Stri
  • 448.
    Web Design Development – CS506 VU // used to store MatrixBean into database after converting it to // a String ) try { String sql = INSERT INTO Matrix(mOrder, mValues) VALUES (?,?); t pStmt = con.prepareStatement(sql); // converting MatrixBean into String by calling toString() String sMatrix = matrix.toString(); // setting order of matrix pStmt.setString( 1 , 2*2 ); tring( 2 , sMatrix ); pdate(); }catch(SQLException sqlex){ System.out.println(sqlex); } } // end saveMatrix overriding d to public void finalize( ) { if(con != null){ }catch(SQ x){ System.out.println(sex); } } // end finalize } // end MatrixDAO class public void saveMatrix(MatrixBean matrix PreparedStatemen // setting matrix values in the form of string pStmt.setS pStmt.executeU // finalize metho release acquired resources try{ con.close(); } LException se © Copyright Virtual University of Pakistan 448
  • 449.
    Web Design Development – CS506 VU matrixresult.jsp Used to display resultant product o %-- importing “bo” package th %@ page import=bo.*% html body h1The resultant Matrix is /h1 llerServlet % MatrixBean productMatrix = (MatrixBean)request.getAttribute(product); at it can be displayed int matrix[][] = productMatrix.getMatrix() ; ABLE TR TD %= matrix[0][0] % /TD TD %= matrix[1][0] % /TD /body /html f two matrices. The code is given below: at contains MatrixBean -% %-- retrieving MatrixBean object from request, that was set on Contro --% // retrieving values in 2d array so th % %-- displaying MatrixBean’s object values -% T TD %= matrix[0][1] % /TD /TR TR TD %= matrix[1][1] % /TD /TABLE © Copyright Virtual University of Pakistan 449
  • 450.
    Web Design Development – CS506 VU web.xml ?xml version=1.0 encoding=UTF-8? web-app servlet-name ControllerServlet /servlet-name se let-class /servlet servlet-let- name ControllerServlet /servlet-name url-pattern /controller /url-pattern /servlet- /web-app References: . Java A Lab Course by Umair Javed. Sang Shin servlet rvlet-class controller.ControllerServlet /serv mapping serv mapping . Java Passion by © Copyright Virtual University of Pakistan 450
  • 451.
    Web Design Development – CS506 VU © Copyright Virtual University of Pakistan 451 Lesson 42 Expression Language Sun Microsystems introduced the Servlet API, in the later half of 1997, positioning it as a powerful alternative for CGI developers who were looking around for an elegant solution that was more efficient and ortable than CGI (Common Gateway Interface) programming. However, it soon became clear that the Servlet ion difficult to implement, from the perspective e community ore a solution that would allow embedding Java Code in HTML – Java Server Pages (JSP) emerge Java as the s ough knowledge t imple lines of java c r? Yes, by using Expression Language (EL). JavaServer Pages Standard Tag Library (JSTL) 1.0 introduced the concept of the EL but it was constrained to only the JSTL tags. With JSP 2.0 you can use the EL with template text. Note: - JSTL will be discussed in the following Handout. Overview ions on them. It is inspired form both the ECMAScript and the XPath expression language. JSP Before and After EL To factor so that you start learning EL with renewed zeal and zest, a comparison is give e EL affects the JSPs. he following figure depicts the situation of a JSP before EL. We have to declare a variable before using it, ata type must be known in advance and most importantly have to use awkward syntax and many more. All ese pr p API had its own drawbacks, with developers finding the solut of code maintainability and extensibility. It is in some ways, this drawback that prompted thto expl d as a result of this exploration. cripting language in JSP scares many people particularly web page designers which have eno work with HTML and some scripting language, faced lot of difficulties in writing some s ode. Can we simplify this problem to ease the life of web designe The Expression Language, not a programming or scripting language, provides a way to simplify expressions in JSP. It is a simple language that is geared towards looking up objects, their properties and performing simple operat add in motivational n blow that illustrates how T dth oblems are highlighted in the following figure:
  • 452.
    Web Design Development – CS506 VU © Copyright Virtual University of Pakistan 452 Contrary to the above figure, have a look on the subsequent figure that gives you a hint how useful EL can c:if test = “$ {p.address == param.add }” t pieces of EL. These are: ƒ Syntax of EL ƒ Automatic type conversion ƒ Access to beans, arrays, lists maps ƒ Access to set of implicit objects EL Syntax The format of writing any EL expression is: $ { validExpression } The valid expressions can consist on these individuals or combination of these given below: ƒ Literals be? Person Name: $ { p.name } … Expression Language Nuggets We’ll discuss the following importan ƒ Expressions identifiers ƒ Arithmetic, logical relational operators
  • 453.
    Web Design Development – CS506 VU ƒ Operators ƒ Variables (object references) ƒ Implicit call to function using property name EL Literals ar The list of literals that can be used as an EL expression and their possible values are given in the tabulformat below: Literals Literal Values Bo n olea true or false Integer Similar to Java e.g. 243, -9642 Floating Point Similar to Java e.g. 54.67, 1.83 String Any string delimited by single or double quote e.g. “hello” , ‘hello’ Null Null Exa l --% EL Operators The lists of operators that can be used in EL expressi are given below: mpes of using EL literals are: . ${ false } %-- evaluates to false --% . ${ 8*3 } %-- evaluates to 24 on Typ e Operator Arithmetic + -* / (div) % (mod) Grouping ( ) Logical (and) ||( or) !(not) Relational == (eq) != (ne) (lt) (gt) = (le) = (ge) Empty value is null or empty. It returns a Bool The empty operator is a prefix operation used to determine if a ean value. Con io ditnal ?: © Copyright Virtual University of Pakistan 453
  • 454.
    Web Design Development – CS506 VU Let us look at some examples that use operators as valid expression: ƒ ${ (6*5) + 5 } %-- evaluate to 35 --% ƒ ${ (x = min) (x = max) } ƒ ${ empty name } Returns true if name is Empty string (“”), Null etc. EL Identifiers Identifiers in the expression language represent the names of objects stored in one of the JSP scopes: on, or application. These types of objects are referred to scoped variables throughout EL has 11 reserved identifiers, corresponding to 11 implicit objects. All other identifiers assumed to refer to les. he Expression Language defines a set of implicit objects given below in tabular format: page, request, sessi this handout. scoped variab EL implicit Objects T Category Implicit Object Operator JSP pageContext The context for the JSP page, used to access the JSP implicit objects such as request, response, session, out, servletContext etc. A Map associating names values of page scoped attributes pageScope requestScope A Map associating names values of request scoped attributes Scopes sessionScope A Map associating names values of session scoped attributes applicationScope A Map associating names values of application scoped attributes param Maps a request parameter name to a single String Request parameter value. Parameters paramValues Maps a request parameter name to an array of values Request header Maps a request header name to a single header value. Headers headerValues Maps a request header name to an array of value. Cookies cookie A Map storing the cookies accompanying the request by name © Copyright Virtual University of Pakistan 454
  • 455.
    Web Design Development – CS506 VU © Copyright Virtual University of Pakistan 455 Initialization Parameters initParam A Map storing the context initialization parameters of the web application by name Examples of using implicit objects are: . $ ates to response implicit object of JSP . ${ param.name } -This expression is equivalent to calling request.getParameter(“name”); ${ cookie.name.value } -Returns the value of the first cookie with the given -Equivalent to if (cookie.getName().equals(“name”){ String val = cookie.getValue(); } umbers using EL his simple example demonstrates you the capabilities of EL. index.jsp is used to collect input for two numbers and their sum is displayed on result.jsp using EL. Let’s first see the code of index.jsp html body Enter two numbers to see their sum um br Second Number: inpu / value=Calculate Sum / /form /body /html { pageContext.response } -Evalu . name Example Code: Summation of Two N T index.jsp form action=result.jsp First Number : input type=text name=n 1 / t type=text name=num2 input type=submit
  • 456.
    Web Design Development – CS506 VU © Copyright Virtual University of Pakistan 456 result.jsp html bers if we used scriptlet quest .getParameter(num1); = request .getParameter(num2); int num1 = Integer.parseInt(no1); int num2 = Integer.parseInt(no2); Resul --% ing two numbers m2} /body EL Identifiers (cont.) We had started our discussion on EL identifiers. Let’s find out how these identifiers (variables) can be om different scopes. Storing Scoped Variables By using java code, either in pure servlet or in a scriptlet of JSP, we can store variables in a particular scope. For example, . S session scope using Java code Assu lass and we want to store its object pin session scope then we can write the following lines of code to accomplish that: HttpSess ; PersonInfo p = new PersonInfo(); p.setName(“ali”); ses.setAttribute(“person” , p); t scope using Java code For the following lines of code, assume that request is of HttpServletRequest type. To store PersonInfo object p in request scope, we’ll write: body %-- The code to sum two num % String no1 = reString no2 % t is: %= num1 + num2 % %-- implicit Object param is used to access request parameters By Using EL summ --% Result is: ${param.num1 + param.nu /html stored/retrieved in/fr toring a variable in me that we have PersonInfo c ion ses = request.getSession(true) . Storing a variable in reques
  • 457.
    Web Design Development – CS506 VU © Copyright Virtual University of Pakistan 457 PersonInfo p = new PersonInfo(); p.setName(“ali”); request.setAttribute(“person” , p); ome another method (with which you are already familiar) to store a variable in a scope, certainly by using JSP action tags, we learned how to store a variable in any particular scope. . Storing a variable in request scope using JSP action tag If we want to store p of type PersonInfo in request scope by using JSP action tags, then we’ll write: jsp:useBean id=”p” class Later, you c ject p by using action tag as well. For example jsp:setProperty Retrieving Scoped Variab ou are already very much familiar o able by using java code and JSP ction tags. Here, we’ll discuss h ieves scoped variables. As already mentioned, identifiers in the valid expression represent t cts stored in one of the JSP scopes: page, request, session and licati n. hen th pres counters an identifier, it searches for a scoped variable with that name first ƒ e d finally in application scope If no such object is located in four scopes, null is returned. in session scope by mean of any mechanism discussed previously and have written the following EL expression to access the name property of p ${p.name} Then EL searches for p first in page scope, then in request scope, then in session scope where it found p. After that it calls p.getName() method. This is also shown in pictorial form below: You must be thinking of s =”PersonInfo” scope=”request”/ an change the properties of ob n ame=“p” property=“name” value=“ali” / les Ya f retrieving any stored scoped vari ow EL retrhe names of obje appo We exsion language en in page scope, ƒ then in request scope, ƒ then in session scop ƒ an Note: - For example, if we’ve stored PersonInfo object p
  • 458.
    Web Design Development – CS506 VU © Copyright Virtual University of Pakistan 458 EL Accessors The dot (.) and bracket ([ ]) operator let you access identifies and their properties. The dot operator typically used for accessing the properties of an object and the bracket operator is generally used to retrieve elements of arrays and collections. . Dot (.) operator as name property and its object person is stored in some scope. Then to access the name property of person object, we’ll write the following expression using EL: Assume that JavaBean PersonInfo h The EL accesses the object’s properties using the JavaBeans conventions therefore getName() must be define sonInfo. Moreover, if property being accessed itself an object, the dot operator can be applied recurs example d in Perively. For ${user. address. city}
  • 459.
    Web Design Development – CS506 VU © Copyright Virtual University of Pakistan 459 . Brack This operator can be applied to arrays collections implementing List interface e.g. ArrayList etc. ƒ ƒ ample, ${ personList[2] } returns the 3rd element stored in it Moreover, this operator can also be applied to collections implementing Map interface e.g. HashMapetc. ƒ Key is specified inside brack ƒ For example, ${ myMap[“id”] } returns the value associated with the id(key) EL – Robust Features racteristics of Expression Language are: e $ { “Hello” ${user.firstName} ${user.lastName} } ƒ EL also supports automatic type conversion; as a result primitive can implicitly wrap and unwrap java classes. For example ƒ Most importantly, if object/identifier is null, no NullPointerException would be thrown☺. For xample Assum ha exception would be thrown and the result would also be null. Using Expressio Language Expression Language can be used in following situations ƒ A custom actions. E.g. jsp:setProperty id = “person” value = ${….} / et ([ ]) operator Index of the element appears inside brackets For ex ets Some powerful cha ƒ Multiple expressions can be combined and intermixed with static text. For exampl into/from their corresponding e. If the expression written is: ${person.name} e tt person is null, then non s attribute values in standard
  • 460.
    Web Design Development – CS506 VU © Copyright Virtual University of Pakistan 460 ƒ In template text – the value of the expression is inserted into the current output. E.g. h3 $ { …… } /h3 ƒ With JSTL (discussed in the next handout) Example So far, we have example in number of different ways. This time EL will be i n.jsp, showperson.jsp, C look on the code of each of ese components: PersonInfo.java The JavaB rson record. import java.io.*; public class PersonInfo implements Serializable{ private Str private String address; private int // no argument cons public PersonIn nam address = ; // setters public void setName(String n){ name = n; address = a; } public void setPhoneNum(int pNo){ phoneNum = pNo; } // getters Code: AddressBook using EL shown you implementation of AddressBook ncorporated in this example. AddressBook code example consists on searchpersoontrollerServlet, PersonInfo and PersonDAO classes. Let’s th ean used to represent one pe package vu; ing name; phoneNum; tructor fo() { e = ; phoneNum = 0; } } public void setAddress(String a){
  • 461.
    Web Design Development – CS506 VU public String getName( ){ return name; } public String getAddress( ){ address; } } } It is used to retrieve/search person records from database. package vu; import java.util.*; import java.sql.*; public class PersonDAO{ private Connection con; // constructor public PersonDAO() throws ClassNotFoundException , SQLException { } //used to establish connection with database private void establishConnection() throws ClassNotFoundException , SQLException { // establishing connection Class.forName(sun.jdbc.odbc.JdbcOdbcDriver); String conUrl = jdbc:odbc:PersonDSN; con = DriverManager.getConnection(conUrl); } // used to search person records against name public ArrayList retrievePersonList(Strin g pName) throws SQLException { ArrayList personList = new ArrayList(); return public int getPhoneNum( ){ return phoneNum; PersonDAO.java establishConnection(); © Copyright Virtual University of Pakistan 461
  • 462.
    Web Design Development – CS506 VU © Copyright Virtual University of Pakistan 462 String sql = SELECT * FROM Person WHERE name = ?; PreparedStatement pStmt = con.prepareStatement(sql); pStmt.setString( 1, pName); System.out.println(retrieve person list); int pNo; while ( rs.next() ) { name = rs.getString(name); add = rs.getString(address); pNo = rs.getInt(phoneNumber); // creating a PersonInfo object PersonInfo personBean = new PersonInfo(); to arraylist personList.add(personBean); // end while } // end retrievePersonList //overriding finalize method to release resources public void finalize( ) { try{ xception sex){ System.out.println(sex); } } // end finalize } // end class ResultSet rs = pStmt.executeQuery(); String name; String add; personBean.setName(name); personBean.setAddress(add); personBean.setPhoneNum(pNo); // adding a bean } return personList; if(con != null){ con.close(); } }catch(SQLE
  • 463.
    Web Design Development – CS506 VU © Copyright Virtual University of Pakistan 463 s T its this data to the ControllerServlet. html h3 Search Person/h3 FORM =search action=controllerservlet / 4 /TD TD input type=text name=name / /TD /TR TR TD COLSPAN=2 ALIGN=CENTER input type=submit value=search / input /TD /TR /FORM /center /body /html ControllerServlet.java The Controller Servlet receives reques and after fetching search results from tabase, forwards the request to showperson.jsp. pack ller; import vu.*; import java.io.*; earchperson.jsp his JSP is used to gather person’s name from the user and subm body center h2 Address Book /h2 name TABLE BORDER=1 TR TD h4 Name/h type=reset value=clear / /TABLE t from searchperson.jsp da age contro import java.net.*;
  • 464.
    Web Design Development – CS506 VU import javax.servlet.*; import javax.servlet.http.*; public class ControllerServlet extends HttpServlet { // end processRequest() // This method only calls processRequest() protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { processRequest(request, response); } // This method only calls processRequest() protected void doPost(HttpServletRequest request, HttpServletResponse response) throws processRequest(request, response); } protected void processRequest(HttpServletRequest request, e response) throws } // end ControllerServlet rson(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // retrieving request parameter “name” entered on showperson.jsp String pName = request.getParameter(name); } ServletException, IOException { HttpServletRespons ServletException, IOException { // defined below searchPerson(request, response); protected void searchPe try { // creating PersonDAO object PersonDAO pDAO = new PersonDAO(); © Copyright Virtual University of Pakistan 464
  • 465.
    Web Design Development – CS506 VU // calling DAO method to retrieve personlist from database // against the name entered by the user A // storing personlist in request scope, later it is retrieved // back on showperson.jsp request.setAttribute(plist, personList); atcher(showperson.jsp); } // end searchPerson showperson.jsp yList (personList) from play records. %-- importing required packages--% %@page import=java.util.* % %@page import=vu.* % html body center h2 Address Book /h2 ing results meet your search criteria/h3 TABLE BORDER=1 TR Address/TH THPhoneNum/TH /TR %-- start of scriptlet --% rrayList personList = pDAO.retrievePersonList(pName); // forwarding request to showperson, so it renders personlist RequestDispatcher rd = request.getRequestDisp rd.forward(request, response); }catch (Exception ex) { System.out.println(Exception is + ex); } This page is used to display the search results. To do so, it reclaims the stored Arrathe request scope. Furthermore, this page also uses the Expression Language to dis h3 Follow THName/TH TH © Copyright Virtual University of Pakistan 465
  • 466.
    Web Design Development – CS506 VU % // retrieving ArrayList from request scope ArrayList personList =(ArrayList)request.getAttribute(plist); =0; ipersonList.size(); i++) { person = (PersonInfo)personList.get(i); // storing PersonInfo object in request scope /* As mentioned, an object must be ome scope to work with Expression Language*/ request.setAttribute(p, person); % %-- accessing properties of stored PersonInfo object with name “p” using EL --% /TD TD ${ p.phoneNum} /TD %-- The following expressions are now replaced by EL statements written above--% %--%= person.getName()% --% %--%= person.getAddress()% --% %--%= % /body PersonInfo person = null; for(int i stored in s %-- end of scriptlet --% TR TD ${ p.name } /TD TD ${ p.address} person.getPhoneNum()% --% /TR % } // end for /TABLE /center /html © Copyright Virtual University of Pakistan 466
  • 467.
    Web Design Development – CS506 VU © Copyright Virtual University of Pakistan 467 web.xml web-app servlet-name ControllerServlet /servlet-name . Java A Lab Course by Umair Javed. l by Sun va.sun.com/j2ee/1.4/docs/tutorial/doc/JSPIntro7.html ?xml version=1.0 encoding=UTF-8? servlet servlet-class controller.ControllerServlet /servlet-class /servlet servlet-mapping servlet-name ControllerServlet /servlet-name url-pattern /controllerservlet /url-pattern /servlet-mapping /web-app References: . Expression Language Tutoria http://ja The JSTL Expression Language by David M. Geary http://www.informit.com/articles/article.asp?p=30946rl=1
  • 468.
    Web Design Development – CS506 VU Lesson 43 JavaServer Pages Standard Tag Library (JSTL) Introduction Thfuncti e JSP Standard Tag Library (JSTL) is a collection of custom tag libraries that implement general-purpose onality common to Web applications, including iteration and conditionalization, data management ting, manipulation of XML, and database access. Like JSP, JSTL is also a specification not an implementation. The development theme of JSTL is “scriptlet free JSP”. These tag libraries provide a wide range of custom action functionality that most JSP authors have found themselves in need of in the past. Having a defined specification for how the functionality is implemented author can learn these custom actions once and then use and reuse them on all future pplication containers that support the specification. Using the JSTL will not only make your JSPs more readable and maintainable, but will allow you to concentrate on good design and implementation practices in your pages. JSTL EL JSTL includes supports for Expression Language thus EL can be used to specify dynamic attribute values ming language. Prior to JSP 2.0, EL can only be used in becomes a standard part of JSP 2.0. This allows the use of EL anywhere tioned, JSTL encapsulates common functionality that a typical JSP author would encounter. This set m rious members of the expert group. Since this expert group has a good cross-section of JSP authors and users, the actions provided in the JSTL uld L is commonly referred to as a single tag library, it is actually composed of four separate tag libraries: ƒ - co o access variables etc. ƒ ML m d processing ƒ SQL - contains tags for accessing and working with database. ƒ Internationalization and formatting - contains tags to support locale messages, text, numbers and date formation format means that a pageproducts on all a for JSTL actions without using full-blown program attributes of JSTL tags but EL now in the document. Functional Overview As men of comon functionality has come about through the input of the va shosuit a wide audience. While the JST Corentains tags for conditions, control flow and tXanipulation - contains tags for XML parsing an © Copyright Virtual University of Pakistan 468
  • 469.
    Web Design Development – CS506 VU Twin Tag Libraries JSTL comes in two flavors to support various skill set personal ) version - Dynamic attribute values of JSTL tags are specified using JSTL expression language (i.e. sion}) ƒ Expression Language (EL ${expres - The EL based JSTL tag libraries along with URIs and preferred prefixes are given below in tabular format Library URI Prefix Core http://java.sun.com/jsp/jstl/core c SQL http://java.sun.com/jsp/jstl/sql sql Internationalization/ Format http://java.sun.com/jsp/jstl/fmt fmt XML http://java.sun.com/jsp/jstl/xml x ƒ Request Time (RT) version ries along with URIs and preferred prefixes are given below in tabular format - Dynamic attribute values of JSTL tags are specified using JSP expression (i.e. %= expression %) - The RT based JSTL tag libra Library URI Prefix Core http://java.sun.com/jsp/jstl/core_rt c_rt SQL http://java.sun.com/jsp/jstl/sql_rt sql_rt Internationalization/ http://java.sun.com/jsp/jstl/fmt_rt fm Format t_rt XML http://java.sun.com/jsp/jstl/xml_rt x_rt Using JSTL As we discussed earlier, JSTL includes f © Copyright Virtual University of Pakistan 469 our standard tag libraries. As is true with any JSP custom tag library, t be included in any page that you want to be able to use this library's tags. For example, to use EL based core tag library, the taglib directive appears as: %@taglib prefix=“c” uri=http://java.sun.com/jsp/jstl/core % a taglib directive mus
  • 470.
    Web Design Development – CS506 VU And to use RT based core tag library, the taglib directive appears as: %@taglib prefix=“c_rt” uri=http://java.sun.com/jsp/jstl/core_rt % Working with Core Actions (tags) The set of tags that are available in the Core tag library come into play for probably most anything you will be doing in your JSPs such as: ore actions: Provides a tag based mechanism for creating and setting scope based variables. Its syntax is as follows: c:set v nam expression” / Where the var attribute specifies the name of the scoped variable, the scope attribute indicates which scope (page | request | session | application) the variable resides in, and the value attribute specifies the value to If the specified variable already exists, it will simply be assigned the indicated value. If not, a new scoped variable is created and initialized to that value. The scope attribute is optional and default to page. Three examples of using c:set are given below. In the first example, a page scoped variable “timezone” is set to a value“Asia / Karachi”. c:set var=“timezone” value=“Asia/Karachi” / equest scoped variable “email” email is set to a value “me@gmail.com” c:set var=“email” scope=”request” value=“me@gmail.com” / In the third example, a page scoped variable “email” is set to value of request parameter “email” by using paramimplicit object. If email parameter is defined in JSP page as: input type=”text” value = “email” / ƒ Manipulation of scoped variables ƒ Output ƒ Conditional logic ƒ loops ƒ URL manipulation ƒ and Handling errors. Let’s walk through some important c c:set ar=“e” scope = “scope” value = “ be bound to the variable. In the second example, a r © Copyright Virtual University of Pakistan 470
  • 471.
    Web Design Development – CS506 VU © Copyright Virtual University of Pakistan 471 Then c:set tag would be used as: c:set var=“email” scope=”request” value=“param.email” / Using c:set with JavaBeans Map tag can also be used to change the property of a bean or the value against some key. For this purpose, the syntax of the c:set tag would look like this: c:set target=“bean/map” property=”property/key” value=“value” / ƒ If target is a bean, sets the value of the property specified. This process is equivalent to jsp:setProperty … / JSP action tag. ƒ If target is a Map, sets the value of the key specified And of course, these beans and maps must be stored in some scope prior to any attempt is made to change their properties. For example, consider the following snippet of code that stores PersonInfo’s object person into request scope using jsp:useBean … / tag. Then using c:set tag, person’s name property is set to “ali”. jsp:useBean id=“person” class=“vu.PersonInfo” scope=“request” / c:set target=“person” property =“name” value = “ali” / c:out A developer will often want to simply display the value of an expression, rather than store it. This can be done by using c:out core tag, the syntax of which appears below: c:out value = “expression” default = “expression” / bute, and then prints the result. If the optional default attribute is specified, the c:out action will print its (default) value if the value attribute's expression valuates either to null or an empty String. This tag is equivalent to JSP expression i.e. %=expression %. Consider the following examples in which the usage of c:out tag has shown. In the first example, string r an empty string then default value “0” would be displayed. c:out value = “${param.num}” default = “0” / c:set This tag evaluates the expression specified by its value attri e “Hello” would be displayed c:out value = “Hello” / In the second example, if request parameter num evaluates to null o
  • 472.
    Web Design Development – CS506 VU The above fragment of code is equivalent to following scriptlet: est.getParameter(“num”); no.equals(“”)) (0); Out.println(no); } bean like name, we’ll write c:out value= “${person.name}” default = “Not Set” / As its name suggests, the c:removeaction is used to delete a scoped variable, and takes two attributes. The var attribute names the variable to be removed, and the optional scope attribute indicates the scope from ich it should be removed and defaults to page. For example, to remove a variable named square from page scope, we’ll write: c:remove var = “square” / d if variable email is required to be removed from request scope, then c:remove tag will look like: c:remove var = “email” scope = “request” / the context of Web applications, iteration is primarily used to fetch and display collections of data, typically in the form of a list or sequence of rows in a table. The primary JSTL action for implementing iterative content is the c:forEach core tag. This tag supports two different styles of iteration: er range (like Java language's for statement) ƒ Iteration over a collection (like Java language's Iterator and Enumeration classes). % tring no = requ if (no == null || { stem.out.println } Else { % If we want to display the property of a c:remove wh An c:forEach In ƒ Iteration over an integ © Copyright Virtual University of Pakistan 472
  • 473.
    Web Design Development – CS506 VU Iteration over an Integer range To iterate over a range of integers, the syntax of the c:forEach tag will look like: c:forEach var=“name” begin=“expression” end=“expression” step=“expression” Body Content /c:forEach The begin and end attributes should be either constant integer values or expressions evaluating to integer values. They specify the initial value of the index for the iteration and the index value at which iteration should cease, respectively. When iterating over a range of integers using c:forEach, these two attributes are required and all others are optional. The step attribute specifies the amount to be added to the index after each iteration. Thus the index of the iteration starts at the value of the begin attribute, is incremented by the value of the step attribute, and halts iteration when it exceeds the value of the endattribute. Note that if the stepattribute is omitted, the step size defaults to 1. If the var attribute is specified, then a scoped variable with the indicated name will be created and assigned the current value of the index for each pass through the iteration. This scoped variable has nested visibility that is it can only be accessed within the body of the c:forEachtag. For example to generate squares corresponding to range of integer values, the c:forEachtag will be used as: c:forEach var=“x” begin=“0” end=“10” step=“2” c:out value=“${x * x}” / /c:forEach By executing the above code, following output would appear: 4 16 36 64 100 Iteration over a Collection When iterating over the members of a collection and arrays etc, one additional attribute of the c:forEach tag is used: the items attribute. Now the c:forEach tag will look similar to this: c:forEach var=“name” items=“expression” Body Content /c:forEach © Copyright Virtual University of Pakistan 473
  • 474.
    Web Design Development – CS506 VU © Copyright Virtual University of Pakistan 474 When you use this form of the c:forEach tag, the items attribute is the only required attribute. T the items attribute should be the collection/array over whose members the iteration is to occur, and is typically specified using an EL expression. If a vari o specified using var attribute, then the named variable will be bound to collection for each iteration pass. For example, to iterate over a Str java code, we used to write in JSP: for(int i=0; imessages.length; i++) { String msg = messag s[i]; % %= msg % % his can be done using c:forEach tag in much simpler way as shown below: c:forEach var=“msg” items=“${messages}” c:out value= “${msg}” / /c:forEach Similarly, to iterate over a persons ArrayList that contains PersonInfo objects, we used to write in JSP: % { PersonInfo p == (PersonInfo)persons.get(i); String name = p.getName(); % %= name % % } // end for % he value of able name is alssuccessive elements of theing array (messages) using % e } // end for % T ArrayList persons = (ArrayList)request.getAttribute(“pList”); for(int i=0; ipersons.size(); i++)
  • 475.
    Web Design Development – CS506 VU © Copyright Virtual University of Pakistan 475 Indeed, the above task can be achieved in much simpler way using c:forEach tag as shown below: c:forEach var=“p” items=“${persons}” c:out value= “${p.name}” / /c:forEach The c:forEach tag processes each element of this list(persons) in turn, assigning it to a scoped variable quired. are c:if Like ordinary Java’s if, used to conditionally process the body content. It simply evaluates a single test expression and then processes its body content only if that expression evaluates to true. If not, the tag's body c:if test= “expression” Body Content /c:if b are equal, the c:if tag is used as: c:if test= “${a == b}” /c:if c:choose c:choose the second conditionalization tag, used in cases in which mutually exclusively test are required to splayed. The syntax is shown below: c:choose c:when test= “expression” Body content …………… named p. Note that typecast is also not re Furthermore, you can use the begin, end, and step attributes to restrict which elements of the collectionincluded in the iteration. content is ignored. The syntax for writing c:iftag is: For example, to display a message “a equals b” if two strings a h2 A equals B /h2 determine what content should be di /c:when
  • 476.
    Web Design Development – CS506 VU © Copyright Virtual University of Pakistan 476 c:otherwise Body content /c:otherwise /c:choose Each condition to be tested is represented by a corresponding c:when tag, of which there must be at least c:when tag whose test evaluates to true will be processed. If none n tests return true, then the body content of the c:otherwisetag will be processed. , that the c:otherwise tag is optional; a c:choose tag can have at most one nested tag. If all c:when tests are false and no c:otherwise action is present, then no c:choose body content will be processed. The example code given below illustrates the usage of c:choose tag in which two strings a b are compared nd appropriates messages are displayed: c:choose c:when test= “a == b” h2 a equals b/h2 /c:when c:when test= “a = b” h2 a is less than b/h2 /c:when c:otherwise h2 Don’t know what a equals to /h2 /c:otherwise /c:choose netBeans 4.1 and JSTL If you are using netBeans 4.1 IDE then you have to add JSTL library to your project manually. To do so, right click on the libraries folder, you can find it under project’s name and select the Add Library option. This is also shown in the following figure: one. Only the body content of the first of the c:whe Note, though c:otherwise a
  • 477.
    Web Design Development – CS506 VU © Copyright Virtual University of Pakistan 477 Thed Ad Library dialog box opens in front of you. Select JSTL 1.1 option and press Add Library button. Now you can refer to any JSTL library in your JSPs.
  • 478.
    Web Design Development – CS506 VU © Copyright Virtual University of Pakistan 478 Note: Remember that the JSTL 1.1 library is only added to current project. You have to repeat this step for each project in which you want to incorporate JSTL. Example Code: AddressBook using JSTL core tags This is the modified version of AddressBook that was built using Expression Language in the last handout. Only showperson.jsp is modified to incorporate JSTL core tags along with Expression Language in place of scriptlets. The remaining participants searchperson.jsp, ControllerServlet, PersonInfo and PersonDAO left unchanged. Let’s look on the code of each of these components: PersonInfo.java The JavaBean used to represent one person record. package vu; ublic class Pers private String name; private String address; private int phoneNum; // no argument constructor public PersonInfo() { name = ; address = ; phoneNum = 0; // setters public void setName(String n){ import java.io.*; p onInfo implements Serializable{ } name = n; } public void setAddress(String a){ address = a; }
  • 479.
    Web Design Development – CS506 VU © Copyright Virtual University of Pakistan 479 public void setPhoneNum(int pNo){ phoneNum = pNo; } } public String getAddress( ){ } public in // getters public String getName( ){ return name; return address; t getPhoneNum( ){ return phoneNum; } }
  • 480.
    Web Design Development – CS506 VU Lesson 44 Client Side Validation JavaServer Faces (JSF) out client side validation and also learn about growing in For v l --it saves time and bandwidth, and gives you ore options to point out to the user where they've gone wrong in filling out the form. want to send the browser to the server validate that all of the required fields on a form were filled out. e can be used to achieve the said objective. However, JavaScript and V hy is Client Side Validation Good? There are two good reasons to use client-side validation: ƒ It's a fast form of validation: if something's wrong, the alarm is triggered upon submission of the form. ƒ You can safely display only one error at a time and focus on the wrong field, to help ensure that the user correctly fills in all the details you need. Code Example: Form Validation using JavaScript For example on the following form, we want to make sure that text filed for name should not be left empty and age field does not contain any negative value. To accomplish this we’ll use JavaScript. If user forgets to provide name and/or enters a negative value, a message would be displayed to the user that indicates what was went wrong? However, if user conforms to requirements, he/she would be taken to another page that displays a greeting message. Note: In this example, JavaScript semantics isn’t discussed over here as I am assuming that you might be familiar with some scripting language. Otherwise, www.w3schools.com In this handout, we’ll talk ab demand Java technology i.e. JSF. First start with client side validation Clie S ntide Validation ms alidation on the client-side is essentia m Furthermore, the browser doesn't have to make a round-trip to the server to perform routine client-side tasks. For example, you wouldn't to Any scripting languag BScript are two popular options W is an excellent resource to learn about scripting languages © Copyright Virtual University of Pakistan 480
  • 481.
    Web Design Development – CS506 VU The code that is used to generate this page is given below: HTML HEAD SCRIPT TYPE = text/javascript !— defining a function that receives form’s reference, defined inside the body and returns false if any quirement violated -- nction validateForm(thisform) of the name field, if it is left empty then displaying a message -- if ( f name.value == ) { return false; } !— if value of age is negative, displaying a message -- !— start of scripting code and mentioning type -- re fu { !— checking the value thisorm.name.value == null || thisform. alert(Username is required); © Copyright Virtual University of Pakistan 481
  • 482.
    Web Design Development – CS506 VU © Copyright Virtual University of Pakistan 482 if (thisform.age.value 0 ) { alert(Age can't be negative); return false; } } alue of onsubmit value, if this method returns false, the user remains on the same page -- FORM method=post onsubmit=return validateForm(this) action = “greeting.jsp” h2 Client Side Validation Example /h2 Age: INPUT type=text name=age size=30 / /HTML // end of function /SCRIPT !—end of script-- /HEAD !— validateForm method is called and specified as a v BR/ Name: INPUT type=text name=name size=30 / BR/ BR/ BR/ BR/ INPUT type=submit value=Submit /FORM /BODY
  • 483.
    Web Design Development – CS506 VU © Copyright Virtual University of Pakistan 483 JavaServer Faces (JSF) JSF technolog le b D A popular open source JSP-based Web application framework helps in defining a structured tion framework and reduces tedious coding but… sn’t provide UI tags imilar sort of problems as with Struts. Ja ƒ A framework which provides solutions for: ƒ Managing their state ƒ Input val g ƒ Automat ƒ Supporting internationalization and accessibility. If you are familiar with Struts and Swing (the standard Java user interface framework for desktop applicatio on of those two frameworks. Like Swing, JSF provides a rich m del that eases event handling and component rendering; and like Struts, JSF provides Web applicati JS Some t rver Faces components are shown below: y simplifies building the user interface for web applications. It does this by providing a higher- vel framework for working with your web applications. Some distinct features will be discussed provided y this technology. To begin with, have a look on some popular existing frameworks ifferent existing frameworks ƒ Struts programming model (MVC), also valida ƒ Adds complexity and doe ƒ Very Java programmer centric ƒ Tapestry Another popular framework that is extensively used in the industry is Tapestry. It has almost s vaServer Faces ƒ Representing UI components ƒ Handling eve nts idation ƒ Data bindin ic conversion age navigation ƒ Defining p ns), think of JavaServer Faces as a combinati coponent mo on lifecycle management through a controller servlet F UI Components of he standard JavaSe
  • 484.
    Web Design Development – CS506 VU S ome custom JavaServer Faces components are aServer Faces components are also available like: And some open course Jav © Copyright Virtual University of Pakistan 484
  • 485.
    Web Design Development – CS506 VU © Copyright Virtual University of Pakistan 485 And some third-party JavaServer Faces components are also available: A JSF application works by processing events triggered by the JSF components on the pages. These events are caused by user actions. For example, when the user clicks a button, the button triggers an event. You, the JSF programmer, decide what the JSF application will do when a particular event is fired. You do this by writing event listeners. In other words, a JSF application is event-driven. For example, if you write a JSF code to create a button, you will write: h:commandButton value=Login“ actionListener=“#{customer.loginActionListener}” action=“#{customer.login}” / The value attribute specifies the text that appeared on the face of a button, the actionListener attributes specifies to call the loginActionListener method written somewhere in a Customer class if an event is triggered and on which to go next, is decided by the login method of Customer class and given as a value of action attribute. The method specified in action attribute should return a String value as the returned Stringvalue is used in page navigation. Note: Many IDE provides visual support for JSF so you can drag and drop components instead of writing tedious coding for defining JSF components as shown above. Sun Studio Creator® is a free open source IDE that provides visual support for JSF and can be downloaded form Sun site. The code examples are also built using this IDE. A code snippet of a Customer class is given below: class Customer { public void loginActionListener(ActionEvent e) { ………………… } public String login() { return “OK”; } }
  • 486.
    Web Design Development – CS506 VU © Copyright Virtual University of Pakistan 486 Example Code: Hello User The example code (“hello user 1”) is given along with the handout. It is strongly advised that you must see the lecture video in order to learn how this example is built. User will provide a name in the text field and his/her name after appending “hello” to it, would be displayed on the same page. Validators make input validation simple and save developers hours of programming. JSF provides a set of validator classes for validating input values entered into input components. Alternatively, you can write your own validator if none of the standard validators suits your needs. Some built-in validators are: ƒ DoubleRangeValidator Any numeric type, between specified maximum and minimum values ƒ LongRangeValidator Any numeric type convertible to long, between specified maximum and minimum values ƒ LengthValidator Ensures that the length of a component's local value falls into a certain range (between minimum maximum). The value must be of String type. Example Code: Hello User The example code (“hello user 2”) is given along with the handout. You can open it using Sun Studio Creator IDE. It is strongly advised that you must see the lecture video in order to learn how this example is built. It is actually a modified version of the last example. This time, we’ll make sure that user couldn’t left blank the name field and must enter a name between ranges of 2 to 10 characters. If any condition fails, an appropriate message would be displayed. JSF – Managed Bean-Intro These are JavaBeans defined in the configuration file and are used to hold the data from JSF components. Managed beans represent the data model, and are passed between business logic and pages. Some other salient features are: ƒ Use the declarative model ƒ Entry point into the model and event handlers ƒ Can have beans with various states Here is an example of a managed-bean element whose scope is session, meaning that an instance of this bean is created at the beginning of a user session. managed-bean managed-bean-namemyBean/managed-bean-name managed-bean-classmyPackage.MyBean/managed-bean-class managed-bean-scopesession/managed-bean-scope /managed-bean
  • 487.
    Web Design Development – CS506 VU © Copyright Virtual University of Pakistan 487 JSF – Value Binding Value binding expressions can be used inside of JSF components to: ƒ Automatically instantiate a JavaBean and place it in the request or session scope. ƒ Override the JavaBean's default values through its accessor methods. ƒ Quickly retrieve Map, List, and array contents from a JavaBean. ƒ Synchronize form contents with value objects across a number of requests. The syntax of binding expressions is based on the JavaServer Pages (JSP) 2.0 Expression Language. In JSP, expressions are delimited with ${}, but in JSF they are delimited with #{}. JSF – Method Binding Unlike a value binding, a method binding does not represent an accessor method. Instead, a method binding represents an activation method. For example, binding an event handler to a method h:commandButton …… actionListener=“#{customer.loginActionListener}” ……… / JSF Navigation Page navigation determines the control flow of a Web application. JSF provides a default navigational handler and this behavior can be configured in configuration. However, you can do it visually in most tools like Sun Studio Creator Note: We have quickly breezed through the JSF technology essentials due to shortage of time. You must explore it by yourself to excel on it. You can find the resources in the last handout to acquire further skills. References: ƒ Java A Lab Course by Umair Javed ƒ Intrduction to JavaServer Faces by Sun Uhttp://java.sun.com U ƒ JavaServer Faces Programming by Kumiawan
  • 488.
    Web Design Development – CS506 VU © Copyright Virtual University of Pakistan 488 Lesson 45 JavaServer Faces In the last lecture, we have covered the basic nutshells of JSF. Having a belief on “learning by doing”, in this lecture another example is also given to show you the capabilities of JSF. Example Code: Addition of Two Numbers The example code (“AddNumbers”) is given along with the handout. It is strongly advised that you must see the lecture video in order to learn the making plus working of this example. This example demonstrates the usage of value and method binding expressions, managed beans, and how to use page navigation technique using IDE etc. Web Services In the remaining handout, we’ll take an overview of web services’ potential, their types and working model. Resources are given at the end for those who are interested in learning new technologies. Introduction Web services are Web-based enterprise applications that use open, XML-based standards and transport protocols to exchange data with calling clients. Web Service is becoming one of those overly overloaded buzzwords these days. Due to their increasing popularity, Java platform Enterprise Edition (J2EE) provides the APIs and tools you need to create and deploy interoperable web services and clients. Web service, Definition by W3C W3C recently has come up with a decent definition of web services. According to W3C, “A Web service is a software application identified by a URI, whose interfaces and binding are capable of being defined, described and discovered by XML artifacts and supports direct interactions with other software applications using XML based messages via internet-based protocols”. Distributed Computing Evolution Let's think a little bit on how distributed computing technology has evolved. In the beginning, things were built and deployed typically in the form of client and server model in which clients talk to a single server, for example, remote procedure calls (RPC).
  • 489.
    Web Design Development – CS506 VU © Copyright Virtual University of Pakistan 489 The second phase can be called web-based computing in which many clients talk to many servers through the net. In this phase, communicating partners still have to go through some pre-arrangement in terms of what common object model they have to use or what common communication protocol they have to agree upon. Finally, the web services model in which service users and service providers can be dynamically connected. And the pretty much every computing device and application participates as both service user and service provider. Characteristics of Web services Web services are XML-based throughout. Pretty much everything in the domain of Web services is defined in XML. For example, the format of the data being exchanged between service user and service provider is defined in XML or the description of web service is defined in XML. Because the only contract that has to be agreed upon between service user and service provider is syntax and semantics of XML messages, as long as valid messages can be generated and understood, it does not matter what programming language is used. So a web service is said to be programming language independent. Web services can be dynamically located and invoked. And typically they will be accessed and invoked over both internet and intranet. ƒ Interoperable Connect across heterogeneous networks using ubiquitous web-based standards ƒ Economical Recycle components, no installation and tight integration of software ƒ Automatic No human intervention required even for highly complex transactions ƒ Accessible Legacy assets internal apps are exposed and accessible on the web ƒ Available Services on any device, anywhere, anytime ƒ Scalable No limits on scope of applications and amount of heterogeneous applications Types of Web service ƒ Data providers For example, a service providing stock quotes ƒ Business-to-business process integration For example, purchase orders ƒ Enterprise application integration Different applications work together simply by adding a webservice wrapper
  • 490.
    Web Design Development – CS506 VU © Copyright Virtual University of Pakistan 490 Comparison between Web page Web service Just to give you a sense on the difference between a web page and a web service, consider the following table: Web page Web Service Has a UI No GUI Interacts with user Interacts with application Works with web browser client Works with any type of client Web service Architectural Components Following are the core building blocks of web service architecture. ƒ Service Description – how do clients know how it works (which functions, parameters etc.)? At the minimum, you need a standard way of describing a web service that is universally understood by all potential service users and service providers. This is important because without commonly agreed upon description of service, a service provider might have to produce individually tailored way of describing its service to all its potential service users. Web Service Description Language (WSDL pronounced as viz-dal) is industry agreed upon XML language that can be used to describe web service. It provides XML format for describing web services in terms of methods, properties, data types and protocols. ƒ Service Registration (Publication) and Discovery There has to be registry by which a service can be published and discovered. Universal Description, Discovery Integration (UDDI), a way to publish and find web services. A repository of web services on the internet where a machine or a human can find different web services. TUwww.uddi.orgUT ƒ Service Invocation Then there has to be standard way of invoking a service. Finally, for business transactions in which secure and reliable message delivery is important, there has to be a standard electronic business framework. The following figure represents simplified web service architecture and summarizes the working of web services:
  • 491.
    Web Design Development – CS506 VU © Copyright Virtual University of Pakistan 491 References: ƒ Java A Lab Course by Umair Javed ƒ Web services overview by sang shin Resources: An excellent resource for learning Java related technologies is: Uhttp://www.apl.jhu.edu/~hall/java/ U ƒTUhttp://java.sun.comUT ƒTUhttp://www.javaworld.comUT ƒTUhttp://www.theserverside.comUT ƒTUhttp://www.jsfcentral.comUT ƒTUhttp://www.jspolympus.comUT ƒ http://www.onjava.com