CS506 - Web Design and Development (Handouts) PDF
CS506 - Web Design and Development (Handouts) PDF
CopyrightVirtualUniversityofPakistan
WebDesignandDevelopment(CS506)
1.1.1
1.1.2
1.1.3
1.1.4
Simple ..................................................................................................................... 23
1.1.5
Object-Oriented....................................................................................................... 23
1.1.6
1.1.7
1.1.8
Portable ................................................................................................................... 24
1.1.9
2.1.1
2.1.2
2.1.3
2.1.4
References ............................................................................................................... 28
2.2
2.2.1
2.2.2
2.2.3
2.2.4
2.2.5
CopyrightVirtualUniversityofPakistan
WebDesignandDevelopment(CS506)
2.2.6
2.3
References: .............................................................................................................. 31
2.3.1
Installation............................................................................................................... 31
2.3.2
2.3.2.1
2.3.2.2
2.3.3
2.4
References ............................................................................................................... 34
2.4.1
HelloWorldApp....................................................................................................... 34
2.4.2
2.4.3
2.4.4
2.5
2.6
References ...................................................................................................................... 37
Strings............................................................................................................................. 38
3.1.1
3.1.2
3.2
3.3
3.4
3.5
3.5.1
3.5.2
3.6
3.7
Reference:....................................................................................................................... 44
4.1.1
Classes .................................................................................................................... 45
4.1.2
Objects .................................................................................................................... 45
4.1.3
Constructor ............................................................................................................. 45
CopyrightVirtualUniversityofPakistan
WebDesignandDevelopment(CS506)
4.1.4
Attributes ................................................................................................................ 45
4.1.5
Methods .................................................................................................................. 45
4.2
4.3
4.4
4.5
4.6
Using a Class................................................................................................................... 48
4.6.1
4.7
4.7.1
Static ....................................................................................................................... 50
4.7.2
4.7.2.1
4.8
Finalize ............................................................................................................................ 51
Reference:....................................................................................................................... 54
5.2
5.3
Polymorphism ................................................................................................................. 58
5.4
5.4.1
Up-casting ............................................................................................................... 60
5.4.2
Down-casting .......................................................................................................... 60
5.5
References: ..................................................................................................................... 60
6.2
6.3
6.3.1
6.4
HashMap ........................................................................................................................ 63
6.4.1
6.5
References: ..................................................................................................................... 65
6.6
6.6.1
Problem ................................................................................................................... 65
CopyrightVirtualUniversityofPakistan
WebDesignandDevelopment(CS506)
6.6.2
6.7
6.6.2.1
6.6.2.2
6.6.2.3
Reference ........................................................................................................................ 69
7.1.1
7.1.2
7.1.3
7.2
7.3
7.4
7.5
7.6
7.6.1
7.6.2
7.7
7.7.1
7.7.2
7.7.3
7.7.4
throw ....................................................................................................................... 73
7.7.5
throws...................................................................................................................... 73
7.8
References: ..................................................................................................................... 73
7.9
7.9.1
7.9.2
Why? ....................................................................................................................... 74
7.9.3
WebDesignandDevelopment(CS506)
8.2
8.3
8.4
Reference ........................................................................................................................ 86
8.5
8.5.1
8.6
8.5.1.1
8.5.1.2
References ...................................................................................................................... 92
9.2
9.3
Interfaces ........................................................................................................................ 95
9.3.1
9.3.2
9.4
9.5
References ...................................................................................................................... 98
WebDesignandDevelopment(CS506)
WebDesignandDevelopment(CS506)
WebDesignandDevelopment(CS506)
WebDesignandDevelopment(CS506)
10
WebDesignandDevelopment(CS506)
11
WebDesignandDevelopment(CS506)
12
WebDesignandDevelopment(CS506)
13
WebDesignandDevelopment(CS506)
14
WebDesignandDevelopment(CS506)
15
WebDesignandDevelopment(CS506)
16
WebDesignandDevelopment(CS506)
17
WebDesignandDevelopment(CS506)
Lecture 36 .............................................................................................................340
36.1 JavaBeans ..................................................................................................................... 345
36.1.1 JavaBeans Design Conventions ............................................................................ 345
36.2 References: ................................................................................................................... 352
18
WebDesignandDevelopment(CS506)
19
WebDesignandDevelopment(CS506)
Lecture 44: Client Side Validation & JavaServer Faces (JSF) .......................459
44.1 Client Side Validation .................................................................................................. 459
44.1.1 Why is Client Side Validation Good? ................................................................... 459
CopyrightVirtualUniversityofPakistan
20
WebDesignandDevelopment(CS506)
CopyrightVirtualUniversityofPakistan
21
WebDesignandDevelopment(CS506)
1.1
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.
From the original Sun Java whitepaper: "Java is a simple, object-oriented, distributed,
interpreted, robust, secure, architecture-neutral, portable, high-performance, multithreaded, and dynamic language."
Here are some original java buzzwords.
CopyrightVirtualUniversityofPakistan
22
WebDesignandDevelopment(CS506)
1.1.4 Simple
1.1.5 Object-Oriented
Java is network friendly -- both in its portable, threaded nature, and because Common
networking operations are built-in to the Java libraries.
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 untrusted code in a "sandbox" where,
for example, it can draw to the screen but cannot access the local file system.
CopyrightVirtualUniversityofPakistan
23
WebDesignandDevelopment(CS506)
1.1.8 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.
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.
1.1.10 High-performance
1.1.11 Multi-Threaded
1.1.12 Dynamic
Class and type information is kept around at runtime. This enables runtime loading
and inspection of code in a very flexible way.
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".
CopyrightVirtualUniversityofPakistan
24
WebDesignandDevelopment(CS506)
Faster Development
o Building an application in Java takes about 50% less time than in C or C++. So,
Faster time to market
o Java is said to be Programmer Efficient.
OOP
o Java is thoroughly OOP language with robust memory system
o 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
o Code re-uses at last -- String, ArrayList, Date, available and documented in a
standard way
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 nonMicrosoft 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.
Java has a lot of hype, but much of it is deserved. Java is very well matched for
many modern problem
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
1.1.17 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
Javas Sun site: http://java.sun.com
Java World : www.javaworld.com
CopyrightVirtualUniversityofPakistan
25
WebDesignandDevelopment(CS506)
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 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.
CopyrightVirtualUniversityofPakistan
26
WebDesignandDevelopment(CS506)
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.
CopyrightVirtualUniversityofPakistan
27
WebDesignandDevelopment(CS506)
2.1.4 References
2.2
Edit,
Compile,
Load,
Verify and
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.
CopyrightVirtualUniversityofPakistan
28
WebDesignandDevelopment(CS506)
CopyrightVirtualUniversityofPakistan
29
WebDesignandDevelopment(CS506)
30
WebDesignandDevelopment(CS506)
not be able to cause damage to your files and your system (as computer viruses might).
2.2.6 References:
2.3
2.3.1 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 Files\Java\jdk1.5.0
CopyrightVirtualUniversityofPakistan
31
WebDesignandDevelopment(CS506)
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
2.3.2.2 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
CopyrightVirtualUniversityofPakistan
32
WebDesignandDevelopment(CS506)
CopyrightVirtualUniversityofPakistan
33
WebDesignandDevelopment(CS506)
2.3.3 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.
2.4
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.
2.4.1 HelloWorldApp
Accessories
Notepad.
Note: Dont copy paste the given below code. Probably it gives errors and you cant 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. }
To save your program, move to File menu and choose save as option.
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.
CopyrightVirtualUniversityofPakistan
34
WebDesignandDevelopment(CS506)
Lines 1-3
o Like in C++, You can add multiple line comments that are ignored by the compiler.
Lines 4
o 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
o 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[] someParam instead of String[] args)
o 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
resides 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
o Again like C++, you can also add single line comment
Lines 7
o 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
o Line 8-9 of the program, the two braces, close the method main() and the
classHelloWorldApp respectively.
CopyrightVirtualUniversityofPakistan
35
WebDesignandDevelopment(CS506)
If program gets successfully compiled, it will create a new file in the same directory named
HelloWorldApp.class that contains the byte-code.
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
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
2.5
An Idiom Explained
About main()
o main is the function from which your program starts
o Why public?
o 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?
o Every Java program starts when the JRE (Java Run Time Environment) calls the
CopyrightVirtualUniversityofPakistan
36
WebDesignandDevelopment(CS506)
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.
o Also to ensure that there is only one copy of the main method per class
Why void?
o Indicates that main ( ) does not return anything.
2.6
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.
Note: Coding exercises in working condition for this lecture are also available on Downloads
section of LMS.
CopyrightVirtualUniversityofPakistan
37
WebDesignandDevelopment(CS506)
Strings
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,
o int i = 4;
o int j = 5;
System.out.println (Hello + i);// will print Hello 4 on screen
o However
System.out.println(i+j);//will print 9 on the console because both i and j
are of type int.
== operator compares addresses (shallow comparison) while equals compares values (deep
comparison)
o E.g. string1.equals(string2)
38
WebDesignandDevelopment(CS506)
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
3.2
CopyrightVirtualUniversityofPakistan
39
WebDesignandDevelopment(CS506)
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
3.3
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.
1 byte
2 bytes
4 bytes
8 bytes
Primitive data types are generally used for local variables, parameters and instance variables
(properties of an object)
Primitive data types 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
CopyrightVirtualUniversityofPakistan
40
WebDesignandDevelopment(CS506)
Also primitive data types are always passed by value while objects are always
passed by reference in java. There is no C++ like methods
o void someMethod(int &a, int & b ) // not available in java
3.4
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.
3.5
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.
CopyrightVirtualUniversityofPakistan
41
WebDesignandDevelopment(CS506)
The following table summarizes the parser methods available to a java programmer.
CopyrightVirtualUniversityofPakistan
42
WebDesignandDevelopment(CS506)
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.
CopyrightVirtualUniversityofPakistan
43
WebDesignandDevelopment(CS506)
3.6
The if-else and switch selection structures are exactly similar to we have in C++. All
relational operators 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++.
3.7
Reference:
Java tutorial: http://www.dickbaldwin.com/java
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.
Note: Coding exercises in working condition for this lecture are also available onDownloads
section of LMS.
CopyrightVirtualUniversityofPakistan
44
WebDesignandDevelopment(CS506)
4.1
4.1.1 Classes
4.1.2 Objects
4.1.3 Constructor
A special method that is implicitly invoked. Used to create an Object (that is,
an Instance of the Class) and to initialize it.
4.1.4 Attributes
4.1.5 Methods
4.2
Defining a Class
CopyrightVirtualUniversityofPakistan
45
WebDesignandDevelopment(CS506)
4.3
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.
o public: accessible anywhere by anyone
o private: Only accessible within this class
o protect: accessible only to the class itself and to its subclasses or other classes in
the same package.
o 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
o Primitives
Numeric (int, float etc) with zero.
Char with null
Boolean with false
o 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
o Same name as class name
o Does not have a return type
o No initialization list
CopyrightVirtualUniversityofPakistan
46
WebDesignandDevelopment(CS506)
4.4
The following example will illustrate how to write a class. We want to write a Student class that
o Roll No
o Name
Provide default, parameterized and copy constructors
o 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
4.5
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.
47
WebDesignandDevelopment(CS506)
}
}
// Standard Getters
public String getName ( ) {
return name;
}
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
4.6
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
o String greet = Hello ; // No new operator
o 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.
CopyrightVirtualUniversityofPakistan
48
WebDesignandDevelopment(CS506)
Create objects of student class by calling default parameterize and copy constructor
Call student class various methods on these objects.
CopyrightVirtualUniversityofPakistan
49
WebDesignandDevelopment(CS506)
4.7
More on Classes
4.7.1 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
CopyrightVirtualUniversityofPakistan
50
WebDesignandDevelopment(CS506)
4.7.2.1 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.
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. (Well 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;
}
}
CopyrightVirtualUniversityofPakistan
51
WebDesignandDevelopment(CS506)
// Standard Getters
public String getName ( ) {
return name;
}
public int getRollNo ( ) {
return rollNo;
}
// 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
CopyrightVirtualUniversityofPakistan
52
WebDesignandDevelopment(CS506)
Next, well write driver class. After creating two objects of student class, we deliberately
loose objects 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.
// File Test.java
public class Test{
public static void main (String args[]){ int numObjs;
// printing current number of objects i.e 0
numObjs = Student.getCountStudents();
System.out.println(Students Objects + numObjs);
// 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 + numObjs);
// 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 + numObjs);
// 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 + numObjs);
} //end of main
} //end of class
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.
CopyrightVirtualUniversityofPakistan
53
WebDesignandDevelopment(CS506)
4.8
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.
Note: Coding exercises in working condition for this lecture are also available on Downloads
section of LMS.
CopyrightVirtualUniversityofPakistan
54
WebDesignandDevelopment(CS506)
Lecture 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.
5.1
55
WebDesignandDevelopment(CS506)
//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 objects class toString method
public String toString() {
System.out.println(in employee toString method);
return "id:" + id + "name:" + name;
}
}//end class
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");
CopyrightVirtualUniversityofPakistan
56
WebDesignandDevelopment(CS506)
Output
CopyrightVirtualUniversityofPakistan
57
WebDesignandDevelopment(CS506)
5.2
The Object class in Java is a superclass for all other classes defined in Java's class
libraries, as well as for user-defined Java classes. For user defined classes, its not
necessary to mention the Object class as a super class, java does 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.
5.3
Polymorphism
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
58
WebDesignandDevelopment(CS506)
Output
CopyrightVirtualUniversityofPakistan
59
WebDesignandDevelopment(CS506)
5.4
Type Casting
In computer science, type conversion or typecasting refers to changing an entity of one data type
into another. Type casting can be categorized into two types
5.4.1 Up-casting
5.4.2 Down-casting
5.5
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.
Note: Coding exercises in working condition for this lecture are also available on Downloads
section of LMS.
Lecture 6: Collections
CopyrightVirtualUniversityofPakistan
60
WebDesignandDevelopment(CS506)
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 dont 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.
6.1
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);
6.2
Collection messages
6.3
Constructor
o creates a collection with no elements.
int size()
o returns the number of elements in a collection.
boolean add(Object)
o adds a new element in the collection.
o returns true if the element is added successfully false otherwise.
boolean isEmpty()
o returns true if this collection contains no element false otherwise.
boolean contains(Object)
o returns true if this collection contains the specified element by using iterative
search.
boolean remove(Object)
o removes a single instance of the specified element from this collection, if it is
present .
Array List
Its like a resizable array. Array List 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.
add (Object)
CopyrightVirtualUniversityofPakistan
61
WebDesignandDevelopment(CS506)
o With the help of this method, any object can be added into Array List because
Object is the superclass of all classes.
o Objects going to add will implicitly up cast.
Object get(int index)
62
WebDesignandDevelopment(CS506)
}
// 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
6.4
HashMap
Store elements in the form of key- value pair form. A key is associated with each object that is stored.
This allows fast retrieval of that object. Keys are unique.
o Keys & Values are stored in the form of objects (implicit up casting is
performed).
o Associates the specified value with the specified key in this map.
o If the map previously contained a mapping for this key, the old value is
replaced.
Object get(Object key)
CopyrightVirtualUniversityofPakistan
63
WebDesignandDevelopment(CS506)
o Returns the value to which the specified key is mapped in this identity hash
map, or null if the map contains no mapping for this key.
o Must downcast to appropriate type when used
int size( )
Output
CopyrightVirtualUniversityofPakistan
64
WebDesignandDevelopment(CS506)
6.5
References:
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 explainations 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.
Note: Coding exercises in working condition for this lecture are also available on Downloads
section of LMS.
6.6
Address Book
Warning: It is strongly advised that you have to type the code given in this example by 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.
6.6.1 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
o
o
o
o
CopyrightVirtualUniversityofPakistan
65
WebDesignandDevelopment(CS506)
The Address book should also support persistence for person records
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
WebDesignandDevelopment(CS506)
Take the example of daily life; generally address book is used to store more than one
person records and we dont 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.
Array List 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
WebDesignandDevelopment(CS506)
} // 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);
}
}
}
} // 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 then 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 objects 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.
6.6.2.3 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
68
WebDesignandDevelopment(CS506)
6.7
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.
Note: Coding exercises in working condition for this lecture are also available on Downloads
section of LMS.
69
WebDesignandDevelopment(CS506)
7.1
Types of Errors
Generally, you can come across three types of errors while developing software. These are
Syntax, Logic & Runtime errors.
Indicates that logic used for coding doesnt produce expected output.
7.2
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
7.3
7.4
Exceptions in Java
An exception in java is represented as an object thats created when an abnormal
CopyrightVirtualUniversityofPakistan
70
WebDesignandDevelopment(CS506)
7.5
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
7.6
Types of Exceptions
Exceptions can be broadly categorized into two types, Unchecked & Checked Exceptions.
CopyrightVirtualUniversityofPakistan
71
WebDesignandDevelopment(CS506)
7.7
Java handles exceptions via 5 keywords. Try, catch, finally, throw & throws.
The basic structure of using try - catch - finally block is shown in the picture below:
CopyrightVirtualUniversityofPakistan
72
WebDesignandDevelopment(CS506)
7.7.4 throw
To manually throw an exception, keyword throw is used. Note: we are not covering throw
clause in this handout
7.7.5 throws
7.8
7.9
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
CopyrightVirtualUniversityofPakistan
73
WebDesignandDevelopment(CS506)
7.9.2 Why?
Since we have passed no argument, therefore the 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]);
CopyrightVirtualUniversityofPakistan
74
WebDesignandDevelopment(CS506)
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.
CopyrightVirtualUniversityofPakistan
75
WebDesignandDevelopment(CS506)
// 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( IOException ex) {
System.out.println(ex);
}
}
}
The code line written inside the catch block will print the exception name on the console if
exception occurs
76
WebDesignandDevelopment(CS506)
{
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( IOException ex) {
System.out.println(ex);
}
finally {
System.out.println(finally block always execute);
}
}
}
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
CopyrightVirtualUniversityofPakistan
77
WebDesignandDevelopment(CS506)
CopyrightVirtualUniversityofPakistan
78
WebDesignandDevelopment(CS506)
If numbers.txt present in the same directory and contains a number, than hopefully no exception
would be thrown.
79
WebDesignandDevelopment(CS506)
Modify: ThrowsDemo.java
Let method2 doesnt 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 IOException{
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(); }
}
CopyrightVirtualUniversityofPakistan
80
WebDesignandDevelopment(CS506)
If file strings.txt exist there, than hopefully line would be displayed on the console.
7.15 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.
Note: Coding exercises in working condition for this lecture are also available on Downloads
section of LMS.
CopyrightVirtualUniversityofPakistan
81
WebDesignandDevelopment(CS506)
Lecture 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.
8.1
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.)
CopyrightVirtualUniversityofPakistan
82
WebDesignandDevelopment(CS506)
8.2
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.
CopyrightVirtualUniversityofPakistan
83
WebDesignandDevelopment(CS506)
8.3
CopyrightVirtualUniversityofPakistan
84
WebDesignandDevelopment(CS506)
// 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);
CopyrightVirtualUniversityofPakistan
85
WebDesignandDevelopment(CS506)
8.4
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.
CopyrightVirtualUniversityofPakistan
86
WebDesignandDevelopment(CS506)
8.5
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. Persons 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:
CopyrightVirtualUniversityofPakistan
87
WebDesignandDevelopment(CS506)
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). Thats 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
CopyrightVirtualUniversityofPakistan
88
WebDesignandDevelopment(CS506)
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 thats 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);
The last step we have done inside loop is that we have again read a line from the file by
CopyrightVirtualUniversityofPakistan
89
WebDesignandDevelopment(CS506)
public AddressBook () {
Persons = new ArrayList();
loadPersons();
}
AddressBook.java
90
WebDesignandDevelopment(CS506)
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 strings local variable line as shown in the following line
of code.
line = p.name +","+ p.address +","+ p.phoneNum;
The next step is to write the line representing one PersonInfo objects information, to
the file. This is done by using println method of PrintWriter as shown below
pw.println(line);
After writing line to the file, the println method will move the cursor/control to the next
line. Thats 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
CopyrightVirtualUniversityofPakistan
91
WebDesignandDevelopment(CS506)
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.
case 4:
ab.savePersons();
System.exit(0);
Test.java
8.6
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.
Note: Coding exercises in working condition for this lecture are also available on Downloads
section of LMS.
CopyrightVirtualUniversityofPakistan
92
WebDesignandDevelopment(CS506)
Before moving on to abstract classes, first examine the following class hierarchy shown
below:
Suppose that in order to exploit polymorphism, we specify that 2-D objects must be able to
compute their area.
o All 2-D classes must respond to area() message.
9.2
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 fully 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 superclass, than it becomes a concrete (a class
whose object can be instantiate) class otherwise we have to declare it as abstract or we cannot
compile it.
CopyrightVirtualUniversityofPakistan
93
WebDesignandDevelopment(CS506)
The most important aspect of abstract class is that reference of an abstract class can point to the
object of concrete classes.
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();
CopyrightVirtualUniversityofPakistan
94
WebDesignandDevelopment(CS506)
s.calculateArea();
}
}//end of class
The compilation and execution of the above program is shown below:
9.3
Interfaces
As we seen one possible javas solution to problem discussed in start of the tutorial. The second
possible javas solution is Interfaces.
Interfaces are special java type which contains only a set of method prototypes, but does not provide
the implementation for these prototypes. All the methods inside an interface are abstract by default
thus an interface is tantamount to a pure abstract class - a class with zero implementation. Interface
can also contains static final constants
95
WebDesignandDevelopment(CS506)
Class Student is implementing the interface Printable. 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 code snippet of student class is given below:
public class Student implements Printable {
private String name;
private String address;
public String toString () {
return "name:"+name +" address:"+address;
}
//providing definition of interfaces print method
public void print() {
System.out.println("Name:" +name+" address"+address);
}
}//end of class
9.4
Interface Characteristics
Similar to abstract 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 javas way of multiple inheritance.
class Circle implements Drawable , Printable { . }
Objects of 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.
CopyrightVirtualUniversityofPakistan
96
WebDesignandDevelopment(CS506)
args[ ]) {
to Politician");
to Coach");
to Lecturer");
CopyrightVirtualUniversityofPakistan
97
WebDesignandDevelopment(CS506)
9.5
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.
Note: Coding exercises in working condition for this lecture are also available on Downloads
section of LMS.
98
WebDesignandDevelopment(CS506)
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.
99
WebDesignandDevelopment(CS506)
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.
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.
100
WebDesignandDevelopment(CS506)
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();
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
Container 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.
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( ) );
CopyrightVirtualUniversityofPakistan
101
WebDesignandDevelopment(CS506)
After creating all components you 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);
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 JFrames are invisible. To make visible frame visible we have passed true
to the setVisible method.
frame.setVisible(false) ;
102
WebDesignandDevelopment(CS506)
// File GUITest.java
//Step 1: import packages
import java.awt.*;
import javax.swing.*;
public class GUITest {
JFrame myFrame ;
//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
103
WebDesignandDevelopment(CS506)
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, youll notice that
the control doesnt return back to command prompt. The reason for this is that the java process is
still running. However if you put this line in your code, when you exit your prompt will return.
10.8 References:
Flow Layout
Grid Layout
Border Layout
Box Layout
Card Layout
GridBag Layout and so on
CopyrightVirtualUniversityofPakistan
104
WebDesignandDevelopment(CS506)
Let us discuss the top three in detail one by one with code examples. These top three will meet most
of your basic needs
10.9.1.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 ( ) {
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();
CopyrightVirtualUniversityofPakistan
105
WebDesignandDevelopment(CS506)
}
} // end of class
Output
10.9.1.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);
CopyrightVirtualUniversityofPakistan
106
WebDesignandDevelopment(CS506)
c.add(b4);
c.add(b5);
myFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
myFrame.setSize(300,150);
myFrame.setVisible(true);
} //end initGUI method
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.
CopyrightVirtualUniversityofPakistan
107
WebDesignandDevelopment(CS506)
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.
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);
CopyrightVirtualUniversityofPakistan
108
WebDesignandDevelopment(CS506)
c.add( b1 , BorderLayout.NORTH );
c.add( b2 , BorderLayout.SOUTH );
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:
CopyrightVirtualUniversityofPakistan
109
WebDesignandDevelopment(CS506)
This GUI has 16 different buttons each of same size and text field on the top and a label my
calculator on the bottom.
So, how we can make this GUI? If Border Layout is selected, it has five regions (each region can
have at most one component) but here we have more than five components to add. Lets try Grid
Layout, but all the components in a Grid have same size and the text field at the top and label at
the bottom has different size. Flow Layout cannot be selected because if we stretch our GUI it will
destroy its shape.
Can we make this GUI? Yes, we can. Making of such GUI is a bit tricky business but General
Purpose Containers are there to provide the solution.
10.10.1 JPanel
It is general purpose container (cant exist alone, it has to be in some toplevel container)
in which we can put in different components (JButton , JTextField etc even other JPanels)
JPanel has its own layout that can be set while creating JPanel instance
JPanel myPanel = new JPanel ( new FlowLayout( ) );
Must be added to a top level container (like JFrame etc) in order to be visible as
they (general purpose containers) cant exist alone.
10.10.2 Solution
To make the calculator GUI shown above, take JFrame (top level container) and set its layout to
border. Then take JPanel (general purpose container) and set its layout to Grid with 4 rows and 4
columns.
Add buttons to JPanel as they all have equal size and JPanel layout has been set to
CopyrightVirtualUniversityofPakistan
110
WebDesignandDevelopment(CS506)
GridLayout. Afterthat, add text field to the north region, label to the south region and
panel to the center region of the JFrames container. The east and west regions are left
blank and the center region will be stretched to cover up these. So, thats how we can build our
calculator GUI.
111
WebDesignandDevelopment(CS506)
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 ();
}
public static void main (String args[ ]) {
CalculatorGUI calGUI = new CalculatorGUI ();
}
} // end of class
10.11 Reference:
Note: Coding exercises in working condition for this lecture are also available on Downloads
section of LMS.
CopyrightVirtualUniversityofPakistan
112
WebDesignandDevelopment(CS506)
Clicking a button
Moving the mouse
Closing Window etc
java.awt.event.*;
javax.swing.event.*;
CopyrightVirtualUniversityofPakistan
113
WebDesignandDevelopment(CS506)
CopyrightVirtualUniversityofPakistan
114
WebDesignandDevelopment(CS506)
Some Example Listeners, the way they are defined in JDK by Sun
public interface ActionListener {
public void actionPerformed(ActionEvent e);
}
CopyrightVirtualUniversityofPakistan
115
WebDesignandDevelopment(CS506)
public
public
public
public
public
}
interface ComponentListener {
void componentHidden(ComponentEvent e);
void componentMoved(ComponentEvent e);
void componentResized(ComponentEvent e);
void componentShown(ComponentEvent e);
o 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.
o Inside the method the class can do whatever it wants to do with that event
o Event Generator and Event Handler can be the same or different classes
o 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
}
}
The event generator is told about the object which can handle its events
Event Generators have a method
CopyrightVirtualUniversityofPakistan
116
WebDesignandDevelopment(CS506)
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 ActionListener{
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");
/* 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 ActionListeners
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
CopyrightVirtualUniversityofPakistan
117
WebDesignandDevelopment(CS506)
Encapsulate information about event that occurred and the source of that event
For example, if you click a button, ActionEvent object is created
11.4.4 JVM
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:
CopyrightVirtualUniversityofPakistan
118
WebDesignandDevelopment(CS506)
CopyrightVirtualUniversityofPakistan
119
WebDesignandDevelopment(CS506)
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(200, 220);
frame.setVisible(true);
}
//constructor
public SmallCalcApp ( ) {
initGUI();
}
120
WebDesignandDevelopment(CS506)
Note: Coding exercises in working condition for this lecture are also available on Downloads
section of LMS.
CopyrightVirtualUniversityofPakistan
121
WebDesignandDevelopment(CS506)
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.
Used for processing interesting mouse events like when mouse is:
o
o
o
o
o
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)
interface MouseListener {
void mousePressed (MouseEvent me);
void mouseClicked (MouseEvent me);
void mouseReleased (MouseEvent me);
void mouseEntered (MouseEvent me);
void mouseExited (MouseEvent me); }
CopyrightVirtualUniversityofPakistan
122
WebDesignandDevelopment(CS506)
CopyrightVirtualUniversityofPakistan
123
WebDesignandDevelopment(CS506)
But, what if we want to display some message (Good Bye) before exiting?
How?
public
public
public
public
public
public
public
public
}
interface WindowListener {
void windowActivated(WindowEvent we);
void windowClosed(WindowEvent we);
void windowClosing(WindowEvent we);
void windowDeactivated(WindowEvent we);
void windowDeiconified(WindowEvent we);
void windowIconified(WindowEvent we);
void windowOpened(WindowEvent we);
CopyrightVirtualUniversityofPakistan
124
WebDesignandDevelopment(CS506)
JFrame frame;
JLabel coordinates;
setting layout
public void initGUI ( ) {
125
WebDesignandDevelopment(CS506)
32.
33.
34.
35.
36.
37.
38.
39.
40.
41.
42.
43.
44.
45.
}
}
}
Note: Coding exercises in working condition for this lecture are also available on Downloads
section of LMS.
CopyrightVirtualUniversityofPakistan
126
WebDesignandDevelopment(CS506)
Solution
For listener interfaces containing more than one event handling methods, jdk defines
adapter classes. Examples are
o For WindowListener WindowAdapter
o For MouseMotionListener MouseMotionAdapter
o 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
MouseMotionListener interface
CopyrightVirtualUniversityofPakistan
127
WebDesignandDevelopment(CS506)
Therefore it has to provide definitions of all the methods inside that interface 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.
we do not have to provide implementations of all the methods again
We only need to override our method of interest.
128
WebDesignandDevelopment(CS506)
24.
25.
26.
27.
Problem
Solution
CopyrightVirtualUniversityofPakistan
129
WebDesignandDevelopment(CS506)
Generally used as a private utility class which does not need to be seen by others
classes
import
import
import
public
java.awt.*;
javax.swing.*;
java.awt.event.*;
class EventEx {
5. JFrame frame;
6. JLabel coordinates;
7. // setting layout
8. public void initGUI ( ) {
9. frame = new JFrame();
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
window events and registering it with generator
*/
14. WindowHandler handler = new WindowHandler ();
15. frame.addWindowListener(handler);
16. frame.setSize(350, 350);
17. frame.setVisible(true);
18. } // end initGUI
//default constructor
19. public EventEx ( ) {
CopyrightVirtualUniversityofPakistan
130
WebDesignandDevelopment(CS506)
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. }
27. } // end of WindowHandler class
28. public static void main(String args[]) {
29. EventEx e = new EventEx();
30. }
31. } // end class
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.*;
2.
import javax.swing.*;
3.
import java.awt.event.*;
4.
public class EventEx {
5. JFrame frame;
6. JLabel coordinates;
7. // setting layout
8. public void initGUI ( )
{
9. frame = new JFrame();
10. Container cont = frame.getContentPane();
CopyrightVirtualUniversityofPakistan
131
WebDesignandDevelopment(CS506)
CopyrightVirtualUniversityofPakistan
132
WebDesignandDevelopment(CS506)
1. import java.awt.*;
2. import javax.swing.*;
3. import java.awt.event.*;
4. public class SmallCalcApp{
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);
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);
CopyrightVirtualUniversityofPakistan
133
WebDesignandDevelopment(CS506)
28. cont.add(plus);
29. cont.add(mul);
30. cont.add(answer);
31. cont.add(ans);
/* Creating an object of the class which is handling
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. }
39. //constructor
40. public SmallCalcApp ( ) {
41. initGUI();
42. }
//Inner class implementation of ActionListener
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+"";
54. ans.setText(result);
55 }
56. else if (event.getSource() == mul) {
57. oper = op1.getText();
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 }
65. } // end actionPerformed method
66. } // end inner class ButtonHandler
67. public static void main(String args[]) {
68. SmallCalcApp scApp = new SmallCalcApp();
69. }
70. }// end class
CopyrightVirtualUniversityofPakistan
134
WebDesignandDevelopment(CS506)
has no name
same as inner class in capabilities
much shorter
Difficult to understand
String s = hello;
System.out.println(s);
hello has a named reference s.
13.5.2 Anonymous
System.out.println(hello);
We generally use anonymous object when there is just a onetime 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.
import
import
import
public
java.awt.*;
javax.swing.*;
java.awt.event.*;
class EventsEx extends WindowAdapter {
135
WebDesignandDevelopment(CS506)
By implementing Interfaces
By extending from Adapter classes
Same class
o putting event handler & generator in one class
Separate class
o Outer class
Putting event handlers & generator in two different classes
o Inner classes
o Anonymous Inner classes
13.7 References
Java A Lab Course by Umair Javed
Note: Coding exercises in working condition for this lecture are also available on Downloads
section of LMS.
CopyrightVirtualUniversityofPakistan
136
WebDesignandDevelopment(CS506)
CopyrightVirtualUniversityofPakistan
137
WebDesignandDevelopment(CS506)
Save the data base in some folder. (Your database will be saved as an .mdb file)
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:
CopyrightVirtualUniversityofPakistan
138
WebDesignandDevelopment(CS506)
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.
CopyrightVirtualUniversityofPakistan
139
WebDesignandDevelopment(CS506)
Import the package java.sql.* that contains useful classes and interfaces to
access & work with database.
import java.sql.*;
CopyrightVirtualUniversityofPakistan
140
WebDesignandDevelopment(CS506)
The next step is to pass the SQL statements & to execute them.
Two methods are generally used for executing SQL queries. These are:
o executeQuery(sql) method
Used for SQL SELECT queries.
Returns the ResultSET object that contains the results of the query and
can be used to access the query results.
String sql
= SELECT * from sometable;
ResultSet rs = stmt.executeQuery(sql);
o executeUpdate(sql) method
This method is used for executing an update statement like INSERT,
UPDATE or DELETE
Returns an Integer value representing the number of rows updated
String sql = INSERT INTO tablename +
(columnNames) Values (values) ;
int count = stmt.executeUpdate(sql);
The ResultSet provides various getXXX methods that takes a column index
or name and returns the data
The ResultSet 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() ){
String name = rs.getString(columnName); //by using column name
String name = rs.getString(1); // or by using column index }
CopyrightVirtualUniversityofPakistan
141
WebDesignandDevelopment(CS506)
142
WebDesignandDevelopment(CS506)
14.5 References:
Note: Coding exercises in working condition for this lecture are also available on Downloads
section of LMS.
CopyrightVirtualUniversityofPakistan
143
WebDesignandDevelopment(CS506)
144
WebDesignandDevelopment(CS506)
CopyrightVirtualUniversityofPakistan
145
WebDesignandDevelopment(CS506)
The Person table is shown in the following diagram after the execution of the
program. Notice that address of the ali is now changed to defence.
Note
When we execute DML statements (insert, update, delete) we have to commit it in the
database explicitly to make the changes permanent or otherwise we can rollback the
previously executed statements.
But in the above code, you have never seen such a statement. This is due to the fact that java will
implicitly commit the changes. However, we can change this java behavior to manual commit.
We will cover these in some later handout.
Retrieves the number of seconds the driver will wait for a Statement object to
execute.
The current query time out limit in seconds, zero means there is no limit
If the limit is exceeded, a SQLException is thrown
15.2.1 Statement
The Statement objects are used for executing simple SQL statements.
CopyrightVirtualUniversityofPakistan
146
WebDesignandDevelopment(CS506)
15.2.2 PreparedStatement
The PreparedStatement are used for executing precompiled SQL statements and passing in
different parameters to it.
We will talk about it in detail shortly.
15.2.3 CallableStatement
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.
We can create PreparedStatement object by using prepareStatement
method of the connection class. The SQL query is passed to this method as an
argument as shown below.
PreparedStatement pStmt = con.prepareStatement (
UPDATE tableName SET columnName =
? + WHERE columnName = ? );
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 int value, we use setInt method. This is shown in the
following code snippet:
pStmt.setString (1 , stringValue);
pStmt.setInt
(2 , intValue)
CopyrightVirtualUniversityofPakistan
147
WebDesignandDevelopment(CS506)
148
WebDesignandDevelopment(CS506)
15.3 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.
Note: Coding exercises in working condition for this lecture are also available on Downloads
section of LMS.
CopyrightVirtualUniversityofPakistan
149
WebDesignandDevelopment(CS506)
16.1 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.
Until now, we have worked & used it in various examples.
For a quick overview, here how we create a default ResultSet object.
String sql = SELECT * FROM Person;
PreparedStatement pStmt = con.prepareStatement(sql);
ResultSet rs = pStmt.executeQuery( );
CopyrightVirtualUniversityofPakistan
150
WebDesignandDevelopment(CS506)
Before retrieving any data from ResultSet, always remember to call next()at
least once because initially cursor is positioned before first row.
16.1.2.2 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:
String name = rs.getString(Name);
String name = rs.getString(3);
These getter methods are also available for other types like getInt(
), getDouble( ) etc.
Consult the Java API documentation for more references.
Note: Remember that first column has an index 1, NOT zero (0).
16.1.2.3 close( )
It is possible to produce ResultSet objects that are scrollable and/or updatable (since JDK
1.2)
With the help of such ResultSet, it is possible to move forward as well as backward with in
ResultSet object.
Another advantage is, rows can be inserted, updated or deleted by using updatable
ResultSet object.
151
WebDesignandDevelopment(CS506)
16.1.2.6 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.
// File ResultSetEx.java
import java.sql.*;
public class ResultSetEx {
public static void main (String args[ ]) {
try {
//Step 2: load driver
Class.forName(sun.jdbc.odbc.JdbcOdbcDriver);
CopyrightVirtualUniversityofPakistan
152
WebDesignandDevelopment(CS506)
16.1.2.7 absolute(int)
Moves the cursor to the given row number in the ResultSet object.
If given row number is positive, moves the cursor forward with respect to beginning of the
result set.
If the given row number is negative, the cursor moves to the absolute row position with
respect to the end of the result set.
For example, calling absolute(-1) positions the cursor on the last row; calling absolute(-2)
moves the cursor to next-to-last row, and so on.
Throws Exception if ResultSet type is TYPE_FORWARD_ONLY
Used to update the column values in the current row or in insert row (discuss later)
Do not update the underlying database
CopyrightVirtualUniversityofPakistan
153
WebDesignandDevelopment(CS506)
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)
16.1.2.9 updateRow( )
Updates the underlying database with new contents of the current row of this ResultSet
object
CopyrightVirtualUniversityofPakistan
154
WebDesignandDevelopment(CS506)
16.1.2.10moveToInsertRow(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.
Doesnt insert the row into a result set or into a database.
For example, initially cursor is positioned on the first row as shown in the diagram:
CopyrightVirtualUniversityofPakistan
155
WebDesignandDevelopment(CS506)
Now, by calling various updaters, we can insert values into the columns of insert row as
shown below.
16.1.2.11 insertRow( )
Inserts the contents of the current row into this ResultSet object and into the database too.
Moves the cursor back to the position where it was before calling
moveToInsertRow()
This is shown in the given below diagram
Note: The cursor must be on the insert row before calling this method or exception
would be raised.
156
WebDesignandDevelopment(CS506)
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,
ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_UPDATABLE);
18.//Step 6: execute the query
19.ResultSet rs = pStmt.executeQuery();
20. // moving cursor to insert row
21. rs.moveToInsertRow();
22. // updating values in insert row
23. rs.updateString( Name
,
imitiaz );
24. rs.updateString( Address ,
cantt
);
25. rs.updateString( phoneNum ,
9201211 );
26. // inserting row in resultset & into database
27. rs.insertRow( );
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
CopyrightVirtualUniversityofPakistan
157
WebDesignandDevelopment(CS506)
Moves the cursor to the last & first row of the ResultSet object respectively.
Throws exception if the ResultSet is TYPE_FORWARD_ONLY
16.1.2.13 getRow( )
16.1.2.14 deleteRow( )
Deletes the current row from this ResultSet object and from the underlying database.
Throws exception if the cursor is on the insert row.
CopyrightVirtualUniversityofPakistan
158
WebDesignandDevelopment(CS506)
), getRow( )and
This code is also the modification of the last one. Changes made are shown in bold face.
1.
2.
3.
4.
5.
// File ResultSetEx.java
import java.sql.*;
public class ResultSetEx {
public static void main (String args[ ]) {
try {
6.
7.
8.
9.
10.
11.
12.
13.
14.
//
ResultSet appropriate fields
String sql =
SELECT * FROM Person;
15.
16.
17.
ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_UPDATABLE);
18.
19.
20.
21.
22.
23.
24.
25.
26.
27.
28.
CopyrightVirtualUniversityofPakistan
159
WebDesignandDevelopment(CS506)
29.
30.
31.
32.
con.close();
}catch(Exception sqlEx){
System.out.println(sqlEx);
}
33.
} // end main
34.
} // end class
After execution, the last row (4) is deleted from ResultSet as well as from
database. The Person table is shown after execution
CopyrightVirtualUniversityofPakistan
160
WebDesignandDevelopment(CS506)
16.2 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.
Note: Coding exercises in working condition for this lecture are also available on Downloads
section of LMS.
CopyrightVirtualUniversityofPakistan
161
WebDesignandDevelopment(CS506)
162
WebDesignandDevelopment(CS506)
Returns the SQL type for the column to compare against types in java.sql.Types
// File MetaDataEx.java
import java.sql.*;
public class MetaDataEx {
public static void main (String args[ ]) {
try {
//Step 2: load driver
Class.forName(sun.jdbc.odbc.JdbcOdbcDriver);
//Step 3: define the connection URL
String url = jdbc:odbc:personDSN;
//Step 4: establish the connection
Connection con = null;
con = DriverManager.getConnection(url, , );
//Step 5: create PrepareStatement by passing sql and
//
ResultSet appropriate fields
String sql =
SELECT * FROM Person;
CopyrightVirtualUniversityofPakistan
163
WebDesignandDevelopment(CS506)
CopyrightVirtualUniversityofPakistan
164
WebDesignandDevelopment(CS506)
17.2 DatabaseMetaData
Database Meta Data will help you in answering such questions
CopyrightVirtualUniversityofPakistan
165
WebDesignandDevelopment(CS506)
Now, you can use the dbMetaData to gain information about the database.
CopyrightVirtualUniversityofPakistan
166
WebDesignandDevelopment(CS506)
125.
126.
127.
128.
System.out.println(Driver: + dName);
// printing whether database is read-only or not
boolean rOnly = dbMetaData.isReadOnly();
System.out.println(Read-Only: + rOnly);
129.
130.
131.
132.
133.
134.
135.
136.
137.} //
CopyrightVirtualUniversityofPakistan
167
WebDesignandDevelopment(CS506)
Translates all JDBC calls into ODBC (Open Database Connectivity) calls and
send them to the ODBC Driver
Generally used for Microsoft database.
Performance is degraded
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.
CopyrightVirtualUniversityofPakistan
168
WebDesignandDevelopment(CS506)
Converts JDBC calls into the vendor-specific DBMS protocol so that client
application can communicate directly with the database server
Completely implemented in Java to achieve platform independence and eliminate
deployment issues.
Performance is typically very good
17.5 References:
Note: Coding exercises in working condition for this lecture are also available on Downloads
section of LMS.
CopyrightVirtualUniversityofPakistan
169
WebDesignandDevelopment(CS506)
CopyrightVirtualUniversityofPakistan
170
WebDesignandDevelopment(CS506)
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.
The following figure shows the situation when myApps JPanel calls its repaint method. Notice
that some portion of window explorer is still remains in front of JButton because yet not repaint event
is sent to it.
CopyrightVirtualUniversityofPakistan
171
WebDesignandDevelopment(CS506)
Next, JPanel forwards repaint event to JButton that causes the button to be displayed in its
original form.
This is all done automatically and we cannot feel this process cause of stunning speed of modern
computers that performs all these steps in flash of eye.
172
WebDesignandDevelopment(CS506)
18.1.2.2 paintBorder( )
18.1.2.3 paintChildren( )
The figure above illustrates the order in which each component that inherits from
JComponent paint itself.
Figure 1 to 2 -painting the background and performing custom painting is performed by the
paintComponent method
In Figure 3 - paintBorder is get called
CopyrightVirtualUniversityofPakistan
173
WebDesignandDevelopment(CS506)
And finally in figure 4 - paintChildern is called that causes the JButton to render itself.
Note: The important thing to note here is for JButton (since it is a JComponent), all these methods
are also called in the same order.
Subclass JPanel
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
174
WebDesignandDevelopment(CS506)
175
WebDesignandDevelopment(CS506)
What to do to move the shapes present in example code 18.1 (last example) when a mouse
is dragged
First time painting is what we already have done
When a mouse is clicked find the co-ordinates of that place and paint Rectangle at that
place by requesting, using repaint() call
Here instead of Hard-coding the position of co-ordinates uses some variables. For example
mx , my
o In the last example code, we draw a rectangle by passing hard-coded values like
20
g.drawRect(20,20,20,20);
o Now, well use variables so that change in a variable value causes to display a
rectangle at a new location
g.drawRect(mx,my,20,20);
Similarly, you have seen a tennis game (during lecture). Now, what to do code the paddle
movement.
In the coming up example. We are doing it using mouse, try it using mouse.
CopyrightVirtualUniversityofPakistan
176
WebDesignandDevelopment(CS506)
177
WebDesignandDevelopment(CS506)
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// creating inner class object
Handler h = new Handler();
// registering MyPanel to handle events
p.addMouseMotionListener(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
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 sync 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
super.paintComponent(g);
Dragging a mouse will produce a similar kind of output shown next
CopyrightVirtualUniversityofPakistan
178
WebDesignandDevelopment(CS506)
179
WebDesignandDevelopment(CS506)
MyPanel p;
// used to control the direction of ball
int x, y;
public AnimTest(){
f = new JFrame();
Container c = f.getContentPane();
c.setLayout(new BorderLayout());
x = 5;
y = 3;
p = new MyPanel(); c.add(p);
f.setSize(400,400);
f.setVisible(true);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// creating a Timer class object, used for firing
// one or more action events after a specified delay
// Timer class constructor requires time in
// milliseconds and object of class that handles
// action events
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){
// if ball reached to maximum width of frame minus
// 40 since diameter of ball is 40 then change the
// X-direction of ball
if (f.getWidth()-40 == p.mX)
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 MyPanels mX & mY
p.mX += x;
p.mY += y;
// call to repaint() method so that ball is drawn on
CopyrightVirtualUniversityofPakistan
180
WebDesignandDevelopment(CS506)
// new locations
p.repaint();
} // end actionPerformed() method
// main method
public static void main(String args[ ]){
AnimTest at = new AnimTest();
}
} // end AnimTest class
19.2 References
Note: Coding exercises in working condition for this lecture are also available on Downloads
section of LMS.
CopyrightVirtualUniversityofPakistan
181
WebDesignandDevelopment(CS506)
Most modern browsers support Java 1.4 if they have the appropriate plugin
Sun provides an application appletviewer to view applets without using browser.
In general you should try to write applets that can be run with any browser
CopyrightVirtualUniversityofPakistan
182
WebDesignandDevelopment(CS506)
CopyrightVirtualUniversityofPakistan
183
WebDesignandDevelopment(CS506)
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 looks like this:
appletviewer Test.html
As a result, you will see the following output
The applets life cycle methods are called in the specific order shown below. Not every applet
needs to override every one of these methods.
CopyrightVirtualUniversityofPakistan
184
WebDesignandDevelopment(CS506)
Lets take a look on each method in detail and find out what they do:
20.5.1 init( )
20.5.2 start( )
20.5.3 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( )
20.5.4 stop( )
To stop the applet's execution, such as when the user leaves the applet's page or quits the
browser.
stop( ) is also called whenever the browser is minimized
CopyrightVirtualUniversityofPakistan
185
WebDesignandDevelopment(CS506)
20.5.5 destroy( )
186
WebDesignandDevelopment(CS506)
Design Process
The Program in a single call of paint method
o Draws string java on 40 random locations
o For every drawing, it selects random font out of 4 different fonts
o For every drawing, it selects random color out of 256 * 256 * 256 RGB colors
CopyrightVirtualUniversityofPakistan
187
WebDesignandDevelopment(CS506)
Returns positive double value greater than or equal to 0.0 or less than 1.0.
Multiply the number with appropriate scaling factor to increase the range and type cast it,
if needed.
o int i = (int)( Math.random() * 5 ); // will generate random numbers between 0 & 4.
Programs Modules
The program is build using many custom methods. Lets discuss each of them one
by one that will help in understanding the 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:
// method drawJava
public void drawJava(Graphics2D g2) {
// generate first number randomly. The panel width is 1000
int 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 selected numbers
g2.drawString("java", x, y);
}
chooseColor( )
This method will choose color randomly out of 256 * 256 * 256 possible colors. The code
snippet is given below:
// method chooseColor
public Color chooseColor() {
CopyrightVirtualUniversityofPakistan
188
WebDesignandDevelopment(CS506)
chooseFont( )
This method will choose a Font for text (java) to be displayed out of 4 available fonts. The code
snippet is given below:
// method chooseFont
public Font chooseFont() {
// generating a random value that helps in choosing a font
int fontChoice = (int) (Math.random() * 4) + 1;
// declaring font reference
Font f = null;
// using switch based logic for selecting font
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);
CopyrightVirtualUniversityofPakistan
189
WebDesignandDevelopment(CS506)
break;
} // end switch
// returns Font object
return f;
} //end chooseFont
paint( )
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.
Lets see, how it happens:
// overriding method paint
public void paint(Graphics g) {
// incrementing clear counter variable.
clearCounter++;
// printing 40 java strings on different locations by
// selcting random font & color
for (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);
// drawing string java by calling drawJava() method
drawJava(g2);
}
// end for loop
Graphics2D g2 = (Graphics2D) g;
// checking if paint is called 10 times then clears the
// screen and set counter again to zero
if (clearCounter == 10) {
g2.clearRect(0, 0, 1000, 700);
clearCounter = 0;
}
} // end paint method
CopyrightVirtualUniversityofPakistan
190
WebDesignandDevelopment(CS506)
Merging Pieces
By inserting all method inside JavaAnim.java class, the program will look like one given below.
Notice that it contains methods discussed above with some extra code with which you are already
familiar.
// File JavaAnim.java
//step 1: importing required packages
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class JavaAnim extends JApplet implements ActionListener {
// used to count how many times paint is called
int clearCounter;
// declaring Timer reference
Timer t;
// overriding init method, used to initialize variables
public void init() {
setBackground(Color.black);
clearCounter = 0;
Timer t = new Timer(1000, this);
t.start();
}
// overriding paint method - discussed above
public void paint(Graphics g) {
clearCounter++;
Graphics2D g2 = (Graphics2D) g;
if (clearCounter == 10) {
g2.clearRect(0, 0, 1000, 700); clearCounter = 0;
}
for (int i = 1; i <= 40; i++) {
Color c = chooseColor(); g2.setColor(c);
Font f = chooseFont(); g2.setFont(f);
drawJava(g2);
}
}
// overriding actionPerformed()of ActionListener interface
// called by Timer object
public void actionPerformed(ActionEvent ae) {
CopyrightVirtualUniversityofPakistan
191
WebDesignandDevelopment(CS506)
repaint();
}
// chooseColor method - discussed above
public Color chooseColor() {
int r = (int) (Math.random() * 255);
int g = (int) (Math.random() * 255);
int b = (int) (Math.random() * 255);
Color c = new Color(r, g, b);
return c;
} // chooseFont method - discussed above
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;
}
// 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);
}
} // end class
The AnimTest.html file is using this applet. The code snippet of it given below:
<html>
<head>
<title> Animated Java Word </title> </head>
CopyrightVirtualUniversityofPakistan
192
WebDesignandDevelopment(CS506)
<body>
<applet code="JavaAnim.class" width=1000 height=700> </applet>
</body>
</html>
20.6 References:
Note: Coding exercises in working condition for this lecture are also available on Downloads
section of LMS.
CopyrightVirtualUniversityofPakistan
193
WebDesignandDevelopment(CS506)
As you have already worked with files, you know that file is an abstraction of your
hard drive. Similarly you can think of a socket as an abstraction of the network.
Each end has input stream (to send data) and output stream (to receive data) wired up
to the other host.
You store and retrieve data through files from hard drive, without knowing the actual
dynamics of the hard drive. Similarly you send and 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 use streams.
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.
CopyrightVirtualUniversityofPakistan
194
WebDesignandDevelopment(CS506)
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.
If everything goes well, the server accepts the connection. Upon acceptance, the
server gets a new socket, a communication socket, bound to a different port number.
The server needs a new socket (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 needs of the connected client. This scheme is helpful when two or more
clients try to connect to a server simultaneously (a very common scenario).
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.
java.net.*;
java.io.*;
CopyrightVirtualUniversityofPakistan
195
WebDesignandDevelopment(CS506)
The scheme is very similar to our home address and then phone number.
To send messages
pw.println(hello world);
To read messages
String recMsg = br.readLine();
CopyrightVirtualUniversityofPakistan
196
WebDesignandDevelopment(CS506)
java.net.*;
java.io.*;
serverPort: 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
CopyrightVirtualUniversityofPakistan
197
WebDesignandDevelopment(CS506)
To send messages:
pw.println(hello world);
To read messages
String recMsg = br.readLine();
198
WebDesignandDevelopment(CS506)
199
WebDesignandDevelopment(CS506)
CopyrightVirtualUniversityofPakistan
200
WebDesignandDevelopment(CS506)
Now, open another command prompt window and run EchoClient.java from it. Look at
EchoServer window; youll see the message of request received. Sooner, the
EchoClient program will ask you to enter name in input dialog box. After entering name
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:
CopyrightVirtualUniversityofPakistan
201
WebDesignandDevelopment(CS506)
21.7 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.
Note: Coding exercises in working condition for this lecture are also available on Downloads
section of LMS.
CopyrightVirtualUniversityofPakistan
202
WebDesignandDevelopment(CS506)
22.1.2 Motivation
203
WebDesignandDevelopment(CS506)
As you have seen a lot of parsing code is required for converting a line into PersonInfo
objects. Serialization mechanism eases developers life by achieving all above in a very
simple way.
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 and writes it too.
System knows how to read the data from Stream and re-create object in memory
The recreated object is of type Object therefore Down-casting is required to convert
it into actual type.
To read that
will be used
object
back,
CopyrightVirtualUniversityofPakistan
ObejctInputStream
and
its
method
readObject()
204
WebDesignandDevelopment(CS506)
ObejctInputStream in;
// reading PersonInfos object. Remember type
casting // is required
PersonInfo obj = (PersonInfo)in.readObject( );
205
WebDesignandDevelopment(CS506)
CopyrightVirtualUniversityofPakistan
206
WebDesignandDevelopment(CS506)
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 .
java.net.*;
java.io.*;
javax.swing.*;
class ServerReadNetEx{
CopyrightVirtualUniversityofPakistan
207
WebDesignandDevelopment(CS506)
Often there is no need to serialize sockets, streams & DB connections etc because they do
not 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
So we can mark them as,
o transient Socket s;
o transient OutputStream os;
o transient Connection con;
Transient fields are returned as null on reading
CopyrightVirtualUniversityofPakistan
208
WebDesignandDevelopment(CS506)
22.5 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.
Note: Coding exercises in working condition for this lecture are also available on Downloads
section of LMS.
CopyrightVirtualUniversityofPakistan
209
WebDesignandDevelopment(CS506)
// File ThreeLoopTest.java
public class ThreeLoopTest {
public static void main (String args[ ]) {
//first loop
for (int i=1; i<= 5; i++)
System.out.println(first +i);
// second loop
for (int j=1; j<= 5; j++)
System.out.println(second + j);
// third loop
for (int k=1; k<= 5; k++)
System.out.println(third + k);
} // end main
} // end class
When the program executes, the loops are executed sequentially, one after the other. It generates the
following output.
CopyrightVirtualUniversityofPakistan
210
WebDesignandDevelopment(CS506)
Note: Each loop has 10 iterations in the ThreadTest program. Your output can be different from the
one given above.
Notice the difference between the outputs of the two programs. In ThreeLoopTest each loop
generated a sequential output while in ThreadTest the output of the loops got intermingled
i.e. concurrency took place and loops executed simultaneously.
CopyrightVirtualUniversityofPakistan
211
WebDesignandDevelopment(CS506)
Let us code our first multithreaded program and try to learn how Java supports
multithreading.
Using Interface
Using Inheritance
Create a class where you want to put some code that can run in parallel with some other
code and let that class implement the Runnable interface.
Runnable interface has the run() method therefore provide the implementation for the
run() method and put your code that you want to run in parallel here.
Instantiate Thread class object by passing Runnable object in constructor
Start thread by calling start() method
CopyrightVirtualUniversityofPakistan
212
WebDesignandDevelopment(CS506)
What is multithreading?
What are Java Threads?
Two ways to write multithreaded Java programs
Now we will re-write the ThreeLoopTest program by using Java Threads. At first we will use the
Interface approach and then we will use Inheritance.
CopyrightVirtualUniversityofPakistan
213
WebDesignandDevelopment(CS506)
// 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
t1.start();
t2.start();
t3.start();
}//end main
} // end class
214
WebDesignandDevelopment(CS506)
job = j;
}
//Override run() method of Thread class
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 of Worker (Worker class is now
//becomes a Thread because it is inheriting from it)class
Worker first = new Worker (first job);
Worker second = new Worker (second job);
Worker third = new Worker (third job);
//start threads to execute
first.start();
second.start();
third.start();
}//end main
} // end class
215
WebDesignandDevelopment(CS506)
Then the second thread is given a chance to run, and so on, until the interpreter exits.
Consider the 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 case). J and K have same
priority (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.
CopyrightVirtualUniversityofPakistan
216
WebDesignandDevelopment(CS506)
CopyrightVirtualUniversityofPakistan
217
WebDesignandDevelopment(CS506)
Output
Second, starvation can occur for lower-priority threads if the higher-priority threads
never terminate, sleep, or wait for I/O indefinitely.
23.6 References:
Note: Coding exercises in working condition for this lecture are also available on Downloads
section of LMS.
CopyrightVirtualUniversityofPakistan
218
WebDesignandDevelopment(CS506)
CopyrightVirtualUniversityofPakistan
219
WebDesignandDevelopment(CS506)
}
// overriding run method
// this method contains the code for file reading
public void run ( ){
try
{
// connecting FileReader with attribute fileName
FileReader 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();
}
fr.close();
br.close();
}catch (Exception e){
System.out.println(e);
}
} // end run() method
}
Next, look at the Test.java class that contains the main() method.
// File Test.java
public 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();
}
}
CopyrightVirtualUniversityofPakistan
220
WebDesignandDevelopment(CS506)
Output
On executing Test class, following kind output would be generated:
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
Threads come out of the sleep when the specified time interval expires or when
interrupted by some other thread
Thread coming out of sleep may go to the running or ready state depending upon
the availability of the processor. 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 chance to run otherwise starvation may occur
sleep()
method can be used for delay purpose i.e. anyone can call
Thread.sleep()method
Note that sleep()
method can throw InterruptedException. So, you
need try-catch block
CopyrightVirtualUniversityofPakistan
221
WebDesignandDevelopment(CS506)
CopyrightVirtualUniversityofPakistan
222
WebDesignandDevelopment(CS506)
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.
223
WebDesignandDevelopment(CS506)
// 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:
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
224
WebDesignandDevelopment(CS506)
Thread.yield( );
System.out.println(job + " = " + i);
} // end for
} // end run
} // end class
Below is the code of YieldEx.java that contains the main () method. It will use the
Worker class created above.
// File YieldEx.java
public class YieldEx {
public static void main (String args[ ]){
// Creating Worker objects
Worker first = new Worker (first job);
Worker second = new Worker (second job);
// Instantiating thread class objects
Thread t1 = new Thread (first );
Thread t2 = new Thread (second);
// starting thread
t1.start();
t2.start();
}
} // end class
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:
CopyrightVirtualUniversityofPakistan
225
WebDesignandDevelopment(CS506)
CopyrightVirtualUniversityofPakistan
226
WebDesignandDevelopment(CS506)
Used when a thread wants to wait for another thread to complete its run() method
For example, if thread2 sent the thread2.join() message, it causes the currently executing
thread to block efficiently until thread2 finishes its run() method
Calling join method can throw InterruptedException, so you must use try-catch block to
handle it
227
WebDesignandDevelopment(CS506)
try {
t1.join();
t2.join();
}
catch (Exception ex) {
System.out.println(ex);
}
System.out.println("All done ");
} // end main
}
Output
On executing JoinEx, notice that Starting is printed first followed by printing workers
jobs. Since main thread does not finish until both threads have finished their run (). Therefore
All done will be print on last.
24.4 References:
Note: Coding exercises in working condition for this lecture are also available on Downloads
section of LMS.
CopyrightVirtualUniversityofPakistan
228
WebDesignandDevelopment(CS506)
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
CopyrightVirtualUniversityofPakistan
229
WebDesignandDevelopment(CS506)
Request Method: It tells the server the type of action that a client wants to perform
URI: Uniform Resource Indicator specifies the address of required document or resource
Header Fields: Optional headers can be used by client to tell server extra
information about request e.g. client software and content type that it understands.
CopyrightVirtualUniversityofPakistan
230
WebDesignandDevelopment(CS506)
Body: Data sent by server as part of response that is finally seen by the user.
An HTTP Response code tell the client about the state of the response i.e. whether its a
valid response or some error has occurred etc. HTTP Response codes fall into five general
categories
o 100-199
Codes in the 100s are informational, indicating that the client should
respond with some other action.
100: Continue with partial request.
o 200-299
Values in the 200s signify that the request was successful.
200: Means everything is fine.
o 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.
o 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.
CopyrightVirtualUniversityofPakistan
231
WebDesignandDevelopment(CS506)
o 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.
CopyrightVirtualUniversityofPakistan
232
WebDesignandDevelopment(CS506)
While in case of dynamic web page s 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.
CopyrightVirtualUniversityofPakistan
233
WebDesignandDevelopment(CS506)
The web page is based on data submitted by the user e.g. results page from search engines
and order confirmation pages at on line stores.
CopyrightVirtualUniversityofPakistan
234
WebDesignandDevelopment(CS506)
The Web page is derived from data that changes frequently e.g. a weather report or news
headlines page.
The Web page uses information from databases or other server-side resources e.g. an ecommerce site could use a servlet to build a Web page that lists the current price and
availability of each item that is for sale.
CopyrightVirtualUniversityofPakistan
235
WebDesignandDevelopment(CS506)
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.
CopyrightVirtualUniversityofPakistan
236
WebDesignandDevelopment(CS506)
Provides a user interface for client to interact with application. This is the only part of
application visible to client.
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.
This layer consists of objects that represent real-world business objects such as an Order,
OrderLineItem, Product, and so on.
25.7 References:
Note: Coding exercises in working condition for this lecture are also available on Downloads
section of LMS.
CopyrightVirtualUniversityofPakistan
237
WebDesignandDevelopment(CS506)
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)
26.2.1 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.
CopyrightVirtualUniversityofPakistan
238
WebDesignandDevelopment(CS506)
26.2.2 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)
26.2.3 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
26.2.4 Portable
Since java is portable and servlets is a java based technology therefore they are generally portable
across web servers
26.2.5 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.
Well also use Apache in this course
J2SE
Additional J2EE based libraries for servlets such as servlet-api.jar and jspapi.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 youll be using.
A capable servlet web engine (webserver)
239
WebDesignandDevelopment(CS506)
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.
2.
3.
4.
5.
6.
240
WebDesignandDevelopment(CS506)
JAVA_HOME indicates the root directory of your jdk. Set the JAVA_HOME
environment variable to tell Tomcat, where to find java
This variable should list the base JDK installation directory, not the bin
subdirectory
To set it, right click on My Computer icon. Select the advanced tab, a System
Properties window will appear in front of you like shown below. Select the
Environment Variables button to proceed.
CopyrightVirtualUniversityofPakistan
241
WebDesignandDevelopment(CS506)
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:\Program
Files\j2sdk_nb\j2sdk1.4.2). This is shown below in the picture. Please note
that bin folder is not included in the path.
242
WebDesignandDevelopment(CS506)
CATALINA_HOME is used to tell your system (in this case your web server Tomcat) where
the required files are.
Note: To run Tomcat (web server) you need to set only the two environment variables
and these are JAVA_HOME & CATALINA_HOME
CopyrightVirtualUniversityofPakistan
243
WebDesignandDevelopment(CS506)
Note: If default page doesnt 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.
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.
244
WebDesignandDevelopment(CS506)
CopyrightVirtualUniversityofPakistan
245
WebDesignandDevelopment(CS506)
The setup will automatically select the Java Virtual Machine path. Click
Install button to move ahead.
Finish the setup with the 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 Programs menu.
Double clicking on this button will open up Apache Tomcat Properties window. From here
you
can
start
or
stop
your
web
server.
You
can
also
configure many options if you want to. This properties window is shown
below:
CopyrightVirtualUniversityofPakistan
246
WebDesignandDevelopment(CS506)
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.
CopyrightVirtualUniversityofPakistan
247
WebDesignandDevelopment(CS506)
Open up a browser window and type http://localhost:8080. This should open the default
page of Tomcat as shown in the next diagram:
Note: If default page doesnt 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.
26.5 References:
Note: Coding exercises in working condition for this lecture are also available on Downloads
section of LMS.
CopyrightVirtualUniversityofPakistan
248
WebDesignandDevelopment(CS506)
Unpack
o Where each directory & file exists in the file system separately
o Used mostly during development
Pack
To make a new application e.g myapp in tomcat you need a specific folder hierarchy.
CopyrightVirtualUniversityofPakistan
249
WebDesignandDevelopment(CS506)
All JSP and html files will be kept in main application folder (C:\jakartatomcat-5.5.9\webapps\myapp)
Create another folder inside myapp
folder and change its name to WEB-INF.
Remember WEB-INF is case sensitive and it is not WEB_INF
Configuration files such as web.xml will go in WEB-INF
folder
(C:\jakarta-tomcat-5.5.9\webapps\myapp\WEB-INF)
Create another folder inside WEB-INF folder and change its name to classes.
Remember classes name is also case sensitive.
Servlets and Java Beans will go in classes folder (C:\jakarta-tomcat5.5.9\webapps\myapp\WEB-INF\classes)
Thats the minimum directory structure required in order to get started. This is also shown in
the figure below:
file.
CopyrightVirtualUniversityofPakistan
250
WebDesignandDevelopment(CS506)
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 .tag
files.
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 dont have to restart the server.
CopyrightVirtualUniversityofPakistan
251
WebDesignandDevelopment(CS506)
to
CopyrightVirtualUniversityofPakistan
252
WebDesignandDevelopment(CS506)
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.
TRACE: Used to trace servers
GET
o Attribute-Value pair is attached with requested URL after ?.
o For example if attribute is name and value is ali then the request will be
http://www.gmail.com/register?name=ali
o For HTTP based servlet, override doGet () methods of HttpServlet class
to handle these type of requests.
POST
o Attribute-Value pair attached within the request body. For your reference HTTP
request diagram is given below again:
CopyrightVirtualUniversityofPakistan
253
WebDesignandDevelopment(CS506)
254
WebDesignandDevelopment(CS506)
import javax.servlet.http.*;
// extending class from HttpServelt
public class HelloWorldServlet extends HttpServlet {
/* overriding doGet() method because writing a URL in the browser
by default generate request of GET type As you can see,
HttpServletRequest and HttpServletResponse are passed to this
method. These objects will help in processing of HTTP request and
generating response for HTTP This method can throw
ServletException or IOException, so we mention these exception
types after method signature
*/
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException
{
/* getting output stream i.e PrintWriter from response object by
calling getWriter method on it As mentioned, for generating
response, we will use HttpServletResponse object
*/
PrintWriter out = response.getWriter();
/* printing Hello World in the browser using PrintWriter
object. You can also write HTML like
out.println(<h1> Hello World </h1>)
*/
out.println(Hello World! );
} // end doGet()
} // end HelloWorldServlet
convey
Inside web.xml, the <web-app> is the root tag representing the web application. All other
tags come inside of it.
</servlet>
255
WebDesignandDevelopment(CS506)
<servlet-mapping>
<servlet-name> HelloWorldServlet </servlet-name> <url-pattern>
/myfirstservlet </url-pattern>
</servlet-mapping>
</web-app>
The <servlet> tag represents ones servlet name and its 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 servlet), <servlet-class> tag is used.
Note: It is important to note here that you can specify any name for a servlet inside
<servlet-name> tag. This name is used for referring to servlet in later part of
web.xml. You can think of it as your id assigned to you by your university while you have
actually different name (like <servlet-class>).
Next we 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 mapping using <servlet-name> tag and then you will define the
URL pattern using <url-pattern> tag. Notice the forward slash (/ ) is used before specifying
the url. You can specify any name of URL. The forward slash indicates the root of your
application.
<url-pattern> /myfirstservlet </url-pattern>
Now you can access HelloWorldServelt (if it is placed in myapp application) by giving
the following url in the browser
http://localhost:8080/myapp/myfirstservlet
Note: Save this web.xml file by placing double quotes(web.xml) around it as you did to save
.java files.
CopyrightVirtualUniversityofPakistan
256
WebDesignandDevelopment(CS506)
Note: By using IDEs like netBeans 4.1, you dont have to write web.xml by
yourself or even to worry about creating directory structure and to copy files inappropriate
locations. However manually undergoing this process will strengthen your concepts and will help
you to understand the underlying mechanics.
27.8 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.
Note: Coding exercises in working condition for this lecture are also available on Downloads
section of LMS.
CopyrightVirtualUniversityofPakistan
257
WebDesignandDevelopment(CS506)
Initialize
Service
Destroy
As you can conclude from the diagram below, that with the passage of time a
servlet passes through these stages one after another.
28.1.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 request. Since there is no constructor available in Servlet so this
urges its use for one time initialization (loading of resources, setting of parameters etc) just as
the init() method of applet.
Initialize stage has the following characteristics and usage
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.
CopyrightVirtualUniversityofPakistan
258
WebDesignandDevelopment(CS506)
28.1.2 Service
The service() method is the engine of the servlet, which actually processes the clients 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 requests.
The figure below show both versions of the implementation of service cycle. In the upper
part of diagram, we assume that servlet is made by sub-classing from GenericServlet.
(Remember, GenericServlet is used for constructing protocol independent servlets.).
To provide the desired functionality, service() method is overridden. The client sends a
request to the web server; a new thread is created to serve this request followed by calling the
service() method. Finally a response is prepared and sent back to the user according to
the request.
CopyrightVirtualUniversityofPakistan
259
WebDesignandDevelopment(CS506)
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 to 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. After forming the response by doGet()
or doPost()
method, the
response is sent back to the service() method that is finally sent to the user by the web
server.
28.1.3 Destroy
The web server may decide to remove a previously loaded servlet instance, perhaps because it is
explicitly asked to do so by the server administrator, or perhaps servlet container shuts down or
the servlet is idle for a long time, 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.
28.2 Summary
CopyrightVirtualUniversityofPakistan
260
WebDesignandDevelopment(CS506)
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.
Form Data
Data that the user explicitly type into an HTML form. For example: registration
information provided for creating a new email account.
CopyrightVirtualUniversityofPakistan
261
WebDesignandDevelopment(CS506)
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, password, select, checkbox,
radio buttons, etc. Now, the question arises: if I submit form data to a Servlet, how do I
extract this form data from servlet? Figuring this out, provides the basis for creating
interactive web applications that respond to user requests.
28.3.2.1 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 extractingform data submitted by
the user:
getParameter(String name)
o Used to retrieve a single form parameter and returns String corresponding to name
specified.
o Empty String is returned in the case when user does not enter any thing in the
specified form field.
o 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().
getParameterValues(String name)
o Returns an array of Strings objects containing all of the given values of the given
request parameter.
o If the name specified does not exist, null is returned
getParameterNames()
o If you are unsure about the parameter names, this method will be helpful
o It returns Enumeration of String objects containing the names of the parameters
that
come with the request.
o If the request has no parameters, the method returns an empty Enumeration.
Note: All these methods discussed above work the same way regardless of the request
type(GET or POST). Also remember that form elements are case sensitive for example,
userName is not the same as the username.
CopyrightVirtualUniversityofPakistan
262
WebDesignandDevelopment(CS506)
Lets have a look on the HTML code used to construct the above page.
<html>
<head>
<title> Reading Two Parameters </title> </head>
<body>
<H2> Please fill out this form: </H2>
<FORM METHOD="GET"
ACTION="http://localhost:8084/paramapp/formservlet"
NAME="myform" >
<BR> Firstname:
<INPUT TYPE = text NAME="firstName">
<BR> Surname:
<INPUT TYPE = text NAME="surName">
<BR>
CopyrightVirtualUniversityofPakistan
263
WebDesignandDevelopment(CS506)
Setting the method attribite to GET means that we want to send the HTTP request
using the GET method which will evantually activate 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.
Setting METHOD value to POST hides the entered information from the user as this
information becomes the part of request body and activates doPost() method of the
servlet.
264
WebDesignandDevelopment(CS506)
265
WebDesignandDevelopment(CS506)
HttpServletResponse. This object will be used to send data back the response. Using
PrintWriter object (out), the names are printed with appended Hello that becomes visible
in the browser.
web.xml
<?xml version="1.0" encoding="ISO-8859-1"?> <web-app>
<servlet>
<servlet-name> FormServlet </servlet-name>
<servlet-class> MyServlet </servlet-class> </servlet>
<servlet-mapping>
<servlet-name> FormServlet </servlet-name>
<url-pattern> /formservlet </url-pattern> </servlet-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 page. You can see it is exactly the same
as mentioned in <url-pattern> tag.
http://localhost:8084/paramapp/formservlet
28.4 References:
Note: Coding exercises in working condition for this lecture are also available on Downloads
section of LMS.
CopyrightVirtualUniversityofPakistan
266
WebDesignandDevelopment(CS506)
29.1.1 ServletConfig
Every Servlet has an object called ServletConfig associated with it as shown in the fig.
below. It contains relevant information about the Servlet like initialization parameters
defined in web.xml
CopyrightVirtualUniversityofPakistan
267
WebDesignandDevelopment(CS506)
Another way to read initialization parameters out side the init () method is
initialization
268
WebDesignandDevelopment(CS506)
}
/*
Both doGet() & doPost() methods are override over here.
processRequest() is called from both these methods. This makes
possible for a servlet to handle both POST and GET requests
identically.
*/
// Handles the HTTP GET request type
protected void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException
{
processRequest(request, response);
}
// Handles the HTTP POST request type
protected void doPost(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException
{
processRequest(request, response);
}
// called from doGet() & doPost()
protected void processRequest(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException
{
PrintWriter out = response.getWriter();
// writing init-parameter value that is store in fileName
out.println(fileName);
out.close();
}
} // end MyServlet
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>
CopyrightVirtualUniversityofPakistan
269
WebDesignandDevelopment(CS506)
<servlet-mapping>
<servlet-name> MyServlet </servlet-name>
<url-pattern> /myservlet </url-pattern>
</web-app>
</servlet-mapping>
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 Servlet will not have access to the
original request object. For example, if the request is redirected from servlet1 to
servlet2, then servlet2 would not be able to access the request object of servlet1.
To have access to the original request object, you must use the request dispatching
technique (discussed later) instead of redirect.
CopyrightVirtualUniversityofPakistan
270
WebDesignandDevelopment(CS506)
CopyrightVirtualUniversityofPakistan
271
WebDesignandDevelopment(CS506)
<html>
<body>
<h2>Your login is incorrect. Please register yourself</h2>
<FORM METHOD="POST" ACTION="" NAME="myForm">
<BR> Name:
<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>
MyServlet.java
MyServlet.java accepts requests from login.html and redirects the user to welcome.html or
register.html based on the verification of username & password provided. Username &
password are compared with fix values in this example, however you can verify these from
database or from a text file etc.
import
import
import
import
public
java.io.*;
java.net.*;
javax.servlet.*;
javax.servlet.http.*;
class MyServlet extends HttpServlet {
272
WebDesignandDevelopment(CS506)
String 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");
} else {
// redirecting user to register.html
response.sendRedirect("register.html");
/* if you want to display an error message to the
user, you can use the following method
response.sendError(
response.SC_PROXY_AUTHENTICATION_REQUIRED, "Send Error Demo" );
*/
} // end else
}
29.2 ServletContext
ServletContext belongs to one web application. Therefore it can be used for sharing
resources among servlets in the same web application.
As initialization parameters, for a single servlet are stored in ServletConfig,
ServetContext can store initialization parameters for the entire web application. These
parameters are also called context attributes and exist for the lifetime of the application.
The following figure illustrates the sharing of context attributes among all the servlets
of a web application.
Note:
CopyrightVirtualUniversityofPakistan
273
WebDesignandDevelopment(CS506)
To clarify the concepts, lets take the help from following figure. User initates the request to
servlet1. servlet1 forwards the request to servlet2 by calling forward(request,
response). Finally a response is returned back to the user by servlet2.
CopyrightVirtualUniversityofPakistan
274
WebDesignandDevelopment(CS506)
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 Servlet1. Servlet1 can also add its own response content and
finally send it back to user.
29.6 References:
Note: Coding exercises in working condition for this lecture are also available on Downloads
section of LMS.
CopyrightVirtualUniversityofPakistan
275
WebDesignandDevelopment(CS506)
30.1 Recap
In the previous lecture we had some discussion about Response Redirection and Request
Dispatcher. We said that Response Redirection was used to redirect response of the Servlet to
another application resource. This resource might be another Servlet or any JSP page.
Two forms of Response redirection were discussed. These were:
30.1.3 Forward:
Forwards the responsibility of request processing to another resource.
30.1.4 Include:
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 one which finishes the response.
CopyrightVirtualUniversityofPakistan
276
WebDesignandDevelopment(CS506)
java.io.*;
java.net.*;
javax.servlet.*;
javax.servlet.http.*;
277
WebDesignandDevelopment(CS506)
java.io.*;
java.net.*;
javax.servlet.*;
javax.servlet.http.*;
278
WebDesignandDevelopment(CS506)
HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
protected void doPost(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
} // end IncludeServlet
In the processRequest(), firstly we get the PrintWriter stream from the
HttpServletResponse object. Then we include an HTML tag to the output of the calling
servlet. One thing that must be considered is that PrintWriter 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 used again in
the calling servlet.
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app>
<servlet>
<servlet-name>MyServlet</servlet-name>
<servlet-class>MyServlet</servlet-class>
</servlet>
<servlet>
<servlet-name>IncludeServlet</servlet-name>
<servlet-class>IncludeServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>MyServlet</servlet-name>
<url-pattern>/myservlet</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>IncludeServlet</servlet-name>
<url-pattern>/includeservlet</url-pattern>
</servlet-mapping>
</web-app>
CopyrightVirtualUniversityofPakistan
279
WebDesignandDevelopment(CS506)
280
WebDesignandDevelopment(CS506)
java.io.*;
java.net.*;
javax.servlet.*;
javax.servlet.http.*;
CopyrightVirtualUniversityofPakistan
281
WebDesignandDevelopment(CS506)
CopyrightVirtualUniversityofPakistan
282
WebDesignandDevelopment(CS506)
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app>
<servlet>
<servlet-name>FirstServlet</servlet-name>
<servlet-class>FirstServlet</servlet-class>
</servlet>
<servlet>
<servlet-name>SecondServlet</servlet-name>
<servlet-class>SecondServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>FirstServlet</servlet-name>
<url-pattern>/firstservlet</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>SecondServlet</servlet-name>
<url-pattern>/secondservlet</url-pattern>
</servlet-mapping>
</web-app>
30.2.2 getAttribute(String)
The objects set by the setAttribute() method can be accessed using getAttribute() method.
Passing the key in the form of string as a parameter to this method will return the object
associated with that particular key in the context. Cast the object into its appropriate type.
30.2.3 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.
CopyrightVirtualUniversityofPakistan
283
WebDesignandDevelopment(CS506)
30.2.4 getRequestURL()
It can be used to track the source of Request. It returns the part of the requests URL with
out query string.
30.2.5 getProtocol()
It returns the name and version of the protocol used.
30.2.6 getHeaderNames()
It returns the enumeration of all available header names that are contained in the request.
30.2.7 getHearderName()
It takes a String parameter that represents the header name and returns that appropriate header.
Null value is returned if there is no header exists with the specified name.
30.3.1 setContentType()
Almost every Servlet uses this header. It is used before getting the PrintWriter Stream. It is used
to set the 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 on the clients browser.
30.3.2 setContentLength()
This method is used to set the content length. It takes length as an integer parameter.
30.3.3 addCookie()
This method is used to add a value to the Set-Cookie header. It takes a Cookie object as a
parameter and adds it to the Cookie-header. We will talk more about Cookies in the session
tracking part.
30.3.4 sendRedirect()
This method redirects the user to the specific URL. This method also accepts the relative URL. It
takes URL string as parameter and redirects the user to that resource.
CopyrightVirtualUniversityofPakistan
284
WebDesignandDevelopment(CS506)
Suppose a user logs on to the online bookshop, selects some books and adds them to his cart. He
enters his billing address and finally submits the order. HTTP cannot track session as it is
stateless in nature and user thinks that the choices made on page1 are remembered on page3.
CopyrightVirtualUniversityofPakistan
285
WebDesignandDevelopment(CS506)
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.
30.5 References:
Note: Coding exercises in working condition for this lecture are also available on Downloads
section of LMS.
CopyrightVirtualUniversityofPakistan
286
WebDesignandDevelopment(CS506)
31.2 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.
CopyrightVirtualUniversityofPakistan
287
WebDesignandDevelopment(CS506)
31.3.1 Cookies
31.3.1.1 What a cookie is?
Dont be tempted? These are not, what you might be thinking off. In fact, in computer
terminology, a cookie is a piece of text that a web server can store on a clients(user)hard disk.
Cookies allow the web sites to store information on a client machine and later retrieve it. The pieces
of information are stored as name-value pair on the client. Later while reconnecting to the same site
(or same domain depending upon the cookie settings), client returns the same name-value pair to
the server.
31.3.1.2 Cookies Voyage
To reveal the mechanism of cookies, lets take an example. We are assuming here
that the web application we are using will set some cookies
If you type URL of a Web site into your browser, your browser sends a request for that web
page
o For example, when you type www.amazon.com a request is send to the Amazons
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 request
o If not, no cookie data will be sent with the request
Amazaon web server receives the request and examines the request for cookies
If cookies are received, amazon can use them
o If no cookie is received, amazon knows that you have not visited before or the
cookies that were previously set got expired.
o Server creates a new cookie and send to your browser in the header of HTTP
Response so that it can be saved on the client machine.
identifying a user during an e-commerce session. For example, this book is added into
shopping cart by this client.
Avoiding username and password as cookies are saved on your machine
customizing a site. For example, you might like email-inbox in a different look form
others. This sort of information can be stored in the form of cookies on your machine and
latter can be used to format inbox according to your choice.
Focused Advertising. For example, a web site can store information in the form of
cookies about the kinds of books, you mostly hunt for.
CopyrightVirtualUniversityofPakistan
288
WebDesignandDevelopment(CS506)
the request
object
of
the
CopyrightVirtualUniversityofPakistan
289
WebDesignandDevelopment(CS506)
java.io.*;
java.net.*;
javax.servlet.*;
javax.servlet.http.*;
290
WebDesignandDevelopment(CS506)
HttpServletResponse response)
throws ServletException, IOException
{
processRequest(request, response);
}
// Handles the HTTP <code>POST</code> method.
protected void doPost(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException
{
processRequest(request, response);
}
// called from both doGet() & doPost()
protected void processRequest(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException
{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
// writing html
out.println("<html>");
out.println("<body>");
out.println("<h2>Cookie Example </h2>");
String msg = "";
boolean repeatVisitor = false;
// reading cookies
Cookie[] cookies = request.getCookies();
// if cookies are returned from request object
if (cookies != null) {
//search for cookie -- repeat
for (int i = 0; i < cookies.length; i++) {
// retrieving one cookie out of array
Cookie c = cookies[i];
// retrieving name & value of the cookie
String name = c.getName();
String val = c.getValue();
// confirming if cookie name equals repeat and
// value equals yes
if( name.equals("repeat") && val.equals("yes"))
{
msg= "Welcome Back";
repeatVisitor = true;
break;
CopyrightVirtualUniversityofPakistan
291
WebDesignandDevelopment(CS506)
}
} // end for
} // end if
// if no cookie with name repeat is found
if (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";
}
// displaying message value
out.println("<h2>" + msg + "</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-name>
<servlet-class> RepeatVisitorServlet </servlet-class> </servlet>
<servlet-mapping>
<servlet-name> RepeatVisitorServlet </servlet-name>
<url-pattern> /repeatexample </url-pattern>
</servlet-mapping>
</web-app>
Output
On first time visiting this URL, an output similar to the one given below would be displayed
CopyrightVirtualUniversityofPakistan
292
WebDesignandDevelopment(CS506)
On refreshing this page or revisiting it within an hour (since the age of cookie was set to 60 mins),
following output should be expected.
CopyrightVirtualUniversityofPakistan
293
WebDesignandDevelopment(CS506)
294
WebDesignandDevelopment(CS506)
295
WebDesignandDevelopment(CS506)
out.println("<body>");
out.println("<h1>Online Book Store</h1>");
String url =
"http://localhost:8084/cookiesessionex/shoppingcartex";
// user will submit the from to the same servlet
out.println("<form action=" + url +">" +
"<h3><input type=checkbox name=firstCB value=firstCB />" +
" java core servlts</h3>" +
"<br>"+
<h3><input type=checkbox name=secondCB value=secondCB />" +
" java how to program</h3>" +
"<br>"+
"<h3><input type=checkbox name=thirdCB value=thirdCB />" +
" java complete reference</h3>" +
"<br>"+
"<input type=submit value=\"Add to Cart\" />" +
"</from>"
);
out.println("<br/>");
out.println("<h1>You have selected followig books</h1>");
out.println("<br/>");
//reteriving
String fBook
String sBook
String tBook
296
WebDesignandDevelopment(CS506)
297
WebDesignandDevelopment(CS506)
web.xml
<?xml version="1.0" encoding="UTF-8"?> <web-app>
<servlet>
<servlet-name> ShoppingCart </servlet-name>
<servlet-class> ShoppingCartServlet </servlet-class> </servlet>
<servlet-mapping>
<servlet-name> ShoppingCart </servlet-name>
<url-pattern> /shoppingcartex </url-pattern> </servletmapping>
</web-app>
31.4 References:
Note: Coding exercises in working condition for this lecture are also available on Downloads
section of LMS.
CopyrightVirtualUniversityofPakistan
298
WebDesignandDevelopment(CS506)
Note: Due to limited space available in rewriting a URL, the extra information is usually limited to a
unique session ID.
The following URLs have been rewritten to pass the session ID 123
What if the user bookmarks the page and the problem get worse if server is not
assigning a unique session id.
Every URL on a page, which needs the session information, must be rewritten
each time page is served, which can cause
o Computationally expensive
o Can increase communication overhead
CopyrightVirtualUniversityofPakistan
299
WebDesignandDevelopment(CS506)
If you want to add more than one parameter, all subsequent parameters are separated by & sign.
For example
Adding two parameters http://server:port/servletex/register ?name=ali&address=gulberg
URLRewriteServlet.java :
import
import
import
import
import
java.io.*;
java.net.*;
javax.servlet.*;
javax.servlet.http.*;
java.util.*;
300
WebDesignandDevelopment(CS506)
CopyrightVirtualUniversityofPakistan
301
WebDesignandDevelopment(CS506)
302
WebDesignandDevelopment(CS506)
CopyrightVirtualUniversityofPakistan
303
WebDesignandDevelopment(CS506)
web.xml
<?xml version="1.0" encoding="UTF-8"?> <web-app>
<servlet>
<servlet-name> URLRewriteServlet </servlet-name>
<servlet-class> URLRewriteServlet </servlet-class>
<servlet-mapping>
<servlet-name> URLRewriteServlet </servlet-name>
<url-pattern> /urlrewriteservlet </url-pattern>
</servlet-mapping>
</web-app>
</servlet>
In the above figure you can see the use of Hidden form fields for storing particular
information.
304
WebDesignandDevelopment(CS506)
CopyrightVirtualUniversityofPakistan
305
WebDesignandDevelopment(CS506)
4. Terminating a Session
After the amount of time, session gets terminated automatically. We can see its
maximum activation time by using getMaxInactiveInterval()
method of
HttpSession
class.
However, we can also terminate any existing session
manually. For this, we need to call invalidate () method of HttpSession
class as shown below.
sess.invalidate()
java.io.*;
java.net.*;
javax.servlet.*;
javax.servlet.http.*;
306
WebDesignandDevelopment(CS506)
{
// used for displaying message (like Welcomem, Newcomer) to
// user
String heading;
response.setContentType("text/html");
// Getting session object
HttpSession session = request.getSession(true);
/* Getting stored information using getAttribute() method */
Integer accessCount =
(Integer)session.getAttribute("sessionCount");
/* If user comes for the first time, accessCount will be
assigned null, so we can guess easily that this a new user */
if (accessCount == null)
{
accessCount = new Integer(1);
heading = "Welcome, Newcomer";
} else
{
heading = "Welcome Back";
307
WebDesignandDevelopment(CS506)
" </H3>" +
" </BODY>" +
" </HTML>"
);
//Closing the PrintWriter stream
out.close();
} // end processRequest
} // end ShowSessionServlet class
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app>
<servlet>
<servlet-name> ShowSession
</servlet-name>
<servlet-class> ShowSessionServlet </servlet-class>
</servlet>
<servlet-mapping>
<servlet-name> ShowSession </servlet-name>
<url-pattern> /showsession </url-pattern>
</servlet-mapping>
</web-app>
CopyrightVirtualUniversityofPakistan
308
WebDesignandDevelopment(CS506)
If Cookies are disabled, both methods encode (rewrite) the specific URL to include the session
ID and returns the new URL. However, if cookies are enabled, the URL is returned
unchanged.
response.encodeRedirectURL(URL);
java.io.*;
java.net.*;
javax.servlet.*;
javax.servlet.http.*;
309
WebDesignandDevelopment(CS506)
CopyrightVirtualUniversityofPakistan
310
WebDesignandDevelopment(CS506)
out.println(
"<h3><a href=" + eURL1 + ">" +
" java core servlets </a> </h3>" + "<br>"+
"<h3><a href=" + eURL2 + ">" +
" java How to Program </a> </h3>"
);
out.println("<br/>");
out.println("<h1>You 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");
out.println("<br/>");
out.println("<h1>You 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 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
311
WebDesignandDevelopment(CS506)
setAttribute(String, Object)
o This method associates a value with a name.
getAttribute(String)
o Extracts previously stored value from a session object. It returns null if no value
is associated with the given name
CopyrightVirtualUniversityofPakistan
312
WebDesignandDevelopment(CS506)
removeAttribute(String)
o This method removes values associated with the name
getId( )
o This method returns the unique identifier of this session
getCreationTime( )
o This method returns time at which session was first created
getMaxInactiveInterval( ) , setMaxInactiveInterval(int)
o To get or set the amount of time session should go without access before being
invalidated.
32.9 References:
Note: Coding exercises in working condition for this lecture are also available on Downloads
section of LMS.
CopyrightVirtualUniversityofPakistan
313
WebDesignandDevelopment(CS506)
Presentation Layer
o Provides a user interface for client to interact with application. This is the only
o Part of application visible to client.
Business Layer
o 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
o This layer consists of objects that represent real-world business objects such as an
CopyrightVirtualUniversityofPakistan
314
WebDesignandDevelopment(CS506)
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.
33.2.1 Step 1
33.2.2 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.
CopyrightVirtualUniversityofPakistan
315
WebDesignandDevelopment(CS506)
//File: PersonInfo.java
public class PersonInfo {
String name;
String address;
String phoneNum;
public PersonInfo(String n, String a, String pn) {
name = n;
address = a;
phoneNum = pn;
}
public String toString( ){
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.
33.2.3 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 everything in a single class.
So, Make a PersonDAO class which contains:
A searchPerson(String name) method that first establishes a connection
to the database and returns PersonInfo object after searching the information of
the specified person from the database.
//File: PersonDAO.java
import java.sql.*;
public class PersonDAO {
// method searchPerson
public PersonInfo searchPerson(String sName){
CopyrightVirtualUniversityofPakistan
316
WebDesignandDevelopment(CS506)
33.2.4 Step 4
To find what user wants to search, we need to give user an interface through which he/she can
enter the input. The SearchPesonServlet.java will do this 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 being used to present a form to the user
and collect input.
Write SearchPersonServlet.java
Will take input for name to search in address book
Submits the request to ShowPersonServlet
//File: SearchPersonServlet.java
import java.io.*;
CopyrightVirtualUniversityofPakistan
317
WebDesignandDevelopment(CS506)
import java.net.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class SearchPersonServlet extends HttpServlet {
protected void processRequest(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println(
"<html>" +
"<body>" +
"<h1> Address Book </h1>" +
"<form action=showperson >" +
// showperson is alias or
// url pattern of
// ShowPersonServlet
"<h2> Enter name to search </h2> <br/>" +
"<input type=text name=pName /> <br/>" +
"<input type=submit value=Search Person />" +
"</form>" +
"</body>" +
"</html>"
);
out.close();
}
// Handles the HTTP GET method.
protected void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
// Handles the HTTP POST method.
protected void doPost(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
}
33.2.5 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
CopyrightVirtualUniversityofPakistan
318
WebDesignandDevelopment(CS506)
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 PersonDAO class Show results
//File : ShowPersonServlet.java
import java.io.*;
import java.net.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class ShowPersonServlet extends HttpServlet {
protected void
processRequest(HttpServletRequestrequest,
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("<h1>Search Results</h1>");
if (person != null){
out.println("<h3>"+ person.toString() +"</h3>" );
}
else{
out.println("<h3>Sorry! No records found</h3>" );
}
out.println("</body>");
out.println("</html>");
out.close();
}
// Handles the HTTP GET method.
protected void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
} // Handles the HTTP POST method.
protected void doPost(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);}} // end ShowPersonServlet
CopyrightVirtualUniversityofPakistan
319
WebDesignandDevelopment(CS506)
CopyrightVirtualUniversityofPakistan
320
WebDesignandDevelopment(CS506)
33.3 Package
Many times when we get a chance to work on a small project, one thing we intend to do is to put
all java files into one single directory (folder). It is quick, easy and harmless. However if our small
project gets bigger, and the number of files is increasing, putting all these files into the same
directory would be a nightmare for us. In java we can avoid this sort of problem by using
Packages.
321
WebDesignandDevelopment(CS506)
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.
One thing you must do after creating a package for the class is to create nested subdirectories to
represent package hierarchy of the class. In our case, we have the worldpackage, which requires
only one directory. So, we create a directory (folder) world and put our HelloWorld.java into it.
CopyrightVirtualUniversityofPakistan
322
WebDesignandDevelopment(CS506)
CopyrightVirtualUniversityofPakistan
323
WebDesignandDevelopment(CS506)
33.5 References:
Note: Coding exercises in working condition for this lecture are also available on Downloads
section of LMS.
CopyrightVirtualUniversityofPakistan
324
WebDesignandDevelopment(CS506)
The web browser makes a request to JSP source code. This code is bifurcated into HTML
and java code by the JSP parser. The java source code is compiled by the Java compiler
resulting in producing a servlet equivalent code of a JSP.
The servlet code is intermixed
with HTML and displayed to the user. It is important to note that a JSP only passes
through all these phases when it is invoked for the first time or when the changes have
been made to JSP. Any later call to JSP does not undergo of compilation phase.
Convenient
o we already know java and HTML. So nothing new to be learned to work with
JSP.
o Like servlets (as seen, ultimately a JSP gets converted into a servlet), provides an
extensive infrastructure for
Tracking sessions
Reading and sending HTML headers
Parsing and decoding HTML form data
Efficient
o Every request for a JSP is handled by a simple JSP java thread as JSP gets
CopyrightVirtualUniversityofPakistan
325
WebDesignandDevelopment(CS506)
converted into a servlet. Hence, the time to execute a JSP document is not
dominated by starting a process.
Portable
o Like Servlets, JSP is also a specification and follows a well standardized API.The
JVM which is used to execute a JSP file is supported on many architectures and
operating systems.
Inexpensive
o There are number of free or inexpensive Web Servers that are good for
commercial quality websites.
Now, compare the JSP code above with the Servlet code given below that is also displaying the
current date.
//File: SearchPersonServlet.java
import
import
import
import
import
public
java.io.*;
java.net.*;
javax.servlet.*;
javax.servlet.http.*;
java.util.*;
class SearchPersonServlet extends HttpServlet {
326
WebDesignandDevelopment(CS506)
CopyrightVirtualUniversityofPakistan
327
WebDesignandDevelopment(CS506)
Action Elements
o Special JSP tags ....<jsp: ../>
Well discuss in detail all the ingredients of JSP. This handout will cover only scripting elements,
remaining ones will be discussed in next handouts.
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 --%>
34.3.2 Expressions
The format of writing a Java expression is:
<%= Java expression %>
These expressions are evaluated, after converted to strings placed into HTML page at the place it
occurred in JSP page
Examples of writing Expressions are:
<h2> Time: <% new java.util.Date() %> </h2>
will print current data & time after converting it to String
<h2> Welcome: <% request.getParameter(name)%> </h2>
will print the name attribute
34.3.3 Scriptlets
The format of writing a scriptlet is: <% Java code %>
After opening up the scriptlet tag, any kind of java code can be written inside it. This code is
inserted verbatim into corresponding servlet.
CopyrightVirtualUniversityofPakistan
328
WebDesignandDevelopment(CS506)
34.3.4 Declarations
The format of writing a declaration tag is: <%! Java code %>
This tag is used to declare variables and methods at class level. The code written inside this tag is
inserted verbatim into servlets class definition.
Example of declaring a class level (attribute) variable is:
<%!
private int someField = 5; %>
%>
Example of declaring a class level method is:
<%!
public void someMethod ( ) {
.
}
%>
329
WebDesignandDevelopment(CS506)
330
WebDesignandDevelopment(CS506)
Declaration:<jsp:declartion> </jsp:declaration>
Expression:<jsp:expression> </jsp:expression>
Scriptlet:<jsp:scriptlet>
</jsp:scriptlet>
Its 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.
<?xml version="1.0" encoding="UTF-8"?>
<jsp:root xmlns:jsp="http://java.sun.com/JSP/Page" version="2.0">
<!-- to change the content type or response encoding change the
following line
-->
<jsp:directive.page contentType="text/xml;charset=UTF-8"/>
<!-- any content can be specified here, e.g.: -->
<jsp:element name="text">
<jsp:body>
<jsp:declaration>
int res;
public int sum(int op1, int op2) {
return op1 + op2;
}
</jsp:declaration>
<jsp:scriptlet>
String op1 = request.getParameter("num1");
String op2 = request.getParameter("num2");
int firstNum = Integer.parseInt(op1);
int secondNum = Integer.parseInt(op2);
res = sum(firstNum, secondNum);
</jsp:scriptlet>
<jsp:text> Sum is: </jsp:text>
<jsp:expression> res </jsp:expression>
</jsp:body>
</jsp:element> </jsp:root>
34.5 References:
Note: Coding exercises in working condition for this lecture are also available on Downloads
section of LMS.
CopyrightVirtualUniversityofPakistan
331
WebDesignandDevelopment(CS506)
We start our discussion from implicit objects. Lets find out what these are?
request
response
332
WebDesignandDevelopment(CS506)
out
<html>
<body>
<h2>Select the page you want to visit</h2>
<form name="myForm" action="controller.jsp" >
<h3>
<input type="radio" name = "page" value="web"/>
Web Design & Develoment
</h3>
<br>
<h3>
<input type="radio" name = "page" value="java"/>
Java
</h3>
CopyrightVirtualUniversityofPakistan
333
WebDesignandDevelopment(CS506)
<br>
<input type="submit" value="Submit" />
</form>
</body>
</html>
controller.jsp
<html>
<body>
<!-- scriptlet -->
<%
// reading parameter page, 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>
web.jsp
<html>
<body>
// use of out implicit object, to generate HTML
<%
out.println( "<h2>" +
"Welcome to Web Design & Development Page" + "</h2>"
);
%>
</body>
</html>
CopyrightVirtualUniversityofPakistan
334
WebDesignandDevelopment(CS506)
java.jsp
<html>
<body>
// use of out implicit object, to generate HTML
<%
out.println( "<h2>" +
"Welcome to Java Page" + "</h2>"
);
%>
</body>
</html>
The details of remaining 5 implicit objects are given below:
session
application
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 configuration options e.g.
init-parameters etc.
pageContext
exception
page
335
WebDesignandDevelopment(CS506)
35.2.1 Format
<%@ 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:<%@ taglib{attribute=val}*%>
The lists of attributes that can be used with page directive are:
language = java
extends = package.class
import = package.*,package.class
session = true | false
info= text
contentType = mimeType
isThreadSafe = true | false
errorPage= relativeURL
isErrorPage = true | false
CopyrightVirtualUniversityofPakistan
336
WebDesignandDevelopment(CS506)
Format
<%@include file=relativeURL%>
Purpose
To include a file in a JSP document at the time document is translated into a servlet. It
may contain JSP code that affects the main page such as response page header settings
etc.
337
WebDesignandDevelopment(CS506)
index.jsp
<html>
<body>
// includes the output of header.jsp
<%@include file="header.jsp" %>
<TABLE BORDER=1>
<TR><TH></TH><TH>Apples<TH>Oranges
<TR><TH>First Quarter<TD>2307<TD>4706
<TR><TH>Second Quarter<TD>2982<TD>5104
<TR><TH>Third Quarter<TD>3011<TD>5220
<TR><TH>Fourth Quarter<TD>3055<TD>5287 </TABLE>
// includes the output of footer.jsp
<%@include file="footer.jsp" %>
</body>
</html>
CopyrightVirtualUniversityofPakistan
338
WebDesignandDevelopment(CS506)
35.4 References:
Note: Coding exercises in working condition for this lecture are also available on Downloads
section of LMS.
CopyrightVirtualUniversityofPakistan
339
WebDesignandDevelopment(CS506)
Lecture 36
In the last handout, we learned how to work with JSP directives and the use of implicit objects.
In this handout, well learn about JavaBeans and what affect they produce. Before learning
JavaBeans, lets start with an example that helps us to understand the impact of using JavaBeans.
340
WebDesignandDevelopment(CS506)
controller.jsp
Based upon the selection made by the user, this page will redirect the user to respective
pages. Those are web.jsp and java.jsp
<html>
<body>
<!-- scriptlet -->
<%
// reading parameter named page
String pageName = request.getParameter("page");
// redirecting user based on selection made
if (pageName.equals("web")) {
response.sendRedirect("web.jsp");
} else if (pageName.equals("java") )
response.sendRedirect("java.jsp");
}
%>
/body>
</html>
web.jsp
This page is used to display course outline of web design and development in a tabular
format after reading them from database. The code is:
// importing java.sql package using page directive, to work with
// database
<%@page import="java.sql.*"%>
<html>
<body>
<center>
<h2> Welcome to Web Design & Development Page </h2>
<h3> Course Outline</h3>
<TABLE BORDER="1" >
<TR>
CopyrightVirtualUniversityofPakistan
341
WebDesignandDevelopment(CS506)
<TH>Session No.</TH>
<TH>Topics</TH>
<TH>Assignments</TH>
</TR>
<%-- start of scriptlet --%>
<%
// establishing conection
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
String conUrl = "jdbc:odbc:CourseDSN";
Connection con = DriverManager.getConnection(conUrl);
// preparing query using join statements
String sql = " SELECT sessionNo, topic, assignment " +
" FROM Course, SessionDetail" +
" WHERE courseName = ? " +
" AND Course.courseId = SessionDetail.courseID";
342
WebDesignandDevelopment(CS506)
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
// importing java.sql package using page directive, to work with
// database
<%@page import="java.sql.*"%>
<html>
<body>
<center>
<h2> Welcome to Java Page </h2>
<h3> Course Outline</h3>
<TABLE BORDER="1" >
<TR>
<TH>Session No.</TH>
<TH>Topics</TH>
<TH>Assignments</TH>
</TR>
<%-- start of scriptlet --%>
<%
// establishing conection
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
String conUrl = "jdbc:odbc:CourseDSN";
CopyrightVirtualUniversityofPakistan
343
WebDesignandDevelopment(CS506)
CopyrightVirtualUniversityofPakistan
344
WebDesignandDevelopment(CS506)
36.1 JavaBeans
A java class that can be easily reused and composed together in an application.
Any java class that follows certain design conventions can be a JavaBean.
345
WebDesignandDevelopment(CS506)
}
// standard getter
public String getName( ) {
return name;
}
// any other method
public void print( ) {
System.out.println(Name is: + name);
}
} // end Bean class
sessionNo
topic
assignment
The CourseDAO (where DAO stands of Data Acess Object) bean encapsulates database
connectivity and result processing logic.
The web.jsp and java.jsp will use both these JavaBeans. The code of these and the JSPs
used in this example are given below.
CourseOutlineBean.java
package vu;
import java.io.*;
public class CourseOutlineBean implements Serializable{
private int sessionNo;
private String topic;
private String assignment;
CopyrightVirtualUniversityofPakistan
346
WebDesignandDevelopment(CS506)
// no argument constructor
public CourseOutlineBean() {
sessionNo = 0;
topic = "";
assignment = "";
}
// setters
public void setSessionNo(int s){
sessionNo = s;
}
public void setTopic(String t){
topic = t;
}
public void setAssignment(String a){
assignment = a;
}
// getters
public int getSessionNo( ){
return sessionNo;
}
public String getTopic( ){
return topic;
}
public String getAssignment( ){
return assignment;
}
} // end class
CourseDAO.java
package vu;
import java.io.*;
import java.sql.*;
import java.util.*;
public class CourseDAO implements Serializable{
private Connection con;
public CourseDAO() {
establishConnection();
}
CopyrightVirtualUniversityofPakistan
347
WebDesignandDevelopment(CS506)
348
WebDesignandDevelopment(CS506)
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
//********** releaseResources method ********************
private void releaseResources(){
try{
if(con != null){
con.close();
}
}catch(Exception ex){
System.out.println();
}
}
} // end releaseResources
}// end CourseDAO
index.jsp
This page is used to display the course options to the user in the radio button form.
<html>
<body>
<h2>Select the page you want to visit</h2>
<form name="myForm" action="controller.jsp" >
<h3>
<input type="radio" name = "page" value="web"/>
Web Design & Develoment
</h3> <br>
<h3>
CopyrightVirtualUniversityofPakistan
349
WebDesignandDevelopment(CS506)
controller.jsp
Based on user selection, redirects the user to desired page.
<html>
<body>
<!-- scriptlet -->
<%
String pageName = request.getParameter("page");
if (pageName.equals("web")) {
response.sendRedirect("web.jsp");
} else if (pageName.equals("java") )
response.sendRedirect("java.jsp");
}
%>
</body>
</html>
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 page also uses the JavaBeans
(CourseOutlineBean & CourseDAO).
<%@page import="java.util.*" %>
<%-- importing vu package that contains the JavaBeans--%>
<%@page import="vu.*" %>
<html>
<body>
<center>
<h2> Welcome to Web Design & Development Course </h2>
CopyrightVirtualUniversityofPakistan
350
WebDesignandDevelopment(CS506)
351
WebDesignandDevelopment(CS506)
36.2 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.
Note: Coding exercises in working condition for this lecture are also available on Downloads
section of LMS.
CopyrightVirtualUniversityofPakistan
352
WebDesignandDevelopment(CS506)
CopyrightVirtualUniversityofPakistan
353
WebDesignandDevelopment(CS506)
354
WebDesignandDevelopment(CS506)
<jsp:useBean
id = m
scope = page
class=vu.MyBean
/>
In the above code snippet, we are assuming that MyBean lies in vu package.
355
WebDesignandDevelopment(CS506)
<%
String name = m.getName( ); out.println(name);
%>
Achieving above functionality using jsp:getProperty action element will look like
this:
<jsp:getProperty name = mproperty = name />
firstNumber
secondNumber
sum
The firstNumber and secondNumbers are write-only properties means for these only
setters would be defined. 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 addition of firstNumber with secondNumber, this
method will assign the result to sum attribute.
package vu;
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;
CopyrightVirtualUniversityofPakistan
356
WebDesignandDevelopment(CS506)
}
// firstNumber & secondNumber are writeonly properties
// setters
public 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>
<h2>Enter two numbers to calculate their sum</h2>
<form name="myForm" action="result.jsp">
<h3>
Enter first number
<input type="text" name="num1" />
<br/>
Enter second number
<input type="text" name="num2" />
<br/>
<input type="submit" value="Calculate Sum" />
</h3>
</form>
</body>
</html>
result.jsp
This page will calculate the sum of two entered numbers by the user and displays the sum
back to user. The addition is performed using SumBean
<%-- importing vu package that contains the SumBean --%>
<%@page import="vu.*"%>
CopyrightVirtualUniversityofPakistan
357
WebDesignandDevelopment(CS506)
<html>
<body>
<h2>The sum is:
<%-- instantiating bean using action element -- %>
<%-//Servlet equivalent code of useBean
SumBean sBean = new SumBean();
--%>
<jsp:useBean 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 type
String and firstNumber is of type int
--%>
<%-//Servlet equivalent code of setProperty for num1
int no = Integer.parseInt(request.getParameter("num1"));
sBean.setFirstNumber(no);
--%>
<jsp:setProperty name="sBean"
property="firstNumber" param="num1" />
<%-//Servlet equivalent code of setProperty for num2
int no = Integer.parseInt(request.getParameter("num2"));
sBean.setSecondNumber(no);
--%>
//Servlet equivalent code of setProperty for num2
int no = Integer.parseInt(request.getParameter("num2"));
sBean.setSecondNumber(no);
<jsp:setProperty name="sBean"
property="secondNumber" param="num2" />
<%
// calling calculateSum() method that will set the value of
// sum attribute
sBean.calculateSum();
%>
<%-// servlet equivalent code of displaying sum
CopyrightVirtualUniversityofPakistan
358
WebDesignandDevelopment(CS506)
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,
session and application.
Lets discover what impact these scopes can produce on JavaBeans objects which are stored in one
of these scopes.
37.3.1 page
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 pageContext
object. The beans values are only available and persist on JSP in which bean is
created.
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 of following diagram:
CopyrightVirtualUniversityofPakistan
359
WebDesignandDevelopment(CS506)
37.3.2 request
This value signifies that, in addition to being bound to local variable, the bean object
should be placed in ServletRequest object for the duration of the current
request. In other words, until you continue to forward the request to another
JSP/servlet, the beans values are available. This has been illustrated in the following
diagram.
CopyrightVirtualUniversityofPakistan
360
WebDesignandDevelopment(CS506)
37.3.3 session
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, objects value stored in HttpSession persists for whole users
session. The figure below helps in understanding this concept.
CopyrightVirtualUniversityofPakistan
361
WebDesignandDevelopment(CS506)
In the diagram above, MyBean is instantiated by specifying scope = session that results
in storing object in HttpSession. A value ali is also stored in m using setter method.
Irrespective of request forwarding or new request generation from second.jsp to
other resources, the values stored in HttpSession remains available until users
session is ended.
37.3.4 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:
CopyrightVirtualUniversityofPakistan
362
WebDesignandDevelopment(CS506)
Lets take another view of session, request & page scopes in the next figure that helps us to
understand the under beneath things.
CopyrightVirtualUniversityofPakistan
363
WebDesignandDevelopment(CS506)
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, objects values stored in session scope
remains available on all these pages.
To understand the difference between sessions & application scope, consider the
following figure:
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.
CopyrightVirtualUniversityofPakistan
364
WebDesignandDevelopment(CS506)
jsp:forward action
37.6 References:
Note: Coding exercises in working condition for this lecture are also available on Downloads
section of LMS.
CopyrightVirtualUniversityofPakistan
365
WebDesignandDevelopment(CS506)
38.1 Motivation
To give you an inspiration, first have a glance over the code snippet we used in JSP of the course
outline example of last lecture. Of course, not all code is given here; its just for your reference to
give you a hint.
<%
CourseDAO courseDAO = new CourseDAO();
// iterating over ArrayList
for ( ) {
//displaying courseoutline
}
%>
Can we replace all the above code with one single line? Yes, by using custom tag we can write like
this:
<mytag:coursetag
pageName=java />
By only specifying the course/page name, this tag will display the course outline in
tabular format. Now, you must have realized how significant changes 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 from database.
It provides mechanism for encapsulating complex functionality for use in JSPs. Thus
CopyrightVirtualUniversityofPakistan
366
WebDesignandDevelopment(CS506)
CopyrightVirtualUniversityofPakistan
367
WebDesignandDevelopment(CS506)
optional_attributes >
some body
</ mytag:hello >
368
WebDesignandDevelopment(CS506)
Tag Handler is also a java class that is implicitly called when the associated tag is
encountered in the JSP.
Must implement SimpleTag interface
Usually extend from SimpleTagSupport class that has already implemented
SimpleTag interface.
For example,
public class MyTagHandler extends SimpelTagSupport {
}
doTag() method
o By default does nothing
o Need to implement / override to code/write functionality of tag
o Invoked when the end element of the tag encountered.
JSP implicit objects (e.g. out etc) are available to tag handler class through
pageContext object.
pageContext object can be obtained using getJspContext() method.
For example to get the reference of implicit out object, we write.
o PageContext pc = (PageContext) getJspContext();
o JspWriter out = pc.getOut();
Note: If you are using any IDE (like netBeans 4.1, in order to build custom tags,
the IDE will write .tld file for you.
38.6.4 Deployment
of
web
Note: Any good IDE will also perform this step on your behalf
CopyrightVirtualUniversityofPakistan
369
WebDesignandDevelopment(CS506)
Approach
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
import javax.servlet.jsp.*;
import javax.servlet.jsp.tagext.*;
370
WebDesignandDevelopment(CS506)
CopyrightVirtualUniversityofPakistan
371
WebDesignandDevelopment(CS506)
index.jsp
<%-using taglib directive, specifying the tld file name as well as
prefix. Note that you you use any value for the prefix attribtute
--%>
<%@taglib uri="/WEB-INF/tlds/customtags.tld" prefix="mytag" %>
<html>
<body>
<h2>A Simple Tag Example</h2>
<h3>
<%-- calling welcome tag with the help of prefix --%>
<mytag:welcome />
</h3>
</body>
</html>
Approach
CopyrightVirtualUniversityofPakistan
372
WebDesignandDevelopment(CS506)
CourseOutlineBean.java
This is the same file used in the last example
package vubean;
import java.io.*;
public class CourseOutlineBean implements Serializable{
private int sessionNo;
private String topic;
private String assignment;
// no argument constructor
public CourseOutlineBean() {
sessionNo = 0;
topic = "";
assignment = "";
}
// setters
public void setSessionNo(int s){
sessionNo = s;
}
public void setTopic(String t){
topic = t;
}
public void setAssignment(String a){
assignment = a;
}
// getters
public int getSessionNo( ){
return sessionNo;
}
public String getTopic( ){
return topic;
}
public String getAssignment( ){
return assignment;
}
} // end class
CopyrightVirtualUniversityofPakistan
373
WebDesignandDevelopment(CS506)
CourseDAO.java
No changes are made to this file too.
package vu;
import
import
import
import
java.io.*;
java.sql.*;
java.util.*;
vubean.*;
374
WebDesignandDevelopment(CS506)
ResultSet rs = pStmt.executeQuery();
int sNo;
String topic;
String assignment;
while ( rs.next() ) {
sNo
= rs.getInt("sessionNo");
topic = rs.getString("topic");
assignment = 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
375
WebDesignandDevelopment(CS506)
}
} // end releaseResources
}// end CourseDAO
MyTagHandler.java
The tag handler class uses JavaBeans (CourseOutlineBean.java &
CourseDAO.java), and includes the logic of displaying course outline in tabular
format.
package vutag;
// importing package that contains the JavaBeans
import vubean.*;
import vu.*;
import javax.servlet.jsp.tagext.*;
import javax.servlet.jsp.*;
import java.util.*;
public class MyTagHandler extends SimpleTagSupport {
/*
Declaration of pageName property.
*/
private String pageName;
public void doTag() throws JspException {
CourseDAO courseDAO = new CourseDAO();
ArrayList courseList = courseDAO.retrieveCourseList(pageName);
// to display course outline in tabular form, this method is
// used define below
display(courseList);
}
/*
Setter for the pageName attribute.
*/
public void setPageName(java.lang.String value) {
this.pageName = value;
}
/*
display method used to print courseoutline in tabular form
*/
private void display(ArrayList courseList)throws JspException{
CopyrightVirtualUniversityofPakistan
376
WebDesignandDevelopment(CS506)
PageContext pc = (PageContext)getJspContext();
JspWriter out = pc.getOut();
try{
// displaying table headers
out.print("<TABLE BORDER=1 >");
out.print("<TR>");
out.print("<TH> Session No </TH>");
out.print("<TH> Topic </TH>");
out.print("<TH> Assignment </TH>");
out.print("</TR>");
// loop to iterate over courseList
for (int i=0; i<courseList.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>");
}catch(java.io.IOException ex){
throw new JspException(ex.getMessage());
}
}
} // end clas MyTagHandler.java
mytaglibrary.tld
<?xml version="1.0" encoding="UTF-8"?>
<taglib version="2.0" xmlns="http://java.sun.com/xml/ns/j2ee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee webjsptaglibrary_2_0.xsd">
<tlib-version>1.0</tlib-version>
<short-name>mytaglibrary</short-name>
<!the value of uri will be used in JSP to refer to this tld -->
<uri>/WEB-INF/tlds/mytaglibrary</uri>
<!
CopyrightVirtualUniversityofPakistan
377
WebDesignandDevelopment(CS506)
Specifying the tag name and tag class. Also mentioning that
this tag has no body
-->
<tag>
<name>coursetag</name>
<tag-class>vutag.MyTagHandler</tag-class>
<body-content>empty</body-content>
<!
Specifying the attribute name and its type
-->
<attribute>
<name>pageName</name>
<type>java.lang.String</type>
</attribute>
</tag>
</taglib>
out.print("</TABLE>");
index.jsp
This page is used to display the course options to the user in the radio button form.
<html>
<body>
<h2>Select the page you want to visit</h2>
<form name="myForm" action="controller.jsp" >
<h3>
<input type="radio" name = "page" value="web"/>
Web Design & Development
</h3>
<br>
<h3>
<input type="radio" name = "page" value="java"/>
Java
</h3>
<br>
<input type="submit" value="Submit" />
</form>
</body>
</html>
CopyrightVirtualUniversityofPakistan
378
WebDesignandDevelopment(CS506)
controller.jsp
Based upon the selection made by the user, this page will redirect the user to respective
pages. Those are web.jsp and java.jsp
<html>
<body>
<!-- scriptlet -->
<%
String pageName = request.getParameter("page");
if (pageName.equals("web")) {
response.sendRedirect("web.jsp");
} else if (pageName.equals("java") )
response.sendRedirect("java.jsp");
}
%>
</body>
</html>
java.jsp
<%-- using taglib directive, specifying the tld file and prefix -%>
<%@taglib uri="/WEB-INF/tlds/mytaglibrary.tld" prefix="mytag"%>
<html>
<body>
<center>
<h2> Welcome to Java Learning Center </h2>
<h3> Course Outline</h3>
<%-calling coursetag and specifying java as attribute
value
--%>
<mytag:coursetag pageName="java" />
</center>
</body>
</html>
CopyrightVirtualUniversityofPakistan
379
WebDesignandDevelopment(CS506)
web.jsp
<%-- using taglib directive, specifying the tld file and prefix -%>
<%@taglib uri="/WEB-INF/tlds/mytaglibrary.tld" prefix="mytag"%>
<html>
<body>
<center>
<h2> Welcome to Java Learning Center </h2>
<h3> Course Outline</h3>
<%-calling coursetag and specifying java as attribute
value
--%>
<mytag:coursetag pageName="java" />
</center>
</body>
</html>
38.9 References:
Note: Coding exercises in working condition for this lecture are also available on Downloads
section of LMS.
CopyrightVirtualUniversityofPakistan
380
WebDesignandDevelopment(CS506)
CopyrightVirtualUniversityofPakistan
381
WebDesignandDevelopment(CS506)
Java Beans
PersonInfo Has following attributes:
o name
o address
o phoneNum
PersonDAO
o Encapsulates database logic.
o Therefore, it will be used to save and retrieve PersonInfo data.
Java Server Pages
addperson.jsp
o Used to collect new person info that will be saved in database.
saveperson.jsp
o Receives person info from addperson.jsp
o Saves it to database
searchperson.jsp
o Used to provide search criteria to search Persons info by providing name
showperson.jsp
o This page receive persons name from searchperson.jsp to search in
o database
o Retrieves and displays person record found against person name
Error Page
addbookerror.jsp
o This page is declared as an error page and used to identify the type of exception.
o In addition to that, it also displays the message associated with the received
exception to the user.
CopyrightVirtualUniversityofPakistan
382
WebDesignandDevelopment(CS506)
383
WebDesignandDevelopment(CS506)
package vu;
import java.util.*;
import java.sql.*;
public class PersonDAO{
private Connection con;
CopyrightVirtualUniversityofPakistan
384
WebDesignandDevelopment(CS506)
// default constructor
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);
}
// used to search the person records against name and returns
// the ArrayList that contains only those PersonInfo 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 = ?";
CopyrightVirtualUniversityofPakistan
385
WebDesignandDevelopment(CS506)
personBean.setName(name);
personBean.setAddress(add);
personBean.setPhoneNum(pNo);
// adding a bean to arraylist
personList.add(personBean);
} // end while
return personList;
} // end retrievePersonList
CopyrightVirtualUniversityofPakistan
386
WebDesignandDevelopment(CS506)
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" />
<TABLE BORDER="1" >
CopyrightVirtualUniversityofPakistan
387
WebDesignandDevelopment(CS506)
<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>
<TR>
<TD> <h4>Phone 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>
</TABLE>
</form>
<h4>
<%-- A link to searchperson.jsp --%>
<a href="searchperson.jsp" > Search Person </a>
</h4>
</center>
</body>
</html>
saveperson.jsp
This JSP page gets data from the addperson.jsp, makes an object of PersonInfo and
saves it to the database using PersonDAO class. Apart from these, it also displays an
informative message to the user if new person record is saved successfully into thedatabase and
two hyperlinks to navigate on to the desired pages as shown in the following diagram:
CopyrightVirtualUniversityofPakistan
388
WebDesignandDevelopment(CS506)
CopyrightVirtualUniversityofPakistan
389
WebDesignandDevelopment(CS506)
searchperson.jsp
It gets search criteria from the user (i.e. name) and sends it to showperson.jsp to display the
search results. The outlook of the page is given below:
The code used to generate the above page given page is:
<%-- defining error page --%>
<%@page errorPage="addbookerror.jsp" %>
<html>
<body>
<center>
<h2> Address Book </h2>
<h3> Search Person</h3>
<%-Form that contains Text input field and sending it to
showperson.jsp
--%>
<form name ="search" action="showperson.jsp" />
<TABLE BORDER="1" >
<TR>
<TD> <h4 >Name</h4>
</TD>
<TD> <input type="text" name="name" />
</TR>
<TR>
<TD COLSPAN="2" ALIGN="CENTER"">
CopyrightVirtualUniversityofPakistan
</TD>
390
WebDesignandDevelopment(CS506)
391
WebDesignandDevelopment(CS506)
<body>
<center>
<h2> Address Book </h2>
<h3> Following results meet your search criteria</h3>
<TABLE BORDER="1" >
<TR>
<TH> Name </TH>
<TH> Address </TH>
<TH> PhoneNum </TH>
</TR>
<jsp:useBean id="pDAO" class="vu.PersonDAO" scope="page" />
<%
// getting search criteria sent by searchperson.jsp
String pName = request.getParameter("name");
// retrieving matching records from the Database using
// retrievePersonList() method of PersonDAO
ArrayList personList = personDAO.retrievePersonList(pName);
PersonInfo person = null;
// Showing all matching records by iterating over ArrayList
for(int i=0; i<personList.size(); i++) {
person = (PersonInfo)personList.get(i);
%>
<TR>
<TD> <%= person.getName()%> </TD>
<TD> <%= person.getAddress()%> </TD>
<TD> <%= person.getPhoneNum()%> </TD>
</TR>
<%
} // end for
%>
</TABLE >
<a href="addperson.jsp" > Add Person </a>
<a href="searchperson.jsp" > Search Person </a>
</center>
</body>
</html>
addbookerror.jsp
This JSP error page is called implicitly by all other JSP pages whenever any uncaught
CopyrightVirtualUniversityofPakistan
392
WebDesignandDevelopment(CS506)
/unhandled exception occurs. It also finds out the type of the exception that is generated,and
shows an appropriate message to the user:
<%-- indicating that this is an error page --%>
<%@page isErrorPage="true" %>
<%-- importing class --%>
<%@page import = "java.sql.SQLException" %>
<html>
<head>
<title>Error</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){
%>
A Class Not Found Exception
<%
} else {
%>
A Exception
<%
} // end if-else
%>
<%-- end scriptlet to determine exception type --%>
occured while interacting with the database
</h3>
CopyrightVirtualUniversityofPakistan
393
WebDesignandDevelopment(CS506)
<h3>
The Error Message was
<%= exception.getMessage() %>
</h3>
<h3 > Please Try Again Later! </h3>
<%-hyperlinks to return back to addperson.jsp or
searchperson.sjp
--%>
<h3>
<a href="controller.jsp?action=addperson" >
Add Person
</a>
<a href="controller.jsp?action=searchperson" >
Search Person
</a>
</h3>
</body>
</html>
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 all of the components cause strong ripple effects whenever a change is
CopyrightVirtualUniversityofPakistan
394
WebDesignandDevelopment(CS506)
made anywhere. High coupling makes classes difficult or impossible to reuse because they
depend on so many other classes. Adding new data views often requires re-implementing or
cutting and pasting business logic code, which then requires maintenance in 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.
CopyrightVirtualUniversityofPakistan
395
WebDesignandDevelopment(CS506)
In Model 1 architecture, view selection is decentralized, because the current page being displayed
determines the next page 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 to display occurs in scriptlet 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 replying back to the client. There is still separation of presentation from content,
because all data access is performed using JavaBeans.
Although the Model 1 architecture should be perfectly suitable for simple applications, it may not
be desirable for complex implementations. Random usage of this architecture usually leads to a
significant amount of scriptlets or Java code embedded within the JSP page, especially if there is a
significant amount of request processing to be performed. While this may not seem to be much of
a problem for Java developers, it is certainly an issue if your JSP pages are created and maintained
by designers which are only aware of HTML and some scripting language.
Note: Probably some of you must be thinking about the case study discussed earlier inthis
handout. Indeed, it is based on MVC Model 1 architecture.
39.4 References:
Note: Coding exercises in working condition for this lecture are also available on Downloads
section of LMS.
CopyrightVirtualUniversityofPakistan
396
WebDesignandDevelopment(CS506)
The page-centric approach has lot of draw backs such as the code becomes a mixture of
presentation, business and data access logic. The maintenance and up-gradation of the application
becomes a nightmare. Scaling of such kind of application is also difficult and lots of code is also
get duplicated.
CopyrightVirtualUniversityofPakistan
397
WebDesignandDevelopment(CS506)
It gives the single point of control to perform security checks and to record logging information
It also encapsulates the incoming data into a form that is usable by the back-end MVC model.
Well discuss it with the help of an example.
The following figure will help you to understand the architecture and functioning of the
application that is built using MVC Model 2 architecture.
The client (browser) sends all the requests to the controller. Servlet/JSP acts as the Controller and
is in charge of the request processing and creation of any beans or objects(Models) used by the
JSP.
JSP is working as View and there is not much processing logic within the JSP page itself,it is
simply responsible for retrieving objects and/or beans, created by the Servlet,extracting dynamic
content from them and put them into the static templates.
CopyrightVirtualUniversityofPakistan
398
WebDesignandDevelopment(CS506)
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.
399
WebDesignandDevelopment(CS506)
The same rule applies to hyperlinks that send the action parameter along with value by using
query string technique.
This eases the controllers 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, lets first see the code of JavaBean that is used in this example.
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){
name = n;
}
public void setAddress(String a){
address = a;
}
public void setPhoneNum(int pNo){
phoneNum = pNo;
}
// getters
public String getName( ){
return name;
}
public String getAddress( ){
return address;
CopyrightVirtualUniversityofPakistan
400
WebDesignandDevelopment(CS506)
}
public int getPhoneNum( ){
return phoneNum;
}
} // end class PersonInfo
PersonDAO
This class will help in retrieving and storing persons records in database. The code is given
below:
package vu;
import java.util.*;
import java.sql.*;
public class PersonDAO{
private Connection con;
// default constructor
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);
}
// used to search the person records against name and returns
// the ArrayList that contains only those PersonInfo 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 = ?";
CopyrightVirtualUniversityofPakistan
401
WebDesignandDevelopment(CS506)
while ( rs.next() ) {
name = rs.getString("name");
add = rs.getString("address");
pNo = rs.getInt("phoneNumber");
// creating a CourseOutlineBean object
PersonInfo personBean = new PersonInfo();
personBean.setName(name);
personBean.setAddress(add);
personBean.setPhoneNum(pNo);
// adding a bean to arraylist
personList.add(personBean);
} // end while
return personList;
} // end retrievePersonList
402
WebDesignandDevelopment(CS506)
pStmt.setString( 2 , add );
pStmt.setInt( 3 , pNo );
pStmt.executeUpdate();
} // end addPerson
// overriding finalize method to release acquired resources
public void finalize( ) {
try{
if(con != null){
con.close();
}
}catch(SQLException sqlex){
System.out.println(sqlex);
}
} // end finalize
} // end PersonDAO class
addperson.jsp
This page is used for entering a new person record into the database. Note that a hyperlink is also
given at the bottom of 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.
CopyrightVirtualUniversityofPakistan
403
WebDesignandDevelopment(CS506)
404
WebDesignandDevelopment(CS506)
</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>
</center>
</body>
</html>
searchperson.jsp
This JSP is used to search the person record against name given in the text field. A hyperlink is
also given at the bottom of addperson.jsp.
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>
CopyrightVirtualUniversityofPakistan
405
WebDesignandDevelopment(CS506)
</TD>
<TR>
<TD COLSPAN="2" ALIGN="CENTER">
406
WebDesignandDevelopment(CS506)
407
WebDesignandDevelopment(CS506)
CopyrightVirtualUniversityofPakistan
408
WebDesignandDevelopment(CS506)
showperson.jsp
This following figure gives you the view when name saad is searched.
409
WebDesignandDevelopment(CS506)
<body>
<center>
<h2> Address Book </h2>
<h3> Following results meet your search criteria</h3>
<TABLE BORDER="1" >
<TR>
<TH> Name </TH>
<TH> Address </TH>
<TH> PhoneNum </TH>
</TR>
<%
// retrieving arraylist stored on controller.jsp to display
// PersonInfo objects
ArrayList personList =
(ArrayList)request.getAttribute("list");
PersonInfo person = null;
for(int i=0; i<personList.size(); i++) {
person = (PersonInfo)personList.get(i);
%>
<%-- displaying PersonInfo details--%>
<TR>
<TD> <%= person.getName()%> </TD>
<TD> <%= person.getAddress()%> </TD>
<TD> <%= person.getPhoneNum()%> </TD>
</TR>
<%
} // end for
%>
</TABLE >
<h4>
<a href="controller.jsp?action=addperson"> Add Person </a>
<a href="controller.jsp?action=searchperson">Search Person</a>
</h4>
</center>
</body>
</html>
addbookerror.jsp
User will view this page only when any sort of exception is generated. The code of this page is
given below:
CopyrightVirtualUniversityofPakistan
410
WebDesignandDevelopment(CS506)
411
WebDesignandDevelopment(CS506)
412
WebDesignandDevelopment(CS506)
413
WebDesignandDevelopment(CS506)
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class ControllerServlet extends HttpServlet {
// 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 ServletException, IOException
{
processRequest(request, response);
}
414
WebDesignandDevelopment(CS506)
searchPerson(request,response);
}
} // end processRequest()
// if request comes to add/save person
private void addPerson(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException
{
try
{
// creating PersonDAO object
PersonDAO pDAO = new PersonDAO();
// creating PersonInfo object
PersonInfo person = new PersonInfo();
// setting properties of Person object
// setting name property
String pName = request.getParameter("name");
person.setName(pName);
// setting address propertyt
String add = request.getParameter("address");
person.setAddress(add);
// setting phoneNumb property
String pNo = request.getParameter("phoneNum");
int phoneNum = Integer.parseInt(pNo);
person.setPhoneNum(phoneNum);
// calling PersonDAO method to save data into database
pDAO.addPerson(person);
// redirecting page to saveperson.jsp
response.sendRedirect("saveperson.jsp");
}catch (SQLException sqlex){
// setting SQLException instance
request.setAttribute("javax.servlet.jsp.JspException" , sqlex);
RequestDispatcher rd =
request.getRequestDispatcher("addbookerror.jsp");
CopyrightVirtualUniversityofPakistan
415
WebDesignandDevelopment(CS506)
rd.forward(request, response);
}catch (ClassNotFoundException cnfe){
// setting ClassNotFoundException instance
request.setAttribute("javax.servlet.jsp.JspException" , cnfe);
RequestDispatcher rd =
request.getRequestDispatcher("addbookerror.jsp");
rd.forward(request, response);
}
}// end addperson()
// if request comes to search person record from database
private void searchPerson(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException{
try {
// creating PersonDAO object
PersonDAO pDAO = new PersonDAO();
String pName = request.getParameter("name");
// calling DAO method to retrieve personlist from database
// against name
ArrayList personList = pDAO.retrievePersonList(pName);
request.setAttribute("list", personList);
// forwarding request to showpeson, so it can render personlist
RequestDispatcher rd =
request.getRequestDispatcher("showperson.jsp");
rd.forward(request, response);
}catch (SQLException sqlex){
// setting SQLException instance
request.setAttribute("javax.servlet.jsp.JspException" , sqlex);
RequestDispatcher rd =
request.getRequestDispatcher("addbookerror.jsp");
rd.forward(request, response);
}catch (ClassNotFoundException cnfe){
// setting ClassNotFoundException instance
request.setAttribute("javax.servlet.jsp.JspException" , cnfe);
RequestDispatcher rd =
request.getRequestDispatcher("addbookerror.jsp");
CopyrightVirtualUniversityofPakistan
416
WebDesignandDevelopment(CS506)
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>
<servlet-mapping>
<servlet-name> ControllerServlet </servlet-name>
<url-pattern> /controller </url-pattern>
</servlet-mapping>
</web-app>
40.4 References:
Note: Coding exercises in working condition for this lecture are also available on Downloads
section of LMS.
CopyrightVirtualUniversityofPakistan
417
WebDesignandDevelopment(CS506)
41.1.1 Layers
The partitioning of a system into layers such that each layer performs a specific type of
functionality and communicates with the layer that adjoins 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 requirements and size of
the application.
CopyrightVirtualUniversityofPakistan
418
WebDesignandDevelopment(CS506)
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 passes the user request to the business layer, which further passes the request to the data
layer. The data layer communicates with the data sources (like Database etc.) or other external
services in order to accomplish the user request.
Lets discuss each layers responsibility in detail:
41.1.1.1 Presentation Layer
It provides a user interface to the client/user to interact with the application. This is the only part
of the application visible to client.
Its job list includes collecting users input, validating users 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).
41.1.1.2 Business Layer
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.
41.1.1.3 Data Layer
It 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
CopyrightVirtualUniversityofPakistan
419
WebDesignandDevelopment(CS506)
example, the address book application needs to retrieve all person records from a database to
display them to the user.
41.1.2 Tiers
As mentioned, layers help in building a tiered architecture. Like layers, there is no restriction on
using number of tiers. An application can be based on Single-tier, Two-tier,Three-tier or N-Tier
(application which 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 also a presentation layer that is used to generate the client presentation
often called server presentation. Well 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 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.
The database server is often running on a separate tier, i.e. DB machine often called Enterprise
information tier.
CopyrightVirtualUniversityofPakistan
420
WebDesignandDevelopment(CS506)
On business layer, JavaBeans (also referred as Plain Old Java Objects (POJO) ) can be used.
While moving towards a bigger architecture, the J2EE provides the special class that fits in
business layer i.e. Enterprise JavaBean (EJB).
EJBs are special java classes that are used 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.
CopyrightVirtualUniversityofPakistan
421
WebDesignandDevelopment(CS506)
Suppose, our client is HTML based. Client does some processing on HTML and transports it to
web server. JSP and Servlets are possible technologies that 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 presentation layer reside on web server and of course controllers are also used over here.
If web server, 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 and JSP/Servlets works in two different servers. As you already know, JSP and Servlets
runs in a web server where as EJBs requires an 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 middle tier. This tier stores and 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.
422
WebDesignandDevelopment(CS506)
o input will be in 4,2,6,5 format separated by commas where 4,2 represents entries of
the first row
Display format
o Displays the matrix as a square
Storage format for DB
o Matrix will be stored as a string in the database along with the order of the matrix
o The following figure shows the table design that will be used to store the results.
CopyrightVirtualUniversityofPakistan
423
WebDesignandDevelopment(CS506)
The data layer has a class MatrixDAO that is used to save the matrix result into database. As
mentioned in the problem statement, that resultant matrix should be saved in the database. So,
MatrixDAO is used to accomplish that.
MatrixDAO called by the MatrixMultiplier, a business layer class. The functionality list
of MatrixMultiplier includes:
- Converting the user input string (e.g. 2,3,4,1) into a proper object i.e. a matrix data structure.
[
- Helps in calculating product of two matrices.
Controller layers 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. Furthermore, ControllerServlet sends the output to the
matrixresult.jsp and receives the input from
matrixinput.jsp.
The MatrixBean representing matrix data structure, as you can see in the figure is used across
several layers. In fact, the object formed by MatrixMultiplier from a user
input string is of MatrixBean type. It is used to transfer data from one layer to another.
First, look on the MatrixBean code given below:
MatrixBean
package bo;
import java.io.*;
public class MatrixBean implements Serializable{
// a 2D array representing matrix
public int matrix[ ][ ] ;
// constructor
public MatrixBean()
{
matrix = new int[2][2];
matrix[0][0] = 0;
matrix[0][1] = 0;
matrix[1][0] = 0;
matrix[1][1] = 0;
}
// setter that takes 4 int values and assigns these to array
public void setMatrix(int w, int x, int y, int z)
{
matrix[0][0] = w;
matrix[0][1] = x;
CopyrightVirtualUniversityofPakistan
424
WebDesignandDevelopment(CS506)
matrix[1][0] = y;
matrix[1][1] = z;
}
// getter returning a 2D array
public int[ ][ ] getMatrix()
{
return matrix;
}
// used to convert 2D array into string
public String toString()
{
return matrix[0][0] + "," + matrix[0][1] + "," +
matrix[1][0] + "," +matrix[1][1] ;
}
} // end MatrixBean
matrixinput.jsp
This JSP is used to collect the input for two matrices in the form of string such as 2,3,5,8.The data
will be submitted to ControllerServlet from this page.
<html>
<body>
<h2>
Enter Two Matrices of order 2 * 2 to compute Product
</h2>
<h3>
<%-controller is an alias/URL pattern of ControllerServlet
--%>
<form name="matrixInput" action="controller" >
First Matrix:
<input type="text" name = "firstMatrix" /> E.g. 2,3,4,1
<br/>
Second Matrix:
<input type="text" name = "secondMatrix" />
<br/>
<input type = "submit" value = "Calculate Product" />
</form>
</h3>
</body>
</html>
CopyrightVirtualUniversityofPakistan
425
WebDesignandDevelopment(CS506)
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.
package controller;
import bl.*;
import bo.* ;
import java.io.*;
import java.net.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class ControllerServlet extends HttpServlet {
// 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 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 = request.getParameter("firstMatrix");
String sMatrix2 = request.getParameter("secondMatrix");
// Creating MatrixMultipler object
MatrixMultiplier mm = new MatrixMultiplier();
// Passing Strings to convertToObject() method of
MatrixMultiplier
CopyrightVirtualUniversityofPakistan
426
WebDesignandDevelopment(CS506)
427
WebDesignandDevelopment(CS506)
428
WebDesignandDevelopment(CS506)
} // end multiply()
// save results (MatrixBean containg product of two matrices)
//into
// database using DAO
public void saveResult( MatrixBean resultMatrix )
{
MatrixDA0 dao = null;
try{
dao = newMatrixDAO();}
catch(ClassNotFoundException e){}
catch(SQLException e){}
dao.saveMatrix(resultMatrix);
}
} // end MatrixMulitplier
MatrixDAO
As class name depicts, it is used to store product results into database. Lets look on the
code to see how it is accomplished.
package dal;
import java.util.*;
import java.sql.*;
import bo.*;
public class MatrixDAO{
private Connection con;
// constructor
public MatrixDAO() 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:MatrixDSN";
con = DriverManager.getConnection(conUrl);
}
// used to store MatrixBean into database after converting it to
// a String
public void saveMatrix(MatrixBean matrix){
try
{
CopyrightVirtualUniversityofPakistan
429
WebDesignandDevelopment(CS506)
pStmt.executeUpdate();
}catch(SQLException sqlex){
System.out.println(sqlex);
}
} // end saveMatrix
// overriding finalize method to release acquired resources
public void finalize( ) {
try{
if(con != null){
con.close();
}
}catch(SQLException sex){
System.out.println(sex);
}
} // end finalize
} // end MatrixDAO class
matrixresult.jsp
Used to display resultant product of two matrices. The code is given below:
<%-- importing bo package that contains MatrixBean --%>
<%@ page import="bo.*"%>
<html>
<body>
<h1>The resultant Matrix is </h1>
CopyrightVirtualUniversityofPakistan
430
WebDesignandDevelopment(CS506)
431
WebDesignandDevelopment(CS506)
<servlet-mapping>
<servlet-name> ControllerServlet </servlet-name>
<url-pattern> /controller </url-pattern>
</servlet-mapping>
</web-app>
41.5 References:
Note: Coding exercises in working condition for this lecture are also available on Downloads
section of LMS.
CopyrightVirtualUniversityofPakistan
432
WebDesignandDevelopment(CS506)
42.1 Overview
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 operations on them. It is inspired form both the ECMAScript
and the XPath expression language.
CopyrightVirtualUniversityofPakistan
433
WebDesignandDevelopment(CS506)
Contrary to the above figure, have a look on the subsequent figure that gives you a hint how
useful EL can be?
CopyrightVirtualUniversityofPakistan
434
WebDesignandDevelopment(CS506)
Syntax of EL
Expressions & identifiers
Arithmetic, logical & relational operators
Automatic type conversion
Access to beans, arrays, lists & maps
Access to set of implicit objects
42.3.1 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
Operators
Variables (object references)
Implicit call to function using property name
EL Literals
The list of literals that can be used as an EL expression and their possible values are given in the
tabular format below:
435
WebDesignandDevelopment(CS506)
EL Operators
The lists of operators that can be used in EL expression are given below:
Identifiers in the expression language represent the names of objects stored in one of the JSP
scopes: page, request, session, or application. These types of objects are referred to scoped
variables throughout this handout.
EL has 11 reserved identifiers, corresponding to 11 implicit objects. All other identifiers
assumed to refer to scoped variables.
EL implicit Objects
The Expression Language defines a set of implicit objects given below in tabular format:
CopyrightVirtualUniversityofPakistan
436
WebDesignandDevelopment(CS506)
Category
Implicit Object
Operator
The context for the JSP page, used to access the JSP
JSP
pageContext
implicit objects such as request, response, session,
Scopes
pageScope
requestScope
attributes
A Map associating names & values of request scoped
attributes
sessionScope
applicationScope
Request
param
Parameters
paramValues
Request
header
Headers
headerValues
Cookies
cookie
Initialization
Parameters
initParam
Examples
of using implicit objects are:
${ pageContext.response }
o Evaluates to response implicit object of JSP
${ param.name }
o This expression is equivalent to calling request.getParameter(name);
${ cookie.name.value }
o Returns the value of the first cookie with the given name
o Equivalent to
if (cookie.getName().equals(name){
String val = cookie.getValue();
}
CopyrightVirtualUniversityofPakistan
437
WebDesignandDevelopment(CS506)
result.jsp
<html>
<body>
<%-- The code to sum two numbers if we used scriptlet
<%
String no1 = request .getParameter("num1");
String no2 = request .getParameter("num2");
int num1 = Integer.parseInt(no1);
int num2 = Integer.parseInt(no2);
%>
Result is: <%= num1 + num2 %>
--%>
<%-- implicit Object param is used to access request parameters
By Using EL summing two numbers
--%>
Result is: ${param.num1 + param.num2}
</body>
</html>
CopyrightVirtualUniversityofPakistan
438
WebDesignandDevelopment(CS506)
By using java code, either in pure servlet or in a scriptlet of JSP, we can store variables in a
particular scope. For example,
o Storing a variable in session scope using Java code
Assume that we have PersonInfo class and we want to store its object p in
session scope then we can write the following lines of code to accomplish that:
HttpSession ses = request.getSession(true);
PersonInfo p = new PersonInfo();
p.setName(ali);
ses.setAttribute(person , p);
o Storing a variable in request 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, well write:
PersonInfo p = new PersonInfo();
p.setName(ali);
request.setAttribute(person , p);
You must be thinking of some 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.
o 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 well write:
<jsp:useBean id=p class=PersonInfo
scope=request/>
Later, you can change the properties of object p by using action tag as well.For example
<jsp:setProperty name=p property=name value=ali
/>
You are already very much familiar of retrieving any stored scoped variable by using java
code and JSP action tags. Here, well discuss how EL retrieves scoped variables. As already
mentioned, identifiers in the valid expression represent the names of objects stored in one of
the JSP scopes: page, request, session and application.
CopyrightVirtualUniversityofPakistan
439
WebDesignandDevelopment(CS506)
When the expression language encounters an identifier, it searches for a scoped variable with
that name first in page scope,then in request scope,then in session scope,and finally in
application scope
Note: - If no such object is located in four scopes, null is returned.
For example, if weve stored PersonInfo object p 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:
42.3.3 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.
Assume that JavaBean PersonInfo has name property and its object person is stored in
some scope. Then to access the name property of person object, well write the following
expression using EL:
CopyrightVirtualUniversityofPakistan
440
WebDesignandDevelopment(CS506)
${person.name}
The EL accesses the objects properties using the JavaBeans conventions therefore getName()
must be defined in PersonInfo. Moreover, if property being accessed itself an object, the dot
operator can be applied recursively. For example
Bracket ([ ]) operator
This operator can be applied to arrays & collections implementing List interface e.g.
ArrayList etc.
o Index of the element appears inside brackets
o For example, ${ personList[2] } returns the 3rd element stored in it
Moreover, this operator can also be applied to collections implementing Map interface e.g.
HashMap etc.
o Key is specified inside brackets
o For example, ${ myMap[id] } returns the value associated with the
Multiple expressions can be combined and intermixed with static text. For example
$ { Hello ${user.firstName} ${user.lastName} }
EL also supports automatic type conversion; as a result primitive can implicitly wrap and
unwrap into/from their corresponding java classes. For example
CopyrightVirtualUniversityofPakistan
441
WebDesignandDevelopment(CS506)
Assume that person is null, then no exception would be thrown and the result would also be
null.
In template text the value of the expression is inserted into the current output. E.g.
<h3> $ { } </h3>
442
WebDesignandDevelopment(CS506)
}
public void setPhoneNum(int pNo){
phoneNum = pNo;
}
// getters
public String getName( ){
return name;
}
public String getAddress( ){
return address;
}
public int getPhoneNum( ){
return phoneNum;
}
}
PersonDAO.java
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 {
establishConnection();
}//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(String pName)
throws SQLException
{
ArrayList personList = new ArrayList();
CopyrightVirtualUniversityofPakistan
443
WebDesignandDevelopment(CS506)
444
WebDesignandDevelopment(CS506)
<html>
<body>
<center>
<h2> Address Book </h2>
<h3> Search Person</h3>
<FORM name ="search" action="controllerservlet" />
<TABLE BORDER="1" >
<TR>
<TD> <h4 >Name</h4> </TD>
<TD> <input type="text" name="name" />
</TR>
</TD>
<html>
<body>
<center>
<h2> Address Book </h2>
<h3> Search Person</h3>
<FORM name ="search" action="controllerservlet" />
<TABLE BORDER="1" >
<TR>
<TD> <h4 >Name</h4> </TD>
<TD> <input type="text" name="name" />
</TR>
</TD>
ControllerServlet.java
The Controller Servlet receives request from searchperson.jsp and after fetching search results
from database, forwards the request to showperson.jsp.
package controller;
import
import
import
import
import
import
vu.*;
java.util.*;
java.io.*;
java.net.*;
javax.servlet.*;
javax.servlet.http.*;
445
WebDesignandDevelopment(CS506)
CopyrightVirtualUniversityofPakistan
446
WebDesignandDevelopment(CS506)
447
WebDesignandDevelopment(CS506)
42.4 References:
Note: Coding exercises in working condition for this lecture are also available on Downloads
section of LMS.
CopyrightVirtualUniversityofPakistan
448
WebDesignandDevelopment(CS506)
CopyrightVirtualUniversityofPakistan
449
WebDesignandDevelopment(CS506)
Library
URI
Prefix
Core
http://java.sun.com/jsp/jstl/core
SQL
http://java.sun.com/jsp/jstl/sql
sql
Internationalization/
http://java.sun.com/jsp/jstl/fmt
fmt
F
XML
http://java.sun.com/jsp/jstl/xml
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
fmt_rt
F
XML
http://java.sun.com/jsp/jstl/xml_rt
x_rt
450
WebDesignandDevelopment(CS506)
c:set
Provides a tag based mechanism for creating and setting scope based variables. Its syntax is as
follows:
<c:set var=name
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 be bound to the variable. 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 valueAsia / Karachi.
<c:set var=timezone value=Asia/Karachi />
In the second example, a request scoped variable email email is set to a value
[email protected]
<c:set var=email scope=request [email protected] />
In the third example, a page scoped variable email is set to value of request parameteremail
by using param implicit object. If email parameter is defined in JSP page as:
<input type=text value = email />
Then c:set tag would be used as:
<c:set var=email scope=request value=param.email />
451
WebDesignandDevelopment(CS506)
<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 PersonInfos object person into
request scope using <jsp:useBean /> tag. Then using c:set tag,
persons name property is set to ali.
<jsp:useBean
/>
id=person
class=vu.PersonInfo
scope=request
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 />
This tag evaluates the expression specified by its value attribute, 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 evaluates 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 Hello would be displayed
<c:out value = Hello />
In the second example, if request parameter num evaluates to null or an empty string then default
value 0 would be displayed.
<c:out value = ${param.num}
default = 0 />
452
WebDesignandDevelopment(CS506)
System.out.println(0);
}else{
Out.println(no);
}
%>
If we want to display the property of a bean like name, well write
<c:out value= ${person.name} default = Not Set />
c:remove
As its name suggests, the c:remove action 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 which it should be removed and defaults to page.
For example, to remove a variable named square from page scope, well write:
<c:remove var = square />
And if variable email is required to be removed from request scope, then c:removetag will
look like:
<c:remove var = email scope = request />
c:forEach
In 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:
Iteration over an integer range (like Java language's for statement)
Iteration over a collection (like Java language's Iterator and Enumeration classes).
453
WebDesignandDevelopment(CS506)
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 end attribute. Note that
if the step attribute 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:forEach
tag.
For example to generate squares corresponding to range of integer values, the c:forEach tag
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>
When you use this form of the c:forEach tag, the items attribute is the only required
attribute. The value of 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 variable name is
also specified using var attribute, then the named variable will be bound to successive elements
of the collection for each iteration pass.
For example, to iterate over a String array (messages) using java code, we used to write in JSP:
<%
for(int i=0; i<messages.length; i++) {
String msg = messages[i];
%>
<%= msg %>
<%
} // end for
%>
CopyrightVirtualUniversityofPakistan
454
WebDesignandDevelopment(CS506)
This 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, w used to
write in JSP:
<%
ArrayList persons = (ArrayList)request.getAttribute(pList);
for(int i=0; i<persons.size(); i++) {
PersonInfo p == (PersonInfo)persons.get(i);
String name = p.getName();
%>
<%= name %>
<%
} // end for
%>
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 named p. Note that typecast is also not required.
Furthermore, you can use the begin, end, and step attributes to restrict which elements of
the collection are included in the iteration.
c:if
Like ordinary Javas 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 content is ignored. The syntax for writing c:if tag is:
<c:if test= expression >
Body Content
</c:if>
For example, to display a message a equals b if two strings a & b are equal, the c:if tag is
used as:
<c:if test= ${a == b} >
<h2> A equals B </h2>
CopyrightVirtualUniversityofPakistan
455
WebDesignandDevelopment(CS506)
</c:if>
c:choose
c:choose the second conditionalization tag, used in cases in which mutually exclusively test
are required to determine what content should be displayed. The syntax is shown below:
<c:choose>
<c:when test= expression >
Body content
</c:when>
<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 one. Only the body content of the first <c:when> tag whose test evaluates to
true will be processed. If none of the <c:when> tests return true, then the body content of the
<c:otherwise> tag will be processed.
Note, though, that the <c:otherwise> tag is optional; a <c:choose> tag can have at most
one nested <c:otherwise> 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 and 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> Dont know what a equals to </h2>
</c:otherwise>
</c:choose>
456
WebDesignandDevelopment(CS506)
The Add 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.
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.
457
WebDesignandDevelopment(CS506)
CopyrightVirtualUniversityofPakistan
458
WebDesignandDevelopment(CS506)
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.
CopyrightVirtualUniversityofPakistan
459
WebDesignandDevelopment(CS506)
-->
return false;
} // end of function
</SCRIPT> <!-end of script-- >
</HEAD>
<BODY>
<!- validateForm method is called and specified as a value 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>
<BR/>
Name: <INPUT type="text" name="name" size="30" />
<BR/> <BR/>
Age: <INPUT type="text" name="age" size="30" />
CopyrightVirtualUniversityofPakistan
460
WebDesignandDevelopment(CS506)
<BR/> <BR/>
<INPUT type="submit" value="Submit">
</FORM>
</BODY>
</HTML>
Representing UI components
Managing their state
Handling events
Input validation
Data binding
Automatic conversion
Defining page navigation
Supporting internationalization and accessibility.
If you are familiar with Struts and Swing (the standard Java user interface framework for desktop
applications), think of JavaServer Faces as a combination of those two frameworks. Like Swing,
JSF provides a rich component model that eases event handling and component rendering; and
like Struts, JSF provides Web application lifecycle management through a controller servlet
CopyrightVirtualUniversityofPakistan
461
WebDesignandDevelopment(CS506)
And some open course JavaServer Faces components are also available like:
CopyrightVirtualUniversityofPakistan
462
WebDesignandDevelopment(CS506)
And some third-party Java Server Faces components are also available:
CopyrightVirtualUniversityofPakistan
463
WebDesignandDevelopment(CS506)
}
public String login() {
return OK;
}}
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.
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.
464
WebDesignandDevelopment(CS506)
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-name>myBean</managed-bean-name>
<managed-bean-class>myPackage.MyBean</managed-bean-class>
<managed-bean-scope>session</managed-bean-scope>
</managed-bean>
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 "#{}".
CopyrightVirtualUniversityofPakistan
465
WebDesignandDevelopment(CS506)
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.
44.3 References:
Note: Coding exercises in working condition for this lecture are also available on Downloads
section of LMS.
CopyrightVirtualUniversityofPakistan
466
WebDesignandDevelopment(CS506)
45.1.1 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.
CopyrightVirtualUniversityofPakistan
467
WebDesignandDevelopment(CS506)
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).
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 prearrangement 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.
468
WebDesignandDevelopment(CS506)
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
Web Service
Has a UI
No GUI
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.
CopyrightVirtualUniversityofPakistan
469
WebDesignandDevelopment(CS506)
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:
45.3 References:
Note: Coding exercises in working condition for this lecture are also available on Downloads
section of LMS.
CopyrightVirtualUniversityofPakistan
470
WebDesignandDevelopment(CS506)
45.4 Resources:
http://java.sun.com
http://www.javaworld.com
http://www.theserverside.com
http://www.jsfcentral.com
http://www.jspolympus.com
http://www.onjava.com
CopyrightVirtualUniversityofPakistan
471