WP Full Notes
WP Full Notes
com
www.rejinpaul.com
UNIT I SCRIPTING. 9
Web page Designing using HTML, Scripting basics- Client side and server side scripting. Java
Script-Object, names, literals, operators and expressions- statements and features- events -
windows -documents - frames - data types - built-in functions- Browser object model - Verifying
forms.-HTML5-CSS3- HTML 5 canvas - Web site creation using tools.
The name is the property you want to set. For example, the paragraph <p> element in the
example carries an attribute whose name is align, which you can use to indicate the alignment of
paragraph on the page.
The value is what you want the value of the property to be set and always put within quotations.
The below example shows three possible values of align attribute: left, center and right.
<p align="left">This is left aligned</p><p align="center">This is center aligned</p><p
align="right">This is right aligned</p>
HTML Entities:
Eg:
p{
color: red;
text-align: center;
}
CSS Selectors:
CSS selectors are used to "find" (or select) HTML elements based on their element name, id,
class, attribute, and more.
Element Selector: The element selector selects elements based on the element name.
Eg:
p{
text-align: center;
color: red;
}
The id Selector: The id selector uses the id attribute of an HTML element to select a specific
element. To select an element with a specific id, write a hash (#) character, followed by the id of
the element.
Eg:
#para1 {
text-align: center;
color: red;
}
The class Selector: The class selector selects elements with a specific class attribute. To select
elements with a specific class, write a period (.) character, followed by the name of the class.
Eg:
.center {
text-align: center;
color: red;
}
<p class="center large">This paragraph refers to two classes.</p>
Grouping Selectors: If you have elements with the same style definitions, It will be better to
group the selectors, to minimize the code.
Eg:
h1, h2, p {
text-align: center;
6
h1 {
color: navy;
margin-left: 20px;
}
Do not add a space between the property value and the unit (such as margin-left: 20 px;). The
correct way is: margin-left: 20px;
Internal Style Sheet:
An internal style sheet may be used if one single page has a unique style. Internal styles are
defined within the <style> element, inside the <head> section of an HTML page:
Eg:
<head>
<style>
body {
background-color: linen;
}
h1 {
color: maroon;
margin-left: 40px;
}
10
11
13
HTML5:
HTML5 is a core technology markup language of the Internet used for structuring and presenting
content for the World Wide Web. As of October 2014 [update] this is the final and complete fifth
revision of the HTML standard of the World Wide Web Consortium (W3C).
HTML5 itself, according to the standard, is a markup language (just like HTML4) but the way
the term is being commonly used is as a conglomerate of web technologies, including javascript
(a programming language), CSS (a styling mechanism), HTML (a markup language) and
sometimes server side languages as well.
The DOCTYPE declaration for HTML5 is very simple: <!DOCTYPE html>
The character encoding (charset) declaration is also very simple: <meta charset="UTF-8">
HTML5 Example:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Title of the document</title>
</head>
<body>
14
</html>
HTML5 Canvas:
The HTML <canvas> element is used to draw graphics on a web page. The graphic to the left is
created with <canvas>.
It shows four elements: a red rectangle, a gradient rectangle, a multicolor rectangle, and a
multicolor text.
What is HTML Canvas?
The HTML <canvas> element is used to draw graphics, on the fly, via JavaScript.
The <canvas> element is only a container for graphics. You must use a JavaScript to actually
draw the graphics.
Canvas has several methods for drawing paths, boxes, circles, text, and adding images.
Canvas Examples
A canvas is a rectangular area on an HTML page. By default, a canvas has no border and no
content. Always specify an id attribute (to be referred to in a script), and a width and height
attribute to define the size of the canvas. To add a border, use the style attribute.
<canvas id="myCanvas" width="200" height="100"></canvas>
Empty canvas:
<canvas id="myCanvas" width="200" height="100" style="border:1px solid #000000;">
</canvas>
Draw a Line
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
ctx.moveTo(0,0);
ctx.lineTo(200,100);
ctx.stroke();
15
Draw a Text
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
ctx.font = "30px Arial";
ctx.fillText("Hello World",10,50);
Stroke Text
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
ctx.font = "30px Arial";
ctx.strokeText("Hello World",10,50);
// Create gradient
var grd = ctx.createLinearGradient(0,0,200,0);
grd.addColorStop(0,"red");
grd.addColorStop(1,"white");
// Fill with gradient
ctx.fillStyle = grd;
ctx.fillRect(10,10,150,80);
16
Java: Java is a programming language and a platform. Java is a high level, robust, secured
and object-oriented programming language.
Platform: Any hardware or software environment in which a program runs is known as a
platform. Since Java has its own runtime environment (JRE) and API, it is called platform.
I. Features of Java OR java buzzwords:
1. Simple
2. Object-Oriented
3. Platform independent
4. Secured
5. Robust
6. Architecture neutral
7. Portable
8. Dynamic
9. Interpreted
10. High Performance
11. Multithreaded
12. Distributed
Simple
Java language is simple because:
syntax is based on C++ (so easier for programmers to learn it after C++).
removed many confusing and/or rarely-used features e.g., explicit pointers, operator
overloading etc.
No need to remove unreferenced objects because there is Automatic Garbage Collection
in java.
Object-oriented
Object-oriented means we organize our software as a combination of different types of
objects that incorporates both data and behaviour.
Basic concepts of OOPs are: Object Class Inheritance Polymorphism Abstraction
Encapsulation
Platform Independent
A platform is the hardware or software environment in which a program runs. There are
two types of platforms software-based and hardware-based. Java provides software-based
platform. The Java platform differs from most other platforms in the sense that it's a
software-based platform that runs on top of other hardware-based platforms.It has two
components:
1. Runtime Environment
2. API(Application Programming Interface)
www.rejinpaul.com
www.rejinpaul.com
Java code can be run on multiple platforms e.g.Windows,Linux,Sun Solaris,Mac/OS etc. Java
code is compiled by the compiler and converted into bytecode.This bytecode is a platform
independent code because it can be run on multiple platforms i.e. Write Once and Run
Anywhere(WORA).
Secured:
Java is secured because:
No explicit pointer
Programs run inside virtual machine sandbox.
Classloader- adds security by separating the package for the classes of the local file system from
that are imported from network sources.
Bytecode Verifier- checks the code fragments for illegal code that can violate access right to objec
Security Manager- determines what resources a class can access such as reading and writing
local disk.
These security are provided by java language. Some security can also be provided by application develope
through SSL,JAAS,cryptography etc.
Robust:
Robust simply means strong. Java uses strong memory management. There are lack of
pointers that avoids security problem. There is automatic garbage collection in java. There is
exception handling and type checking mechanism in java. All these points make java robust.
Architecture-neutral:
No implementation dependent features e.g. size of primitive types is set.
Portable:
May carry the java bytecode to any platform.
High-performance:
Java is faster than traditional interpretation since byte code is "close" to native code .
Distributed:
Can able to create distributed applications in java using RMI and EJB. Files can be accessed
by calling the methods from any machine on the internet.
Multi-threaded:
A thread is like a separate program, executing concurrently. Possible to write Java programs
that deal with many tasks at once by defining multiple threads. The main advantage of multi-
threading is that it shares the same memory. Threads are important for multi-media, Web
applications etc.
Simple Java Program:
class Simple{
www.rejinpaul.com
www.rejinpaul.com
public static void main(String args[])
{
System.out.println("Hello Java");
}
}
class keyword is used to declare a class in java.
public keyword is an access modifier which represents visibility, it means it is visible
to all.
static is a keyword, any method declared as static, is known as static method. The
core advantage of static method is that there is no need to create object to invoke the
static method. The main method is executed by the JVM, so it doesn't require creating
object to invoke the main method. So it saves memory.
void is the return type of the method, it means it doesn't return any value.
main represents startup of the program.
String[] args is used for command line argument.
System.out.println() is used print statement.
class Testarray5{
public static void main(String args[]){
//creating two matrices
int a[][]={{1,3,4},{3,4,5}};
int b[][]={{1,3,4},{3,4,5}};
www.rejinpaul.com
www.rejinpaul.com
//creating another matrix to store the sum of two matrices
int c[][]=new int[2][3];
}}
Copying Array:
Syntax:
public static void arraycopy(Object src, int srcPos,Object dest, int destPos, int length )
eg: char[] src = { 'd', 'e', 'c', 'a', 'f', 'f', 'e','i', 'n', 'a', 't', 'e', 'd' };
char[] dest = new char[7];
System.arraycopy(src, 2, dest, 0, 7);
III. Operators:
Operator in java is a symbol that is used to perform operations. There are many types
of operators in java such as unary operator, arithmetic operator, relational operator,
shift operator, bitwise operator, ternary operator and assignment operator.
Operators Precedence
postfix expr++ expr--
unary ++expr --expr +expr -expr ~ !
multiplicative */%
additive +-
shift << >> >>>
relational < > <= >= instanceof
equality == !=
bitwise AND &
bitwise exclusive OR ^
bitwise inclusive OR |
logical AND &&
logical OR ||
ternary ?:
assignment = += -= *= /= %= &= ^= |= <<= >>= >>>=
Example Program:
import java.lang.*;
class methodOL
{
void area(int a){System.out.println("square="+a*a);}
void area(double a){System.out.println("circle="+3.14*a*a);}
void area(int a,int b){System.out.println("Rectangle="+a*b);}
public static void main(String args[])
{
char side=12;
methodOL obj=new methodOL();
obj.area(20);
obj.area(20.5);//OL varying type
obj.area(20,10);//OL varying parameter
obj.area(side);//OL and type promotion
}
}
OUTPUT:
square=400
circle=1319.585
Rectangle=200
square=144
Method Constructor:
1. Definition: Constructor in java is a special type of method that is used to initialize the
object.
2. Java constructor is invoked at the time of object creation. It constructs the values i.e.
provides data for the object that is why it is known as constructor.
Rules :
1. Constructor name must be same as its class name
2. Constructor must have no explicit return type. Constructor returns current class
instance (You cannot use return type yet it returns a value).
3. Like object creation, starting a thread, calling method are performed in the
constructor .
There are two types of constructors:
1. Default constructor (no-arg constructor)
A constructor that has no parameter is known as default constructor. syntax
<class_name>(){}
If there is no constructor in a class, compiler automatically creates a default
constructor.
2. Parameterized constructor
A constructor that has parameters is known as parameterized constructor.
www.rejinpaul.com
www.rejinpaul.com
Parameterized constructor is used to provide different values to the distinct objects.
Constructor Overloading:
Constructor overloading is a technique in Java in which a class can have any number
of constructors that differ in parameter lists. The compiler differentiates these
constructors by taking into account the number of parameters in the list and their type.
Difference between constructor and method in java:
There are many differences between constructors and methods. They are given below.
Method is used to
Constructor is used to initialize
expose behavior of an
the state of an object.
object.
Method is invoked
Constructor is invoked implicitly.
explicitly.
Student(Student s){
id = s.id;
name =s.name;
}
void display(){System.out.println(id+" "+name);}
example:
class Student implements Cloneable{
int rollno;
String name;
System.out.println(s1.rollno+" "+s1.name);
System.out.println(s2.rollno+" "+s2.name);
}catch(CloneNotSupportedException c){}
}
}
This keyword:
this is a reference variable that refers to the current object.
Here is given the 6 usage of java this keyword.
1. this keyword can be used to refer current class instance variable.
2. this() can be used to invoke current class constructor.
3. this keyword can be used to invoke current class method (implicitly)
4. this can be passed as an argument in the method call.
5. this can be passed as argument in the constructor call.
6. this keyword can also be used to return the current class instance.
If there is ambiguity between the instance variable and parameter, this keyword
resolves the problem of ambiguity.
Eg:
Class student
{
int id; String name;
student(int id,String name)//ambiquity in (id ,name) parameter and instance
variable.
{
this.id=id;
this.name=name;
}
}
The this() constructor call can be used to invoke the current class constructor
(constructor chaining). This approach is better if class has many constructors and
wants to reuse that constructor.
Call to this() must be the first statement in constructor.
Eg:
Student(int id,String name){
this.id = id;
this.name = name;
}
Student(int id,String name,String city){
this(id,name);//now no need to initialize id and name
this.city=city;
}
www.rejinpaul.com
www.rejinpaul.com
The method of the current class can be invoked by using the this keyword. If not used
the this keyword, compiler automatically adds this keyword while invoking the
method.
The this keyword can also be passed as an argument in the method. It is mainly used
in the event handling.Can pass the this keyword in the constructor also. It is useful if
we have to use one object in multiple classes.
Eg:
class B{
A4 obj;
B(A4 obj){
this.obj=obj;
}
void display(){
System.out.println(obj.data);//using data member of A4 class
}
}
class A4{
int data=10;
A4(){
B b=new B(this);
b.display();
}
public static void main(String args[]){
A4 a=new A4();
}
}
Can return the this keyword as an statement from the method. In such case, return
type of the method must be the class type (non-primitive).
Eg: class A{
A getA(){
return this;
}
void msg(){System.out.println("Hello java");}
}
class Test1{
public static void main(String args[]){
new A().getA().msg();
}
}
Inheritance:
Inheritance in java is a mechanism in which one object acquires all the properties and
behaviors of parent object. Inheritance represents the IS-A relationship, also known
as parent-child relationship.
Uses:
For Method Overriding (so runtime polymorphism can be achieved).
For Code Reusability.
Syntax:
class Subclass-name extends Superclass-name
www.rejinpaul.com
www.rejinpaul.com
{
//methods and fields
}
The extends keyword indicates that you are making a new class that derives from an existing
class.
In the terminology of Java, a class that is inherited is called a super class. The new class is
called a subclass.
Types of inheritance in java:
On the basis of class, there can be three types of inheritance in java: single, multilevel and
hierarchical.
In java programming, multiple and hybrid inheritance is supported through interface only not
by classes.
Reason: To reduce the complexity and simplify the language, multiple inheritances are not
supported in java.
Java wants to handle ambiguity in multiple inheritance during compile time rather than at
run time.
Example:
interface printable{
void print();
}
3) Abstract class can have final, non-final, static Interface has only static and final variables.
and non-static variables.
4) Abstract class can have static methods, main Interface can't have static methods, main
method and constructor. method or constructor.
5) Abstract class can provide the implementation Interface can't provide the implementation of
of interface. abstract class.
6) The abstract keyword is used to declare abstract The interface keyword is used to declare
class. interface.
7) Example: Example:
public abstract class Shape{ public interface Drawable{
public abstract void draw(); void draw();
} }
Packages:
Definition: A package is a grouping of related types providing access protection and name
space management. Types refers to classes, interfaces, enumerations, and annotation types.
Suppose write a group of classes that represent graphic objects, such as circles, rectangles,
lines, and points. Also write an interface, Draggable, that classes implement if they can be
dragged with the mouse.
Advantage:
Can easily determine that these types are related.
Know where to find types that can provide graphics-related functions.
The type names won’t conflict with the type names in other packages because the
package creates a new namespace.
Can allow types within the package to have unrestricted access to one another yet
still restrict access for types outside the package.
Creating a Package:
To create a package, choose a name for the package and put a package statement
with that name at the top of every source file that contains the types that want to be
included in the package.
The package statement (for example, package graphics;) must be the first line in the
source file. There can be only one package statement in each source file, and it
applies to all types in the file.
Naming Conventions:
Package names are written in all lower case to avoid conflict with the names of classes or
interfaces.
Companies use their reversed Internet domain name to begin their package names—for
example, com.example.mypackage for a package named mypackage created by a
programmer at example.com.
Packages in the Java language itself begin with java. or javax.
Using Package Members
The types that comprise a package are known as the package members.
To use a public package member from outside its package, do one of the following:
www.rejinpaul.com
www.rejinpaul.com
Refer to the member by its fully qualified name
To solve ambiguity.
Eg: Rectangle class in user defined package and awt package are differentiated by
using
graphics.Rectangle
Import the package member
Eg: import graphics.Rectangle;
Import the member's entire package
Eg: import java.*
The subpackages of packages are imported separately. In java package awt is a package and
color is subpackage both has to be imported.
import java.awt.*
import java.awt.color.*
Static import:static import is a feature that expands the capabilities of import keyword. It is
used to import static member of a class. We all know that static member are referred in
association with its class name outside the class. Using static import, it is possible to refer to
the static member directly without its class name. There are two general form of static import
statement.The first form of static import statement, import only a single static member of a
class
Syntax
import static package.class-name.static-member-name;
Example
import static java.lang.Math.sqrt; //importing static method sqrt of Math class
The second form of static import statement,imports all the static member of a class
Syntax
import static package.class-type-name.*;
Example
import static java.lang.Math.*; //importing all static member of Math class
www.rejinpaul.com
www.rejinpaul.com
VI. EXCEPTION HANDLING:
An exception is a run-time error. A Java exception is an object that describes an exceptional
(that is, error) condition that has occurred in a piece of code.
Java exception handling is managed via five keywords: try, catch, throw, throws, and
finally.
the general form of an exception-handling block:
try {
// block of code to monitor for errors
}
catch (ExceptionType1 exOb) {
// exception handler for ExceptionType1
}
catch (ExceptionType2 exOb) {
// exception handler for ExceptionType2
}
// ...
finally {
// block of code to be executed after try block ends
}
Here, ExceptionType is the type of exception that has occurred.
Exception Types:
All exception types are subclasses of the built-in class Throwable.
throwable
Exceptions error
Important subclass of Exception, called Runtime Exception is automatically defined for the
programs and includes things such as division by zero and invalid array indexing.
Exceptions of type Error are used by the Java run-time system to indicate errors having to do
with the run-time environment, itself created in response to catastrophic failures that cannot
usually be handled by program.
Uncaught Exceptions:
Any exception that is not caught by the program will ultimately be processed by the default
handler provided by the Java run-time system. The default handler displays a string
describing the exception, prints a stack trace from the point at which the exception occurred,
and terminates the program.
Using try and catch:
First, it allows fixing the error. Second, it prevents the program from automatically
terminating.
Example program:
class Exc2 {
public static void main(String args[]) {
int d, a;
try { // monitor a block of code.
d = 0;
a = 42 / d;
System.out.println("This will not be printed.");
} catch (ArithmeticException e) { // catch divide-by-zero error
www.rejinpaul.com
www.rejinpaul.com
System.out.println("Division by zero.");
}
System.out.println("After catch statement.");
}
}
This program generates the following output:
Division by zero.
After catch statement.
A try and its catch statement form a unit. The scope of the catch clause is restricted to those
statements specified by the immediately preceding try statement. A catch statement cannot
catch an exception thrown by another try statement (except in the case of nested try
statements, described shortly). The statements that are protected by try must be surrounded
by curly braces. (That is, they must be within a block.)Don’t use try on a single statement.
The goal of most well-constructed catch clauses should be to resolve the exceptional
condition and then continue on as if the error had never happened.
Displaying a Description of an Exception:
Throwable overrides the toString( ) method (defined by Object) so that it returns a string
containing a description of the exception. Display this description in a println( ) statement by
simply passing the exception as an argument. For example, the catch block in the preceding
program can be rewritten like this:
catch (ArithmeticException e) {
System.out.println("Exception: " + e);
a = 0; // set a to zero and continue
}
Multiple catch Clauses:
In some cases, more than one exception could be raised by a single piece of code. To handle
this type of situation, can able to specify two or more catch clauses, each catching a different
type of exception. When an exception is thrown, each catch statement is inspected in order,
and the first one whose type matches that of the exception is executed. After one catch
statement executes, the others are bypassed, and execution continues after the try/catch block.
When using multiple catch statements, it is important to remember that exception subclasses
must come before any of their super classes. This is because a catch statement that uses a
superclass will catch exceptions of that type plus any of its subclasses. Thus, a subclass
would never be reached if it came after its superclass. Further, in Java, unreachable code is an
compile time error.
Nested try Statements:
The try statement can be nested. That is, a try statement can be inside the block of another
try. Each time a try statement is entered, the context of that exception is pushed on the stack.
If an inner try statement does not have a catch handler for a particular exception, the stack is
unwound and the next try statement’s catch handlers are inspected for a match. This
continues until one of the catch statements succeeds, or until the entire nested try statements
are exhausted. If no catch statement matches, then the Java run-time system will handle the
exception.
Eg:
class NestTry {
public static void main(String args[]) {
try {
int a = args.length;
/* If no command-line args are present,
www.rejinpaul.com
www.rejinpaul.com
the following statement will generate
a divide-by-zero exception. */
int b = 42 / a;
System.out.println("a = " + a);
try { // nested try block
/* If one command-line arg is used,
then a divide-by-zero exception
will be generated by the following code. */
if(a==1) a = a/(a-a); // division by zero
/* If two command-line args are used,
then generate an out-of-bounds exception. */
if(a==2) {
int c[] = { 1 };
c[42] = 99; // generate an out-of-bounds exception
}
} catch(ArrayIndexOutOfBoundsException e) {
System.out.println("Array index out-of-bounds: " + e);
}
} catch(ArithmeticException e) {
System.out.println("Divide by 0: " + e);
}
}
}
www.rejinpaul.com
www.rejinpaul.com
Throw:
The flow of execution stops immediately after the throw statement; any subsequent
statements are not executed. The nearest enclosing try block is inspected to see if it has a
catch statement that matches the type of exception. If it does find a match, control is
transferred to that statement. If not, then the next enclosing try statement is inspected, and so
on. If no matching catch is found, then the default exception handler halts the program and
prints the stack trace.
// Demonstrate throw.
class ThrowDemo {
Exception defines four constructors. Exception( ) Exception(String msg) The first form
creates an exception that has no description. The second form lets you specify a description
of the exception.
Chained Exceptions:
The chained exception feature allows to associate another exception with an exception. This
second exception describes the cause of the first exception. For example, imagine a situation
in which a method throws an ArithmeticException because of an attempt to divide by zero.
However, the actual cause of the problem was that an I/O error occurred, which caused the
divisor to be set improperly. To allow chained exceptions, two constructors and two methods
were added to Throwable.
The constructors are shown here:
Throwable(Throwable causeExc)
Throwable(String msg, Throwable causeExc)
In the first form, causeExc is the exception that causes the current exception. That is,
causeExc is the underlying reason that an exception occurred. The second form allows to
specify a description at the same time that you specify a cause exception. These two
constructors have also been added to the Error, Exception, and RuntimeException classes.
The chained exception methods added to Throwable are getCause( ) and initCause( ).
Throwable initCause(Throwable causeExc)
The getCause( ) method returns the exception that underlies the current exception. If there is
no underlying exception, null is returned. The initCause( ) method associates causeExc with
the invoking exception and returns a reference to the exception.
Chained exceptions can be carried on to whatever depth is necessary. Thus, the cause
exception can, itself, have a cause. Be aware that overly long chains of exceptions may
indicate poor design.
www.rejinpaul.com
www.rejinpaul.com
VII. MULTITHREADED PROGRAMMING:
A multithreaded program contains two or more parts that can run concurrently. Each
part of such a program is called a thread, and each thread defines a separate path of
execution. Thus, multithreading is a specialized form of multitasking.
Two distinct types of multitasking: process based and thread-based
properties multithreading multiprocessing
thread defines a
A process is, a program that is
Definition separate path of
executing.
execution
Threads, on the
other hand, are
lightweight. They
share the same
Processes are heavyweight
address space and
Memory space tasks that require their own
cooperatively share
separate address spaces.
the same
heavyweight
process.
Smallest unit
thread process
of code
less overhead than
High overhead than
overhead multitasking
multitasking processes
processes
Context
Low cost. Costly.
Switching
Inter process Inexpensive and
expensive and limited
communication limited
Life cycle of a thread:
New-A new thread begins its life cycle in the new state. It remains in this state until
the program starts the thread. It is also referred to as a born thread.
5-Timed waiting- A runnable thread can enter the timed waiting state for a specified
interval of time. A thread in this state transitions back to the runnable state when that
time interval expires or when the event it is waiting for occurs.
6-Not Runnable- after Runnable states these three states are assumed to be in a not
Runnable state. These three states
are waiting, Timed_waiting(sleeping) and Terminated.
7-Terminated- In this state the thread is dead.
Thread Priorities:
Thread priorities are integers that specify the relative priority of one thread to another.
A thread’s priority is used to decide when to switch from one running thread to the
next. This is called a context switch.
Rules that determine when a context switch takes place
1. A thread can voluntarily relinquish control- sleep,I/O
2. A thread can be preempted by a higher-priority thread.
3. two threads with the same priority time-sliced automatically in round-robin
fashion.
JVM selects to run a Runnable thread with the highest priority.
All Java threads have a priority in the range 1-10.
Top priority is 10, lowest priority is 1.Default Priority 5
Thread.MIN_PRIORITY - minimum thread priority
Thread.MAX_PRIORITY - maximum thread priority
Thread.NORM_PRIORITY - maximum thread priority
Whenever a new Java thread is created it has the same priority as the thread
which created it.
Thread priority can be changed by the final void setPriority(int level) method , final
int getPriority( ).
Synchronization:
Because multithreading introduces an asynchronous behavior to programs, there must be
a way to enforce synchronicity when needed. Most multithreaded systems expose
monitors as objects that your program must explicitly acquire and manipulate. In Java
each object has its own implicit monitor that is automatically entered when one of the
object’s synchronized methods is called. Once a thread is inside a synchronized method,
no other thread can call any other synchronized method on the same object. When two or
more threads need access to a shared resource, they need some way to ensure that the
resource will be used by only one thread at a time. The process by which this is achieved
is called synchronization. Key to synchronization is the concept of the monitor (also
called a semaphore).
A monitor is an object that is used as a mutually exclusive lock, or mutex. Only one
thread can own a monitor at a given time. When a thread acquires a lock, it is said to have
entered the monitor. All other threads attempting to enter the locked monitor will be
suspended until the first thread exits the monitor. These other threads are said to be
waiting for the monitor. A thread that owns a monitor can reenter the same monitor if it
so desires.
www.rejinpaul.com
www.rejinpaul.com
Achieved in two ways:
1. Using Synchronized Methods
To enter an object’s monitor, just call a method that has been modified with the
synchronized keyword. While a thread is inside a synchronized method, all other threads
that try to call it (or any other synchronized method) on the same instance have to wait.
To exit the monitor and relinquish control of the object to the next waiting thread, the
owner of the monitor simply returns from the synchronized method.
2. The synchronized Statement
calls to the methods defined by this class is kept inside a synchronized block.
This is the general form of the synchronized statement:
synchronized(object) {
// statements to be synchronized
}
Here, object is a reference to the object being synchronized. A synchronized block
ensures that a call to a method that is a member of object occurs only after the current
thread has successfully entered object’s monitor.
Messaging:
After dividing program into separate threads, define how threads will communicate with
each other.
Java provides a way for two or more threads to talk to each other, via calls to predefined
methods that all objects have. Java’s messaging system allows a thread to enter a
synchronized method on an object, and then wait there until some other thread explicitly
notifies it to come out.
Java includes an elegant interprocess communication mechanism via the wait( ), notify( ),
and notifyAll( ) methods. These methods are implemented as final methods in Object, so
all classes have them. All three methods can be called only from within a synchronized
context.
• wait( ) tells the calling thread to give up the monitor and go to sleep until some other
thread enters the same monitor and calls notify( ).
• notify( ) wakes up a thread that called wait( ) on the same object.
• notifyAll( ) wakes up all the threads that called wait( ) on the same object. One of the
threads will be granted access.
These methods are declared within Object, as shown here:
final void wait( ) throws InterruptedException
final void notify( )
final void notifyAll( )
Additional forms of wait( ) exist that allow to specify a period of time to wait.
spurious wakeup:
Although wait( ) normally waits until notify( ) or notifyAll( ) is called, there is a
possibility that in very rare cases the waiting thread could be awakened due to no
apparent reason and called spurious wakeup.
Deadlock:
A special type of error that need to be avoided is deadlock, which occurs when two
threads have a circular dependency on a pair of synchronized objects. Deadlock is a
difficult error to debug for two reasons:
• In general, it occurs only rarely, when the two threads time-slice in just the right way.
• It may involve more than two threads and two synchronized objects.
Creating a Thread:
The Thread Class and the Runnable Interface:
www.rejinpaul.com
www.rejinpaul.com
The Thread class defines several methods that help manage threads:
VIII. INPUT/OUTPUT
Streams:
Java programs perform I/O through streams. A stream is an abstraction that either
produces or consumes information. An input stream can abstract many different kinds
of input: from a disk file, a keyboard, or a network socket. an output stream may refer
to the console, a disk file, or a network connection.
Byte and character Streams: Byte Stream:8-bit,binary data based. Character
Stream:16-bit,Text based.
System: The class which encapsulates several aspects of the run-time environment.
System also contains three predefined stream variables: in, out, and err. These fields
are declared as public, static, and final within System.
Reading Console Input:
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
Reading Characters:
int read( ) throws IOException - Each time that read( ) is called, it reads a character
from the input stream and returns it as an integer value else -1.
br.read();
Reading Strings: String readLine( ) throws IOException
Writing Console Output:
void write(int byteval)-This method writes to the stream the byte specified by byteval.
print( ) and println( )- methods are defined by the class PrintStream
The PrintWriter Class:
PrintWriter(OutputStream outputStream, boolean flushOnNewline)
PrintWriter pw = new PrintWriter(System.out, true);
Reading and Writing Files:
FileInputStream(String fileName) throws FileNotFoundException
FileOutputStream(String fileName) throws FileNotFoundException
if the file does not exist, then FileNotFoundException is thrown. For output streams,
if the file cannot be created, then FileNotFoundException is thrown. When an output
file is opened, any preexisting file by the same name is destroyed. File should be
closed by calling close( ). It is defined by both FileInputStream and
FileOutputStream.
void close( ) throws IOException
int read( ) throws IOException
www.rejinpaul.com
www.rejinpaul.com
IX. String Handling:
In the Java programming language, strings are objects. The Java platform provides the
String class to create and manipulate strings. In java, string is an object. String class is
used to create string object.
Creating Strings:
There are two ways to create String object:
1.By String Literal
2. By new keyword
1) String literal
String literal is created by double quote. Example:
String s=”Hello”;
Each time when we create a string literal, the JVM checks the string constant pool
first. If the string already exists in the pool, a reference to the pooled instance returns.
If the string does not exist in the pool, a new String object instantiates, then is placed
in the pool. For example:
1.String s1=”Java”;
2. String s2=”Java”;//no new object will be created
In the above example only one object will be created. First time JVM will find no
string object with the name “Java” in string constant pool, so it will create a new
object. Second time it will find the string with the name “Java” in string constant
pool, so it will not create new object whether will return the reference to the same
instance.
Why java uses concept of string literal? Java uses string literal to make Java more
memory efficient (because no new objects are created if it exists already in string
constant pool).
String objects are stored in a special memory area known as string constant pool
inside the Heap memory. The most direct way to create a string is to write:
String str = “Hello world!”;
Note: The String class is immutable, so that once it is created a String object cannot
be changed. If there is a necessity to make a lot of modifications to Strings of
characters, then use String Buffer & String Builder Classes.
2) By new keyword
String s=new String(“Java”);//creates two objects and one reference variable
In such case, JVM will create a new String object in normal(nonpool) Heap memory
and the literal “Java” will be placed in the string constant pool. The variable s will
refer to the object in Heap(nonpool).
public class StringDemo{
public static void main(String args[])
{
char[] helloArray = { ‘h’, ‘e’, ‘l’, ‘l’, ‘o’, ‘.’};
String helloString = new String(helloArray);
System.out.println( helloString );
}}
String Methods in java:
String method cannot manipulate the string.
www.rejinpaul.com
www.rejinpaul.com
StringBuffer methods:
StringBuffer sb=new StringBuffer(“abc”);
Instance method call Return type Return value
sb.charAt(1) char y
sb.length() int 3
19-since room for 16
sb.capacity() int additional char is added
automatically.
sb.replace(0,1,”cb”) StringBuffer cba
StringBuilder
J2SE 5 adds a new string class to Java’s already powerful string handling capabilities.
This new class is called StringBuilder. It is identical to StringBuffer except for one
important difference: it is not synchronized, which means that it is not thread-safe.
The advantage of StringBuilder is faster performance. However, in cases in which you
are using multithreading,you must use StringBuffer rather than StringBuilder.
Difference Between String , StringBuilder and StringBuffer
String StringBuffer StringBuilder
immutable mutable mutable
Storage area: constant
heap heap
pool
- syncronized not synchronized
thread-safe thread-safe not thread-safe
Fast performance Slow Fast
www.rejinpaul.com
www.rejinpaul.com
www.rejinpaul.com
www.rejinpaul.com
Results, handling database Queries. Networking– InetAddress class – URL class- TCP sockets - UDP
Networking Basics:
Computers running on the Internet communicate to each other using either the Transmission Control
Protocol (TCP) or the User Datagram Protocol (UDP), as this diagram illustrates:
TCP
When two applications want to communicate to each other reliably, they establish a connection and send
data back and forth over that connection. This is analogous to making a telephone call. TCP guarantees that
data sent from one end of the connection actually gets to the other end and in the same order it was sent.
Otherwise, an error is reported.
TCP provides a point-to-point channel for applications that require reliable communications. The Hypertext
Transfer Protocol (HTTP), File Transfer Protocol (FTP), and Telnet are all examples of applications that
require a reliable communication channel. The order in which the data is sent and received over the network
is critical to the success of these applications. When HTTP is used to read from a URL, the data must be
received in the order in which it was sent. Otherwise, it is a jumbled HTML file, a corrupt zip file, or some
other invalid information.
Definition:
TCP (Transmission Control Protocol) is a connection-based protocol that provides a reliable flow of data
between two computers.
UDP
The UDP protocol provides for communication that is not guaranteed between two applications on the
network. UDP is not connection-based like TCP. Rather, it sends independent packets of data,
called datagrams, from one application to another. Sending datagrams is much like sending a letter through
the postal service: The order of delivery is not important and is not guaranteed, and each message is
independent of any other.
Definition:
UDP (User Datagram Protocol) is a protocol that sends independent packets of data, called datagrams, from
one computer to another with no guarantees about arrival. UDP is not connection-based like TCP.
www.rejinpaul.com
www.rejinpaul.com
Consider, for example, a clock server that sends the current time to its client when requested to do so. If the
client misses a packet, it doesn't really make sense to resend it because the time will be incorrect when the
client receives it on the second try. If the client makes two requests and receives packets from the server out
of order, it doesn't really matter because the client can figure out that the packets are out of order and make
another request. The reliability of TCP is unnecessary in this instance because it causes performance
degradation and may hinder the usefulness of the service.
Another example of a service that doesn't need the guarantee of a reliable channel is the ping command. The
purpose of the ping command is to test the communication between two programs over the network. In fact,
ping needs to know about dropped or out-of-order packets to determine how good or bad the connection is.
A reliable channel would invalidate this service altogether.
Note:
Many firewalls and routers have been configured not to allow UDP packets. If you're having trouble
connecting to a service outside your firewall, or if clients are having trouble connecting to your service, ask
your system administrator if UDP is permitted.
Understanding Ports:
Generally speaking, a computer has a single physical connection to the network. All data destined for a
particular computer arrives through that connection. However, the data may be intended for different
applications running on the computer. The computer knows to which application to forward the data through
the use of ports.
Data transmitted over the Internet is accompanied by addressing information that identifies the computer and
the port for which it is destined. The computer is identified by its 32-bit IP address, which IP uses to deliver
data to the right computer on the network. Ports are identified by a 16-bit number, which TCP and UDP use
to deliver the data to the right application.
In connection-based communication such as TCP, a server application binds a socket to a specific port
number. This has the effect of registering the server with the system to receive all data destined for that port.
A client can then rendezvous with the server at the server's port, as illustrated here:
Definition:
The TCP and UDP protocols use ports to map incoming data to a particular process running on a computer.
Port numbers range from 0 to 65,535(216) because ports are represented by 16-bit numbers. The port
numbers ranging from 0 - 1023 are restricted; they are reserved for use by well-known services such as
HTTP and FTP and other system services. These ports are called well-known ports. Your applications
should not attempt to bind to them.
Through the classes in java.net, Java programs can use TCP or UDP to communicate over the Internet.
The URL, URLConnection, Socket, and ServerSocket classes all use TCP to communicate over the network.
The DatagramPacket, DatagramSocket, and MulticastSocket classes are for use with UDP.
www.rejinpaul.com
www.rejinpaul.com
Java.net Package:
URL is an acronym for Uniform Resource Locator and is a reference (an address) to a resource on the
Internet. Provide URLs to Web browser so that it can locate files on the Internet.
Java programs that interact with the Internet also may use URLs to find the resources on the Internet they
wish to access. Java programs can use a class called URL in the java.net package to represent a URL
address.
Definition:
Protocol identifier: For the URL http://example.com, the protocol identifier is http.
Resource name: For the URL http://example.com, the resource name is example.com.
Note that the protocol identifier and the resource name are separated by a colon and two forward slashes.
The protocol identifier indicates the name of the protocol to be used to fetch the resource. The example uses
the Hypertext Transfer Protocol (HTTP), which is typically used to serve up hypertext documents. HTTP is
just one of many different protocols used to access different types of resources on the net. Other protocols
include File Transfer Protocol (FTP), Gopher, File, and News.
The resource name is the complete address to the resource. The format of the resource name depends
entirely on the protocol used, but for many protocols, including HTTP, the resource name contains one or
more of the following components:
Host Name: The name of the machine on which the resource live.
Filename: The pathname to the file on the machine.
Port Number: The port number to which to connect (typically optional).
www.rejinpaul.com
www.rejinpaul.com
Reference:A reference to a named anchor within a resource that usually identifies a specific location within
a file (typically optional).
Creating a URL
Within Java programs, can create a URL object that represents a URL address. The URL object always
refers to an absolute URL but can be constructed from an absolute URL, a relative URL, or from URL
components.
Relative:
two URLs at the site example.com:
http://example.com/pages/page1.html
http://example.com/pages/page2.html
Create URL objects for these pages relative to their common base URL: http://example.com/pages/ like this:
URL myURL = new URL("http://example.com/pages/");
URL page1URL = new URL(myURL, "page1.html");
URL page2URL = new URL(myURL, "page2.html");
public URL(String protocol, String host, String file) throws MalformedURLException
new URL("http", "example.com", "/pages/page1.html");
public URL(String protocol, String host, int port, String file) throws MalformedURLException
URL gamelan = new URL("http", "example.com", 80, "pages/page1.html");
Parsing a URL
Parsing a URL is to find out the host name, filename, and other information. The URL class provides
methods for retrieving individual components of the represented URL (such as the protocol and the host
name). It also provides comparison methods for determining if two URL objects reference the same content.
1. protected void set(String protocol, String host, int port, String file, String ref)
Sets the fields of the URL. This is not a public method so that only URLStreamHandlers can modify URL
fields. URLs are otherwise constant.
2. public int getPort()
Gets the port number. Returns -1 if the port is not set.
3. public String getProtocol()
Gets the protocol name.
4. public String getHost()
Gets the host name.
5. public String getFile()
Gets the file name.
6. public String getRef()
www.rejinpaul.com
www.rejinpaul.com
Gets the ref.
7. public boolean equals(Object obj)
Compares two URLs. Returns true if and only if they are equal, false otherwise.
8. public URLConnection openConnection() throws IOException
Creates (if not already in existance) a URLConnection object that contains a connection to the remote object
referred to by the URL.
9. public final InputStream openStream() throws IOException
Opens an input stream.
10. public final Object getContent() throws IOException
Gets the contents from this opened connection.
Example Program:
import java.net.*;
public class TestURL1
{
public static void main(String args[])throws MalformedURLException
{
URL page1=new URL("https://www.example.com:8080/doc/Notes-on-JavaBeans");
System.out.println("Protocol:"+page1.getProtocol());
System.out.println("HOST:"+page1.getHost());
System.out.println("Port:"+page1.getPort());
System.out.println("FileName:"+page1.getFile());
}
OUTPUT:
After successfully created a URL, call the URL's openStream() method to get a stream from which read the
contents of the URL. The openStream() method returns a java.io.InputStream object, so reading from a URL
is as easy as reading from an input stream.
The following small Java program uses openStream() to get an input stream on the
URL http://www.oracle.com/. It then opens a BufferedReader on the input stream and reads from
the BufferedReader thereby reading from the URL. Everything read is copied to the standard output stream:
import java.net.*;
import java.io.*;
Some URLs, such as many that are connected to cgi-bin scripts, allow to (or even require to) write
information to the URL. For example, a search script may require detailed query data to be written to the
URL before the search can be performed.
However, rather than getting an input stream directly from the URL, this program explicitly retrieves
a URLConnection object and gets an input stream from the connection. The connection is opened implicitly
by calling getInputStream. Then, like URLReader, this program creates a BufferedReader on the input
stream and reads from it. The bold statements highlight the differences between this example and the
previous program:
import java.net.*;
import java.io.*;
Many HTML pages contain forms — text fields and other GUI objects that let to enter data to send to the
server. After you type in the required information and initiate the query by clicking a button, your Web
browser writes the data to the URL over the network. At the other end the server receives the data, processes
it, and then sends you a response, usually in the form of a new HTML page.
www.rejinpaul.com
www.rejinpaul.com
Many of these HTML forms use the HTTP POST METHOD to send data to the server. Thus writing to a
URL is often called posting to a URL. The server recognizes the POST request and reads the data sent from
the client.
For a Java program to interact with a server-side process it simply must be able to write to a URL, thus
providing data to the server. It can do this by following these steps:
1. Create a URL.
Method Description
Example program:
import java.net.*;
public class TestInetaddress
{
public static void main(String args[])throws UnknownHostException
{
InetAddress a=InetAddress.getLocalHost();
System.out.println("Localhost:"+a);
InetAddress a1=InetAddress.getByName(args[0]);
System.out.println("hostname:"+a1);
InetAddress a2[]=InetAddress.getAllByName(args[0]);
for(int i=0;i<a2.length;i++)
System.out.println("hostname:"+i+":"+a2[i]);
}
}
OUTPUT:
D:\subjects\web programming\lab programs>javac TestInetaddress.java
D:\subjects\web programming\lab programs>java TestInetaddress www.google.com
Localhost:MSK-PC/192.168.198.1
hostname:www.google.com/74.125.68.106
hostname:0:www.google.com/74.125.68.106
hostname:1:www.google.com/74.125.68.99
hostname:2:www.google.com/74.125.68.147
hostname:3:www.google.com/74.125.68.103
hostname:4:www.google.com/74.125.68.104
hostname:5:www.google.com/74.125.68.105
www.rejinpaul.com
www.rejinpaul.com
TCP Sockets:
URLs and URLConnections provide a relatively high-level mechanism for accessing resources on the
Internet whether lower-level network communication is provided by Socket for example, when you want to
write a client-server application.
Socket and ServerSocket classes are used for connection-oriented socket programming and DatagramSocket
and DatagramPacket classes are used for connection-less socket programming.
2. Port number.
Socket class
A socket is simply an endpoint for communications between the machines. The Socket class can be used to
create a socket.
Important methods
Method Description
1) public InputStream getInputStream() returns the InputStream attached with this socket.
2) public OutputStream getOutputStream() returns the OutputStream attached with this socket.
ServerSocket class
The ServerSocket class can be used to create a server socket. This object is used to establish communication
with the clients.
Important methods
Method Description
1) public Socket accept() returns the socket and establish a connection between server and
client.
2) public synchronized void closes the server socket.
close()
Example Program:
Client Program:
import java.net.*;
import java.io.*;
}
}
Server Program:
import java.net.*;
import java.io.*;
import java.util.Date;
UDP Sockets:
Java DatagramSocket and DatagramPacket classes are used for connection-less socket programming.
Java DatagramSocket class:
Java DatagramSocket class represents a connection-less socket for sending and receiving datagram packets.
A datagram is basically an information but there is no guarantee of its content, arrival or arrival time.
Commonly used Constructors of DatagramSocket class
DatagramSocket() throws SocketException: it creates a datagram socket and binds it with the
available Port Number on the localhost machine.
DatagramSocket(int port) throws SocketException: it creates a datagram socket and binds it with the
given Port Number.
DatagramSocket(int port, InetAddress address) throws SocketException: it creates a datagram socket
and binds it with the specified port number and host address.
Java DatagramPacket class
Java DatagramPacket is a message that can be sent or received. If you send multiple packets, it may arrive in
any order. Additionally, packet delivery is not guaranteed.
Commonly used Constructors of DatagramPacket class
www.rejinpaul.com
www.rejinpaul.com
DatagramPacket(byte[] barr, int length): it creates a datagram packet. This constructor is used to
receive the packets.
DatagramPacket(byte[] barr, int length, InetAddress address, int port): it creates a datagram packet.
This constructor is used to send the packets.
Example Program:
Client:
import java.net.*;
import java.io.*;
}
Server:
import java.net.*;
import java.io.*;
import java.lang.Runtime.*;
import java.net.InetAddress.*;
Java RMI or Remote Method Invocation is an example of Remote Procedure Call (RPC)enabling
client program to locate the server object and remotely invoke the methods from server through server’s stub
and skeleton function. Java RMI is usually referred to Distributed Object rather than RPC. This is because
Java natively is object oriented programming. So we say object as a whole. Moreover, RPC somehow is
mentioned to procedural programming.
}
Rmiserver.java:
import java.rmi.server.*;
import java.rmi.Naming.*;
public class rmiserver extends UnicastRemoteObject implements Computeinterface
{
public rmiserver() throws RemoteException{}
public int add(int a,int b)throws RemoteException
{
return a+b;
}
public int sub(int a,int b)throws RemoteException
{
return a-b;
}
public int mul(int a,int b)throws RemoteException
{
return a*b;
}
public static void main(String args[])throws
RemoteException,MalformedURLException,NotBoundException
{
rmiserver rs=new rmiserver();
Registry r=LocateRegistry.getRegistry();
r.rebind("rmiserver",rs);
}
}
www.rejinpaul.com
www.rejinpaul.com
Rmiclient.java:
import java.io.*;
import java.rmi.*;
import java.rmi.registry.*;
import java.net.*;
import java.rmi.Naming;
public class rmiclient
{
public static void main(String args[])throws IOException,RemoteException,NotBoundException
{
int a,b;
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter the first number");
a=Integer.parseInt(br.readLine());
System.out.println("Enter the second number");
b=Integer.parseInt(br.readLine());
Registry r=LocateRegistry.getRegistry();
Computeinterface ci=(Computeinterface) r.lookup("rmiserver");
System.out.println("sum="+ci.add(a,b));
System.out.println("diff="+ci.sub(a,b));
System.out.println("product="+ci.mul(a,b));
}
}
www.rejinpaul.com
www.rejinpaul.com
JAVA BEANS:
A “Bean” is a reusable software component model based on sun’s java bean specification that can be
manipulated visually in a builder tool.
The term software component model describe how to create and use reusable software components
to build an application
Builder tool is nothing but an application development tool which lets you both to create new beans
or use existing beans to create an application.
To enrich the software systems by adopting component technology JAVA came up with the concept
called Java Beans.
Java provides the facility of creating some user defined components by means of Bean programming.
Advantages of Java Beans:
1. The java beans posses the property of “Write once and run anywhere”.
2. Beans can work in different local platforms.
3. Beans have the capability of capturing the events sent by other objects and vice versa enabling object
communication.
4. The properties, events and methods of the bean can be controlled by the application developer.(ex. Add
new properties)
5. Beans can be configured with the help of auxiliary software during design time.(no hassle at runtime)
6. The configuration setting can be made persistent.(reused)
7. Configuration setting of a bean can be saved in persistent storage and restored later.
JavaBeans basic rules:
A Java Bean should:
be public , implements the Serializable interface ,have a no-arg constructor and be derived from
javax.swing.JComponent or java.awt.Component if it is visual.
The classes and interfaces defined in the java.beans package enable you to create JavaBeans.
The Java Bean components can exist in one of the following three phases of development:
• Construction phase
• Build phase
• Execution phase
It supports the standard component architecture features of
Properties
Events
Methods
Persistence.
In addition Java Beans provides support for
Introspection (Allows Automatic Analysis of a java beans)
Customization(To make it easy to configure a java beans component
The JavaBean Component Specification:
Customization: Is the ability of JavaBean to allow its properties to be changed in build and execution phase.
Persistence:- Is the ability of JavaBean to save its state to disk or storage device and restore the saved state
when the JavaBean is reloaded.
Communication:-Is the ability of JavaBean to notify change in its properties to other JavaBeans or the
container.
Introspection:- Is the ability of a JavaBean to allow an external application to query the properties,methods,
and events supported by it.
Features of a JavaBean:
Support for “introspection” so that a builder tool can analyze how a bean works.
Support for “customization” to allow the customisation of the appearance and behaviour of a bean.
www.rejinpaul.com
www.rejinpaul.com
Support for “events” as a simple communication metaphor than can be used to connect up beans.
Support for “properties”, both for customization and for programmatic use.
Support for “persistence”, so that a bean can save and restore its customized state.
Steps to Develop a User-Defined JavaBean:
1. Create a directory for the new bean
2. Create the java bean source file(s)
3. Compile the source file(s)
4. Create a manifest file
5. Generate a JAR file
6. Start BDK
7. Load Jar file
8. Test.
Introspection:
Introspection can be defined as the technique of obtaining information about bean properties, events and
methods. Without introspection, the JavaBeans technology could not operate.
Persistence:
Persistence means an ability to save properties and events of user deffined beans to non-volatile storage and
retrieve later.That is the state of the bean is stored and retrived.
Property:
A property is a subset of a Bean’s state. Examples of bean properties include color, label, font, font size, and
display size.
Types of JavaBeans Properties:
Simple properties:- Simple properties refer to the private variables of a JavaBean that can have only a
single value. Simple properties are retrieved and specified using the get and set methods respectively.
Boolean properties:- A Boolean property is a property which is used to represent the values True or
False. Let N be the name of the property and T be the type of the value then the methods are
public boolean isN();
public void setN(boolean parameter);
public Boolean getN();
Indexed properties:- Indexed Properties consists of multiple values.If a simple property can hold an
array of value they are no longer called simple butinstead indexed properties. An indexed property
may expose set/get methods to read/write one element in the array (so-called ’index getter/setter’)
and/or so-called ’array getter/setter’ which read/write the entire array.
Bound properties:- A bean that has a bound property generates an event when the property is
changed.
Constrained properties:- It generates an event when an attempt is made to change its value.
Handling Events in JavaBeans:
Enables Beans to communicate and connect together.
Beans generate events and these events can be sent to other objects.
Event means any activity that interrupts the current ongoing activity.
Example: mouse clicks, pressing key…
www.rejinpaul.com
www.rejinpaul.com
JDBC:
JDBC Overview:
The JDBC API is a Java API that can access any kind of tabular data, especially data stored in a Relational
Database.
JDBC helps to write Java applications that manage these three programming activities:
1. Connect to a data source, like a database
2. Send queries and update statements to the database
3. Retrieve and process the results received from the database in answer to the query.
JDBC Product Components
JDBC includes four components:
1. The JDBC API — The JDBC™ API provides programmatic access to relational data from the
Java™ programming language. Using the JDBC API, applications can execute SQL statements,
retrieve results, and propagate changes back to an underlying data source. The JDBC API can also
interact with multiple data sources in a distributed, heterogeneous environment.
The JDBC API is part of the Java platform, which includes the Java™ Standard Edition (Java™ SE
) and the Java™ Enterprise Edition (Java™ EE). The JDBC 4.0 API is divided into two
packages: java.sql and javax.sql. Both packages are included in the Java SE and Java EE platforms.
2. JDBC Driver Manager — The JDBC DriverManager class defines objects which can connect Java
applications to a JDBC driver. DriverManager has traditionally been the backbone of the JDBC
architecture. It is quite small and simple.
The Standard Extension packages javax.naming and javax.sql make to use a DataSource object
registered with a Java Naming and Directory Interface™ (JNDI) naming service to establish a
connection with a data source.
3. JDBC Test Suite — The JDBC driver test suite helps to determine that JDBC drivers will run the
program. i.e to test whether the program runs in the driver or not.
4. JDBC-ODBC Bridge — The Java Software bridge provides JDBC access via ODBC drivers. i.e
connects database drivers to database.
The first two of these four JDBC components are used to connect to a database and then build a java
program that uses SQL commands to communicate with a test Relational Database. The last two
components are used in specialized environments to test web applications, or to communicate with
ODBC-aware DBMSs.
JDBC Architecture:
Two-tier and Three-tier Processing Models
The JDBC API supports both two-tier and three-tier processing models for database access.
Figure 1: Two-tier Architecture for Data Access.
www.rejinpaul.com
www.rejinpaul.com
C:\Program Files\Java\jdk1.7.0_79\db\bin>
C:\Program Files\Java\jdk1.7.0_79\db\bin>setEmbeddedCP.bat
program:
import java.sql.*;
public class MYdbase
{
public static void main(String args[])
{
try
{
www.rejinpaul.com
www.rejinpaul.com
Class.forName("org.apache.derby.jdbc.EmbeddedDriver").newInstance();
String path = "d:/subjects/web programming/lab programs/MyDbTest1;";
Connection con = DriverManager.getConnection("jdbc:derby:"+path+"create=true");
Statement s=con.createStatement();
String selTable = "SELECT * FROM emp";
s.execute(selTable);
ResultSet rs = s.getResultSet();
while((rs!=null) && (rs.next()))
{
System.out.println(rs.getString(1) + " : " + rs.getString(2));
}
s.close();
con.close();
}catch(Exception ex){ex.printStackTrace();}
}
}
Output:
UNIT IV APPLETS 9
Java applets- Life cycle of an applet – Adding images to an applet – Adding sound to an applet. Passing
parameters to an applet. Event Handling. Introducing AWT: Working with Windows Graphics and Text. Using
AWT Controls, Layout Managers and Menus. Servlet – life cycle of a servlet. The Servlet API, Handling HTTP
Request and Response, using Cookies, Session Tracking. Introduction to JSP.
Java applets:
Definition:
Applet is a special type of small java program that is embedded in the webpage to generate the dynamic content.
It runs inside the java enabled web browser and works at client side.
Difference between Applet and java application:
An applet is a Java class that extends the java.applet.Applet class.
A main method is not invoked on an applet, and an applet class will not define main.
Applets are designed to be embedded within an HTML page.
When a user views an HTML page that contains an applet, the code for the applet is downloaded to the
user's machine.
A JVM is required to view an applet. The JVM can be either a plug-in of the Web browser or a separate
runtime environment. The JVM on the user's machine creates an instance of the applet class and invokes
various methods during the applet's lifetime.
Applets have strict security rules that are enforced by the Web browser. The security of an applet is
often referred to as sandbox security, comparing the applet to a child playing in a sandbox with various
rules that must be followed.
Other classes that the applet needs can be downloaded in a single Java Archive JAR file.
Differences summarized:
Feature Application Applet
Main() method Present Not present
Advantage:
1. Platform Independent.
2. Applets don’t have compatibility issues with different versions of java.
3. Applets cache quickly, that’s why there will be no latency in downloading of them.
4. It can also be used for a real time application.
5. They can pay out different type of action on client-side machine like-
Playing sound
1
1. init() – Execution of an applet starts from here. It is coequal to born stage of a thread. This is the first
method (it is called before all other methods). A programmer can exploit this method to instantiate
objects, initialize variables, setting background and foreground colors in GUI etc. In this method Applet
is created but remains inactive.
2. start() – In this method Applet become active, and become eligible for processor time. Because an
inactive Applet is not eligible for processor time.
3. paint() – this method is requested instantly after the start () method, this method takes
a java.awt.Graphics object as parameter, this is the only place where a programmer can write his code.
4. stop() – This method makes an Applet inactive temporarily, and it is called directly when the user
moves off the page on which the applet sits.
import java.awt.*;
import java.applet.*;
public class applet1 extends Applet
{
public void paint(Graphics g)
{
g.drawString("Hello World",10,30);
}
}
Applet1.html
<html>
<applet code="applet1.class" height=300 width=300>
</applet>
</html>
Steps to execute:
First step is to create the image's URL object by calling either the getDocumentBase() or getCodeBase()
method. The former returns the URL of the directory from which the current HTML file was loaded,
whereas the latter returns the URL of the directory from which the applet was run.
public URL getDocumentBase(): is used to return the URL of the document in which applet is
embedded.
public URL getCodeBase(): is used to return the base URL.
Create the Object for image using the function public Image getImage(URL u, String image){}
Load the image in applet . public abstract boolean drawImage(Image img, int x, int y,
ImageObserver observer): is used draw the specified image.
Other drawimage methods:
drawImage(Image img, int x, int y, Color bgcolor, ImageObserver observer)
Draws as much of the specified image as is currently available.
drawImage(Image img, int x, int y, ImageObserver observer)
Draws as much of the specified image as is currently available.
drawImage(Image img, int x, int y, int width, int height, Color bgcolor, ImageObserver observer)
Draws as much of the specified image as has already been scaled to fit inside the specified rectangle.
drawImage(Image img, int x, int y, int width, int height, ImageObserver observer)
Draws as much of the specified image as has already been scaled to fit inside the specified rectangle.
drawImage(Image img, int dx1, int dy1, int dx2, int dy2, int sx1, int sy1, int sx2,
int sy2, Color bgcolor, ImageObserver observer)
Draws as much of the specified area of the specified image as is currently available, scaling it on the fly to fit
inside the specified area of the destination drawable surface.
drawImage(Image img, int dx1, int dy1, int dx2, int dy2, int sx1, int sy1, int sx2,
int sy2, ImageObserver observer)
Draws as much of the specified area of the specified image as is currently available, scaling it on the fly to fit
inside the specified area of the destination drawable surface.
Example program:
import java.applet.Applet;
4
}
}
Html file
html>
<applet code="AppletImage.class" height=300 width=300>
<param name="img" value="java.png">
</applet>
</html>
Output:
}
}
Html file:
<html>
<applet code="Appletparameter.class" height=500 width= 400>
<param name="xpos" value="30"/>
<param name="ypos" value="40"/>
<param name="mg" value="Hello World"/>
</applet>
</html>
Abstract Windowing Toolkit:(AWT)
The hierarchy of Java AWT classes are given below:
Container
The Container is a component in AWT that can contain another components like buttons, textfields, labels etc.
The classes that extends Container class are known as container such as Frame, Dialog and Panel.
Window
The window is the container that have no borders and menu bars. You must use frame, dialog or another
window for creating a window.
Panel
The Panel is the container that doesn't contain title bar and menu bars. It can have other components like button,
textfield etc.
Frame
The Frame is the container that contain title bar and can have menu bars. It can have other components like
button, textfield etc.
Useful Methods of Component class
Method Description
public void add(Component c) inserts a component on this component.
public void setSize(int width,int height) sets the size (width and height) of the component.
public void setLayout(LayoutManager m) defines the layout manager for the component.
public void setVisible(boolean status) changes the visibility of the component, by default false.
To create simple awt example, you need a frame. There are two ways to create a frame in AWT.
o By extending Frame class (inheritance)
class First extends Frame
o By creating the object of Frame class (association)
class First2{
First2(){
Frame f=new Frame();
AWT controls:
Controls are components that allow a user to interact with your application.
- A component is a graphical object.
- A few examples of components are:
1. Button
2. Canvas
3. Checkbox, CheckBox Group
4. Choice
5. Container
6. Label
7. List
8. Scrollbar
9. Text Component
10. Image
11. Canvas
12. Dialog
13. File Dialog
Every user interface considers the following three main aspects:
UI elements : Thes are the core visual elements the user eventually sees and interacts with. GWT
provides a huge list of widely used and common elements varying from basic to complex which we will
cover in this tutorial.
Layouts: They define how UI elements should be organized on the screen and provide a final look and
feel to the GUI (Graphical User Interface). This part will be covered in Layout chapter.
Behavior: These are events which occur when the user interacts with UI elements. This part will be
covered in Event Handling chapter.
Creation of menus involves many steps to be followed in an order. Following are the steps.
3. Create menus
7. Event handling
AWT Menu Controls:
1 MenuComponent
It is the top level class for all menu related controls.
2 MenuBar
The MenuBar object is associated with the top-level window.
3 MenuItem
The items in the menu must belong to the MenuItem or any of its subclass.
4 Menu
The Menu object is a pull-down menu component which is displayed from the menu bar.
5 CheckboxMenuItem
CheckboxMenuItem is subclass of MenuItem.
6 PopupMenu
PopupMenu can be dynamically popped up at a specified position within a component.
Graphics controls allows application to draw onto the component or on image.
Example Program:
9
date.add(new MenuItem("Today"));
exit.add(new MenuItem("Close"));
// linking listener
files.addActionListener(this);
date.addActionListener(this);
exit.addActionListener(this);
add(ta, "Center");
setTitle("Menu Practice");
setSize(400, 400);
setVisible(true);
}
public void actionPerformed(ActionEvent e)
{
10
if(str.equals("Close"))
{
System.exit(0);
}
else if(str.equals("Today"))
{
ta.setText("Today: " + new java.util.Date());
}
else
{
try
{
FileReader fr = new FileReader(str);
}
fr.close();
}
catch(IOException e1)
{
ta.setText("Exception: " + e1);
}
}
}
public static void main(String args[])
{
new MenuDemo();
}
}
11
Event Handling:
Changing the state of an object is known as an event.
In AWT components, every component (except Panel and Label) generates events when interacted by the user
like clicking over a button or pressing enter key in a text field etc. Listeners handle the events. The style (or
design pattern) Java follows to handle the events are as follows:
The event handling Java involves four types of classes.
1. Event Sources
2. Event classes
3. Event Listeners
4. Event Adapters
1. Event Sources
Event sources are components, subclasses of java.awt.Component, capable to generate events. The event
source can be a button, TextField or a Frame etc.
2. Event classes
Almost every event source generates an event and is named by some Java class. For example, the event
generated by button is known as ActionEvent and that of Checkbox is known as ItemEvent. All the events are
listed in java.awt.event package. Following list gives a few components and their corresponding listeners.
Frame WindowEvent
Scrollbar AdjustmentEvent
The events generated by hardware components (like MouseEvent and KeyEvent) are known as low-level
events and the events generated by software components (like Button, List) are known as semantic events.
3. Event Listeners
The events generated by the GUI components are handled by a special group of interfaces known as "listeners".
Note, Listener is an interface. Every component has its own listener, say, AdjustmentListener handles the events
13
WindowListener Frame
AdjustmentListener Scrollbar
KeyListener Keyboard
Adapters make event handling code simple to write. But adapter is an abstract class where as listener is an
interface. Both are from java.awt.event package. Any listener interface containing more than one abstract
method has got corresponding adapter class. But ActionListener, ItemListener and AdjustmentListener do not
have corresponding adapter class as they come with only one abstract method.
4. Event Adapters
When a listener includes many abstract methods to override, the coding becomes heavy to the programmer. For
example, to close the frame, override seven abstract methods of WindowListener, in which, in fact using only
one method. To avoid this heavy coding, the designers come with another group of classes known as
"adapters". Adapters are abstract classes defined in java.awt.event package. Every listener that has more than
one abstract method has got a corresponding adapter class.
When an adapter is used, a separate class is to be created as the main class already extends Frame Since java
does not support multiple inheritances.
Following table gives some important listeners and their corresponding adapter classes.
14
3) AWT doesn't support pluggable look and feel. Swing supports pluggable look and
feel.
4) AWT provides less components than Swing. Swing provides more powerful
componentssuch as tables, lists,
scrollpanes, colorchooser, tabbedpane
etc.
16
17
repaint();
}
public void mouseReleased(MouseEvent e)
{
str = "You released mouse";
repaint();
}
public void mouseClicked(MouseEvent e)
{
str = "You clicked mouse";
repaint();
}
public void mouseEntered(MouseEvent e)
{
str = "Mouse entered frame";
repaint();
}
public void mouseExited(MouseEvent e)
{
str = "Mouse existed frame";
repaint();
}
// write paint() method to draw on applet window
public void paint(Graphics g)
{
g.drawString(str, 75, 150);
}
}
Example Programs:
1.Counter example:
import java.awt.*;
import java.awt.event.*;
public class Countdown extends Frame implements ActionListener
{
TextField tf;
Label l;
Button b;
int count=80;
public void countFrame()
{
tf=new TextField();
tf.setBounds(30,30,30,30);
tf.setEditable(false);
18
l=new Label("Counter");
l.setBounds(20,20,20,20);
b=new Button("Count");
b.setBounds(40,40,40,40);
b.addActionListener(this);
add(l);
add(tf);
add(b);
tf.setText(count + "");
setSize(300,200);
setVisible(true);
setLayout(new FlowLayout());
setTitle("AWT Counter");
}
public void actionPerformed(ActionEvent ae)
{
count--;
tf.setText(count + "");
}
19
LayoutManagers:
The LayoutManagers are used to arrange components in a particular manner. LayoutManager is an interface
that is implemented by all the classes of layout managers. There are following classes that represents the layout
managers:
1. java.awt.BorderLayout
2. java.awt.FlowLayout
3. java.awt.GridLayout
4. java.awt.CardLayout
5. java.awt.GridBagLayout
BorderLayout:
The BorderLayout is used to arrange the components in five regions: north, south, east, west and center. Each
region (area) may contain one component only. It is the default layout of frame or window. The BorderLayout
provides five constants for each region:
1. public static final int NORTH
2. public static final int SOUTH
3. public static final int EAST
4. public static final int WEST
5. public static final int CENTER
Constructors of BorderLayout class:
BorderLayout(): creates a border layout but with no gaps between the components.
JBorderLayout(int hgap, int vgap): creates a border layout with the given horizontal and
vertical gaps between the components.
Example program:
import java.awt.*;
import javax.swing.*;
f.add(b1,BorderLayout.NORTH);
f.add(b2,BorderLayout.SOUTH);
f.add(b3,BorderLayout.EAST);
f.add(b4,BorderLayout.WEST);
f.add(b5,BorderLayout.CENTER);
f.setSize(300,300);
20
OUTPUT:
GridLayout
The GridLayout is used to arrange the components in rectangular grid. One component is displayed in each
rectangle.
Constructors of GridLayout class:
1. GridLayout(): creates a grid layout with one column per component in a row.
2. GridLayout(int rows, int columns): creates a grid layout with the given rows and columns but no gaps
between the components.
3. GridLayout(int rows, int columns, int hgap, int vgap): creates a grid layout with the given rows and
columns alongwith given horizontal and vertical gaps.
Example Program:
import java.awt.*;
import javax.swing.*;
f.add(b1);f.add(b2);f.add(b3);f.add(b4);f.add(b5);
f.add(b6);f.add(b7);f.add(b8);f.add(b9);
f.setLayout(new GridLayout(3,3));
//setting grid layout of 3 rows and 3 columns
f.setSize(300,300);
f.setVisible(true);
}
public static void main(String[] args) {
new MyGridLayout();
}
}
OUTPUT:
FlowLayout
The FlowLayout is used to arrange the components in a line, one after another (in a flow). It is the default
layout of applet or panel.
Fields of FlowLayout class:
1. public static final int LEFT
2. public static final int RIGHT
3. public static final int CENTER
4. public static final int LEADING
5. public static final int TRAILING
Constructors of FlowLayout class:
22
1. FlowLayout(): creates a flow layout with centered alignment and a default 5 unit horizontal and vertical
gap.
2. FlowLayout(int align): creates a flow layout with the given alignment and a default 5 unit horizontal
and vertical gap.
3. FlowLayout(int align, int hgap, int vgap): creates a flow layout with the given alignment and the
given horizontal and vertical gap.
Example program:
import java.awt.*;
import javax.swing.*;
f.add(b1);f.add(b2);f.add(b3);f.add(b4);f.add(b5);
f.setLayout(new FlowLayout(FlowLayout.RIGHT));
//setting flow layout of right alignment
f.setSize(300,300);
f.setVisible(true);
}
public static void main(String[] args) {
new MyFlowLayout();
}
}
OUTPUT:
23
24
Servlet – life cycle of a servlet. The Servlet API, Handling HTTP Request and Response, using
Cookies, Session Tracking. Introduction to JSP.
Tomcat WebServer :
A “servlet container” is like a mini server, but only for serving html, jsp and servlets.
Many servlet containers could be used for this course. Some may even be easier to
configure than tomcat, but tomcat provides an easy-to-use development/deployment tool
and also complies with the servlet specification best of all containers.
Tomcat is from Apache and is open-source.
Tomcat can be used as a stand-alone servlet container.
You can install the Apache server with Tomcat, and then proceed to configure each for
their individual purposes. (The server would relay servlet requests to Tomcat.)
Application:
Search Engines
E-Commerce Applications
Shopping Carts
Product Catalogs
Intranet Applications
Groupware Applications: – bulletin boards – file sharing
Servlets vs CGI:
When a servlet is FIRST requested, it is loaded into the servlet engine. The init() method of
the servlet is invoked so that the servlet may initialize itself.
Once initialization is complete, the request is then forwarded to the appropriate method (ie.
doGet or doPost)
The servlet is then held in memory. Subsequent requests are simply forwarded to the servlet
object.
When the engine wishes to remove the servlet, its destroy() method is invoked.
Servlets can receive multiple requests for multiple clients at any given time. Therefore,
servlets must be thread safe
The life cycle methods are
void init(ServletConfig config)
–Initializes the servlet.
void service(ServletRequest req, ServletResponse res)
–Carries out a single request from the client.
void destroy()
–Cleans up whatever resources are being held (e.g., memory, file handles, threads) and makes
sure that any persistent state is synchronized with the servlet's current in-memory state.
Servlet API:
Every servlet must implement javax.servlet.Servlet interface
Most servlets implement the interface by extending one of these classes
–javax.servlet.GenericServlet
–javax.servlet.http.HttpServlet
Interface javax.servlet.Servlet
The Servlet interface defines methods
–to initialize a servlet
– to receive and respond to client requests
–to destroy a servlet and its resources
– to get any startup information
– to return basic information about itself, such as its author, version and copyright.
Developers need to directly implement this interface only if their servlets cannot (or choose
not to) inherit from GenericServlet or HttpServlet.
GenericServlet – Methods
void init(ServletConfig config)
–Initializes the servlet.
• void service(ServletRequest req, ServletResponse res)
–Carries out a single request from the client.
•void destroy()
–Cleans up whatever resources are being held (e.g., memory, file handles, threads) and makes
sure that any persistent state is synchronized with the servlet's current in-memory state.
•ServletConfig getServletConfig()
–Returns a servlet config object, which contains any initialization parameters and startup
configuration for this servlet.
• String getServletInfo()
–Returns a string containing information about the servlet, such as its author, version, and
copyright.
HttpServlet – Methods
The servlet container creates a ServletResponse object and passes it as an argument to the
servlet's service method.
HttpServletResponse – Methods:
java.io.PrintWriter
getWriter()
Returns a PrintWriter object that can send character text to the client
void setContentType (java.lang.String type)
Sets the content type of the response being sent to the client. The content type may include the
type of character encoding used, for example, text/html; charset=ISO-8859-4
Int getBufferSize()
Returns the actual buffer size used for the response
Example Program for Servlet:
ServletExample.java
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import java.util.*;
out.println("<html>");
out.println("<head>");
out.println("<title>Servlet Example</title>");
out.println("</head>");
out.println("<body>");
out.println("<h3>Welcome to Servlet</h3>");
out.println("Time:"+(new Date()).toLocaleString());
out.println("</body>");
out.println("</html>");
}
}
Web.xml
<servlet>
<servlet-name>Example</servlet-name>
<servlet-class>ServletExample</servlet-class>
</servlet>
6
<servlet-mapping>
<servlet-name>Example</servlet-name>
<url-pattern>/servletexample</url-pattern>
</servlet-mapping>
OUTPUT:
Types of Cookie:
Advantage of Cookies:
1. Simplest technique of maintaining the state.
2. Cookies are maintained at client side.
Disadvantage of Cookies:
1. It will not work if cookie is disabled from the browser.
2. Only textual information can be set in Cookie object.
Cookie class:
javax.servlet.http.Cookie class provides the functionality of using cookies. It provides a
lot of useful methods for cookies.
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.http.Cookie;
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String n=request.getParameter("userName");
out.print("Welcome "+n);
out.close();
}catch(Exception e){System.out.println(e);}
}
}
SecondServlet.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
response.setContentType("text/html");
PrintWriter out = response.getWriter();
Cookie ck[]=request.getCookies();
out.print("Hello "+ck[0].getValue());
out.close();
}catch(Exception e){System.out.println(e);}
}
}
web.xml
<web-app>
<servlet>
<servlet-name>s1</servlet-name>
<servlet-class>FirstServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>s1</servlet-name>
<url-pattern>/servlet1</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>s2</servlet-name>
<servlet-class>SecondServlet</servlet-class>
10
</servlet>
<servlet-mapping>
<servlet-name>s2</servlet-name>
<url-pattern>/servlet2</url-pattern>
</servlet-mapping>
</web-app>
OUTPUT:
11
Introduction to JSP
JSP technology is used to create web application. It focuses more on presentation logic of the
web apllication.JSP pages are easier to maintain then a Servlet. JSP pages are opposite of
Servlets. Servlet adds HTML code inside Java code while JSP adds Java code inside HTML.
Everything a Servlet can do, a JSP page can also do it.
JSP enables us to write HTML pages containing tags that run powerful Java programs. JSP
separates presentation and business logic as Web designer can design and update JSP pages
without learning the Java language and Java Developer can also write code without concerning
the web design.
JSP Life Cycle:
JSP pages are converted into Servlet by the Web Container. The Container translates a JSP page
into servletclass source(.java) file and then compiles into a Java Servlet class.
The jspInit() – This method is executed first after the JSP is loaded. – The jspInit() is only called
once during any JSP component life time. –The jspInit() – <%!public void jspinit(){}%>
_jspService() – This method is executed for processing client request and send the response back
to client.
jspDestroy() – This method is executed to destroy the JSP object
JSP Elements:
Besides HTML tag elements, JSP provides four basic categories of constructors (markup tags):
directives, scripting elements, standard actions, and comments.
JSP Syntax
12
JSP Directives
JSP directives provide directions and instructions to the container, telling it how to handle certain
aspects of JSP processing. A JSP directive affects the overall structure of the servlet class.
The page Directive:
<%@ page import="package.class" %>
• <%@ page import="java.util.*" %>
• <%@ page contentType="text/html" %>
– <% response.setContentType("text/html"); %>
The include Directive:
The include directive is used to include a file during the translation phase. This directive tells the
container to merge the content of other external files with the current JSP during the translation
phase. You may include directives anywhere in your JSP page.
The general usage form of this directive is as follows:
<%@ include file="relative url" >
The taglib Directive:
The taglib directive declares that your JSP page uses a set of custom tags, identifies the location
of the library, and provides a means for identifying the custom tags in your JSP page.
The taglib directive follows the following syntax:
<%@ taglib uri="uri" prefix="prefixOfTag" >
Scripting Elements:
There are three types of Scripting Elements
Declaration
Expression
Scriptlets
Declaration Element: The JSP declaration element defines page-scope variables to store
information or defines supporting methods that the rest of a JSP page may need. Declaration
elements do not produce outputs.
Its syntax is
13
14
WEB SERVICES:
Definition: Web services are XML-based information exchange systems that use the Internet for direct
application-to-application interaction. These systems can include programs, objects, messages, or
documents.
Properties:
Web service,
Is available over the Internet or private (intranet) networks
Uses a standardized XML messaging system
Is not tied to any one operating system or programming language
Is self-describing via a common XML grammar
Is discoverable via a simple find mechanism
Characteristics:
XML-Based
Loosely Coupled
Coarse-Grained
Ability to be Synchronous or Asynchronous
Supports Remote Procedure Calls(RPCs)
Supports Document Exchange
Components of Web Services:
The basic web services platform is XML + HTTP. All the standard web services work using the following
components
SOAP (Simple Object Access Protocol)
UDDI (Universal Description, Discovery and Integration)
WSDL (Web Services Description Language)
Working Steps of Web Service:
A web service enables communication among various applications by using open standards such as HTML,
XML, WSDL, and SOAP. A web service takes the help of:
XML to tag the data
SOAP to transfer a message
WSDL to describe the availability of service.
Can able to build a Java-based web service on Solaris that is accessible from Visual Basic program that runs
on Windows.
www.rejinpaul.com
www.rejinpaul.com
WSDL:
Web Services Description Language (WSDL) is a format for describing a Web Services interface. It is a
way to describe services and how they should be bound to specific network addresses. WSDL has three
parts:
Definitions
Operations
Service bindings
Definitions are generally expressed in XML and include both data type definitions and message definitions
that use the data type definitions. These definitions are usually based upon some agreed upon XML
vocabulary.
Operations describe actions for the messages supported by a Web service. There are four types of
operations:
One-way: Messages sent without a reply required
Request/response: The sender sends a message and the received sends a reply.
Solicit response: A request for a response. (The specific definition for this action is pending.)
Notification: Messages sent to multiple receivers. (The specific definition for this action is pending.)
Operations are grouped into port types. Port types define a set of operations supported by the Web service.
Service bindings connect port types to a port. A port is defined by associating a network address with a port
type. A collection of ports defines a service. This binding is commonly created using SOAP, but other forms
may be used. These other forms could include CORBA Internet Inter-ORB Protocol (IIOP), DCOM, .NET,
Java Message Service (JMS), or WebSphere MQ to name a few.
The following figure shows the relationship of the basic parts of WSDL:
The following figure illustrates the use of WSDL. At the left is a service provider. At the right is a service
consumer. The steps involved in providing and consuming a service are:
1. A service provider describes its service using WSDL. This definition is published to a repository of
services. The repository could use Universal Description, Discovery, and Integration (UDDI). Other
forms of directories could also be used.
2. A service consumer issues one or more queries to the repository to locate a service and determine
how to communicate with that service.
3. Part of the WSDL provided by the service provider is passed to the service consumer. This tells the
service consumer what the requests and responses are for the service provider.
4. The service consumer uses the WSDL to send a request to the service provider.
5. The service provider provides the expected response to the service consumer.
www.rejinpaul.com
www.rejinpaul.com
UDDI:
UDDI is based on a common set of industry standards, including HTTP, XML, XML Schema, and SOAP. It
provides an infrastructure for a Web Services-based software environment for both publicly available
services and services only exposed internally within an organization. The UDDI Business Registry system
consists of three directories:
UDDI white pages: basic information such as a company name, address, and phone numbers, as well
as unique identifiers for the company tax IDs. This information allows others to discover web
service based upon business identification.
UDDI yellow pages: detailed business data, organized by relevant business classifications. Yellow
pages uses commonly accepted industrial categorization schemes, industry codes, product codes,
business identification codes and the like to make it easier for companies to search through the
listings and find exactly what they want
UDDI green pages: Green pages contain technical information about a web service. A green page
allows someone to bind to a Web service after it's been found. Also information about a company's
key business processes, such as operating platform, supported programs, purchasing methods,
shipping and billing requirements, and other higher-level business protocols.
The figure shows the invocation pattern:
www.rejinpaul.com
www.rejinpaul.com
<?xml version="1.0"?>
<soap:Envelope
xmlns:soap="http://www.w3.org/2003/05/soap-envelope/"
soap:encodingStyle="http://www.w3.org/2003/05/soap-encoding">
...
Message information goes here
...
</soap:Envelope>
Advantages of Soap Web Services:
Slow: SOAP uses XML format that must be parsed to be read. It defines many standards that must be
followed while developing the SOAP applications. So it is slow and consumes more bandwidth and
resource.
WSDL dependent: SOAP uses WSDL and doesn't have any other mechanism to discover the service.
<?xml version="1.0"?>
<soap:Envelope
xmlns:soap="http://www.w3.org/2003/05/soap-envelope/"
soap:encodingStyle="http://www.w3.org/2003/05/soap-encoding">
<soap:Body xmlns:m="http://www.example.org/stock">
<m:GetStockPrice>
<m:StockName>IBM</m:StockName>
</m:GetStockPrice>
</soap:Body>
</soap:Envelope>
<?xml version="1.0"?>
<soap:Envelope
xmlns:soap="http://www.w3.org/2003/05/soap-envelope/"
soap:encodingStyle="http://www.w3.org/2003/05/soap-encoding">
<soap:Body xmlns:m="http://www.example.org/stock">
<m:GetStockPriceResponse>
<m:Price>34.5</m:Price>
</m:GetStockPriceResponse>
</soap:Body>
</soap:Envelope>
www.rejinpaul.com
www.rejinpaul.com
JAVA WEB SERVICES:
Java web service application perform communication through WSDL (Web Services Description
Language). There are two ways to write java web service application code: SOAP and RESTful.
Java Web Services API
There are two main API's defined by Java for developing web service applications since JavaEE 6.
1) JAX-WS: for SOAP web services. The are two ways to write JAX-WS application code: by RPC style
and Document style.
2) JAX-RS: for RESTful web services. There are mainly 2 implementation currently in use for creating
JAX-RS application: Jersey and RESTeasy.
There are many difference between these two style of web services e.g. SOAP take morebandwidth because
of heavy weight XML based protocol but REST takes less bandwidth because of popular use of JSON as
message protocol and leveraging HTTP method to define action. This also means that REST is faster than
SOAP based web services. You can derive many differences between SOAP and RESTful with the fact that
its HTTP based e.g. REST URLs can be cached or bookmarked.
JAVA-WS API:
There are two ways to develop JAX-WS example.
1. RPC style
2. Document style
What is Literal?
In simplest definition, literal it means that the data is serialized according to a schema
JAVA-RS API:
What is REST?
REST is an architectural style of developing web services which take advantage of ubiquity of HTTP
protocol and leverages HTTP method to define actions. REST stands for REpresntational State Transfer.
Jersey:
Jersey RESTful Web Services framework is open source, production quality, framework for developing
RESTful Web Services in Java that provides support for JAX-RS APIs and serves as a JAX-RS (JSR 311 &
JSR 339) Reference Implementation.
Jersey framework is more than the JAX-RS Reference Implementation. Jersey provides its own API that
extend the JAX-RS toolkit with additional features and utilities to further simplify RESTful service and
client development.
www.rejinpaul.com
www.rejinpaul.com
RESTEasy:
RESTEasy is the JAX-RS implementation provided by JBoss project. Can use RESTEasy to create restful
web services. RESTEasy provides tighter integration with the JBoss Application Server but can deploy it on
any servlet container.
JAX-RS API compliant – so mostly there is a need to plug it with JAX-RS API coding to create rest
web services.
Provides support for writing client programs using JAX-RS 2.0 client API.
Rich set of providers – XML, JSON, YAML, Multipart, XOP, Atom, etc.
Xml html
XML was designed to carry HTML was designed to
data - with focus on what data display data - with focus on
is how data looks
data-description language. presentation language,
self-describing not self-describing
user defined tags no pre
use only pre defined tags
defined tags
tree structured not structured
Extendible Non extendible
XML is case sensitive. HTML is not case sensitive.
HTML does not preserve
XML preserve whitespaces.
whitespaces.
XML provides a framework HTML is a markup
to define markup languages. language itself.
XML makes it mandatory to In HTML, it is not necessary
use a closing tag. to use a closing tag.
Syntax:
<root>
<child>
<subchild>.....</subchild>
</child>
</root>
www.rejinpaul.com
www.rejinpaul.com
A prolog defines the XML version and the character encoding.
<?xml version="1.0" encoding="UTF-8"?> -prolog
<bookstore> -root element
<book category="cooking"> -child of root, Category-attribute of book
<title lang="en">Everyday Italian</title>
<author>Giada De Laurentiis</author>
<year>2005</year>
<price>30.00</price>
</book>
</bookstore>
Syntax Rules:
XML documents must contain one root element that is the parent of all other elements.
The XML prolog is optional. If it exists, it must come first in the document.
The XML prolog does not have a closing tag. This is not an error. The prolog is not a part of the
XML document.
In XML, it is illegal to omit the closing tag. All elements must have a closing tag.
XML tags are case sensitive. The tag <Letter> is different from the tag <letter>.
In XML, all elements must be properly nested within each other. order is important.
In XML, the attribute values must always be quoted.
White-space is Preserved in XML.XML does not truncate multiple white-spaces .
XML Stores New Line as LF
Comments in XML-<!-- This is a comment -->
Entity References-Some characters have a special meaning in XML.
XML Elements:
An XML element is everything from (including) the element's start tag to (including) the element's end tag.
An element can contain:
text
attributes
other elements
or a mix of the above
Empty XML Elements-An element with no content is said to be empty.<element></element> or</element>.
XML elements must follow these naming rules:
Element names are case-sensitive
Element names must start with a letter or underscore
Element names cannot start with the letters xml (or XML, or Xml, etc)
Element names can contain letters, digits, hyphens, underscores, and periods
Element names cannot contain spaces
no words are reserved (except xml).
www.rejinpaul.com
www.rejinpaul.com
XML Elements are Extensible.eg;<date> extended as <day>,<month>,<year>
XML Attributes
Attributes are designed to contain data related to a specific element. Attribute values must always be quoted.
Either single or double quotes can be used.
Avoid XML Attributes?
Some things to consider when using attributes are:
attributes cannot contain multiple values (elements can)
attributes cannot contain tree structures (elements can)
attributes are not easily expandable (for future changes)
XML Attributes for Metadata- eg: id attribute. ID references are assigned to elements to refer elements.
XML Namespaces:
XML Namespaces provide a method to avoid element name conflicts.
Name Conflicts:
In XML, element names are defined by the developer. This often results in a conflict when trying to mix
XML documents from different XML applications.
Eg:
This XML carries HTML table information:
<table>
<tr>
<td>Apples</td>
<td>Bananas</td>
</tr>
</table>
This XML carries information about a table (a piece of furniture):
<table>
<name>African Coffee Table</name>
<width>80</width>
<length>120</length>
</table>
Name conflicts in XML can easily be avoided using a name prefix.
XML Namespaces - The xmlns Attribute
When using prefixes in XML, a namespace for the prefix must be defined.
The namespace can be defined by an xmlns attribute in the start tag of an element.
The namespace declaration has the following syntax. xmlns:prefix="URI".
Syntax:
Eg:
<root>
<h:table xmlns:h="http://www.w3.org/TR/html4/">
<h:tr>
<h:td>Apples</h:td>
<h:td>Bananas</h:td>
</h:tr>
</h:table>
<f:table xmlns:f="urn:Corp:furniture">
<f:name>African Coffee Table</f:name>
<f:width>80</f:width>
www.rejinpaul.com
www.rejinpaul.com
<f:length>120</f:length>
</f:table>
Default name space:
Defining a default namespace for an element saves us from using prefixes in all the child elements. It has the
following syntax:
xmlns="namespaceURI" i.e without arbitrary text string.
Eg:
<table xmlns="http://www.w3.org/TR/html4/">
<tr>
<td>Apples</td>
<td>Bananas</td>
</tr>
</table>
The purpose of using an URI is to give the namespace a unique name. URI represents nothing more than a
logical namespace name.
<xs:element name="employee">
<xs:complexType>
<xs:sequence>
<xs:element name="firstname" type="xs:string"/>
<xs:element name="lastname" type="xs:string"/>
<xs:element name="email" type="xs:string"/>
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:schema>
employee.xml
<?xml version="1.0"?>
<employee
xmlns="http://www.javatpoint.com"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.javatpoint.com employee.xsd">
<firstname>vimal</firstname>
<lastname>jaiswal</lastname>
<email>[email protected]</email>
</employee>
www.rejinpaul.com
www.rejinpaul.com
DTD:
What is DTD?
DTD stands for Document Type Definition. It defines the legal building blocks of an XML document. It is
used to define document structure with a list of legal elements and attributes.
Purpose of DTD:
Its main purpose is to define the structure of an XML document. It contains a list of legal elements and
define the structure with the help of them.
Eg:
employee.xml
<?xml version="1.0"?>
<employee>
<firstname>vimal</firstname>
<lastname>jaiswal</lastname>
<email>[email protected]</email>
</employee>
employee
employee.dtd
Description of DTD:
<!DOCTYPE employee : It defines that the root element of the document is employee.
<!ELEMENT employee: It defines that the employee element contains 3 elements "firstname, lastname and
email".
<!ELEMENT firstname: It defines that the firstname element is #PCDATA typed. (parse-able data type).
<!ELEMENT lastname: It defines that the lastname element is #PCDATA typed. (parse-able data type).
<!ELEMENT email: It defines that the email element is #PCDATA typed. (parse-able data type).
2) DTDs are derived from SGML syntax. XSDs are written in XML.
3) DTD doesn't support datatypes. XSD supports datatypes for elements and attributes.
5) DTD doesn't define order for child XSD defines order for child elements.
elements.
7) DTD is not simple to learn. XSD is simple to learn because you don't need to learn
new language.
8) DTD provides less control on XML XSD provides more control on XML structure.
structure.
The difference between well-formed and valid XML is simple: Valid XML has a DTD associated with it
and has been verified against all the rules contained in the DTD in addition to being well-formed.
Merely well-formed XML, on the other hand, is not necessarily valid, although it may be.
CDATA
CDATA: (Unparsed Character data): CDATA contains the text which is not parsed further in an XML
document. Tags inside the CDATA text are not treated as markup and entities will not be expanded.Let's
take an example for CDATA:
<?xml version="1.0"?>
<employee>
<![CDATA[
<firstname>vimal</firstname>
<lastname>jaiswal</lastname>
<email>[email protected]</email>
]]>
</employee>
PCDATA
PCDATA: (Parsed Character Data): XML parsers are used to parse all the text in an XML document.
PCDATA stands for Parsed Character data. PCDATA is the text that will be parsed by a parser. Tags inside
the PCDATA will be treated as markup and entities will be expanded.
www.rejinpaul.com
www.rejinpaul.com
www.rejinpaul.com
www.rejinpaul.com
XSLT:
XSLT stands for Extensible Stylesheet Language Transformations. It is both a style sheet specification and a
kind of programming language that allows you to transform an XML document into the format of your
choice: stripped ASCII text, HTML, RTF, and even other dialects of XML.
XSLT transforms an XML source-tree into an XML result-tree.
What is XSLT?
XSLT stands for XSL Transformations
XSLT is the most important part of XSL
XSLT transforms an XML document into another XML document
XSLT uses XPath to navigate in XML documents
XSLT is a W3C Recommendation
XQuery:
XQuery is designed to query XML data - not just XML files, but anything that can appear as XML,
including databases.
1. <xsl:template> Element
An XSL style sheet consists of one or more set of rules that are called templates. A template contains rules
to apply when a specified node is matched.
The <xsl:template> element is used to build templates.
The match attribute is used to associate a template with an XML element. The match attribute can also be
used to define a template for the entire XML document. The value of the match attribute is an XPath
expression (i.e. match="/" defines the whole document).
2. <xsl:value-of> Element
The <xsl:value-of> element is used to extract the value of a selected node and add it to the output stream
of the transformation. The value of the select attribute is an XPath expression.
3. The <xsl:for-each> Element
The <xsl:for-each> element allows to do looping in XSLT. The XSL <xsl:for-each> element can be used
to select every XML element of a specified node-set. The value of the select attribute is an XPath
www.rejinpaul.com
www.rejinpaul.com
expression. An XPath expression works like navigating a file system; where a forward slash (/) selects
subdirectories.
It is possible to filter the output from the XML file by adding a criterion to the select attribute in the
<xsl:for-each> element.
<xsl:for-each select="catalog/cd[artist='Bob Dylan']">
Legal filter operators are:
= (equal)
!= (not equal)
< less than
> greater than
4. The <xsl:sort> Element
The <xsl:sort> element is used to sort the output. To sort the output, simply add an <xsl:sort>
element inside the <xsl:for-each> element in the XSL file. The select attribute indicates what XML
element to sort on.
5. The <xsl:if> Element:
To put a conditional if test against the content of the XML file, add an <xsl:if> element to the XSL
document.
Syntax:
<xsl:if test="expression">
...some output if the expression is true...
</xsl:if>
To add a conditional test, add the <xsl:if> element inside the <xsl:for-each> element in the XSL file.
6. The <xsl:choose> Element
Syntax:
<xsl:choose>
<xsl:when test="expression">
... some output ...
</xsl:when>
<xsl:otherwise>
... some output ....
</xsl:otherwise>
</xsl:choose>
To insert a multiple conditional test against the XML file, add the <xsl:choose>, <xsl:when>, and
<xsl:otherwise> elements to the XSL file.
XPATH :
Selecting Nodes
XPath uses path expressions to select nodes in an XML document. The node is selected by following a path
or steps. The most useful path expressions are listed below:
Expression Description
// Selects nodes in the document from the current node that match the selection no matter
where they are
@ Selects attributes
www.rejinpaul.com
www.rejinpaul.com
In the table below we have listed some path expressions and the result of the expressions:
Path Expression Result
//book Selects all book elements no matter where they are in the document
bookstore//book Selects all book elements that are descendant of the bookstore element, no matter
where they are under the bookstore element
Predicates:
Predicates are used to find a specific node or a node that contains a specific value.
Predicates are always embedded in square brackets.
In the table below we have listed some path expressions with predicates and the result of the expressions:
Path Expression Result
/bookstore/book[1] Selects the first book element that is the child of the bookstore
element.
Note: In IE 5,6,7,8,9 first node is[0], but according to W3C, it is [1].
To solve this problem in IE, set the SelectionLanguage to XPath:
In JavaScript: xml.setProperty("SelectionLanguage","XPath");
/bookstore/book[last()] Selects the last book element that is the child of the bookstore element
/bookstore/book[last()-1] Selects the last but one book element that is the child of the bookstore
element
/bookstore/book[position()<3] Selects the first two book elements that are children of the bookstore
element
//title[@lang] Selects all the title elements that have an attribute named lang
//title[@lang='en'] Selects all the title elements that have a "lang" attribute with a value of
"en"
/bookstore/book[price>35.00] Selects all the book elements of the bookstore element that have a price
element with a value greater than 35.00
/bookstore/book[price>35.00] Selects all the title elements of the book elements of the bookstore
/title element that have a price element with a value greater than 35.00
www.rejinpaul.com
www.rejinpaul.com
Selecting Unknown Nodes:
XPath wildcards can be used to select unknown XML nodes.
Wildcard Description
/bookstore/* Selects all the child element nodes of the bookstore element
//title[@*] Selects all title elements which have at least one attribute of any
kind
//book/title | //book/price Selects all the title AND price elements of all book elements
//title | //price Selects all the title AND price elements in the document
/bookstore/book/title | //price Selects all the title elements of the book element of the bookstore
element AND all the price elements in the document
Example program:
First.xml
<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type="text/xsl" href="First.xsl"?>
<catalog>
<cd>
<title>programming languages</title>
<author>Ravi Sethi</author>
<country>India</country>
<company>Pearson</company>
<price>279</price>
<year>2012</year>
</cd>
<cd>
<title>Data mining</title>
<author>Han Kamber</author>
<country>UK</country>
<company>Elsevier</company>
<price>700</price>
<year>2000</year>
</cd>
<cd>
www.rejinpaul.com
www.rejinpaul.com
<title>Operating System</title>
<author>Silberschatz</author>
<country>USA</country>
<company>Wiley</company>
<price>500</price>
<year>2009</year>
</cd>
</catalog>
First.xsl
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="/">
<html>
<body>
<h2>My Book Collection</h2>
<table border="1">
<tr bgcolor="#9acd32">
<th>Title</th>
<th>Author</th>
</tr>
<xsl:for-each select="catalog/cd">
<tr>
<td><xsl:value-of select="title"/></td>
<xsl:choose>
<xsl:when test="price > 300">
<td bgcolor="#ff00ff">
<xsl:value-of select="author"/></td>
</xsl:when>
<xsl:otherwise>
<td><xsl:value-of select="author"/></td>
</xsl:otherwise>
</xsl:choose>
</tr>
</xsl:for-each>
</table>
</body>
</html>
</xsl:template>
</xsl:stylesheet>