CS8651-Internet Programming NOTES 2
CS8651-Internet Programming NOTES 2
in
Srividya College of Engineering and Technology, Virudhunagar Course material –Lecture Notes
UNIT I
Introduction to java
Java is an Object-Oriented Language. As a language that has the Object Oriented feature, Java
supports the following fundamental concepts:
Polymorphism
Inheritance
Encapsulation
n
Abstraction
g.i
Classes
Objects
Instance
n
Method
Message Parsing
eri
In this chapter, we will look into the concepts Classes and Objects.
e
Object - Objects have states and behaviors. Example: A dog has states - color, name,
gin
breed as well as behaviors -wagging, barking, eating. An object is an instance of a class.
Class - A class can be defined as a template/blue print that describes the behaviors/states
that object of its type support.
en
Objects in Java:
Let us now look deep into what are objects. If we consider the real-world we can find many
arn
objects around us, Cars, Dogs, Humans, etc. All these objects have a state and behavior.
If we consider a dog, then its state is - name, breed, color, and the behavior is - barking,
wagging, running
Le
If you compare the software object with a real world object, they have very similar
characteristics.
w.
Software objects also have a state and behavior. A software object's state is stored in fields and
behavior is shown via methods.
ww
So in software development, methods operate on the internal state of an object and the object-to-
object communication is done via methods.
Classes in Java:
void barking(){
}
void hungry(){
}
n
g.i
void sleeping(){
}
}
n
A class can contain any of the following variable types.
eri
Local variables: Variables defined inside methods, constructors or blocks are called
local variables. The variable will be declared and initialized within the method and the
e
variable will be destroyed when the method has completed.
gin
Instance variables: Instance variables are variables within a class but outside any
method. These variables are instantiated when the class is loaded. Instance variables can
be accessed from inside any method, constructor or blocks of that particular class.
Class variables: Class variables are variables declared with in a class, outside any
en
A class can have any number of methods to access the value of various kinds of methods. In the
arn
Below mentioned are some of the important topics that need to be discussed when looking into
classes of the Java Language.
Le
Constructors:
w.
When discussing about classes, one of the most important sub topic would be constructors. Every
class has a constructor. If we do not explicitly write a constructor for a class the Java compiler
builds a default constructor for that class.
ww
Each time a new object is created, at least one constructor will be invoked. The main rule of
constructors is that they should have the same name as the class. A class can have more than one
constructor.
Java also supports Singleton Classes where you would be able to create only one instance of a
class.
n
Creating an Object:
g.i
As mentioned previously, a class provides the blueprints for objects. So basically an object is
created from a class. In Java, the new key word is used to create new objects.
n
There are three steps when creating an object from a class:
eri
Declaration: A variable declaration with a variable name with an object type.
Instantiation: The 'new' key word is used to create the object.
e
Initialization: The 'new' keyword is followed by a call to a constructor. This call
gin
initializes the new object.
If we compile and run the above program, then it would produce the following result:
ww
Instance variables and methods are accessed via created objects. To access an instance variable
the fully qualified path should be as follows:
Example:
n
This example explains how to access instance variables and methods of a class:
g.i
public class Puppy{
n
int puppyAge;
eri
public Puppy(String name){
// This constructor has one parameter, name.
System.out.println("Passed Name is :" + name );
} e
gin
public void setAge( int age ){
puppyAge = age;
}
en
}
public static void main(String []args){
/* Object creation */
Puppy myPuppy = new Puppy( "tommy" );
Le
If we compile and run the above program, then it would produce the following result:
Puppy's age is :2
Variable Value :2
As the last part of this section let's now look into the source file declaration rules. These rules are
essential when declaring classes, import statements and package statements in a source file.
n
The public class name should be the name of the source file as well which should be
g.i
appended by .java at the end. For example : The class name is . public class Employee{}
Then the source file should be as Employee.java.
If the class is defined inside a package, then the package statement should be the first
n
statement in the source file.
If import statements are present then they must be written between the package statement
eri
and the class declaration. If there are no package statements then the import statement
should be the first line in the source file.
Import and package statements will imply to all the classes present in the source file. It is
e
not possible to declare different import and/or package statements to different classes in
gin
the source file.
Classes have several access levels and there are different types of classes; abstract classes, final
classes, etc. I will be explaining about all these in the access modifiers chapter.
en
Apart from the above mentioned types of classes, Java also has some special classes called Inner
classes and Anonymous classes.
arn
Java Package:
In simple, it is a way of categorizing the classes and interfaces. When developing applications in
Le
Java, hundreds of classes and interfaces will be written, therefore categorizing these classes is a
must as well as makes life much easier.
w.
Import statements:
In Java if a fully qualified name, which includes the package and the class name, is given then
ww
the compiler can easily locate the source code or classes. Import statement is a way of giving the
proper location for the compiler to find that particular class.
For example, the following line would ask compiler to load all the classes available in directory
java_installation/java/io :
import java.io.*;
For our case study, we will be creating two classes. They are Employee and EmployeeTest.
First open notepad and add the following code. Remember this is the Employee class and the
class is a public class. Now, save this source file with the name Employee.java.
The Employee class has four instance variables name, age, designation and salary. The class has
one explicitly defined constructor, which takes a parameter.
n
import java.io.*;
g.i
public class Employee{
String name;
int age;
n
String designation;
double salary;
eri
// This is the constructor of the class Employee
public Employee(String name){
this.name = name; e
gin
}
// Assign the age of the Employee to the variable age.
public void empAge(int empAge){
age = empAge;
en
}
/* Assign the designation to the variable designation.*/
public void empDesignation(String empDesig){
arn
designation = empDesig;
}
/* Assign the salary to the variable salary.*/
public void empSalary(double empSalary){
Le
salary = empSalary;
}
/* Print the Employee details */
w.
System.out.println("Designation:" + designation );
System.out.println("Salary:" + salary);
}
}
As mentioned previously in this tutorial, processing starts from the main method. Therefore in-
order for us to run this Employee class there should be main method and objects should be
created. We will be creating a separate class for these tasks.
Given below is the EmployeeTest class, which creates two instances of the class Employee and
invokes the methods for each object to assign values for each variable.
import java.io.*;
public class EmployeeTest{
n
Employee empOne = new Employee("James Smith");
g.i
Employee empTwo = new Employee("Mary Anne");
n
empOne.empAge(26);
empOne.empDesignation("Senior Software Engineer");
eri
empOne.empSalary(1000);
empOne.printEmployee();
empTwo.empAge(21); e
gin
empTwo.empDesignation("Software Engineer");
empTwo.empSalary(500);
empTwo.printEmployee();
}
en
Now, compile both the classes and then run EmployeeTest to see the result as follows:
arn
Age:21
Designation:Software Engineer
Salary:500.0
Control Statements
There may be a situation when we need to execute a block of code several number of times, and
is often referred to as a loop.
Java has very flexible three looping mechanisms. You can use one of the following three loops:
while Loop
do...while Loop
for Loop
n
g.i
As of Java 5, the enhanced for loop was introduced. This is mainly used for Arrays.
n
A while loop is a control structure that allows you to repeat a task a certain number of times.
eri
Syntax:
When executing, if the boolean_expression result is true, then the actions inside the loop will be
arn
Here, key point of the while loop is that the loop might not ever run. When the expression is
tested and the result is false, the loop body will be skipped and the first statement after the while
Le
Example:
w.
while( x < 20 ) {
System.out.print("value of x : " + x );
x++;
System.out.print("\n");
}
}
value of x : 10
value of x : 11
value of x : 12
value of x : 13
value of x : 14
value of x : 15
n
value of x : 16
g.i
value of x : 17
value of x : 18
value of x : 19
n
The do...while Loop:
eri
A do...while loop is similar to a while loop, except that a do...while loop is guaranteed to execute
at least one time.
e
gin
Syntax:
do
{
//Statements
arn
}while(Boolean_expression);
Notice that the Boolean expression appears at the end of the loop, so the statements in the loop
execute once before the Boolean is tested.
Le
If the Boolean expression is true, the flow of control jumps back up to do, and the statements in
the loop execute again. This process repeats until the Boolean expression is false.
w.
Example:
ww
do{
System.out.print("value of x : " + x );
x++;
System.out.print("\n");
}while( x < 20 );
}
}
value of x : 10
value of x : 11
value of x : 12
value of x : 13
n
value of x : 14
g.i
value of x : 15
value of x : 16
value of x : 17
n
value of x : 18
value of x : 19
eri
The for Loop:
e
A for loop is a repetition control structure that allows you to efficiently write a loop that needs to
gin
execute a specific number of times.
A for loop is useful when you know how many times a task is to be repeated.
en
Syntax:
The initialization step is executed first, and only once. This step allows you to declare
and initialize any loop control variables. You are not required to put a statement here, as
ww
The Boolean expression is now evaluated again. If it is true, the loop executes and the
process repeats itself (body of loop, then update step, then Boolean expression). After the
Boolean expression is false, the for loop terminates.
Example:
n
for(int x = 10; x < 20; x = x+1) {
g.i
System.out.print("value of x : " + x );
System.out.print("\n");
}
n
}
}
eri
This would produce the following result:
value of x : 10 e
gin
value of x : 11
value of x : 12
value of x : 13
value of x : 14
en
value of x : 15
value of x : 16
value of x : 17
arn
value of x : 18
value of x : 19
As of Java 5, the enhanced for loop was introduced. This is mainly used for Arrays.
w.
Syntax:
for(declaration : expression)
{
//Statements
}
Declaration: The newly declared block variable, which is of a type compatible with the
elements of the array you are accessing. The variable will be available within the for
block and its value would be the same as the current array element.
Expression: This evaluates to the array you need to loop through. The expression can be
an array variable or method call that returns an array.
Example:
n
for(int x : numbers ){
g.i
System.out.print( x );
System.out.print(",");
}
n
System.out.print("\n");
String [] names ={"James", "Larry", "Tom", "Lacy"};
eri
for( String name : names ) {
System.out.print( name );
System.out.print(",");
} e
gin
}
}
10,20,30,40,50,
James,Larry,Tom,Lacy,
arn
The break keyword is used to stop the entire loop. The break keyword must be used inside any
Le
The break keyword will stop the execution of the innermost loop and start executing the next line
w.
Syntax:
ww
break;
Example:
for(int x : numbers ) {
if( x == 30 ) {
break;
}
System.out.print( x );
System.out.print("\n");
}
n
}
g.i
}
n
10
eri
20
In a for loop, the continue keyword causes flow of control to immediately jump to the
en
update statement.
In a while loop or do/while loop, flow of control immediately jumps to the Boolean
expression.
arn
Syntax:
continue;
w.
Example:
for(int x : numbers ) {
if( x == 30 ) {
continue;
}
System.out.print( x );
System.out.print("\n");
}
}
}
10
20
40
n
50
g.i
Inheritance
n
Inheritance can be defined as the process where one object acquires the properties of another.
eri
With the use of inheritance the information is made manageable in a hierarchical order.
When we talk about inheritance, the most commonly used keyword would be extends and
e
implements. These words would determine whether one object IS-A type of another. By using
gin
these keywords we can make one object acquire the properties of another object.
IS-A Relationship:
en
IS-A is a way of saying : This object is a type of that object. Let us see how the extends keyword
is used to achieve inheritance.
arn
Now, based on the above example, In Object Oriented terms, the following are true:
With use of the extends keyword the subclasses will be able to inherit all the properties of the
superclass except for the private properties of the superclass.
n
We can assure that Mammal is actually an Animal with the use of the instance operator.
g.i
Example:
n
public class Dog extends Mammal{
eri
public static void main(String args[]){
true
Le
true
true
w.
Since we have a good understanding of the extends keyword let us look into how the
implements keyword is used to get the IS-A relationship.
ww
The implements keyword is used by classes by inherit from interfaces. Interfaces can never be
extended by the classes.
Example:
Let us use the instanceof operator to check determine whether Mammal is actually an Animal,
and dog is actually an Animal
interface Animal{}
n
g.i
class Mammal implements Animal{}
n
public static void main(String args[]){
eri
Mammal m = new Mammal();
Dog d = new Dog();
e
System.out.println(m instanceof Animal);
gin
System.out.println(d instanceof Mammal);
System.out.println(d instanceof Animal);
}
}
en
true
true
true
Le
HAS-A relationship:
These relationships are mainly based on the usage. This determines whether a certain class HAS-
w.
A certain thing. This relationship helps to reduce duplication of code as well as bugs.
This shows that class Van HAS-A Speed. By having a separate class for Speed, we do not have
to put the entire code that belongs to speed inside the Van class., which makes it possible to
reuse the Speed class in multiple applications.
In Object-Oriented feature, the users do not need to bother about which object is doing the real
work. To achieve this, the Van class hides the implementation details from the users of the Van
class. So basically what happens is the users would ask the Van class to do a certain action and
the Van class will either do the work by itself or ask another class to perform the action.
A very important fact to remember is that Java only supports only single inheritance. This means
n
that a class cannot extend more than one class. Therefore following is illegal:
g.i
public class extends Animal, Mammal{}
n
However, a class can implement one or more interfaces. This has made Java get rid of the
impossibility of multiple inheritance.
eri
Packages
e
Packages are used in Java in order to prevent naming conflicts, to control access, to make
gin
searching/locating and usage of classes, interfaces, enumerations and annotations easier, etc.
Programmers can define their own packages to bundle group of classes/interfaces, etc. It is a
Le
good practice to group related classes implemented by you so that a programmer can easily
determine that the classes, interfaces, enumerations, annotations are related.
w.
Since the package creates a new namespace there won't be any name conflicts with names in
other packages. Using packages, it is easier to provide access control and it is also easier to
locate the related classes.
ww
Creating a package:
When creating a package, you should choose a name for the package and put a package
statement with that name at the top of every source file that contains the classes, interfaces,
enumerations, and annotation types that you want to include in the package.
The package statement should 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.
If a package statement is not used then the class, interfaces, enumerations, and annotation types
will be put into an unnamed package.
Example:
Let us look at an example that creates a package called animals. It is common practice to use
lowercased names of packages to avoid any conflicts with the names of classes, interfaces.
n
/* File name : Animal.java */
g.i
package animals;
interface Animal {
n
public void eat();
public void travel();
eri
}
return 0;
}
ww
Now, you compile these two files and put them in a sub-directory called animals and try to run
as follows:
$ mkdir animals
$ cp Animal.class MammalInt.class animals
$ java animals/MammalInt
Mammal eats
Mammal travels
If a class wants to use another class in the same package, the package name does not need to be
used. Classes in the same package find each other without any special syntax.
n
g.i
Example:
Here, a class named Boss is added to the payroll package that already contains Employee. The
n
Boss can then refer to the Employee class without using the payroll prefix, as demonstrated by
the following Boss class.
eri
package payroll;
}
}
arn
What happens if Boss is not in the payroll package? The Boss class must then use one of the
following techniques for referring to a class in a different package.
The fully qualified name of the class can be used. For example:
Le
payroll.Employee
w.
The package can be imported using the import keyword and the wild card (*). For
example:
ww
import payroll.*;
The class itself can be imported using the import keyword. For example:
import payroll.Employee;
Note: A class file can contain any number of import statements. The import statements must
appear after the package statement and before the class declaration.
The name of the package becomes a part of the name of the class, as we just discussed in
the previous section.
The name of the package must match the directory structure where the corresponding
bytecode resides.
n
g.i
Put the source code for a class, interface, enumeration, or annotation type in a text file whose
name is the simple name of the type and whose extension is .java. For example:
n
// File Name : Car.java
eri
package vehicle;
Now, put the source file in a directory whose name reflects the name of the package to which the
class belongs:
en
....\vehicle\Car.java
arn
In general, a company uses its reversed Internet domain name for its package names. Example: A
company's Internet domain name is apple.com, then all its package names would start with
w.
Example: The company had a com.apple.computers package that contained a Dell.java source
ww
....\com\apple\computers\Dell.java
At the time of compilation, the compiler creates a different output file for each class, interface
and enumeration defined in it. The base name of the output file is the name of the type, and its
extension is .class
For example:
package com.apple.computers;
public class Dell{
}
class Ups{
n
Now, compile this file as follows using -d option:
g.i
$javac -d . Dell.java
n
This would put compiled files as follows:
eri
.\com\apple\computers\Dell.class
.\com\apple\computers\Ups.class
e
You can import all the classes or interfaces defined in \com\apple\computers\ as follows:
gin
import com.apple.computers.*;
Like the .java source files, the compiled .class files should be in a series of directories that reflect
en
the package name. However, the path to the .class files does not have to be the same as the path
to the .java source files. You can arrange your source and class directories separately, as:
arn
<path-one>\sources\com\apple\computers\Dell.java
<path-two>\classes\com\apple\computers\Dell.class
Le
By doing this, it is possible to give the classes directory to other programmers without revealing
your sources. You also need to manage source and class files in this manner so that the compiler
and the Java Virtual Machine (JVM) can find all the types your program uses.
w.
The full path to the classes directory, <path-two>\classes, is called the class path, and is set with
the CLASSPATH system variable. Both the compiler and the JVM construct the path to your
ww
Say <path-two>\classes is the class path, and the package name is com.apple.computers, then the
compiler and JVM will look for .class files in <path-two>\classes\com\apple\compters.
A class path may include several paths. Multiple paths should be separated by a semicolon
(Windows) or colon (Unix). By default, the compiler and the JVM search the current directory
and the JAR file containing the Java platform classes so that these directories are automatically
in the class path.
To display the current CLASSPATH variable, use the following commands in Windows and
UNIX (Bourne shell):
n
In Windows -> C:\> set CLASSPATH=
g.i
In UNIX -> % unset CLASSPATH; export CLASSPATH
n
In Windows -> set CLASSPATH=C:\users\jack\java\classes
eri
In UNIX -> % CLASSPATH=/home/jack/java/classes; export CLASSPATH
e
gin
Abstraction
Abstraction refers to the ability to make a class abstract in OOP. An abstract class is one that
cannot be instantiated. All other functionality of the class still exists, and its fields, methods, and
en
constructors are all accessed in the same manner. You just cannot create an instance of the
abstract class.
arn
If a class is abstract and cannot be instantiated, the class does not have much use unless it is
subclass. This is typically how abstract classes come about during the design phase. A parent
class contains the common functionality of a collection of child classes, but the parent class itself
is too abstract to be used on its own.
Le
Abstract Class:
w.
Use the abstract keyword to declare a class abstract. The keyword appears in the class
declaration somewhere before the class keyword.
ww
this.name = name;
this.address = address;
this.number = number;
}
public double computePay()
{
System.out.println("Inside Employee computePay");
return 0.0;
}
public void mailCheck()
n
{
g.i
System.out.println("Mailing a check to " + this.name
+ " " + this.address);
}
n
public String toString()
{
eri
return name + " " + address + " " + number;
}
public String getName()
{ e
gin
return name;
}
public String getAddress()
{
en
return address;
}
public void setAddress(String newAddress)
arn
{
address = newAddress;
}
public int getNumber()
Le
{
return number;
}
w.
Notice that nothing is different in this Employee class. The class is now abstract, but it still has
ww
When you would compile above class then you would get the following error:
n
Employee.java:46: Employee is abstract; cannot be instantiated
g.i
Employee e = new Employee("George W.", "Houston, TX", 43);
^
1 error
n
Extending Abstract Class:
eri
We can extend Employee class in normal way as follows:
salary)
{
super(name, address, number);
arn
setSalary(salary);
}
public void mailCheck()
{
Le
}
public double getSalary()
{
ww
return salary;
}
public void setSalary(double newSalary)
{
if(newSalary >= 0.0)
{
salary = newSalary;
}
}
Here, we cannot instantiate a new Employee, but if we instantiate a new Salary object, the Salary
object will inherit the three fields and seven methods from Employee.
n
/* File name : AbstractDemo.java */
g.i
public class AbstractDemo
{
public static void main(String [] args)
n
{
Salary s = new Salary("Mohd Mohtashim", "Ambehta, UP", 3, 3600.00);
eri
Employee e = new Salary("John Adams", "Boston, MA", 2, 2400.00);
Constructing an Employee
Constructing an Employee
Call mailCheck using Salary reference --
Le
Abstract Methods:
If you want a class to contain a particular method but you want the actual implementation of that
method to be determined by child classes, you can declare the method in the parent class as
abstract.
The abstract keyword is also used to declare a method as abstract. An abstract method consists of
a method signature, but no method body.
Abstract method would have no definition, and its signature is followed by a semicolon, not
curly braces as follows:
n
g.i
//Remainder of class definition
}
n
Declaring a method as abstract has two results:
eri
The class must also be declared abstract. If a class contains an abstract method, the class
must be abstract as well.
Any child class must either override the abstract method or declare itself abstract.
e
gin
A child class that inherits an abstract method must override it. If they do not, they must be
abstract and any of their children must override it.
Eventually, a descendant class has to implement the abstract method; otherwise, you would have
en
follows:
{
private double salary; // Annual salary
w.
return salary/52;
}
Interface
An interface is not a class. Writing an interface is similar to writing a class, but they are two
different concepts. A class describes the attributes and behaviors of an object. An interface
contains behaviors that a class implements.
Unless the class that implements the interface is abstract, all the methods of the interface need to
be defined in the class.
n
An interface is similar to a class in the following ways:
g.i
An interface can contain any number of methods.
An interface is written in a file with a .java extension, with the name of the interface
n
matching the name of the file.
The bytecode of an interface appears in a .class file.
eri
Interfaces appear in packages, and their corresponding bytecode file must be in a
directory structure that matches the package name.
e
However, an interface is different from a class in several ways, including:
gin
You cannot instantiate an interface.
An interface does not contain any constructors.
All of the methods in an interface are abstract.
en
An interface cannot contain instance fields. The only fields that can appear in an interface
must be declared both static and final.
An interface is not extended by a class; it is implemented by a class.
arn
Declaring Interfaces:
Le
The interface keyword is used to declare an interface. Here is a simple example to declare an
interface:
w.
Example:
An interface is implicitly abstract. You do not need to use the abstract keyword when
declaring an interface.
Each method in an interface is also implicitly abstract, so the abstract keyword is not
needed.
Methods in an interface are implicitly public.
n
Example:
g.i
/* File name : Animal.java */
interface Animal {
n
public void eat();
eri
public void travel();
}
Implementing Interfaces: e
gin
When a class implements an interface, you can think of the class as signing a contract, agreeing
to perform the specific behaviors of the interface. If a class does not perform all the behaviors of
the interface, the class must declare itself as abstract.
en
A class uses the implements keyword to implement an interface. The implements keyword
appears in the class declaration following the extends portion of the declaration.
arn
m.travel();
}
}
Mammal eats
Mammal travels
When overriding methods defined in interfaces there are several rules to be followed:
n
g.i
Checked exceptions should not be declared on implementation methods other than the
ones declared by the interface method or subclasses of those declared by the interface
method.
n
The signature of the interface method and the same return type or subtype should be
maintained when overriding the methods.
eri
An implementation class itself can be abstract and if so interface methods need not be
implemented.
e
When implementation interfaces there are several rules:
gin
A class can implement more than one interface at a time.
A class can extend only one class, but implement many interfaces.
An interface can extend another interface, similarly to the way that a class can extend
en
another class.
Extending Interfaces:
arn
An interface can extend another interface, similarly to the way that a class can extend another
class. The extends keyword is used to extend an interface, and the child interface inherits the
methods of the parent interface.
Le
//Filename: Sports.java
public interface Sports
{
ww
//Filename: Football.java
public interface Football extends Sports
{
public void homeTeamScored(int points);
public void visitingTeamScored(int points);
//Filename: Hockey.java
public interface Hockey extends Sports
{
public void homeGoalScored();
public void visitingGoalScored();
public void endOfPeriod(int period);
public void overtimePeriod(int ot);
n
}
g.i
The Hockey interface has four methods, but it inherits two from Sports; thus, a class that
implements Hockey needs to implement all six methods. Similarly, a class that implements
n
Football needs to define the three methods from Football and the two methods from Sports.
eri
Extending Multiple Interfaces:
A Java class can only extend one parent class. Multiple inheritance is not allowed. Interfaces are
e
not classes, however, and an interface can extend more than one parent interface.
gin
The extends keyword is used once, and the parent interfaces are declared in a comma-separated
list.
en
For example, if the Hockey interface extended both Sports and Event, it would be declared as:
Tagging Interfaces:
The most common use of extending interfaces occurs when the parent interface does not contain
Le
any methods. For example, the MouseListener interface in the java.awt.event package extended
java.util.EventListener, which is defined as:
w.
package java.util;
public interface EventListener
{}
ww
An interface with no methods in it is referred to as a tagging interface. There are two basic
design purposes of tagging interfaces:
Creates a common parent: As with the EventListener interface, which is extended by dozens of
other interfaces in the Java API, you can use a tagging interface to create a common parent
among a group of interfaces. For example, when an interface extends EventListener, the JVM
knows that this particular interface is going to be used in an event delegation scenario.
Adds a data type to a class: This situation is where the term tagging comes from. A class that
implements a tagging interface does not need to define any methods (since the interface does not
have any), but the class becomes an interface type through polymorphism.
Exception
An exception is a problem that arises during the execution of a program. An exception can occur
for many different reasons, including the following:
n
A file that needs to be opened cannot be found.
g.i
A network connection has been lost in the middle of communications or the JVM has run
out of memory.
n
Some of these exceptions are caused by user error, others by programmer error, and others by
physical resources that have failed in some manner.
eri
To understand how exception handling works in Java, you need to understand the three
categories of exceptions:
e
gin
Checked exceptions: A checked exception is an exception that is typically a user error or
a problem that cannot be foreseen by the programmer. For example, if a file is to be
opened, but the file cannot be found, an exception occurs. These exceptions cannot
simply be ignored at the time of compilation.
en
Errors: These are not exceptions at all, but problems that arise beyond the control of the
user or the programmer. Errors are typically ignored in your code because you can rarely
do anything about an error. For example, if a stack overflow occurs, an error will arise.
They are also ignored at the time of compilation.
Le
Exception Hierarchy:
w.
All exception classes are subtypes of the java.lang.Exception class. The exception class is a
subclass of the Throwable class. Other than the exception class there is another subclass called
Error which is derived from the Throwable class.
ww
Errors are not normally trapped form the Java programs. These conditions normally happen in
case of severe failures, which are not handled by the java programs. Errors are generated to
indicate errors generated by the runtime environment. Example : JVM is out of Memory.
Normally programs cannot recover from errors.
The Exception class has two main subclasses: IOException class and RuntimeException Class.
n
n g.i
eri
Here is a list of most common checked and unchecked Java's Built-in Exceptions.
Exceptions Methods:
e
gin
Following is the list of important medthods available in the Throwable class.
1
Returns a detailed message about the exception that has occurred. This message is initialized
in the Throwable constructor.
arn
5 Returns an array containing each element on the stack trace. The element at index 0
represents the top of the call stack, and the last element in the array represents the method at
the bottom of the call stack.
public Throwable fillInStackTrace()
6
Fills the stack trace of this Throwable object with the current stack trace, adding to any
previous information in the stack trace.
Catching Exceptions:
A method catches an exception using a combination of the try and catch keywords. A try/catch
block is placed around the code that might generate an exception. Code within a try/catch block
is referred to as protected code, and the syntax for using try/catch looks like the following:
try
{
//Protected code
}catch(ExceptionName e1)
n
{
g.i
//Catch block
}
n
A catch statement involves declaring the type of exception you are trying to catch. If an
exception occurs in protected code, the catch block (or blocks) that follows the try is checked. If
eri
the type of exception that occurred is listed in a catch block, the exception is passed to the catch
block much as an argument is passed into a method parameter.
Example: e
gin
The following is an array is declared with 2 elements. Then the code tries to access the 3rd
element of the array which throws an exception.
en
}
System.out.println("Out of the block");
}
ww
A try block can be followed by multiple catch blocks. The syntax for multiple catch blocks looks
like the following:
try
{
//Protected code
}catch(ExceptionType1 e1)
{
//Catch block
}catch(ExceptionType2 e2)
n
{
g.i
//Catch block
}catch(ExceptionType3 e3)
{
n
//Catch block
}
eri
The previous statements demonstrate three catch blocks, but you can have any number of them
after a single try. If an exception occurs in the protected code, the exception is thrown to the first
e
catch block in the list. If the data type of the exception thrown matches ExceptionType1, it gets
gin
caught there. If not, the exception passes down to the second catch statement. This continues
until the exception either is caught or falls through all catches, in which case the current method
stops execution and the exception is thrown down to the previous method on the call stack.
en
Example:
try
{
file = new FileInputStream(fileName);
Le
x = (byte) file.read();
}catch(IOException i)
{
w.
i.printStackTrace();
return -1;
}catch(FileNotFoundException f) //Not valid!
ww
{
f.printStackTrace();
return -1;
}
If a method does not handle a checked exception, the method must declare it using the throws
keyword. The throws keyword appears at the end of a method's signature.
You can throw an exception, either a newly instantiated one or an exception that you just caught,
by using the throw keyword. Try to understand the different in throws and throw keywords.
import java.io.*;
public class className
{
public void deposit(double amount) throws RemoteException
{
n
// Method implementation
g.i
throw new RemoteException();
}
//Remainder of class definition
n
}
eri
A method can declare that it throws more than one exception, in which case the exceptions are
declared in a list separated by commas. For example, the following method declares that it
throws a RemoteException and an InsufficientFundsException:
e
gin
import java.io.*;
public class className
{
public void withdraw(double amount) throws RemoteException,
en
InsufficientFundsException
{
// Method implementation
arn
}
//Remainder of class definition
}
Le
The finally keyword is used to create a block of code that follows a try block. A finally block of
w.
Using a finally block allows you to run any cleanup-type statements that you want to execute, no
ww
A finally block appears at the end of the catch blocks and has the following syntax:
try
{
//Protected code
}catch(ExceptionType1 e1)
{
//Catch block
}catch(ExceptionType2 e2)
{
//Catch block
}catch(ExceptionType3 e3)
{
//Catch block
}finally
{
//The finally block always executes.
n
}
g.i
Example:
n
public class ExcepTest{
eri
public static void main(String args[]){
int a[] = new int[2];
try{
e
System.out.println("Access element three :" + a[3]);
gin
}catch(ArrayIndexOutOfBoundsException e){
System.out.println("Exception thrown :" + e);
}
finally{
en
a[0] = 6;
System.out.println("First element value: " +a[0]);
System.out.println("The finally statement is executed");
arn
}
}
}
Le
You can create your own exceptions in Java. Keep the following points in mind when writing
your own exception classes:
n
class MyException extends Exception{
g.i
}
You just need to extend the Exception class to create your own Exception class. These are
n
considered to be checked exceptions. The following InsufficientFundsException class is a user-
defined exception that extends the Exception class, making it a checked exception. An exception
eri
class is like any other class, containing useful fields and methods.
Example:
e
gin
// File Name InsufficientFundsException.java
import java.io.*;
{
private double amount;
public InsufficientFundsException(double amount)
arn
{
this.amount = amount;
}
public double getAmount()
Le
{
return amount;
}
w.
To demonstrate using our user-defined exception, the following CheckingAccount class contains
ww
n
{
g.i
if(amount <= balance)
{
balance -= amount;
n
}
else
eri
{
double needs = amount - balance;
throw new InsufficientFundsException(needs);
} e
gin
}
public double getBalance()
{
return balance;
en
}
public int getNumber()
{
arn
return number;
}
}
Le
The following BankDemo program demonstrates invoking the deposit() and withdraw() methods
of CheckingAccount.
w.
System.out.println("\nWithdrawing $600...");
c.withdraw(600.00);
}catch(InsufficientFundsException e)
{
System.out.println("Sorry, but you are short $"
+ e.getAmount());
e.printStackTrace();
}
}
}
n
g.i
Compile all the above three files and run BankDemo, this would produce the following result:
Depositing $500...
n
Withdrawing $100...
eri
Withdrawing $600...
Sorry, but you are short $200.0
InsufficientFundsException e
gin
at CheckingAccount.withdraw(CheckingAccount.java:25)
at BankDemo.main(BankDemo.java:13)
Common Exceptions:
en
JVM Exceptions: - These are exceptions/errors that are exclusively or logically thrown
by the JVM. Examples : NullPointerException, ArrayIndexOutOfBoundsException,
ClassCastException,
Programmatic exceptions: - These exceptions are thrown explicitly by the application
Le
program using Java. A multithreaded program contains two or more parts that can run
concurrently and each part can handle different task at the same time making optimal use of the
available resources specially when your computer has multiple CPUs.
ww
By definition multitasking is when multiple processes share common processing resources such
as a CPU. Multithreading extends the idea of multitasking into applications where you can
subdivide specific operations within a single application into individual threads. Each of the
threads can run in parallel. The OS divides processing time not only among different
applications, but also among each thread within an application.
Multithreading enables you to write in a way where multiple activities can proceed concurrently
in the same program.
A thread goes through various stages in its life cycle. For example, a thread is born, started, runs,
and then dies. Following diagram shows complete life cycle of a thread.
n
n g.i
e eri
gin
Above-mentioned stages are explained here:
en
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.
Runnable: After a newly born thread is started, the thread becomes runnable. A thread in
arn
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.
w.
Terminated: A runnable thread enters the terminated state when it completes its task or
otherwise terminates.
ww
Thread Priorities:
Every Java thread has a priority that helps the operating system determine the order in which
threads are scheduled.
Java thread priorities are in the range between MIN_PRIORITY (a constant of 1) and
MAX_PRIORITY (a constant of 10). By default, every thread is given priority
NORM_PRIORITY (a constant of 5).
Threads with higher priority are more important to a program and should be allocated processor
time before lower-priority threads. However, thread priorities cannot guarantee the order in
which threads execute and very much platform dependentant.
If your class is intended to be executed as a thread then you can achieve this by implementing
Runnable interface. You will need to follow three basic steps:
Step 1:
n
g.i
As a first step you need to implement a run() method provided by Runnable interface. This
method provides entry point for the thread and you will put you complete business logic inside
this method. Following is simple syntax of run() method:
n
public void run( )
eri
Step 2:
e
At second step you will instantiate a Thread object using the following constructor:
gin
Thread(Runnable threadObj, String threadName);
Where, threadObj is an instance of a class that implements the Runnable interface and
en
Step 3
arn
Once Thread object is created, you can start it by calling start( ) method, which executes a call
to run( ) method. Following is simple syntax of start() method:
Le
void start( );
Example:
w.
n
System.out.println("Thread " + threadName + " exiting.");
g.i
}
n
{
System.out.println("Starting " + threadName );
eri
if (t == null)
{
t = new Thread (this, threadName);
t.start (); e
gin
}
}
}
en
Creating Thread-1
Starting Thread-1
Creating Thread-2
Starting Thread-2
Running Thread-1
Thread: Thread-1, 4
Running Thread-2
Thread: Thread-2, 4
Thread: Thread-1, 3
Thread: Thread-2, 3
Thread: Thread-1, 2
Thread: Thread-2, 2
Thread: Thread-1, 1
Thread: Thread-2, 1
Thread Thread-1 exiting.
Thread Thread-2 exiting.
n
g.i
The second way to create a thread is to create a new class that extends Thread class using the
following two simple steps. This approach provides more flexibility in handling multiple threads
created using available methods in Thread class.
n
Step 1
eri
You will need to override run( ) method available in Thread class. This method provides entry
point for the thread and you will put you complete business logic inside this method. Following
is simple syntax of run() method: e
gin
public void run( )
Step 2
en
Once Thread object is created, you can start it by calling start( ) method, which executes a call
to run( ) method. Following is simple syntax of start() method:
arn
void start( );
Example:
Le
n
public void start ()
g.i
{
System.out.println("Starting " + threadName );
if (t == null)
n
{
t = new Thread (this, threadName);
eri
t.start ();
}
}
e
gin
}
Creating Thread-1
Starting Thread-1
ww
Creating Thread-2
Starting Thread-2
Running Thread-1
Thread: Thread-1, 4
Running Thread-2
Thread: Thread-2, 4
Thread: Thread-1, 3
Thread: Thread-2, 3
Thread: Thread-1, 2
Thread: Thread-2, 2
Thread: Thread-1, 1
Thread: Thread-2, 1
Thread Thread-1 exiting.
Thread Thread-2 exiting.
Thread Methods:
n
SN Methods with Description
g.i
public void start()
1
n
Starts the thread in a separate path of execution, then invokes the run() method on this
eri
Thread object.
public void run()
2 e
If this Thread object was instantiated using a separate Runnable target, the run() method is
gin
invoked on that Runnable
object.
en
name.
public final void setPriority(int priority)
4
Le
Sets the priority of this Thread object. The possible values are between 1 and 10.
public final void setDaemon(boolean on)
5
w.
The current thread invokes this method on a second thread, causing the current thread to
block until the second thread terminates or the specified number of milliseconds passes.
public void interrupt()
7
Interrupts this thread, causing it to continue execution if it was blocked for any reason.
public final boolean isAlive()
8
Returns true if the thread is alive, which is any time after the thread has been started but
The previous methods are invoked on a particular Thread object. The following methods in the
Thread class are static. Invoking one of the static methods performs the operation on the
currently running thread.
n
1
g.i
Causes the currently running thread to yield to any other threads of the same priority that are
waiting to be scheduled.
public static void sleep(long millisec)
n
2
Causes the currently running thread to block for at least the specified number of
eri
milliseconds.
public static boolean holdsLock(Object x)
3
e
Returns true if the current thread holds the lock on the given Object.
gin
public static Thread currentThread()
4
Returns a reference to the currently running thread, which is the thread that invokes this
en
method.
public static void dumpStack()
5
arn
Prints the stack trace for the currently running thread, which is useful when debugging a
multithreaded application.
Le
Example:
The following ThreadClassDemo program demonstrates some of these methods of the Thread
class. Consider a class DisplayMessage which implements Runnable:
w.
while(true)
{
System.out.println(message);
}
}
}
n
// Create a thread to extentd Thread
g.i
public class GuessANumber extends Thread
{
private int number;
n
public GuessANumber(int number)
{
eri
this.number = number;
}
public void run()
{ e
gin
int counter = 0;
int guess = 0;
do
{
en
counter++;
}while(guess != number);
System.out.println("** Correct! " + this.getName()
+ " in " + counter + " guesses.**");
Le
}
}
w.
Following is the main program which makes use of above defined classes:
thread1.start();
System.out.println("Starting thread3...");
n
Thread thread3 = new GuessANumber(27);
g.i
thread3.start();
try
{
n
thread3.join();
}catch(InterruptedException e)
eri
{
System.out.println("Thread interrupted.");
}
e
System.out.println("Starting thread4...");
gin
Thread thread4 = new GuessANumber(75);
thread4.start();
System.out.println("main() is ending...");
en
}
}
arn
This would produce the following result. You can try this example again and again and you
would get different result every time.
Hello
Hello
Hello
ww
Hello
Goodbye
Goodbye
Goodbye
Goodbye
Goodbye
.......
IO Stream
The java.io package contains nearly every class you might ever need to perform input and output
(I/O) in Java. All these streams represent an input source and an output destination. The stream
in the java.io package supports many data such as primitives, Object, localized characters, etc.
A stream can be defined as a sequence of data. The InputStream is used to read data from a
source and the OutputStream is used for writing data to a destination.
Java provides strong but flexible support for I/O related to Files and networks but this tutorial
n
covers very basic functionality related to streams and I/O. We would see most commonly used
g.i
example one by one:
Byte Streams
n
Java byte streams are used to perform input and output of 8-bit bytes. Though there are many
eri
classes related to byte streams but the most frequently used classes are , FileInputStream and
FileOutputStream. Following is an example which makes use of these two classes to copy an
input file into an output file:
e
gin
import java.io.*;
{
FileInputStream in = null;
FileOutputStream out = null;
arn
try {
in = new FileInputStream("input.txt");
out = new FileOutputStream("output.txt");
Le
int c;
while ((c = in.read()) != -1) {
w.
out.write(c);
}
}finally {
ww
if (in != null) {
in.close();
}
if (out != null) {
out.close();
}
}
}
}
As a next step, compile above program and execute it, which will result in creating output.txt file
with the same content as we have in input.txt. So let's put above code in CopyFile.java file and
do the following:
$javac CopyFile.java
$java CopyFile
n
g.i
Character Streams
Java Byte streams are used to perform input and output of 8-bit bytes, where as Java Character
n
streams are used to perform input and output for 16-bit unicode. Though there are many classes
related to character streams but the most frequently used classes are , FileReader and
eri
FileWriter.. Though internally FileReader uses FileInputStream and FileWriter uses
FileOutputStream but here major difference is that FileReader reads two bytes at a time and
FileWriter writes two bytes at a time.
e
gin
We can re-write above example which makes use of these two classes to copy an input file
(having unicode characters) into an output file:
import java.io.*;
en
{
FileReader in = null;
FileWriter out = null;
Le
try {
in = new FileReader("input.txt");
out = new FileWriter("output.txt");
w.
int c;
while ((c = in.read()) != -1) {
ww
out.write(c);
}
}finally {
if (in != null) {
in.close();
}
if (out != null) {
out.close();
}
}
}
}
As a next step, compile above program and execute it, which will result in creating output.txt file
with the same content as we have in input.txt. So let's put above code in CopyFile.java file and
n
do the following:
g.i
$javac CopyFile.java
$java CopyFile
n
Standard Streams
eri
All the programming languages provide support for standard I/O where user's program can take
input from a keyboard and then produce output on the computer screen. If you are aware if C or
e
C++ programming languages, then you must be aware of three standard devices STDIN,
gin
STDOUT and STDERR. Similar way Java provides following three standard streams
Standard Input: This is used to feed the data to user's program and usually a keyboard is
used as standard input stream and represented as System.in.
en
Standard Output: This is used to output the data produced by the user's program and
usually a computer screen is used to standard output stream and represented as
System.out.
arn
Standard Error: This is used to output the error data produced by the user's program
and usually a computer screen is used to standard error stream and represented as
System.err.
Le
Following is a simple program which creates InputStreamReader to read standard input stream
until the user types a "q":
w.
import java.io.*;
try {
cin = new InputStreamReader(System.in);
System.out.println("Enter characters, 'q' to quit.");
char c;
do {
c = (char) cin.read();
System.out.print(c);
} while(c != 'q');
}finally {
if (cin != null) {
cin.close();
}
}
}
}
n
g.i
Let's keep above code in ReadConsole.java file and try to compile and execute it as below. This
program continues reading and outputting same character until we press 'q':
n
$javac ReadConsole.java
$java ReadConsole
eri
Enter characters, 'q' to quit.
1
1
e e
gin
e
q
q
en
As described earlier, A stream can be defined as a sequence of data. The InputStream is used to
arn
read data from a source and the OutputStream is used for writing data to a destination.
The two important streams are FileInputStream and FileOutputStream, which would be
discussed in this tutorial:
FileInputStream:
This stream is used for reading data from the files. Objects can be created using the keyword new
and there are several types of constructors available.
Following constructor takes a file name as a string to create an input stream object to read the
file.:
n
g.i
InputStream f = new FileInputStream("C:/java/hello");
Following constructor takes a file object to create an input stream object to read the file. First we
n
create a file object using File() method as follows:
eri
File f = new File("C:/java/hello");
InputStream f = new FileInputStream(f);
e
Once you have InputStream object in hand, then there is a list of helper methods which can be
gin
used to read to stream or to do other operations on the stream.
1
This method closes the file output stream. Releases any system resources associated with the
arn
2 This method cleans up the connection to the file. Ensures that the close method of this file
Le
output stream is called when there are no more references to this stream. Throws an
IOException.
public int read(int r)throws IOException{}
w.
3
This method reads the specified byte of data from the InputStream. Returns an int. Returns
the next byte of data and -1 will be returned if it's end of file.
ww
There are other important input streams available, for more detail you can refer to the following
links:
ByteArrayInputStream
DataInputStream
FileOutputStream:
FileOutputStream is used to create a file and write data into it. The stream would create a file, if
it doesn't already exist, before opening it for output.
n
g.i
Here are two constructors which can be used to create a FileOutputStream object.
Following constructor takes a file name as a string to create an input stream object to write the
n
file:
eri
OutputStream f = new FileOutputStream("C:/java/hello")
Following constructor takes a file object to create an output stream object to write the file. First,
e
we create a file object using File() method as follows:
gin
File f = new File("C:/java/hello");
OutputStream f = new FileOutputStream(f);
en
Once you have OutputStream object in hand, then there is a list of helper methods, which can be
used to write to stream or to do other operations on the stream.
arn
This method closes the file output stream. Releases any system resources associated with the
file. Throws an IOException
protected void finalize()throws IOException {}
w.
2 This method cleans up the connection to the file. Ensures that the close method of this file
output stream is called when there are no more references to this stream. Throws an
ww
IOException.
public void write(int w)throws IOException{}
3
This methods writes the specified byte to the output stream.
public void write(byte[] w)
4
Writes w.length bytes from the mentioned byte array to the OutputStream.
There are other important output streams available, for more detail you can refer to the following
links:
ByteArrayOutputStream
DataOutputStream
Example:
n
import java.io.*;
g.i
public class fileStreamTest{
n
public static void main(String args[]){
eri
try{
byte bWrite [] = {11,21,3,40,5};
OutputStream os = new FileOutputStream("test.txt");
for(int x=0; x < bWrite.length ; x++){ e
gin
os.write( bWrite[x] ); // writes the bytes
}
os.close();
en
}catch(IOException e){
System.out.print("Exception");
}
w.
}
}
ww
The above code would create file test.txt and would write given numbers in binary format. Same
would be output on the stdout screen.
There are several other classes that we would be going through to get to know the basics of File
Navigation and I/O.
File Class
FileReader Class
FileWriter Class
Directories in Java:
A directory is a File which can contains a list of other files and directories. You use File object to
create directories, to list down files available in a directory. For complete detail check a list of all
the methods which you can call on File object and what are related to directories.
Creating Directories:
n
g.i
There are two useful File utility methods, which can be used to create directories:
The mkdir( ) method creates a directory, returning true on success and false on failure.
n
Failure indicates that the path specified in the File object already exists, or that the
directory cannot be created because the entire path does not exist yet.
eri
The mkdirs() method creates both a directory and all the parents of the directory.
d.mkdirs();
}
}
Le
Note: Java automatically takes care of path separators on UNIX and Windows as per
w.
conventions. If you use a forward slash (/) on a Windows version of Java, the path will still
resolve correctly.
ww
Listing Directories:
You can use list( ) method provided by File object to list down all the files and directories
available in a directory as follows:
import java.io.File;
try{
// create new file object
file = new File("/tmp");
n
g.i
// for each name in the path array
for(String path:paths)
{
n
// prints filename and directory name
System.out.println(path);
eri
}
}catch(Exception e){
// if any error occurs
e.printStackTrace(); e
gin
}
}
}
en
This would produce following result based on the directories and files available in your /tmp
directory:
arn
test1.txt
test2.txt
ReadDir.java
ReadDir.class
Le
Applet
w.
An applet is a Java program that runs in a Web browser. An applet can be a fully functional Java
application because it has the entire Java API at its disposal.
ww
There are some important differences between an applet and a standalone Java application,
including the following:
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.
n
Life Cycle of an Applet:
g.i
Four methods in the Applet class give you the framework on which you build any serious applet:
n
init: This method is intended for whatever initialization is needed for your applet. It is
called after the param tags inside the applet tag have been processed.
eri
start: This method is automatically called after the browser calls the init method. It is
also called whenever the user returns to the page containing the applet after having gone
off to other pages.
e
stop: This method is automatically called when the user moves off the page on which the
gin
applet sits. It can, therefore, be called repeatedly in the same applet.
destroy: This method is only called when the browser shuts down normally. Because
applets are meant to live on an HTML page, you should not normally leave resources
behind after a user leaves the page that contains the applet.
en
paint: Invoked immediately after the start() method, and also any time the applet needs
to repaint itself in the browser. The paint() method is actually inherited from the java.awt.
arn
import java.applet.*;
import java.awt.*;
w.
{
g.drawString ("Hello World", 25, 50);
}
}
These import statements bring the classes into the scope of our applet class:
java.applet.Applet.
java.awt.Graphics.
Without those import statements, the Java compiler would not recognize the classes Applet and
Graphics, which the applet class refers to.
Every applet is an extension of the java.applet.Applet class. The base Applet class provides
methods that a derived Applet class may call to obtain information and services from the browser
context.
n
g.i
Get applet parameters
Get the network location of the HTML file that contains the applet
Get the network location of the applet class directory
n
Print a status message in the browser
Fetch an image
eri
Fetch an audio clip
Play an audio clip
Resize the applet
e
gin
Additionally, the Applet class provides an interface by which the viewer or browser obtains
information about the applet and controls the applet's execution. The viewer may:
request information about the author, version and copyright of the applet
en
The Applet class provides default implementations of each of these methods. Those
Le
The "Hello, World" applet is complete as it stands. The only method overridden is the paint
w.
method.
Invoking an Applet:
ww
An applet may be invoked by embedding directives in an HTML file and viewing the file
through an applet viewer or Java-enabled browser.
The <applet> tag is the basis for embedding an applet in an HTML file. Below is an example that
invokes the "Hello, World" applet:
<html>
<title>The Hello, World Applet</title>
<hr>
<applet code="HelloWorldApplet.class" width="320" height="120">
If your browser was Java-enabled, a "Hello, World"
message would appear here.
</applet>
<hr>
</html>
Based on the above examples, here is the live applet example: Applet Example.
n
Note: You can refer to HTML Applet Tag to understand more about calling applet from HTML.
g.i
The code attribute of the <applet> tag is required. It specifies the Applet class to run. Width and
height are also required to specify the initial size of the panel in which an applet runs. The applet
n
directive must be closed with a </applet> tag.
eri
If an applet takes parameters, values may be passed for the parameters by adding <param> tags
between <applet> and </applet>. The browser ignores text and other tags between the applet
tags.
e
gin
Non-Java-enabled browsers do not process <applet> and </applet>. Therefore, anything that
appears between the tags, not related to the applet, is visible in non-Java-enabled browsers.
The viewer or browser looks for the compiled Java code at the location of the document. To
en
specify otherwise, use the codebase attribute of the <applet> tag as shown:
<applet codebase="http://amrood.com/applets"
arn
If an applet resides in a package other than the default, the holding package must be specified in
the code attribute using the period character (.) to separate package/class components. For
Le
example:
<applet code="mypackage.subpackage.TestApplet.class"
w.
width="320" height="120">
The following example demonstrates how to make an applet respond to setup parameters
specified in the document. This applet displays a checkerboard pattern of black and a second
color.
The second color and the size of each square may be specified as parameters to the applet within
the document.
CheckerApplet gets its parameters in the init() method. It may also get its parameters in the
paint() method. However, getting the values and saving the settings once at the start of the
applet, instead of at every refresh, is convenient and efficient.
The applet viewer or browser calls the init() method of each applet it runs. The viewer calls init()
once, immediately after loading the applet. (Applet.init() is implemented to do nothing.)
Override the default implementation to insert custom initialization code.
The Applet.getParameter() method fetches a parameter given the parameter's name (the value of
a parameter is always a string). If the value is numeric or other non-character data, the string
n
must be parsed.
g.i
The following is a skeleton of CheckerApplet.java:
n
import java.applet.*;
import java.awt.*;
eri
public class CheckerApplet extends Applet
{
int squareSize = 50;// initialized to default size
public void init () {} e
gin
private void parseSquareSize (String param) {}
private Color parseColor (String param) {}
public void paint (Graphics g) {}
}
en
setForeground (fg);
}
private void parseSquareSize (String param)
ww
{
if (param == null) return;
try {
squareSize = Integer.parseInt (param);
}
catch (Exception e) {
// Let default value remain
}
}
The applet calls parseSquareSize() to parse the squareSize parameter. parseSquareSize() calls the
library method Integer.parseInt(), which parses a string and returns an integer. Integer.parseInt()
throws an exception whenever its argument is invalid.
Therefore, parseSquareSize() catches exceptions, rather than allowing the applet to fail on bad
input.
The applet calls parseColor() to parse the color parameter into a Color value. parseColor() does a
series of string comparisons to match the parameter value to the name of a predefined color. You
need to implement these methods to make this applet works.
n
g.i
Specifying Applet Parameters:
The following is an example of an HTML file with a CheckerApplet embedded in it. The HTML
n
file specifies both parameters to the applet by means of the <param> tag.
eri
<html>
<title>Checkerboard Applet</title>
<hr>
e
<applet code="CheckerApplet.class" width="480" height="320">
gin
<param name="color" value="blue">
<param name="squaresize" value="30">
</applet>
<hr>
en
</html>
It is easy to convert a graphical Java application (that is, an application that uses the AWT and
Le
that you can start with the java program launcher) into an applet that you can embed in a web
page.
w.
Make an HTML page with the appropriate tag to load the applet code.
ww
Supply a subclass of the JApplet class. Make this class public. Otherwise, the applet
cannot be loaded.
Eliminate the main method in the application. Do not construct a frame window for the
application. Your application will be displayed inside the browser.
Move any initialization code from the frame window constructor to the init method of the
applet. You don't need to explicitly construct the applet object.the browser instantiates it
for you and calls the init method.
Remove the call to setSize; for applets, sizing is done with the width and height
parameters in the HTML file.
Event Handling:
Applets inherit a group of event-handling methods from the Container class. The Container class
defines several methods, such as processKeyEvent and processMouseEvent, for handling
n
particular types of events, and then one catch-all method called processEvent.
g.i
In order to react an event, an applet must override the appropriate event-specific method.
n
import java.awt.event.MouseListener;
import java.awt.event.MouseEvent;
eri
import java.applet.Applet;
import java.awt.Graphics;
e
public class ExampleEventHandling extends Applet
gin
implements MouseListener {
StringBuffer strBuffer;
en
n
}
g.i
public void mouseEntered(MouseEvent event) {
n
}
public void mouseExited(MouseEvent event) {
eri
}
public void mousePressed(MouseEvent event) {
}
e
public void mouseReleased(MouseEvent event) {
gin
}
}
}
arn
<html>
<title>Event Handling</title>
Le
<hr>
<applet code="ExampleEventHandling.class"
width="300" height="300">
w.
</applet>
<hr>
</html>
ww
Initially, the applet will display "initializing the applet. Starting the applet." Then once you click
inside the rectangle "mouse clicked" will be displayed as well.
Based on the above examples, here is the live applet example: Applet Example.
Displaying Images:
An applet can display images of the format GIF, JPEG, BMP, and others. To display an image
within the applet, you use the drawImage() method found in the java.awt.Graphics class.
import java.applet.*;
import java.awt.*;
import java.net.*;
n
public class ImageDemo extends Applet
g.i
{
private Image image;
private AppletContext context;
n
public void init()
{
eri
context = this.getAppletContext();
String imageURL = this.getParameter("image");
if(imageURL == null)
{ e
gin
imageURL = "java.jpg";
}
try
{
en
{
e.printStackTrace();
// Display in browser status bar
context.showStatus("Could not load image!");
Le
}
}
public void paint(Graphics g)
w.
{
context.showStatus("Displaying image");
g.drawImage(image, 0, 0, 200, 84, null);
ww
<html>
<title>The ImageDemo applet</title>
<hr>
Based on the above examples, here is the live applet example: Applet Example.
Playing Audio:
n
An applet can play an audio file represented by the AudioClip interface in the java.applet
g.i
package. The AudioClip interface has three methods, including:
public void play(): Plays the audio clip one time, from the beginning.
n
public void loop(): Causes the audio clip to replay continually.
public void stop(): Stops playing the audio clip.
eri
To obtain an AudioClip object, you must invoke the getAudioClip() method of the Applet class.
The getAudioClip() method returns immediately, whether or not the URL resolves to an actual
e
audio file. The audio file is not downloaded until an attempt is made to play the audio clip.
gin
Following is the example showing all the steps to play an audio:
import java.applet.*;
en
import java.awt.*;
import java.net.*;
public class AudioDemo extends Applet
arn
{
private AudioClip clip;
private AppletContext context;
public void init()
Le
{
context = this.getAppletContext();
String audioURL = this.getParameter("audio");
w.
if(audioURL == null)
{
audioURL = "default.au";
ww
}
try
{
URL url = new URL(this.getDocumentBase(), audioURL);
clip = context.getAudioClip(url);
}catch(MalformedURLException e)
{
e.printStackTrace();
context.showStatus("Could not load audio file!");
}
}
public void start()
{
if(clip != null)
{
clip.loop();
}
}
public void stop()
n
{
g.i
if(clip != null)
{
clip.stop();
n
}
}
eri
}
</html>
Le
w.
ww
Unit –II
You can program for the Web, using your skills as a Visual Basic programmer, no matter what your level of
experience with Internet technology. If you are new to the Internet or unfamiliar with its technology, Visual
Basic allows you to quickly and easily produce functional applications. If you are more experienced with
Internet technology, you can work at a more advanced level.
n
From one perspective, Internet technology simply provides another area for your development efforts. When
g.i
you deploy Internet applications on the Web, you may go about it differently — incorporating HTML pages
with your Visual Basic code, providing security features, and so on — but you're still calling methods, setting
properties, and handling events. In this way, all of your knowledge as a Visual Basic developer can be carried
n
into the Internet arena.
eri
From another perspective, applying Internet technology enables you to extend your development skills in
exciting new ways. For example, writing Visual Basic code that manipulates HTML pages allows you to
decrease deployment costs, reduce client maintenance problems, and reach the broad audience of the Internet.
e
gin
Internet Clients and Servers
A common way to think about Internet development is in terms of client/server relationships. In this case, the
client is the browser, and the server is the Web server. Most interactions on the Internet or an intranet can be
en
thought of in terms of requests and responses. The browser makes a request to the Web server (usually to
display a page the user wants to see) and the Web server returns a response (usually an HTML page, an
element, or an image) to the browser.
arn
The Internet encompasses two categories: the Internet and the intranet. The Internet is a global, distributed
network of computers operating on a protocol called TCP/IP. An intranet is also a network of computers
operating on the TCP/IP protocol, but it is not global. Generally, intranets are restricted to a particular set of
w.
users and are not accessible by the outside world. For example, many corporations use a corporate intranet to
provide information to their employees, and run another Internet site for external users. Users within the
company can access both the intranet sites and the Internet, but users outside the company can access only the
ww
HTML Pages
HTML (HyperText Markup Language) is a language that allows you to display documents in a Web browser.
You use HTML to create .htm files that are displayed in a browser. When you create an Internet application in
Visual Basic, your user interface is usually made up of HTML pages rather than forms. In many ways, an .htm
file (which allows you to display HTML pages) is similar to a Visual Basic .frm file (which allows you to
display a Visual Basic form).
Note While the user interface is generally made up of HTML pages, it can also contain a mix of Visual Basic
forms and HTML pages.
An .htm file is a text document that contains a series of tags that tell the browser how to display the file. These
HTML tags supply information about the page's structure, appearance, and content. The following figure shows
the relationship between page in the browser and its HTML tags:
n
n g.i
e eri
gin
en
arn
Le
w.
In addition to describing the structural relationships among page elements, some HTML tags also contain
ww
attributes. Attributes provide details about a particular tag. For example, the tag that inserts an image onto a
page contains an attribute that specifies the name of the file to insert. The tag is shown below.
You use the concepts of object-oriented programming in your Visual Basic Internet applications just as you do
in forms-based Visual Basic applications. In Visual Basic Internet applications, you use Internet-related object
models to access and manipulate information and controls on your HTML pages.
There are two types of Visual Basic Internet applications: IIS applications and DHTML applications. In IIS
applications, you make use of the Active Server Pages (ASP) object model to retrieve information from the
user, send information to the browser, and maintain information about the current session. In DHTML
applications, you use the Dynamic HTML (DHTML) object model to manipulate the elements on an HTML
page.
n
The important point to remember is that you access the information on your HTML pages through objects,
regardless of whether the objects themselves are ASP or DHTML. The object models are explained in much
g.i
greater detail in the chapters describing each type of application.
For More Information See "A History of Development on the Internet" for more information on the
n
differences between IIS and DHTML applications. See the "Developing DHTML Applications" chapter for
eri
more information on using Dynamic HTML objects. See the "Developing IIS Applications with Webclasses"
chapter for more information on using ASP objects. See the MSDN™ Web site at http://msdn.microsoft.com/
for details on using HTML and Internet technologies.
Web page e
gin
A document displayable in a web browser
Web site
en
A collection of webpages
Web Server
arn
Search Engine
Le
HTML Basics
Welcome to HTML Basics. This workshop leads you through the basics of Hyper Text Markup Language
n
(HTML). HTML is the building block for web pages. You will learn to use HTML to author an HTML page
g.i
to display in a web browser.
n
Objectives:
eri
By the end of this workshop, you will be able to:
▪ Use a text editor to author an HTML document.
▪ Be able to use basic tags to denote paragraphs, emphasis or special type.
▪ Create hyperlinks to other documents. e
gin
▪ Create an email link.
▪ Add images to your document.
▪ Use a table for layout.
▪ Apply colors to your HTML document.
en
Prerequisites:
arn
You will need a text editor, such as Notepad and an Internet browser, such as Internet Explorer or Netscape.
Q: What is Notepad and where do I get it?
A: Notepad is the default Windows text editor. On most Windows systems, click your Start button and
Le
select Ignore rich text commands in HTML files. This is very important because if you don't do this
HTML codes probably won't work.
ww
One thing you should avoid using is a word processor (like Microsoft Word) for authoring your HTML
documents.
HTML is a format that tells a computer how to display a web page. The documents themselves are plain text
files with special "tags" or codes that a web browser uses to interpret and display information on your
computer screen.
CS6501 Internet Programming – Unit-II Page 4
n
g.i
<html>
n
<head>
<title>My First Webpage</title>
eri
</head>
<body>
This is my first homepage. <b>This text is bold</b>
</body>
</html> e
gin
Save the file as mypage.html. Start your Internet browser. Select Open (or Open Page) in the File menu of
your browser. A dialog box will appear. Select Browse (or Choose File) and locate the html file you just
created - mypage.html - select it and click Open.
en
When you save an HTML file, you can use either the .htm or the .html extension. The .htm extension comes
from the past when some of the commonly used software only allowed three letter extensions. It is perfectly
safe to use either .html or .htm, but be consistent. mypage.htm and mypage.html are treated as different files
Le
by the browser.
w.
A good way to learn HTML is to look at how other people have coded their html pages. To find out, simply
ww
click on the View option in your browsers toolbar and select Source or Page Source. This will open a
window that shows you the actual HTML of the page. Go ahead and view the source html for this page.
HTML Tags
▪ HTML tags are not case sensitive, <b> means the same as <B>
In HTML there are both logical tags and physical tags. Logical tags are designed to describe (to the browser)
the enclosed text's meaning. An example of a logical tag is the <strong> </strong> tag. By placing text in
between these tags you are telling the browser that the text has some greater importance. By default all
browsers make the text appear bold when in between the <strong>and
</strong>tags.
Physical tags on the other hand provide specific instructions on how to display the text they enclose. Examples
n
of physical tags include:
g.i
▪ <b>: Makes the text bold.
▪ <big>: Makes the text usually one size bigger than what's around it.
n
▪ <i>: Makes text italic.
Physical tags were invented to add style to HTML pages because style sheets were not around, though the
eri
original intention of HTML was to not have physical tags. Rather than use physical tags to style your
HTML pages, you should use style sheets.
HTML Elements e
gin
Remember the HTML example from the previous page:
<html>
<head>
en
The purpose of the <b>tag is to define an HTML element that should be displayed as bold. This is
<body>
This is my first homepage. <b>This text is bold</b>
</body>
This HTML element starts with the start tag <body>, and ends with the end tag </body>. The purpose of the
<body> tag is to define the HTML element that contains the body of the HTML document.
Nested Tags
You may have noticed in the example above, the <body>tag also contains other tags, like the <b>tab. When
you enclose an element in with multiple tags, the last tag opened should be the first tag closed. For example:
n
<p><b><em>This is the proper way to close nested tags. </em></b></p>
n g.i
Note: It doesn't matter which tag is first, but they must be closed in the proper order.
eri
Why Use Lowercase Tags?
e
gin
You may notice we've used lowercase tags even though I said that HTML tags are not case sensitive.
<B>means the same as <b>. The World Wide Web Consortium (W3C), the group responsible for
developing web standards, recommends lowercase tags in their HTML 4 recommendation, and XHTML
(the next generation HTML) requires lowercase tags.
en
Tag Attributes
arn
Tags can have attributes. Attributes can provide additional information about the HTML elements on your
page. The <tag> tells the browser to do something, while the attribute tells the browser how to do it. For
instance, if we add the bgcolor attribute, we can tell the browser that the background color of your page
Le
name="value". Attributes are always added to the start tag of an HTML element and the value is
surrounded by quotes.
ww
The most important tags in HTML are tags that define headings, paragraphs and line breaks.
Tag Description
<html> Defines an HTML document
Headings
n
Headings are defined with the <h1>to <h6>tags. <h1>defines the largest heading while <h6>defines the
smallest.
g.i
<h1>This is a heading</h1>
<h2>This is a heading</h2>
<h3>This is a heading</h3>
n
<h4>This is a heading</h4>
eri
<h5>This is a heading</h5>
<h6> This is a heading</h6>
HTML automatically adds an extra blank line before and after a heading. A useful heading attribute is align.
<h5 align="left">I can align headings </h5>
e
gin
<h5 align="center">This is a centered heading </h5>
<h5 align="right">This is a heading aligned to the right </h5>
en
Paragraphs
Paragraphs are defined with the <p>tag. Think of a paragraph as a block of text. You can use the align
arn
Important: You must indicate paragraphs with <p> elements. A browser ignores any
indentations or blank lines in the source text. Without <p> elements, the document becomes
w.
one large paragraph. HTML automatically adds an extra blank line before and after a paragraph.
Line Breaks
ww
The <br> tag is used when you want to start a new line, but don't want to start a new paragraph. The
<br>tag forces a line break wherever you place it. It is similar to single spacing in a document.
Horizontal Rule
The <hr>element is used for horizontal rules that act as dividers between sections, like this:
The horizontal rule does not have a closing tag. It takes attributes such as align and width. For instance:
n
g.i
This Code Would Display
<hr width="50%" align="center">
n
eri
Comments in HTML
e
The comment tag is used to insert a comment in the HTML source code. A comment can be placed
gin
anywhere in the document and the browser will ignore everything inside the brackets. You can use
comments to write notes to yourself, or write a helpful message to someone looking at your source code.
en
Notice you don't see the text between the tags <!-- and -->. If you look at the source code, you would see the
Le
comment. To view the source code for this page, in your browser window, select View and then select
Source.
w.
Note: You need an exclamation point after the opening bracket <!-- but not before the closing
bracket -->.
ww
HTML automatically adds an extra blank line before and after some elements, like before and after a
paragraph, and before and after a heading. If you want to insert blank lines into your document, use the
<br>tag.
As mentioned before, there are logical styles that describe what the text should be and physical styles which
actually provide physical formatting. It is recommended to use the logical tags and use style sheets to style
the text in those tags.
Tag Description
<abbr> Defines an abbreviation Tag Description
<acronym> Defines an acronym <b> Defines bold text
<address> Defines an address element <big> Defines big text
n
<cite> Defines a citation <i> Defines italic text
<small> Defines small text
g.i
<code> Defines computer codetext
<blockquote> Defines a long quotation <sup> Defines superscripted text
<del> Defines text <sub> Defines subscripted text
n
<dfn> Defines a definition term <tt> Defines teletype text
<em> Defines emphasized text <u> Deprecated. Use styles instead
eri
<ins> Defines inserted text
<kbd> Defines keyboard text
<pre> Defines preformatted text
<q> Defines a short quotation e
gin
<samp> Defines sample computer code
<strong> Defines strong text
<var> Defines a variable
en
Character tags like <strong> and <em>produce the same physical display as <b> and <i>but are more
uniformly supported across different browsers.
arn
Some characters have a special meaning in HTML, like the less than sign (<) that defines the start of an
HTML tag. If we want the browser to actually display these characters we must insert character entities in
place of the actual characters themselves.
w.
semicolon (;). The & means we are beginning a special character, the ; means ending a special character
and the letters in between are sort of an abbreviation for what it's for. To display a less than sign in an
HTML document we must write: < or < The advantage of using a name instead of a number is that
a name is easier to remember. The disadvantage is that not all browsers support the newest entity names,
while the support for entity numbers is very good in almost all browsers.
Non-breaking Space
n
The most common character entity in HTML is the non-breaking space . Normally HTML will
g.i
truncate spaces in your text. If you add 10 spaces in your text, HTML will remove 9 of them. To add spaces
to your text, use the character entity.
n
eri
This Code Would Display
<p> This code would appear This code would appear as this.
as this.</p>
e
gin
This Code Would Display
<p> This code would This code would appear with three extra
appear with three extra spaces.</p> spaces.
en
HTML Fonts
arn
The <font>tag in HTML is deprecated. The World Wide Web Consortium (W3C) has removed the
<font>tag from its recommendations. In future versions of HTML, style sheets (CSS) will be used to define
the layout and display properties of HTML elements. The <font>Tag Should NOT be used.
Le
HTML Backgrounds
w.
Backgrounds
The <body> tag has two attributes where you can specify backgrounds. The background can be a color or an
ww
image.
Bgcolor
The bgcolor attribute specifies a background-color for an HTML page. The value of this attribute can be a
hexadecimal number, an RGB value, or a color name:
<body bgcolor="#000000">
<body bgcolor="rgb(0,0,0)">
<body bgcolor="black">
Background
The background attribute can also specify a background-image for an HTML page. The value of this
attribute is the URL of the image you want to use. If the image is smaller than the browser window, the
image will repeat itself until it fills the entire browser window.
<body background="clouds.gif">
n
<bodybackground="http://profdevtrain.austincc.edu/html/graphics/clouds.gif">
g.i
The URL can be relative (as in the first line above) or absolute (as in the second line above). If
you want to use a background image, you should keep in mind:
n
eri
▪ Will the background image increase the loading time too much?
▪ Will the background image look good with other images on the page?
▪ Will the background image look good with the text colors on the page?
▪
▪ e
Will the background image look good when it is repeated on the page?
Will the background image take away the focus from the text?
gin
en
arn
Le
w.
ww
<html>
<head>
<title>My First Webpage</title>
</head>
<body background="http://profdevtrain.austincc.edu/html/graphics/clouds.gif" bgcolor="#EDDD9E">
<h1 align="center">My First Webpage</h1>
<p>Welcome to my <strong>first</strong> webpage. I am writing this page using a text editor and plain
old html.</p>
<p>By learning html, I'll be able to create webpages like a <del>beginner</del> pro....<br>
which I am of course.</p>
</body>
n
</html>
g.i
Save your page as mypage3.html and view it in your browser. To view how the page should look, visit
this web page: http://profdevtrain.austincc.edu/html/mypage3.html
n
eri
Notice we gave our page a background color as well as a background image. If for some reason the web
page is unable to find the picture, it will display our background color.
HTML Colors e
gin
Color Values
en
Colors are defined using a hexadecimal notation for the combination of red, green, and blue color values
(RGB). The lowest value that can be given to one light source is 0 (hex #00). The highest value is 255 (hex
#FF). This table shows the result of combining red, green, and blue:
arn
#FF0000 rgb(255,0,0)
#00FF00 rgb(0,255,0)
#0000FF rgb(0,0,255)
w.
#FFFF00 rgb(255,255,0)
#00FFFF rgb(0,255,255)
#FF00FF rgb(255,0,255)
ww
#C0C0C0 rgb(192,192,192)
#FFFFFF rgb(255,255,255)
Color Names
A collection of color names is supported by most browsers. To view a table of color names that are
supported by most browsers visit this web page: http://profdevtrain.austincc.edu/html/color_names.htm
Note: Only 16 color names are supported by the W3C HTML 4.0 standard (aqua, black, blue,
fuchsia, gray, green, lime, maroon, navy, olive, purple, red, silver, teal, white, and yellow). For
all other colors you should use the Color HEX value.
n
#F0F8FF AliceBlue
g.i
#FAEBD7 AntiqueWhite
#7FFFD4 Aquamarine
#000000 Black
n
#0000FF Blue
#8A2BE2 BlueViolet
eri
#A52A2A Brown
color palette. To view the 216 Cross Platform Colors visit this web page:
http://profdevtrain.austincc.edu/html/216.html
arn
The combination of Red, Green and Blue values from 0 to 255 gives a total of more than 16 million different
colors to play with (256 x 256 x 256). Most modern monitors are capable of displaying at least 16,384
different colors. To assist you in using color schemes, check out
http://wellstyled.com/tools/colorscheme2/index-en.html. This site lets you test different color schemes for
w.
HTML Lists
HTML provides a simple way to show unordered lists (bullet lists) or ordered lists (numbered lists).
Unordered Lists
An unordered list is a list of items marked with bullets (typically small black circles). An unordered list starts
with the <ul> tag. Each list item starts with the <li> tag.
Ordered Lists
An ordered list is also a list of items. The list items are marked with numbers. An ordered list starts with the
<ol> tag. Each list item starts with the <li> tag.
n
g.i
This Code Would Display
n
<ol>
<li>Coffee</li> 1. Coffee
eri
<li>Milk</li> 2. Milk
</ol>
e
Inside a list item you can put paragraphs, line breaks, images, links, other lists, etc.
gin
Definition Lists
en
Definition lists consist of two parts: a term and a description. To mark up a definition list, you need three
HTML elements; a container <dl>, a definition term <dt>, and a definition description <dd>.
arn
<dd>Style sheets are used to provide Style sheets are used to provide
presentational suggestions for documents presentational suggestions for
marked up in HTML. documents marked up in HTML.
w.
</dd>
</dl>
Inside a definition-list definition (the <dd>tag) you can put paragraphs, line breaks, images, links, other lists,
etc
ww
<html>
<head>
<title>My First Webpage</title>
</head>
<body bgcolor="#EDDD9E">
<h1 align="center">My First Webpage</h1>
<p>Welcome to my <strong>first</strong> webpage. I am writing this page using a text editor and plain old
html.</p>
<p>By learning html, I'll be able to create web pages like a pro....<br> which I am of
course.</p>
HTML Links
n
g.i
HTML uses the <a> anchor tag to create a link to another document or web page.
n
An anchor can point to any resource on the Web: an HTML page, an image, a sound file, a movie, etc. The
eri
syntax of creating an anchor:
<a href="url">Text to be displayed</a>
The <a> tag is used to create an anchor to link from, the href attribute is used to tell the address of the
e
document or page we are linking to, and the words between the open and close of the anchor tag will be
gin
displayed as a hyperlink.
With the target attribute, you can define where the linked document will be opened. By default, the link will
Le
open in the current window. The code below will open the document in a new browser window:
Email Links
To create an email link, you will use mailto: plus your email address. Here is a link to ACC's Help Desk:
<a href="mailto:helpdesk@austincc.edu">Email Help Desk</a>
To add a subject for the email message, you would add ?subject= after the email address. For example:
<a href="mailto:helpdesk@austincc.edu?subject=Email Assistance">Email HelpDesk</a>
The name attribute is used to create a named anchor. When using named anchors we can create links that
can jump directly to a specific section on a page, instead of letting the user scroll around to find what he/she
is looking for. Unlike an anchor that uses href, a named anchor doesn't change the appearance of the text
(unless you set styles for that anchor) or indicate in any way that there is anything special about the text.
Below is the syntax of a named anchor:
<a name="top">Text to be displayed</a>
To link directly to the top section, add a # sign and the name of the anchor to the end of a URL, like this:
This Code Would Display
<a href="http://profdevtrain.austincc.edu/html
/10links.html#top">Back to top of page </a> Back to top of page
n
A hyperlink to the top of the page from within the file
10links.html will look like this:
g.i
<a href="#top">Back to top of page </a> Back to top of page
n
eri
Note: Always add a trailing slash to subfolder references. If you link like this:
href="http://profdevtrain.austincc.edu/html", you will generate two HTTP requests to the
server, because the server will add a slash to the address and create a new request like this:
e
href="http://profdevtrain.austincc.edu/html/"
gin
en
Named anchors are often used to create "table of contents" at the beginning of a large document. Each
chapter within the document is given a named anchor, and links to each of these anchors are put at the top
of the document. If a browser cannot find a named anchor that has been specified, it goes to the top of the
arn
HTML Images
Le
The <img>tag is empty, which means that it contains attributes only and it has no closing tag. To display
an image on a page, you need to use the src attribute. Src stands for "source". The value of the src attribute
is the URL of the image you want to display on your page. The syntax of defining an image:
ww
<img src="graphics/chef.gif">
Not only does the source attribute specify what image to use, but where the image is located. The
above image, graphics/chef.gif, means that the browser will look for the image name chef.gif in a
graphics folder in the same folder as the html document itself.
n
folder down from the html document that called for
it. This can go on down as many layers as
g.i
necessary.
n
src="../chef.gif"means that the image is in one
folder up from the html document that called for it.
e eri
gin
src="../../chef.gif"means that the image is two
folders up from the html document that called for it.
en
directory.
Le
The browser puts the image where the image tag occurs in the document. If you put an image tag between
two paragraphs, the browser shows the first paragraph, then the image, and then the second paragraph.
The alt attribute is used to define an alternate text for an image. The value of the alt attribute is
author-defined text:
The alt attribute tells the reader what he or she is missing on a page if the browser can't load images. The
browser will then display the alternate text instead of the image. It is a good practice to include the alt
attribute for each image on a page, to improve the display and usefulness of your document for people who
have text-only browsers or use screen readers.
n
g.i
Image Dimensions
n
When you have an image, the browser usually figures out how big the image is all by itself. If you put in
eri
the image dimensions in pixels however, the browser simply reserves a space for the image, then loads the
rest of the page. Once the entire page is loads it can go back and fill in the images. Without dimensions,
when it runs into an image, the browser has to pause loading the page, load the image, then continue
loading the page. The chef image would then be:
e
<img src="graphics/chef.gif" width="130" height="101" alt="Smiling HappyChef">
gin
Open the file mypage2.html in your text editor and add code highlighted in bold:
<html>
en
<head>
<title>My First Webpage</title>
</head>
arn
<body>
<h1 align="center">My First Web page</h1>
<p>Welcome to my first webpage. I am writing this page using a text editor and plain old html.</p>
<p>By learning html, I'll be able to create web pages like a pro....<br> which I
Le
am of course.</p>
<!-- Who would have guessed how easy this would be :) -->
<p><img src="graphics/chef.gif" width="130" height="101" alt="Smiling Happy Chef"
align="center"></p>
w.
</html>
Tables
Tables are defined with the <table>tag. A table is divided into rows (with the <tr>tag), and each row is
divided into data cells (with the <td> tag). The letters td stands for table data, which is the content of a data
cell. A data cell can contain text, images, lists, paragraphs, forms, horizontal rules, tables, etc.
This Code Would Display
<table>
<tr>
<td>row 1, cell 1</td>
<td>row 1, cell 2</td>
</tr> row 1, cell 1 row 1, cell 2
<tr> row 2, cell 1 row 2, cell 2
<td>row 2, cell 1</td>
<td>row 2, cell 2</td>
</tr>
</table>
Tables and the Border Attribute
n
g.i
To display a table with borders, you will use the border attribute.
n
This Code Would Display
eri
<table border="1">
<tr>
<td>Row 1, cell 1</td> row 1, cell 1 row 1, cell 2
<td>Row 1, cell 2</td>
</tr> e
gin
</table>
and....
en
<tr>
<td>Row 1, cell 1</td> row 1, cell 1 row 1, cell 2
<td>Row 1, cell 2</td>
</tr>
Le
</table>
Open up your text editor. Type in your <html>, <head> and <body>tags. From here on I will only be writing
w.
<table border="1">
<tr>
<td>Tables can be used to layout information</td>
<td> <img src="http://profdevtrain.austincc.edu/html/graphics/chef.gif">
</td>
</tr>
</table>
Headings in a Table
n
<tr>
row 2, cell 1 row 2, cell 2
g.i
<td>row 2, cell 1</td>
<td>row 2, cell 2</td>
</tr>
</table>
n
eri
Cell Padding and Spacing
The <table>tag has two attributes known as cellspacing and cellpadding. Here is a table example without
e
these properties. These properties may be used separately or together.
gin
This Code Would Display
<table border="1">
<tr>
<td>some text</td>
en
<td>some text</td>
</tr> some text some text
<tr> some text some text
arn
<td>some text</td>
<td>some text</td>
</tr>
</table>
Cellspacing is the pixel width between the individual data cells in the table (The thickness of the lines
Le
making the table grid). The default is zero. If the border is set at 0, the cellspacing lines will be invisible.
This Code Would Display
<table border="1" cellspacing="5">
w.
<tr>
<td>some text</td>
<td>some text</td> some text some text
ww
</tr><tr>
<td>some text</td> some text some text
<td>some text</td>
</tr>
</table>
Cellpadding is the pixel space between the cell contents and the cell border. The default for this property is
also zero. This feature is not used often, but sometimes comes in handy when you have your borders turned
on and you want the contents to be away from the border a bit for easy viewing. Cellpadding is invisible,
even with the border property turned on. Cellpadding can be handled in a style sheet.
n
g.i
Tag Description
<table> Defines a table
<th> Defines a table header
n
<tr> Defines a table row
<td> Defines a table cell
eri
<caption> Defines a table caption
<colgroup> Defines groups of table columns
<col> Defines the attribute values for one or more columns in a table
Table Size e
gin
Table Width
The width attribute can be used to define the width of your table. It can be defined as a fixed width or a
en
relative width. A fixed table width is one where the width of the table is specified in pixels. For example,
this code, <table width="550">, will produce a table that is 550 pixels wide. A relative table width is
specified as a percentage of the width of the visitor's viewing window. Hence this code, <table
arn
There are arguments in favor of giving your tables a relative width because such table widths yield pages
that work regardless of the visitor's screen resolution. For example, a table width of 100% will always span
w.
the entire width of the browser window whether the visitor has a 800x600 display or a 1024x768 display
(etc). Your visitor never needs to scroll horizontally to read your page, something that is regarded by most
people as being very annoying.
ww
One very common practice with HTML, is to An HTML <table> is used to divide a part of
use HTML tables to format the layout of an this Web page into two columns.
HTML page. The trick is to use a table without borders,
A part of this page is formatted with two and maybe a little extra cell-padding.
columns. As you can see on this page, there is No matter how much text you add to this
a left column and a right column. page, it will stay inside its column borders.
This text is displayed in the left column.
<html>
<head>
<title>My First Web Page </title>
n
</head>
g.i
<body>
<table width="90%" cellpadding="5" cellspacing="0" >
<tr bgcolor="#EDDD9E">
<td width="200" valign="top"><img src="graphics/contact.gif" width="100" height="100"></td>
n
<td valign="top"><h1 align="right">Janet Doeson</h1>
eri
<h3 align="right">Technical Specialist</h3></td>
</tr>
<tr>
<td width="200">
<h3>Menu</h3> e
gin
<ul>
<li><a href="home.html">Home</a></li>
<li> <a href="faq.html">FAQ</a></li>
<li> <a href="contact.html">Contact</a></li>
en
<p>Welcome to my first webpage. I created this webpage without the assistance of a webpage editor.
Just my little text editor and a keen understanding of html.</p>
<p>Look around. Notice I'm able to use paragraphs, lists and headings. You may not be able to tell, but
the layout is done with a table. I'm very clever. </p>
Le
<blockquote>
<p>I always wanted to be somebody, but now I realize I should have been more specific.</p>
<cite>Lily Tomlin </cite> </blockquote> </td>
</tr>
w.
</table>
<hr width="90%" align="left">
<address>
ww
Cascading Style Sheets, fondly referred to as CSS, is a simple design language intended to
simplify the process of making web pages presentable.
CSS handles the look and feel part of a web page. Using CSS, you can control the color of the
text, the style of fonts, the spacing between paragraphs, how columns are sized and laid out, what
background images or colors are used, as well as a variety of other effects.
CSS is easy to learn and understand but it provides powerful control over the presentation of an
HTML document. Most commonly, CSS is combined with the markup languages HTML or
n
XHTML.
g.i
Advantages of CSS:
n write CSS once and then reuse same sheet in multiple HTML
pages. You can define a style for each HTML element and apply it to as many Web pages as you
n
want.
If you are using CSS, you do not need to write HTML tag attributes every time. Just write one
eri
CSS rule of a tag and apply to all the occurrences of that tag. So less code means faster download
times.
Easy maintenance
e
gin
To make a global change, simply change the style, and all elements in all the web pages will be
updated automatically.
Superior styles to HTML
CSS has a much wider array of attributes than HTML so you can give far better look to your
en
HTML document, different versions of a website can be presented for handheld devices such as
PDAs and cell phones or for printing.
Global web standards
Le
Now HTML attributes are being deprecated and it is being recommended to use CSS. So its a
good idea to start using CSS in all the HTML pages to make them compatible to future browsers.
w.
ww
Introduction to JavaScript
JavaScript is a programming language that can be included on web pages to make them more
interactive. You can use it to check or modify the contents of forms, change images, open new
windows and write dynamic page content. You can even use it with CSS to make DHTML
(Dynamic HyperText Markup Language). This allows you to make parts of your web pages
appear or disappear or move around on the page. JavaScripts only execute on the page(s) that are
on your browser window at any set time. When the user stops viewing that page, any scripts that
were running on it are immediately stopped. The only exceptions are cookies or various client
side storage APIs, which can be used by many pages to store and pass information between
n
them, even after the pages have been closed.
g.i
Before we go any further, let me say; JavaScript has nothing to do with Java. If we are honest,
JavaScript, originally nicknamed LiveWire and then LiveScript when it was created by Netscape,
n
should in fact be called ECMAscript as it was renamed when Netscape passed it to the ECMA
for standardisation.
eri
JavaScript is a client side, interpreted, object oriented, high level scripting language, while Java
is a client side, compiled, object oriented high level language. Now after that mouthful, here's
what it means. e
gin
Client side
Programs are passed to the computer that the browser is on, and that computer runs them.
The alternative is server side, where the program is run on the server and only the results
en
are passed to the computer that the browser is on. Examples of this would be PHP, Perl,
ASP, JSP etc.
Interpreted
arn
The program is passed as source code with all the programming language visible. It is
then converted into machine code as it is being used. Compiled languages are converted
into machine code first then passed around, so you never get to see the original
programming language. Java is actually dual half compiled, meaning it is half compiled
Le
(to 'byte code') before it is passed, then executed in a virtual machine which converts it to
fully compiled code just before use, in order to execute it on the computer's processor.
Interpreted languages are generally less fussy about syntax and if you have made
w.
mistakes in a part they never use, the mistake usually will not cause you any problems.
Scripting
This is a little harder to define. Scripting languages are often used for performing
ww
repetitive tasks. Although they may be complete programming languages, they do not
usually go into the depths of complex programs, such as thread and memory
management. They may use another program to do the work and simply tell it what to do.
They often do not create their own user interfaces, and instead will rely on the other
programs to create an interface for them. This is quite accurate for JavaScript. We do not
have to tell the browser exactly what to put on the screen for every pixel (though there is
a relatively new API known as canvas that makes this possible if needed), we just tell it
that we want it to change the document, and it does it. The browser will also take care of
the memory management and thread management, leaving JavaScript free to get on with
the things it wants to do.
High level
Written in words that are as close to english as possible. The contrast would be with
assembly code, where each command can be directly translated into machine code.
Object oriented
The basic part of a script is a variable, literal or object. A variable is a word that represents a
n
piece of text, a number, a boolean true or false value or an object. A literal is the actual number
g.i
or piece of text or boolean value that the variable represents. An object is a collection of
variables held together by a parent variable, or a document component.
n
The next most important part of a script is an operator. Operators assign literal values to
variables or say what type of tests to perform.
eri
The next most important part of a script is a control structure. Control structures say what scripts
should be run if a test is satisfied.
e
gin
Functions collect control structures, actions and assignments together and can be told to run
those pieces of script as and when necessary.
The most obvious parts of a script are the actions it performs. Some of these are done with
en
operators but most are done using methods. Methods are a special kind of function and may do
things like submitting forms, writing pages or displaying messages.
arn
Events can be used to detect actions, usually created by the user, such as moving or clicking the
mouse, pressing a key or resetting a form. When triggered, events can be used to run functions.
Lastly and not quite so obvious is referencing. This is about working out what to write to access
Le
As an example, think of the following situation. A person clicks a submit button on a form.
w.
When they click the button, we want to check if they have filled out their name in a text box and
if they have, we want to submit the form. So, we tell the form to detect the submit event. When
the event is triggered, we tell it to run the function that holds together the tests and actions. The
ww
function contains a control structure that uses a comparison operator to test the text box to see
that it is not empty. Of course we have to work out how to reference the text box first. The text
box is an object. One of the variables it holds is the text that is written in the text box. The text
written in it is a literal. If the text box is not empty, a method is used that submits the form.
n
n g.i
e eri
gin
With the object model, JavaScript gets all the power it needs to create dynamic HTML:
Regular Expression
Regular expressions are patterns used to match character combinations in strings. In JavaScript,
regular expressions are also objects. These patterns are used with the exec and test methods of
RegExp, and with the match, replace, search, and split methods of String. This chapter describes
JavaScript regular expressions.
n
g.i
Using a regular expression literal, as follows:
var re = /ab+c/;
n
Regular expression literals provide compilation of the regular expression when the script is
eri
loaded. When the regular expression will remain constant, use this for better performance.
Using the constructor function provides runtime compilation of the regular expression. Use the
constructor function when you know the regular expression pattern will be changing, or you
en
don't know the pattern and are getting it from another source, such as user input.
Simple patterns are constructed of characters for which you want to find a direct match. For
example, the pattern /abc/ matches character combinations in strings only when exactly the
ww
characters 'abc' occur together and in that order. Such a match would succeed in the strings "Hi,
do you know your abc's?" and "The latest airplane designs evolved from slabcraft." In both cases
the match is with the substring 'abc'. There is no match in the string 'Grab crab' because while it
contains the substring 'ab c', it does not contain the exact substring 'abc'.
The following table provides a complete list and description of the special characters that can be
n
used in regular expressions.
g.i
Special characters in regular expressions.
n
Character Meaning
eri
Matches according to the following rules:
e
A backslash that precedes a non-special character indicates that the next character is
special and is not to be interpreted literally. For example, a 'b' without a preceding '\'
gin
generally matches lowercase 'b's wherever they occur. But a '\b' by itself doesn't
match any character; it forms the special word boundary character.
\
A backslash that precedes a special character indicates that the next character is not
en
special and should be interpreted literally. For example, the pattern /a*/ relies on the
special character '*' to match 0 or more a's. By contrast, the pattern /a\*/ removes the
arn
Do not forget to escape \ itself while using the RegExp("pattern") notation because \
is also an escape character in strings.
Le
Matches beginning of input. If the multiline flag is set to true, also matches
immediately after a line break character.
w.
^ For example, /^A/ does not match the 'A' in "an A", but does match the 'A' in "An E".
ww
The '^' has a different meaning when it appears as the first character in a character set
pattern. See complemented character sets for details and an example.
Matches end of input. If the multiline flag is set to true, also matches immediately
$ before a line break character.
For example, /t$/ does not match the 't' in "eater", but does match it in "eat".
* Matches the preceding character 0 or more times. Equivalent to {0,}.
Character Meaning
For example, /bo*/ matches 'boooo' in "A ghost booooed" and 'b' in "A bird
warbled", but nothing in "A goat grunted".
Matches the preceding character 1 or more times. Equivalent to {1,}.
+
For example, /a+/ matches the 'a' in "candy" and all the a's in "caaaaaaandy", but
n
nothing in "cndy".
g.i
Matches the preceding character 0 or 1 time. Equivalent to {0,1}.
For example, /e?le?/ matches the 'el' in "angel" and the 'le' in "angle" and also the 'l'
n
in "oslo".
eri
If used immediately after any of the quantifiers *, +, ?, or {}, makes the quantifier
non-greedy (matching the fewest possible characters), as opposed to the default,
?
e
which is greedy (matching as many characters as possible). For example, applying
gin
/\d+/ to "123abc" matches "123". But applying /\d+?/ to that same string matches
only the "1".
en
Also used in lookahead assertions, as described in the x(?=y) and x(?!y) entries of
this table.
arn
(The decimal point) matches any single character except the newline character.
.
For example, /.n/ matches 'an' and 'on' in "nay, an apple is on the tree", but not 'nay'.
Le
Matches 'x' and remembers the match, as the following example shows. The
parentheses are called capturing parentheses.
w.
(x) The '(foo)' and '(bar)' in the pattern /(foo) (bar) \1 \2/ match and remember the first
two words in the string "foo bar foo bar". The \1 and \2 in the pattern match the
ww
string's last two words. Note that \1, \2, \n are used in the matching part of the regex.
In the replacement part of a regex the syntax $1, $2, $n must be used, e.g.: 'bar
foo'.replace( /(...) (...)/, '$2 $1' ).
Matches 'x' but does not remember the match. The parentheses are called non-
capturing parentheses, and let you define subexpressions for regular expression
(?:x) operators to work with. Consider the sample expression /(?:foo){1,2}/. If the
expression was /foo{1,2}/, the {1,2} characters would apply only to the last 'o' in
'foo'. With the non-capturing parentheses, the {1,2} applies to the entire word 'foo'.
Character Meaning
n
Matches 'x' only if 'x' is not followed by 'y'. This is called a negated lookahead.
g.i
x(?!y)
For example, /\d+(?!\.)/ matches a number only if it is not followed by a decimal
point. The regular expression /\d+(?!\.)/.exec("3.141") matches '141' but not '3.141'.
n
Matches either 'x' or 'y'.
x|y
eri
For example, /green|red/ matches 'green' in "green apple" and 'red' in "red apple."
Matches exactly n occurrences of the preceding character. N must be a positive
integer.
e
gin
{n}
For example, /a{2}/ doesn't match the 'a' in "candy," but it does match all of the a's in
"caandy," and the first two a's in "caaandy."
en
Where n and m are positive integers and n <= m. Matches at least n and at most m
occurrences of the preceding character. When m is omitted, it's treated as ∞.
{n,m}
arn
For example, /a{1,3}/ matches nothing in "cndy", the 'a' in "candy," the first two a's
in "caandy," and the first three a's in "caaaaaaandy". Notice that when matching
"caaaaaaandy", the match is "aaa", even though the original string had more a's in it.
Le
Character set. This pattern type matches any one of the characters in the brackets,
including escape sequences. Special characters like the dot(.) and asterisk (*) are not
special inside a character set, so they don't need to be escaped. You can specify a
w.
"brisket" and the 'c' in "city". The patterns /[a-z.]+/ and /[\w.]+/ match the entire
string "test.i.ng".
A negated or complemented character set. That is, it matches anything that is not
enclosed in the brackets. You can specify a range of characters by using a hyphen.
[^xyz] Everything that works in the normal character set also works here.
For example, [^abc] is the same as [^a-c]. They initially match 'r' in "brisket" and 'h'
in "chop."
Character Meaning
Matches a backspace (U+0008). You need to use square brackets if you want to
[\b]
match a literal backspace character. (Not to be confused with \b.)
Matches a word boundary. A word boundary matches the position where a word
character is not followed or preceeded by another word-character. Note that a
n
matched word boundary is not included in the match. In other words, the length of a
g.i
matched word boundary is zero. (Not to be confused with [\b].)
Examples:
n
/\bm/ matches the 'm' in "moon" ;
/oo\b/ does not match the 'oo' in "moon", because 'oo' is followed by 'n' which is a
eri
word character;
\b /oon\b/ matches the 'oon' in "moon", because 'oon' is the end of the string, thus not
followed by a word character;
e
/\w\b\w/ will never match anything, because a word character can never be followed
gin
by both a non-word and a word character.
of characters is fairly limited: it consists solely of the Roman alphabet in both upper-
and lower-case, decimal digits, and the underscore character. Accented characters,
such as "é" or "ü" are, unfortunately, treated as word breaks.
arn
Matches a non-word boundary. This matches a position where the previous and next
character are of the same type: Either both must be words, or both must be non-
\B words. The beginning and end of a string are considered non-words.
Le
For example, /\B../ matches 'oo' in "noonday", and /y\B./ matches 'ye' in "possibly
yesterday."
w.
Character Meaning
Matches a single white space character, including space, tab, form feed, line feed.
n
Equivalent to [ \f\n\r\t\v\u00a0\u1680\u180e\u2000-\u200a
\s
g.i
\u2028\u2029\u202f\u205f\u3000].
n
Matches a single character other than white space. Equivalent to [^ \f\n\r\t\v
\u00a0\u1680\u180e\u2000-\u200a\u2028\u2029\u202f\u205f\u3000].
eri
\S
\w z0-9_].
For example, /\w/ matches 'a' in "apple," '5' in "$5.28," and '3' in "3D."
arn
Where n is a positive integer, a back reference to the last substring matching the n
parenthetical in the regular expression (counting left parentheses).
\n
For example, /apple(,)\sorange\1/ matches 'apple, orange,' in "apple, orange, cherry,
w.
peach."
Matches a NULL (U+0000) character. Do not follow this with another digit, because
\0
ww
\xhh Matches the character with the code hh (two hexadecimal digits)
\uhhhh Matches the character with the code hhhh (four hexadecimal digits).
Escaping user input to be treated as a literal string within a regular expression can be
accomplished by simple replacement:
function escapeRegExp(string){
return string.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
}
Using parentheses
Parentheses around any part of the regular expression pattern cause that part of the matched
n
substring to be remembered. Once remembered, the substring can be recalled for other use, as
g.i
described in Using Parenthesized Substring Matches.
For example, the pattern /Chapter (\d+)\.\d*/ illustrates additional escaped and special characters
n
and indicates that part of the pattern should be remembered. It matches precisely the characters
'Chapter ' followed by one or more numeric characters (\d means any numeric character and +
eri
means 1 or more times), followed by a decimal point (which in itself is a special character;
preceding the decimal point with \ means the pattern must look for the literal character '.'),
followed by any numeric character 0 or more times (\d means numeric character, * means 0 or
e
more times). In addition, parentheses are used to remember the first matched numeric characters.
gin
This pattern is found in "Open Chapter 4.3, paragraph 6" and '4' is remembered. The pattern is
not found in "Chapter 3 and 4", because that string does not have a period after the '3'.
en
To match a substring without causing the matched part to be remembered, within the parentheses
preface the pattern with ?:. For example, (?:\d+) matches one or more numeric characters but
does not remember the matched characters.
arn
Regular expressions are used with the RegExp methods test and exec and with the String
Le
methods match, replace, search, and split. These methods are explained in detail in the JavaScript
reference.
w.
Method Description
A RegExp method that executes a search for a match in a string. It returns an array of
exec
information.
test A RegExp method that tests for a match in a string. It returns true or false.
match A String method that executes a search for a match in a string. It returns an array of
Method Description
A String method that tests for a match in a string. It returns the index of the match, or -1
search
if the search fails.
n
A String method that executes a search for a match in a string, and replaces the matched
replace
g.i
substring with a replacement substring.
A String method that uses a regular expression or a fixed string to break a string into an
n
split
array of substrings.
eri
When you want to know whether a pattern is found in a string, use the test or search method; for
e
more information (but slower execution) use the exec or match methods. If you use exec or
match and if the match succeeds, these methods return an array and update properties of the
gin
associated regular expression object and also of the predefined regular expression object,
RegExp. If the match fails, the exec method returns null (which coerces to false).
en
In the following example, the script uses the exec method to find a match in a string.
If you do not need to access the properties of the regular expression, an alternative way of
creating myArray is with this script:
Le
If you want to construct the regular expression from a string, yet another alternative is this script:
With these scripts, the match succeeds and returns the array and updates the properties shown in
the following table.
Property In this
bject Description
or index example
["dbbd",
The matched string and all remembered substrings.
"bb"]
myArray index The 0-based index of the match in the input string. 1
input The original string. "cdbbdbsbz"
[0] The last matched characters. "dbbd"
The index at which to start the next match. (This property is set only if the
n
lastIndex regular expression uses the g option, described in Advanced Searching With 5
g.i
myRe Flags.)
The text of the pattern. Updated at the time that the regular expression is
source
created, not executed.
n
As shown in the second form of this example, you can use a regular expression created with an
eri
object initializer without assigning it to a variable. If you do, however, every occurrence is a new
regular expression. For this reason, if you use this form without assigning it to a variable, you
cannot subsequently access the properties of that regular expression. For example, assume you
have this script: e
gin
var myRe = /d(b+)d/g;
var myArray = myRe.exec("cdbbdbsbz");
console.log("The value of lastIndex is " + myRe.lastIndex);
en
The occurrences of /d(b+)d/g in the two statements are different regular expression objects and
hence have different values for their lastIndex property. If you need to access the properties of a
regular expression created with an object initializer, you should first assign it to a variable.
ww
The number of possible parenthesized substrings is unlimited. The returned array holds all that
were found. The following examples illustrate how to use parenthesized substring matches.
The following script uses the replace() method to switch the words in the string. For the
replacement text, the script uses the $1 and $2 in the replacement to denote the first and second
parenthesized substring matches.
var re = /(\w+)\s(\w+)/;
var str = "John Smith";
var newstr = str.replace(re, "$2, $1");
console.log(newstr);
n
g.i
Advanced searching with flags
Regular expressions have four optional flags that allow for global and case insensitive searching.
n
These flags can be used separately or together in any order, and are included as part of the
regular expression.
eri
Regular expression flags
Flag e Description
gin
g Global search.
en
i Case-insensitive search.
m Multi-line search.
arn
y Perform a "sticky" search that matches starting at the current position in the target string.
Le
var re = /pattern/flags;
w.
or
ww
Note that the flags are an integral part of a regular expression. They cannot be added or removed
later.
For example, re = /\w+\s/g creates a regular expression that looks for one or more characters
followed by a space, and it looks for this combination throughout the string.
var re = /\w+\s/g;
This displays ["fee ", "fi ", "fo "]. In this example, you could replace the line:
var re = /\w+\s/g;
with:
n
var re = new RegExp("\\w+\\s", "g"); and get the same result.
g.i
The m flag is used to specify that a multiline input string should be treated as multiple lines. If
the m flag is used, ^ and $ match at the start or end of any line within the input string instead of
n
the start or end of the entire string.
eri
Date Object
Both the Date(string) constructor and parse() method work on exactly the the same date formats.
e
The difference is that the constructor creates a Date object, while the static Date.parse() method
gin
returns a number - more precisely, the number of milliseconds since Jan 1, 1970:?
console.log(d2); //1332302400000
console.log(typeof d2); //number
Either of the above will also work for numeric date formats, assuming that you're dealing with a
Le
result in unpredictable results at best. Oddly, according to Wikipedia, the standard Calendar date
representation allows both the YYYY-MM-DD and YYYYMMDD formats, as well as the year-
month-only YYYY-MM format.
ww
There are three types of errors in programming: (a) Syntax Errors, (b) Runtime Errors, and (c)
Logical Errors.
Syntax Errors
Syntax errors, also called parsing errors, occur at compile time in traditional programming
languages and at interpret time in JavaScript.
For example, the following line causes a syntax error because it is missing a closing parenthesis.
<script type="text/javascript">
<!--
window.print(;
n
//-->
g.i
</script>
When a syntax error occurs in JavaScript, only the code contained within the same thread as the
n
syntax error is affected and the rest of the code in other threads gets executed assuming nothing
in them depends on the code containing the error.
eri
Runtime Errors
e
Runtime errors, also called exceptions, occur during execution (after compilation/interpretation).
gin
For example, the following line causes a runtime error because here the syntax is correct, but at
runtime, it is trying to call a method that does not exist.
en
<script type="text/javascript">
<!--
window.printme();
arn
//-->
</script>
Exceptions also affect the thread in which they occur, allowing other JavaScript threads to
Le
Logical Errors
w.
Logic errors can be the most difficult type of errors to track down. These errors are not the result
of a syntax or runtime error. Instead, they occur when you make a mistake in the logic that drives
ww
your script and you do not get the result you expected.
You cannot catch those errors, because it depends on your business requirement what type of
logic you want to put in your program.
The latest versions of JavaScript added exception handling capabilities. JavaScript implements
the try...catch...finally construct as well as the throw operator to handle exceptions.
You can catch programmer-generated and runtime exceptions, but you cannot catch JavaScript
syntax errors.
<script type="text/javascript">
<!--
try {
// Code to run
[break;]
n
}
g.i
catch ( e ) {
// Code to run if an exception occurs
n
[break;]
}
eri
[ finally {
// Code that is always executed regardless of
// an exception occurring e
gin
}]
//-->
</script>
en
The try block must be followed by either exactly one catch block or one finally block (or one of
both). When an exception occurs in the try block, the exception is placed in e and the catch
block is executed. The optional finally block executes unconditionally after try/catch.
arn
Examples
Here is an example where we are trying to call a non-existing function which in turn is raising an
Le
<html>
w.
<head>
<script type="text/javascript">
ww
<!--
function myFunc()
{
var a = 100;
alert("Value of variable a is : " + a );
}
//-->
</script>
</head>
<body>
<p>Click the following to see the result:</p>
<form>
<input type="button" value="Click Me" onclick="myFunc();" />
</form>
</body>
n
</html>
g.i
Event Handler
n
An event handler executes a segment of a code based on certain events occurring within the
eri
application, such as onLoad, onClick. JavaScript event handers can be divided into two parts:
interactive event handlers and non-interactive event handlers. An interactive event handler is the
one that depends on the user interactivity with the form or the document. For example,
e
onMouseOver is an interactive event handler because it depends on the users action with the
gin
mouse. On the other hand non-interactive event handler would be onLoad, because this event
handler would automatically execute JavaScript code without the user's interactivity. Here are all
the event handlers available in JavaScript:
en
onAbort:
An onAbort event handler executes JavaScript code when the user aborts loading an image.
<HTML>
<TITLE>Example of onAbort Event Handler</TITLE>
<HEAD>
</HEAD>
<BODY>
<H3>Example of onAbort Event Handler</H3>
<b>Stop the loading of this image and see what happens:</b><p>
<IMG SRC="reaz.gif" onAbort="alert('You stopped the loading the image!')">
</BODY>
</HTML>
Here, an alert() method is called using the onAbort event handler when the user aborts loading
the image.
n
g.i
onBlur:
n
An onBlur event handler executes JavaScript code when input focus leaves the field of a text,
textarea, or a select option. For windows, frames and framesets the event handler executes
eri
JavaScript code when the window loses focus. In windows you need to specify the event handler
in the <BODY> attribute. For example:
<BODY BGCOLOR='#ffffff' onBlur="document.bgcolor='#000000'">
e
Note: On a Windows platform, the onBlur event does not work with <FRAMESET>.
gin
See Example:
<HTML>
en
function valid(form){
var input=0;
input=document.myform.data.value;
if (input<0){
Le
</SCRIPT>
</HEAD>
<BODY>
ww
In this example, 'data' is a text field. When a user attempts to leave the field, the onBlur event
handler calls the valid() function to confirm that 'data' has a legal value. Note that the keyword
this is used to refer to the current object.
onChange:
The onChange event handler executes JavaScript code when input focus exits the field after the
user modifies its text.
n
See Example:
g.i
<HTML>
<TITLE>Example of onChange Event Handler</TITLE>
n
<HEAD>
<SCRIPT LANGUAGE="JavaScript">
eri
function valid(form){
var input=0;
input=document.myform.data.value;
e
alert("You have changed the value from 10 to " + input );
gin
}
</SCRIPT>
</HEAD>
<BODY>
en
directly implementing the javax.servlet.Servlet interface we extend a class that has implemented
the interface like javax.servlet.GenericServlet or javax.servlet.http.HttpServlet.
ww
n
n g.i
e eri
gin
Servlet Exceution
This is how a servlet execution takes place when client (browser) makes a request to the
en
webserver.
arn
Le
w.
ww
a) Servlet Interface
To write a servlet we need to implement Servlet interface. Servlet interface can be implemented
directly or indirectly by extending GenericServlet or HttpServlet class.
The first time a servlet is invoked, the init method is called. It is called only once during the
lifetime of a servlet. So, we can put all your initialization code here.
The Service method is used for handling the client request. As the client request reaches to the
container it creates a thread of the servlet object, and request and response object are also
created. These request and response object are then passed as parameter to the service method,
which then process the client request. The service method in turn calls the doGet or doPost
n
methods (if the user has extended the class from HttpServlet ).
g.i
c) Number of instances
n
Basic Structure of a Servlet
public class firstServlet extends HttpServlet {
eri
public void init() {
/* Put your initialization code in this method,
* as this method is called only once */
} e
gin
public void service() {
// Service request for Servlet
}
public void destroy() {
en
// For taking the servlet out of service, this method is called only once
}
}
arn
A servlet life cycle can be defined as the entire process from its creation till the destruction. The
Le
The init method is designed to be called only once. It is called when the servlet is first created,
and not called again for each user request. So, it is used for one-time initializations, just as with
the init method of applets.
The servlet is normally created when a user first invokes a URL corresponding to the servlet, but
you can also specify that the servlet be loaded when the server is first started.
When a user invokes a servlet, a single instance of each servlet gets created, with each user
request resulting in a new thread that is handed off to doGet or doPost as appropriate. The init()
method simply creates or loads some data that will be used throughout the life of the servlet.
n
// Initialization code...
g.i
}
n
The service() method is the main method to perform the actual task. The servlet container (i.e.
eri
web server) calls the service() method to handle requests coming from the client( browsers) and
to write the formatted response back to the client.
e
Each time the server receives a request for a servlet, the server spawns a new thread and calls
gin
service. The service() method checks the HTTP request type (GET, POST, PUT, DELETE, etc.)
and calls doGet, doPost, doPut, doDelete, etc. methods as appropriate.
The service () method is called by the container and service method invokes doGe, doPost,
Le
doPut, doDelete, etc. methods as appropriate. So you have nothing to do with service() method
but you override either doGet() or doPost() depending on what type of request you receive from
the client.
w.
The doGet() and doPost() are most frequently used methods with in each service request. Here is
the signature of these two methods.
ww
A GET request results from a normal request for a URL or from an HTML form that has no
METHOD specified and it should be handled by doGet() method.
// Servlet code
}
A POST request results from an HTML form that specifically lists POST as the METHOD and it
should be handled by doPost() method.
n
throws ServletException, IOException {
g.i
// Servlet code
}
n
The destroy() method :
eri
The destroy() method is called only once at the end of the life cycle of a servlet. This method
gives your servlet a chance to close database connections, halt background threads, write cookie
lists or hit counts to disk, and perform other such cleanup activities.
e
gin
After the destroy() method is called, the servlet object is marked for garbage collection. The
destroy method definition looks like this:
// Finalization code...
}
arn
Architecture Digram:
First the HTTP requests coming to the server are delegated to the servlet container.
The servlet container loads the servlet before invoking the service() method.
Then the servlet container handles multiple requests by spawning multiple threads, each
thread executing the service() method of a single instance of the servlet.
session
A session is a conversation between the server and a client. A conversation consists series of
continuous request and response.
n
Why should a session be maintained?
g.i
When there is a series of continuous request and response from a same client to a server, the
server cannot identify from which client it is getting requests. Because HTTP is a stateless
n
protocol.
eri
When there is a need to maintain the conversational state, session tracking is needed. For
example, in a shopping cart application a client keeps on adding items into his cart using
multiple requests. When every request is made, the server should identify in which client’s cart
e
the item is to be added. So in this scenario, there is a certain need for session tracking.
gin
Solution is, when a client makes a request it should introduce itself by providing unique
identifier every time. There are five different methods to achieve this.
en
1. User authorization
arn
2. Hidden fields
3. URL rewriting
4. Cookies
5. Session tracking API
Le
The first four methods are traditionally used for session tracking in all the server-side
technologies. The session tracking API method is provided by the underlying technology (java
w.
servlet or PHP or likewise). Session tracking API is built on top of the first four methods.
1. User Authorization
ww
Users can be authorized to use the web application in different ways. Basic concept is that the
user will provide username and password to login to the application. Based on that the user can
be identified and the session can be maintained.
2. Hidden Fields
server for session tracking. These fields are not visible directly to the user, but can be viewed
using view source option from the browsers. This type doesn’t need any special configuration
from the browser of server and by default available to use for session tracking. This cannot be
used for session tracking when the conversation included static resources lik html pages.
3. URL Rewriting
n
When a request is made, additional parameter is appended with the url. In general added
additional parameter will be sessionid or sometimes the userid. It will suffice to track the session.
g.i
This type of session tracking doesn’t need any special support from the browser. Disadvantage
is, implementing this type of session tracking is tedious. We need to keep track of the parameter
as a chain link until the conversation completes and also should make sure that, the parameter
n
doesn’t clash with other application parameters.
eri
4. Cookies
Cookies are the mostly used technology for session tracking. Cookie is a key value pair of
e
information, sent by the server to the browser. This should be saved by the browser in its space
gin
in the client computer. Whenever the browser sends a request to that server it sends the cookie
along with it. Then the server can identify the client using the cookie.
In java, following is the source code snippet to create a cookie:
en
Session tracking is easy to implement and maintain using the cookies. Disadvantage is that, the
users can opt to disable cookies using their browser preferences. In such case, the browser will
not save the cookie at client computer and session tracking fails.
Le
Session tracking API is built on top of the first four methods. This is inorder to help the
developer to minimize the overhead of session tracking. This type of session tracking is provided
by the underlying technology. Lets take the java servlet example. Then, the servlet container
ww
manages the session tracking task and the user need not do it explicitly using the java servlets.
This is the best of all methods, because all the management and errors related to session tracking
will be taken care of by the container itself.
Every client of the server will be mapped with a javax.servlet.http.HttpSession object. Java
servlets can use the session object to store and retrieve java objects across the session. Session
tracking is at the best when it is implemented using session tracking api.
package com.journaldev.servlet.session;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
n
import javax.servlet.http.HttpServletRequest;
g.i
import javax.servlet.http.HttpServletResponse;
/**
n
* Servlet implementation class LoginServlet
*/
eri
@WebServlet("/LoginServlet")
public class LoginServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
private final String userID = "Pankaj"; e
gin
private final String password = "journaldev";
response.sendRedirect("LoginSuccess.jsp");
}else{
RequestDispatcher rd = getServletContext().getRequestDispatcher("/login.html");
ww
JSP
JSP technology is used to create web application just like Servlet technology. It can be thought
of as an extension to servlet because it provides more functionality than servlet such as
expression language, jstl etc.
A JSP page consists of HTML tags and JSP tags. The jsp pages are easier to maintain than
servlet because we can separate designing and development. It provides some additional features
such as Expression Language, Custom Tag etc.
n
Advantage of JSP over Servlet
g.i
There are many advantages of JSP over servlet. They are as follows:
n
1) Extension to Servlet
eri
JSP technology is the extension to servlet technology. We can use all the features of servlet in
JSP. In addition to, we can use implicit objects, predefined tags, expression language and
Custom tags in JSP, that makes JSP development easy.
e
gin
2) Easy to maintain
JSP can be easily managed because we can easily separate our business logic with presentation
logic. In servlet technology, we mix our business logic with the presentation logic.
en
If JSP page is modified, we don't need to recompile and redeploy the project. The servlet code
needs to be updated and recompiled if we have to change the look and feel of the application.
Le
In JSP, we can use a lot of tags such as action tags, jstl, custom tags etc. that reduces the code.
w.
n
n g.i
e eri
gin
As depicted in the above diagram, JSP page is translated into servlet by the help of JSP
translator. The JSP translator is a part of webserver that is responsible to translate the JSP page
en
into servlet. Afterthat Servlet page is compiled by the compiler and gets converted into the class
file. Moreover, all the processes that happens in servlet is performed on JSP later like
initialization, committing response to the browser and destroy.
arn
To create the first jsp page, write some html code as given below, and save it by .jsp extension.
We have save this file as index.jsp. Put it in a folder and paste the folder in the web-apps
directory in apache tomcat to run the jsp page.
w.
index.jsp
ww
Let's see the simple example of JSP, here we are using the scriptlet tag to put java code in the
JSP page. We will learn scriptlet tag later.
1. <html>
2. <body>
3. <% out.print(2*5); %>
4. </body>
5. </html>
n
g.i
Do I need to follow directory structure to run a simple JSP ?
No, there is no need of directory structure if you don't have class files or tld files. For example,
n
put jsp files in a folder directly and deploy that folder.It will be running fine.But if you are using
bean class, Servlet or tld file then directory structure is required.
The JavaServer Pages Standard Tag Library (JSTL) is a collection of useful JSP tags which
encapsulates core functionality common to many JSP applications.
JSTL has support for common, structural tasks such as iteration and conditionals, tags for
manipulating XML documents, internationalization tags, and SQL tags. It also provides a
framework for integrating existing custom tags with JSTL tags.
The JSTL tags can be classified, according to their functions, into following JSTL tag library
n
groups that can be used when creating a JSP page:
g.i
Core Tags
Formatting tags
n
SQL tags
XML tags
eri
JSTL Functions
Download the binary distribution from Apache Standard Taglib and unpack the
compressed file.
en
To use the Standard Taglib from its Jakarta Taglibs distribution, simply copy the JAR
files in the distribution's 'lib' directory to your application's webapps\ROOT\WEB-
INF\lib directory.
arn
To use any of the libraries, you must include a <taglib> directive at the top of each JSP that uses
the library.
Le
Core Tags:
The core group of tags are the most frequently used JSTL tags. Following is the syntax to include
w.
uri="http://java.sun.com/jsp/jstl/core" %>
Tag Description
<c:out > Like <%= ... >, but for expressions.
<c:set > Sets the result of an expression evaluation in a 'scope'
<c:remove > Removes a scoped variable (from a particular scope, if specified).
n
Subtag of <choose> that follows <when> tags and runs only if all
g.i
<c:otherwise >
of the prior conditions evaluated to 'false'.
Retrieves an absolute or relative URL and exposes its contents to
<c:import>
either the page, a String in 'var', or a Reader in 'varReader'.
n
The basic iteration tag, accepting many different collection types
eri
<c:forEach >
and supporting subsetting and other functionality .
<c:forTokens> Iterates over tokens, separated by the supplied delimeters.
<c:param>
e
Adds a parameter to a containing 'import' tag's URL.
gin
<c:redirect > Redirects to a new URL.
<c:url> Creates a URL with optional query parameters
Formatting tags:
en
The JSTL formatting tags are used to format and display text, the date, the time, and numbers for
internationalized Web sites. Following is the syntax to include Formatting library in your JSP:
arn
Tag Description
<fmt:formatNumber> To render numerical value with specific precision or format.
Parses the string representation of a number, currency, or
ww
<fmt:parseNumber>
percentage.
<fmt:formatDate> Formats a date and/or time using the supplied styles and pattern
<fmt:parseDate> Parses the string representation of a date and/or time
<fmt:bundle> Loads a resource bundle to be used by its tag body.
<fmt:setLocale> Stores the given locale in the locale configuration variable.
Loads a resource bundle and stores it in the named scoped variable
<fmt:setBundle>
or the bundle configuration variable.
Specifies the time zone for any time formatting or parsing actions
<fmt:timeZone>
nested in its body.
<fmt:setTimeZone> Stores the given time zone in the time zone configuration variable
<fmt:message> To display an internationalized message.
<fmt:requestEncoding> Sets the request character encoding
SQL tags:
n
The JSTL SQL tag library provides tags for interacting with relational databases (RDBMSs)
such as Oracle, mySQL, or Microsoft SQL Server.
g.i
Following is the syntax to include JSTL SQL library in your JSP:
n
<%@ taglib prefix="sql"
eri
uri="http://java.sun.com/jsp/jstl/sql" %>
Tag e Description
gin
<sql:setDataSource> Creates a simple DataSource suitable only for prototyping
Executes the SQL query defined in its body or through the sql
<sql:query>
attribute.
en
Executes the SQL update defined in its body or through the sql
<sql:update>
attribute.
arn
XML tags:
The JSTL XML tags provide a JSP-centric way of creating and manipulating XML documents.
ww
The JSTL XML tag library has custom tags for interacting with XML data. This includes parsing
XML, transforming XML data, and flow control based on XPath expressions.
Before you proceed with the examples, you would need to copy following two XML and XPath
related libraries into your <Tomcat Installation Directory>\lib:
Tag Description
<x:out> Like <%= ... >, but for XPath expressions.
Use to parse XML data specified either via an attribute or in the tag
<x:parse>
body.
n
<x:set > Sets a variable to the value of an XPath expression.
g.i
Evaluates a test XPath expression and if it is true, it processes its
<x:if >
body. If the test condition is false, the body is ignored.
<x:forEach> To loop over nodes in an XML document.
n
Simple conditional tag that establishes a context for mutually
eri
<x:choose> exclusive conditional operations, marked by <when> and
<otherwise>
Subtag of <choose> that includes its body if its expression evalutes
<x:when >
to 'true' e
gin
Subtag of <choose> that follows <when> tags and runs only if all
<x:otherwise >
of the prior conditions evaluated to 'false'
<x:transform > Applies an XSL transformation on a XML document
en
Use along with the transform tag to set a parameter in the XSLT
<x:param >
stylesheet
arn
JSTL Functions:
JSTL includes a number of standard functions, most of which are common string manipulation
Le
functions. Following is the syntax to include JSTL Functions library in your JSP:
Function Description
fn:contains() Tests if an input string contains the specified substring.
Tests if an input string contains the specified substring in a case
fn:containsIgnoreCase()
insensitive way.
fn:endsWith() Tests if an input string ends with the specified suffix.
fn:escapeXml() Escapes characters that could be interpreted as XML markup.
fn:indexOf() Returns the index withing a string of the first occurrence of a
specified substring.
fn:join() Joins all elements of an array into a string.
Returns the number of items in a collection, or the number of
fn:length()
characters in a string.
Returns a string resulting from replacing in an input string all
fn:replace()
occurrences with a given string.
fn:split() Splits a string into an array of substrings.
fn:startsWith() Tests if an input string starts with the specified prefix.
n
fn:substring() Returns a subset of a string.
g.i
fn:substringAfter() Returns a subset of a string following a specific substring.
fn:substringBefore() Returns a subset of a string before a specific substring.
n
fn:toLowerCase() Converts all of the characters of a string to lower case.
fn:toUpperCase() Converts all of the characters of a string to upper case.
eri
fn:trim() Removes white spaces from both ends of a string.
e
gin
Creating HTML forms by embedding JSP code
To start off the exploration of HTML forms, it's best to start with a small form and expand from
en
there. Also, it's better to start with a JSP rather than a servlet, because it is easier to write out the
HTML. Most of the form handling for JSPs and servlets is identical, so after you know how to
retrieve form information from a JSP, you know how to do it from a servlet. Listing 3.1 shows an
arn
HTML file containing a simple input form that calls a JSP to handle the form.
<html>
<body>
Le
<option value="double">double</option>
<option value="float">float</option>
<option value="int">int</option>
<option value="long">long</option>
</select>
<br>
<input type="submit">
</form>
</body>
</html>
n
g.i
The SimpleFormHandler JSP does little more than retrieve the form variables and print out their
values. Listing 3.2 shows the contents of SimpleFormHandler.jsp, which you can see is pretty
short.
n
<html>
eri
<body>
<%
e
gin
// Grab the variables from the form.
String firstName = request.getParameter("firstName");
String lastName = request.getParameter("lastName");
String sex = request.getParameter("sex");
en
</body>
</html>
w.
ww
Unit – IV
PHP
When working with data values in PHP, we need some convenient way to store these values so that we
can easily access them and make reference to them whenever necessary. This is where PHP variables
come in. It is often useful to think of variables as computer memory locations where data is to be stored.
When declaring a variable in PHP it is assigned a name that can be used to reference it in other locations
in the PHP script. The value of the variable can be accessed, the value can be changed, and the type of
n
variable can be altered all by referencing the name assigned at variable creation time.
g.i
Naming and Creating a Variable in PHP
Before learning how to declare a variable in PHP it is first important to understand some rules about
n
variable names (also known as variable naming conventions). All PHP variable names must be pre-fixed
eri
with a $. It is this prefix which informs the PHP pre-processor that it is dealing with a variable. The first
character of the name must be either a letter or an underscore (_). The remaining characters must
comprise only of letters, numbers or underscores. All other characters are deemed to be invalid for use in
e
a variable name. Let's look at some valid and invalid PHP variable names:
gin
$_myName // valid
$myName // valid
$__myvar // valid
en
$myVar21 // valid
$_1Big // invalid - underscore must be followed by a letter
$1Big // invalid - must begin with a letter or underscore
arn
Variable names in PHP are case-sensitive. This means that PHP considers $_myVariable to be a
completely different variable to one that is named ''$_myvariable.
Values are assigned to variables using the PHP assignment operator. The assignment operator is
ww
represented by the = sign. To assign a value to a variable therefore, the variable name is placed on the
left of the expression, followed by the assignment operator. The value to be assigned is then placed to
the right of the assignment operator. Finally the line, as with all PHP code statements, is terminated with
a semi-colon (;).
$myShape = "Circle";
We have now declared a variable with the name myShape and assigned a string value to it of "Circe". We
can similarly declare a variable to contain an integer value:
$numberOfShapes = 6;
The above assignment creates a variable named numberOfShapes and assigns it a numeric value of 6.
Once a variable has been created, the value assigned to that variable can be changed at any time using
the same assignment operator approach:
n
<?php
$numberOfShapes = 6; // Set initial values
g.i
$myShape = "Circle";
$numberOfShapes = 7; // Change the initial values to new values
$myShape = "Square";
n
eri
?>
e
gin
Now that we have learned how to create a variable and assign an initial value to it we now need to look
at how to access the value currently assigned to a variable. In practice, accessing a variable is as simple
as referencing the name it was given when it was created.
en
For example, if we want to display the value which we assigned to our numberOfShapes variable we can
simply reference it in our echo command:
arn
<?php
echo "The number of shapes is $numberOfShapes.";
?>
Le
<?php
echo "$myShape is the value of the current shape.";
?>
The examples we have used for accessing variable values are straightforward because we have always
had a space character after the variable name. The question arises as to what should be done if we need
to put other characters immediately after the variable name. For example:
<?php
Unfortunately PHP will see the th on the end of the $numberOfShapes variable name as being part of the
name. It will then try to output the value of a variable called $numberOfShapesth, which does not exist.
n
This results in nothing being displayed for this variable:
g.i
The Circle is the shape.
Fortunately we can get around this issue by placing braces ({ and }) around the variable name to
n
distinguish the name from any other trailing characters:
eri
<?php
echo "The Circle is the ${numberOfShapes}th shape";
?>
e
gin
To give us the desired output:
PHP comes standard with many functions and constructs. There are also functions that require specific
PHP extensions compiled in, otherwise fatal "undefined function" errors will appear. For example, to use
image functions such as imagecreatetruecolor(), PHP must be compiled with GD support. Or, to use
mysql_connect(), PHP must be compiled with MySQL support. There are many core functions that are
Le
included in every version of PHP, such as the string and variable functions. A call to phpinfo() or
get_loaded_extensions() will show which extensions are loaded into PHP. Also note that many
extensions are enabled by default and that the PHP manual is split up by extension. See the
w.
configuration, installation, and individual extension chapters, for information on how to set up PHP.
ww
Reading and understanding a function's prototype is explained within the manual section titled how to
read a function definition. It's important to realize what a function returns or if a function works directly
on a passed in value. For example, str_replace() will return the modified string while usort() works on
the actual passed in variable itself. Each manual page also has specific information for each function like
information on function parameters, behavior changes, return values for both success and failure, and
availability information. Knowing these important (yet often subtle) differences is crucial for writing
correct PHP code.
Besides the built-in PHP functions, we can create our own functions.
A function is a block of statements that can be used repeatedly in a program.
A function will not execute immediately when a page loads.
A function will be executed by a call to the function.
n
Create a User Defined Function in PHP
g.i
A user defined function declaration starts with the word "function":
Syntax
n
function functionName() {
eri
code to be executed;
}
e
In the example below, we create a function named "writeMsg()". The opening curly brace ( { ) indicates
gin
the beginning of the function code and the closing curly brace ( } ) indicates the end of the function. The
function outputs "Hello world!". To call the function, just write its name:
Example
en
<?php
function writeMsg() {
arn
Information can be passed to functions through arguments. An argument is just like a variable.
ww
Arguments are specified after the function name, inside the parentheses. You can add as many arguments
as you want, just seperate them with a comma.
The following example has a function with one argument ($fname). When the familyName() function is
called, we also pass along a name (e.g. Jani), and the name is used inside the function, which outputs
several different first names, but an equal last name:
Example
<?php
function familyName($fname) {
echo "$fname Refsnes.<br>";
}
n
familyName("Jani");
familyName("Hege");
g.i
familyName("Stale");
familyName("Kai Jim");
familyName("Borge");
n
?>
eri
Example
<?php
e
gin
function familyName($fname, $year) {
echo "$fname Refsnes. Born in $year <br>";
}
en
familyName("Hege", "1975");
familyName("Stale", "1978");
familyName("Kai Jim", "1983");
arn
?>
The following example shows how to use a default parameter. If we call the function setHeight() without
arguments it takes the default value as argument:
w.
Example
ww
<?php
function setHeight($minheight = 50) {
echo "The height is : $minheight <br>";
}
setHeight(350);
setHeight(); // will use the default value of 50
setHeight(135);
setHeight(80);
?>
Example
n
<?php
function sum($x, $y) {
g.i
$z = $x + $y;
return $z;
}
n
echo "5 + 10 = " . sum(5, 10) . "<br>";
eri
echo "7 + 13 = " . sum(7, 13) . "<br>";
echo "2 + 4 = " . sum(2, 4);
?>
Connecting to a Database e
gin
PHP 5 and later can work with a MySQL database using:
PDO will work on 12 different database systems, where as MySQLi will only work with MySQL
databases.
w.
So, if you have to switch your project to use another database, PDO makes the process easy. You only
have to change the connection string and a few queries. With MySQLi, you will need to rewrite the
ww
Both support Prepared Statements. Prepared Statements protect from SQL injection, and are very
important for web application security.
In this, and in the following chapters we demonstrate three ways of working with PHP and MySQL:
MySQLi (object-oriented)
MySQLi (procedural)
PDO
MySQLi Installation
For Linux and Windows: The MySQLi extension is automatically installed in most cases, when php5
mysql package is installed.
n
g.i
PDO Installation
n
Open a Connection to MySQL
eri
Before we can access data in the MySQL database, we need to be able to connect to the server:
// Create connection
$conn = new mysqli($servername, $username, $password);
arn
// Check connection
if ($conn->connect_error) {
Le
?>
<?php
$servername = "localhost";
$username = "username";
$password = "password";
// Create connection
$conn = mysqli_connect($servername, $username, $password);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
echo "Connected successfully";
?>
Example (PDO)
<?php
$servername = "localhost";
n
$username = "username";
g.i
$password = "password";
try {
n
$conn = new PDO("mysql:host=$servername;dbname=myDB", $username, $password);
// set the PDO error mode to exception
eri
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
echo "Connected successfully";
}
catch(PDOException $e) e
gin
{
echo "Connection failed: " . $e->getMessage();
}
?>
en
The connection will be closed automatically when the script ends. To close the connection before, use
the following:
Le
$conn->close();
w.
mysqli_close($conn);
Example (PDO)
$conn = null;
Using Cookies
A cookie is often used to identify a user. A cookie is a small file that the server embeds on the user's
computer. Each time the same computer requests a page with a browser, it will send the cookie too. With
PHP, you can both create and retrieve cookie values.
n
Create Cookies With PHP
g.i
A cookie is created with the setcookie() function.
Syntax
n
eri
setcookie(name, value, expire, path, domain, secure, httponly);
Only the name parameter is required. All other parameters are optional.
We then retrieve the value of the cookie "user" (using the global variable $_COOKIE). We also use the
isset() function to find out if the cookie is set:
arn
Example
<?php
$cookie_name = "user";
Le
<html>
<body>
ww
<?php
if(!isset($_COOKIE[$cookie_name])) {
echo "Cookie named '" . $cookie_name . "' is not set!";
} else {
echo "Cookie '" . $cookie_name . "' is set!<br>";
echo "Value is: " . $_COOKIE[$cookie_name];
}
?>
</body>
</html>
To modify a cookie, just set (again) the cookie using the setcookie() function:
Example
n
<?php
g.i
$cookie_name = "user";
$cookie_value = "Alex Porter";
setcookie($cookie_name, $cookie_value, time() + (86400 * 30), "/");
n
?>
<html>
eri
<body>
<?php
if(!isset($_COOKIE[$cookie_name])) {
e
gin
echo "Cookie named '" . $cookie_name . "' is not set!";
} else {
echo "Cookie '" . $cookie_name . "' is set!<br>";
echo "Value is: " . $_COOKIE[$cookie_name];
en
}
?>
arn
</body>
</html>
Delete a Cookie
Le
To delete a cookie, use the setcookie() function with an expiration date in the past:
Example
w.
<?php
// set the expiration date to one hour ago
ww
<?php
echo "Cookie 'user' is deleted.";
?>
</body>
</html>
The following example creates a small script that checks whether cookies are enabled. First, try to create
n
a test cookie with the setcookie() function, then count the $_COOKIE array variable:
g.i
Example
<?php
n
setcookie("test_cookie", "test", time() + 3600, '/');
?>
eri
<html>
<body>
<?php
e
gin
if(count($_COOKIE) > 0) {
echo "Cookies are enabled.";
} else {
echo "Cookies are disabled.";
en
}
?>
arn
</body>
</html>
Le
Regular Expressions
w.
Regular expressions are nothing more than a sequence or pattern of characters itself. They provide the
foundation for pattern-matching functionality.
ww
Using regular expression you can search a particular string inside a another string, you can replace one
string by another string and you can split a string into many chunks.
PHP offers functions specific to two sets of regular expression functions, each corresponding to a
certain type of regular expression. You can use any of them based on your comfort.
The structure of a POSIX regular expression is not dissimilar to that of a typical arithmetic expression:
various elements (operators) are combined to form more complex expressions.
The simplest regular expression is one that matches a single character, such as g, inside strings such as
n
g, haggle, or bag.
g.i
Lets give explaination for few concepts being used in POSIX regular expression. After that we will
introduce you wih regular expression related functions.
n
Brackets
eri
Brackets ([]) have a special meaning when used in the context of regular expressions. They are used to
find a range of characters.
Expression Description
e
gin
[0-9] It matches any decimal digit from 0 through 9.
The ranges shown above are general; you could also use the range [0-3] to match any decimal digit
ranging from 0 through 3, or the range [b-v] to match any lowercase character ranging from b through v.
Le
Quantifiers
The frequency or position of bracketed character sequences and single characters can be denoted by a
w.
special character. Each pecial character having a specific connotation. The +, *, ?, {int. range}, and $
flags all follow a character sequence.
ww
Expression Description
p? It matches any string containing zero or more p's. This is just an alternative way to use p*.
n
g.i
Examples
Following examples will clear your concepts about matching chracters.
n
Expression Description
eri
[^a-zA-Z] It matches any string not containing any of the characters ranging from a through z and A
through Z.
p.p e
It matches any string containing p, followed by any character, in turn followed by another p.
gin
^.{2}$ It matches any string containing exactly two characters.
p(hp)* It matches any string containing a p followed by zero or more instances of the sequence hp.
arn
classes, are available. Character classes specify an entire range of characters, for example, the alphabet
or an integer set:
Expression Description
w.
[[:alnum:]] It matches any string containing alphanumeric characters aA through zZ and 0 through 9.
Function Description
ereg() The ereg() function searches a string specified by string for a string specified by pattern,
returning true if the pattern is found, and false otherwise.
ereg_replace() The ereg_replace() function searches for string specified by pattern and replaces pattern
with replacement if found.
eregi() The eregi() function searches throughout a string specified by pattern for a string specified
n
by string. The search is not case sensitive.
g.i
eregi_replace() The eregi_replace() function operates exactly like ereg_replace(), except that the search
for pattern in string is not case sensitive.
n
split() The split() function will divide a string into various elements, the boundaries of each
eri
element based on the occurrence of pattern in string.
spliti() The spliti() function operates exactly in the same manner as its sibling split(), except that
e
it is not case sensitive.
gin
sql_regcase() The sql_regcase() function can be thought of as a utility function, converting each
character in the input parameter string into a bracketed expression containing two
characters.
en
Perl-style regular expressions are similar to their POSIX counterparts. The POSIX syntax can be used
almost interchangeably with the Perl-style regular expression functions. In fact, you can use any of the
quantifiers introduced in the previous POSIX section.
Le
Lets give explaination for few concepts being used in PERL regular expressions. After that we will
introduce you wih regular expression related functions.
w.
Metacharacters
A metacharacter is simply an alphabetical character preceded by a backslash that acts to give the
ww
Character Description
. a single character
n
[^aeiou] matches a single character outside the given set
g.i
(foo|bar|baz) matches any of the alternatives specified
Modifiers
n
Several modifiers are available that can make your work with regexps much easier, like case sensitivity,
eri
searching in multiple lines etc.
Modifier Description
i Makes the match case insensitive e
gin
m Specifies that if the string has newline or carriage
return characters, the ^ and $ operators will now
match against a newline boundary, instead of a
en
string boundary
o Evaluates the expression only once
arn
PHP offers following functions for searching strings using Perl-compatible regular expressions:
Function Description
ww
preg_match() The preg_match() function searches string for pattern, returning true if pattern exists,
and false otherwise.
preg_replace() The preg_replace() function operates just like ereg_replace(), except that regular
expressions can be used in the pattern and replacement input parameters.
preg_split() The preg_split() function operates exactly like split(), except that regular expressions
are accepted as input parameters for pattern.
preg_grep() The preg_grep() function searches all elements of input_array, returning all elements
matching the regexp pattern.
XML
n
XML is a markup language that looks a lot like HTML. An XML document is plain text and contains
g.i
tags delimited by < and >.There are two big differences between XML and HTML:
XML doesn't define a specific set of tags you must use.
n
XML is extremely picky about document structure.
eri
XML gives you a lot more freedom than HTML. HTML has a certain set of tags: the <a></a> tags
surround a link, the <p> startsa paragraph and so on. An XML document, however, can use any tags you
e
want. Put <rating></rating> tags around a movie rating, >height></height> tags around someone's
gin
height. Thus XML gives you option to device your own tags.
XML is very strict when it comes to document structure. HTML lets you play fast and loose with some
en
opening and closing tags. BUt this is not the case with XML.
<ul>
<li>Braised Sea Cucumber
Le
</ul>
This is not a valid XML document because there are no closing </li> tags to match up with the three
ww
opening <li> tags. Every opened tag in an XML document must be closed.
</ul>
To create a SimpleXML object from an XML document stored in a string, pass the string
to simplexml_load_string( ). It returns a SimpleXML object.
n
g.i
Example
Try out following example:
n
<?php
eri
$channel =<<<_XML_
<channel>
e
gin
<title>What's For Dinner<title>
<link>http://menu.example.com/<link>
<description>Choose what to eat tonight.</description>
en
</channel>
_XML_;
arn
$xml = simplexml_load_string($channel);
Le
?>
The What's For Dinner channel is available at http://menu.example.com/. The description is "Choose
what to eat tonight."
NOTE: You can use function simplexml_load_file( filename) if you have XML content in a file.
For a complete detail of XML parsing function check PHP Function Reference.
SimpleXML is good for parsing existing XML documents, but you can't use it to create a new one from
scratch.
The easiest way to generate an XML document is to build a PHP array whose structure mirrors that of
the XML document and then to iterate through the array, printing each element with appropriate
formatting.
Example
n
Try out following example:
g.i
<?php
n
$channel = array('title' => "What's For Dinner",
eri
'link' => 'http://menu.example.com/',
'description' => 'Choose what to eat tonight.');
print "<channel>\n"; e
gin
foreach ($channel as $element => $content) {
print " <$element>";
en
print htmlentities($content);
print "</$element>\n";
arn
}
print "</channel>";
?>
Le
<channel>
<title>What's For Dinner</title>
ww
<link>http://menu.example.com/</link>
<description>Choose what to eat tonight.</description>
</channel></html>
DOM
A DOM (Document Object Model) defines a standard way for accessing and manipulating documents.
The XML DOM defines a standard way for accessing and manipulating XML documents.
All elements can be accessed through the DOM tree. Their content (text and attributes) can be modified or
deleted, and new elements can be created. The elements, their text, and their attributes are all known as
nodes.
You can learn more about the XML DOM in our XML DOM tutorial.
n
The HTML DOM
g.i
The HTML DOM defines a standard way for accessing and manipulating HTML documents.
n
You can learn more about the HTML DOM in our JavaScript tutorial.
Example
<html>
arn
<body>
<h1>W3Schools Internal Note</h1>
<div>
<b>To:</b> <span id="to"></span><br />
Le
<script>
if (window.XMLHttpRequest)
ww
xmlDoc=xmlhttp.responseXML;
document.getElementById("to").innerHTML=
xmlDoc.getElementsByTagName("to")[0].childNodes[0].nodeValue;
document.getElementById("from").innerHTML=
xmlDoc.getElementsByTagName("from")[0].childNodes[0].nodeValue;
document.getElementById("message").innerHTML=
xmlDoc.getElementsByTagName("body")[0].childNodes[0].nodeValue;
</script>
n
</body>
g.i
</html>
n
Load an XML String - Cross-browser Example
eri
The following example parses an XML string into an XML DOM object and then extracts some info from
it with a JavaScript:
Example
e
gin
<html>
<body>
<h1>W3Schools Internal Note</h1>
<div>
en
</div>
<script>
Le
txt="<note>";
txt=txt+"<to>Tove</to>";
txt=txt+"<from>Jani</from>";
w.
txt=txt+"<heading>Reminder</heading>";
txt=txt+"<body>Don't forget me this weekend!</body>";
txt=txt+"</note>";
ww
if (window.DOMParser)
{
parser=new DOMParser();
xmlDoc=parser.parseFromString(txt,"text/xml");
}
else // Internet Explorer
{
xmlDoc=new ActiveXObject("Microsoft.XMLDOM");
xmlDoc.async=false;
xmlDoc.loadXML(txt);
}
document.getElementById("to").innerHTML=
xmlDoc.getElementsByTagName("to")[0].childNodes[0].nodeValue;
document.getElementById("from").innerHTML=
xmlDoc.getElementsByTagName("from")[0].childNodes[0].nodeValue;
document.getElementById("message").innerHTML=
n
xmlDoc.getElementsByTagName("body")[0].childNodes[0].nodeValue;
</script>
g.i
</body>
</html>
n
Document Type Definition
eri
An XML document with correct syntax is called "Well Formed".
An XML document validated against a DTD is "Well Formed" and "Valid".
e
gin
Valid XML Documents
A "Valid" XML document is a "Well Formed" XML document, which also conforms to the rules of a
DTD:
en
<to>Tove</to>
<from>Jani</from>
<heading>Reminder</heading>
Le
The DOCTYPE declaration, in the example above, is a reference to an external DTD file. The content of
w.
XML DTD
The purpose of a DTD is to define the structure of an XML document. It defines the structure with a list
of legal elements:
<!DOCTYPE note
[
<!ELEMENT note (to,from,heading,body)>
<!ELEMENT to (#PCDATA)>
!DOCTYPE note defines that the root element of the document is note
!ELEMENT note defines that the note element must contain four elements: "to, from, heading,
body"
n
!ELEMENT to defines the to element to be of type "#PCDATA"
g.i
!ELEMENT from defines the from element to be of type "#PCDATA"
!ELEMENT heading defines the heading element to be of type "#PCDATA"
!ELEMENT body defines the body element to be of type "#PCDATA"
n
eri
Using DTD for Entity Declaration
e
A doctype declaration can also be used to define special characters and character strings, used in the
gin
document:
Example
<!DOCTYPE note [
arn
<note>
<to>Tove</to>
w.
<from>Jani</from>
<heading>Reminder</heading>
<body>Don't forget me this weekend!</body>
ww
<footer>&writer; ©right;</footer>
</note>
With a DTD, independent groups of people can agree on a standard for interchanging data.
With a DTD, you can verify that the data you receive from the outside world is valid.
XSLT (eXtensible Stylesheet Language Transformations) is the recommended style sheet language for
XML.
XSLT is far more sophisticated than CSS. With XSLT you can add/remove elements and attributes to or
from the output file. You can also rearrange and sort elements, perform tests and make decisions about
which elements to hide and display, and a lot more.
XSLT Example
n
We will use the following XML document:
g.i
<?xml version="1.0" encoding="UTF-8"?>
<breakfast_menu>
n
<food>
eri
<name>Belgian Waffles</name>
<price>$5.95</price>
<description>Two of our famous Belgian Waffles with plenty of real maple syrup</description>
<calories>650</calories> e
gin
</food>
<food>
<name>Strawberry Belgian Waffles</name>
en
<price>$7.95</price>
<description>Light Belgian waffles covered with strawberries and whipped cream</description>
<calories>900</calories>
arn
</food>
<food>
Le
cream</description>
<calories>900</calories>
</food>
ww
<food>
<name>French Toast</name>
<price>$4.50</price>
<description>Thick slices made from our homemade sourdough bread</description>
<calories>600</calories>
</food>
<food>
<name>Homestyle Breakfast</name>
<price>$6.95</price>
<description>Two eggs, bacon or sausage, toast, and our ever-popular hash browns</description>
<calories>950</calories>
</food>
</breakfast_menu>
n
Example XSLT Stylesheet:
g.i
<?xml version="1.0" encoding="UTF-8"?>
<html xsl:version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<body style="font-family:Arial;font-size:12pt;background-color:#EEEEEE">
n
<xsl:for-each select="breakfast_menu/food">
eri
<div style="background-color:teal;color:white;padding:4px">
<span style="font-weight:bold"><xsl:value-of select="name"/> - </span>
<xsl:value-of select="price"/>
</div>
e
<div style="margin-left:20px;margin-bottom:1em;font-size:10pt">
gin
<p>
<xsl:value-of select="description"/>
<span style="font-style:italic"> (<xsl:value-of select="calories"/> calories per serving)</span>
en
</p>
</div>
</xsl:for-each>
arn
</body>
</html>
Le
w.
ww
Unit – IV
PHP
When working with data values in PHP, we need some convenient way to store these values so that we
can easily access them and make reference to them whenever necessary. This is where PHP variables
come in. It is often useful to think of variables as computer memory locations where data is to be stored.
When declaring a variable in PHP it is assigned a name that can be used to reference it in other locations
in the PHP script. The value of the variable can be accessed, the value can be changed, and the type of
n
variable can be altered all by referencing the name assigned at variable creation time.
g.i
Naming and Creating a Variable in PHP
Before learning how to declare a variable in PHP it is first important to understand some rules about
n
variable names (also known as variable naming conventions). All PHP variable names must be pre-fixed
eri
with a $. It is this prefix which informs the PHP pre-processor that it is dealing with a variable. The first
character of the name must be either a letter or an underscore (_). The remaining characters must
comprise only of letters, numbers or underscores. All other characters are deemed to be invalid for use in
e
a variable name. Let's look at some valid and invalid PHP variable names:
gin
$_myName // valid
$myName // valid
$__myvar // valid
en
$myVar21 // valid
$_1Big // invalid - underscore must be followed by a letter
$1Big // invalid - must begin with a letter or underscore
arn
Variable names in PHP are case-sensitive. This means that PHP considers $_myVariable to be a
completely different variable to one that is named ''$_myvariable.
Values are assigned to variables using the PHP assignment operator. The assignment operator is
ww
represented by the = sign. To assign a value to a variable therefore, the variable name is placed on the
left of the expression, followed by the assignment operator. The value to be assigned is then placed to
the right of the assignment operator. Finally the line, as with all PHP code statements, is terminated with
a semi-colon (;).
$myShape = "Circle";
We have now declared a variable with the name myShape and assigned a string value to it of "Circe". We
can similarly declare a variable to contain an integer value:
$numberOfShapes = 6;
The above assignment creates a variable named numberOfShapes and assigns it a numeric value of 6.
Once a variable has been created, the value assigned to that variable can be changed at any time using
the same assignment operator approach:
n
<?php
$numberOfShapes = 6; // Set initial values
g.i
$myShape = "Circle";
$numberOfShapes = 7; // Change the initial values to new values
$myShape = "Square";
n
eri
?>
e
gin
Now that we have learned how to create a variable and assign an initial value to it we now need to look
at how to access the value currently assigned to a variable. In practice, accessing a variable is as simple
as referencing the name it was given when it was created.
en
For example, if we want to display the value which we assigned to our numberOfShapes variable we can
simply reference it in our echo command:
arn
<?php
echo "The number of shapes is $numberOfShapes.";
?>
Le
<?php
echo "$myShape is the value of the current shape.";
?>
The examples we have used for accessing variable values are straightforward because we have always
had a space character after the variable name. The question arises as to what should be done if we need
to put other characters immediately after the variable name. For example:
<?php
Unfortunately PHP will see the th on the end of the $numberOfShapes variable name as being part of the
name. It will then try to output the value of a variable called $numberOfShapesth, which does not exist.
n
This results in nothing being displayed for this variable:
g.i
The Circle is the shape.
Fortunately we can get around this issue by placing braces ({ and }) around the variable name to
n
distinguish the name from any other trailing characters:
eri
<?php
echo "The Circle is the ${numberOfShapes}th shape";
?>
e
gin
To give us the desired output:
PHP comes standard with many functions and constructs. There are also functions that require specific
PHP extensions compiled in, otherwise fatal "undefined function" errors will appear. For example, to use
image functions such as imagecreatetruecolor(), PHP must be compiled with GD support. Or, to use
mysql_connect(), PHP must be compiled with MySQL support. There are many core functions that are
Le
included in every version of PHP, such as the string and variable functions. A call to phpinfo() or
get_loaded_extensions() will show which extensions are loaded into PHP. Also note that many
extensions are enabled by default and that the PHP manual is split up by extension. See the
w.
configuration, installation, and individual extension chapters, for information on how to set up PHP.
ww
Reading and understanding a function's prototype is explained within the manual section titled how to
read a function definition. It's important to realize what a function returns or if a function works directly
on a passed in value. For example, str_replace() will return the modified string while usort() works on
the actual passed in variable itself. Each manual page also has specific information for each function like
information on function parameters, behavior changes, return values for both success and failure, and
availability information. Knowing these important (yet often subtle) differences is crucial for writing
correct PHP code.
Besides the built-in PHP functions, we can create our own functions.
A function is a block of statements that can be used repeatedly in a program.
A function will not execute immediately when a page loads.
A function will be executed by a call to the function.
n
Create a User Defined Function in PHP
g.i
A user defined function declaration starts with the word "function":
Syntax
n
function functionName() {
eri
code to be executed;
}
e
In the example below, we create a function named "writeMsg()". The opening curly brace ( { ) indicates
gin
the beginning of the function code and the closing curly brace ( } ) indicates the end of the function. The
function outputs "Hello world!". To call the function, just write its name:
Example
en
<?php
function writeMsg() {
arn
Information can be passed to functions through arguments. An argument is just like a variable.
ww
Arguments are specified after the function name, inside the parentheses. You can add as many arguments
as you want, just seperate them with a comma.
The following example has a function with one argument ($fname). When the familyName() function is
called, we also pass along a name (e.g. Jani), and the name is used inside the function, which outputs
several different first names, but an equal last name:
Example
<?php
function familyName($fname) {
echo "$fname Refsnes.<br>";
}
n
familyName("Jani");
familyName("Hege");
g.i
familyName("Stale");
familyName("Kai Jim");
familyName("Borge");
n
?>
eri
Example
<?php
e
gin
function familyName($fname, $year) {
echo "$fname Refsnes. Born in $year <br>";
}
en
familyName("Hege", "1975");
familyName("Stale", "1978");
familyName("Kai Jim", "1983");
arn
?>
The following example shows how to use a default parameter. If we call the function setHeight() without
arguments it takes the default value as argument:
w.
Example
ww
<?php
function setHeight($minheight = 50) {
echo "The height is : $minheight <br>";
}
setHeight(350);
setHeight(); // will use the default value of 50
setHeight(135);
setHeight(80);
?>
Example
n
<?php
function sum($x, $y) {
g.i
$z = $x + $y;
return $z;
}
n
echo "5 + 10 = " . sum(5, 10) . "<br>";
eri
echo "7 + 13 = " . sum(7, 13) . "<br>";
echo "2 + 4 = " . sum(2, 4);
?>
Connecting to a Database e
gin
PHP 5 and later can work with a MySQL database using:
PDO will work on 12 different database systems, where as MySQLi will only work with MySQL
databases.
w.
So, if you have to switch your project to use another database, PDO makes the process easy. You only
have to change the connection string and a few queries. With MySQLi, you will need to rewrite the
ww
Both support Prepared Statements. Prepared Statements protect from SQL injection, and are very
important for web application security.
In this, and in the following chapters we demonstrate three ways of working with PHP and MySQL:
MySQLi (object-oriented)
MySQLi (procedural)
PDO
MySQLi Installation
For Linux and Windows: The MySQLi extension is automatically installed in most cases, when php5
mysql package is installed.
n
g.i
PDO Installation
n
Open a Connection to MySQL
eri
Before we can access data in the MySQL database, we need to be able to connect to the server:
// Create connection
$conn = new mysqli($servername, $username, $password);
arn
// Check connection
if ($conn->connect_error) {
Le
?>
<?php
$servername = "localhost";
$username = "username";
$password = "password";
// Create connection
$conn = mysqli_connect($servername, $username, $password);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
echo "Connected successfully";
?>
Example (PDO)
<?php
$servername = "localhost";
n
$username = "username";
g.i
$password = "password";
try {
n
$conn = new PDO("mysql:host=$servername;dbname=myDB", $username, $password);
// set the PDO error mode to exception
eri
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
echo "Connected successfully";
}
catch(PDOException $e) e
gin
{
echo "Connection failed: " . $e->getMessage();
}
?>
en
The connection will be closed automatically when the script ends. To close the connection before, use
the following:
Le
$conn->close();
w.
mysqli_close($conn);
Example (PDO)
$conn = null;
Using Cookies
A cookie is often used to identify a user. A cookie is a small file that the server embeds on the user's
computer. Each time the same computer requests a page with a browser, it will send the cookie too. With
PHP, you can both create and retrieve cookie values.
n
Create Cookies With PHP
g.i
A cookie is created with the setcookie() function.
Syntax
n
eri
setcookie(name, value, expire, path, domain, secure, httponly);
Only the name parameter is required. All other parameters are optional.
We then retrieve the value of the cookie "user" (using the global variable $_COOKIE). We also use the
isset() function to find out if the cookie is set:
arn
Example
<?php
$cookie_name = "user";
Le
<html>
<body>
ww
<?php
if(!isset($_COOKIE[$cookie_name])) {
echo "Cookie named '" . $cookie_name . "' is not set!";
} else {
echo "Cookie '" . $cookie_name . "' is set!<br>";
echo "Value is: " . $_COOKIE[$cookie_name];
}
?>
</body>
</html>
To modify a cookie, just set (again) the cookie using the setcookie() function:
Example
n
<?php
g.i
$cookie_name = "user";
$cookie_value = "Alex Porter";
setcookie($cookie_name, $cookie_value, time() + (86400 * 30), "/");
n
?>
<html>
eri
<body>
<?php
if(!isset($_COOKIE[$cookie_name])) {
e
gin
echo "Cookie named '" . $cookie_name . "' is not set!";
} else {
echo "Cookie '" . $cookie_name . "' is set!<br>";
echo "Value is: " . $_COOKIE[$cookie_name];
en
}
?>
arn
</body>
</html>
Delete a Cookie
Le
To delete a cookie, use the setcookie() function with an expiration date in the past:
Example
w.
<?php
// set the expiration date to one hour ago
ww
<?php
echo "Cookie 'user' is deleted.";
?>
</body>
</html>
The following example creates a small script that checks whether cookies are enabled. First, try to create
n
a test cookie with the setcookie() function, then count the $_COOKIE array variable:
g.i
Example
<?php
n
setcookie("test_cookie", "test", time() + 3600, '/');
?>
eri
<html>
<body>
<?php
e
gin
if(count($_COOKIE) > 0) {
echo "Cookies are enabled.";
} else {
echo "Cookies are disabled.";
en
}
?>
arn
</body>
</html>
Le
Regular Expressions
w.
Regular expressions are nothing more than a sequence or pattern of characters itself. They provide the
foundation for pattern-matching functionality.
ww
Using regular expression you can search a particular string inside a another string, you can replace one
string by another string and you can split a string into many chunks.
PHP offers functions specific to two sets of regular expression functions, each corresponding to a
certain type of regular expression. You can use any of them based on your comfort.
The structure of a POSIX regular expression is not dissimilar to that of a typical arithmetic expression:
various elements (operators) are combined to form more complex expressions.
The simplest regular expression is one that matches a single character, such as g, inside strings such as
n
g, haggle, or bag.
g.i
Lets give explaination for few concepts being used in POSIX regular expression. After that we will
introduce you wih regular expression related functions.
n
Brackets
eri
Brackets ([]) have a special meaning when used in the context of regular expressions. They are used to
find a range of characters.
Expression Description
e
gin
[0-9] It matches any decimal digit from 0 through 9.
The ranges shown above are general; you could also use the range [0-3] to match any decimal digit
ranging from 0 through 3, or the range [b-v] to match any lowercase character ranging from b through v.
Le
Quantifiers
The frequency or position of bracketed character sequences and single characters can be denoted by a
w.
special character. Each pecial character having a specific connotation. The +, *, ?, {int. range}, and $
flags all follow a character sequence.
ww
Expression Description
p? It matches any string containing zero or more p's. This is just an alternative way to use p*.
n
g.i
Examples
Following examples will clear your concepts about matching chracters.
n
Expression Description
eri
[^a-zA-Z] It matches any string not containing any of the characters ranging from a through z and A
through Z.
p.p e
It matches any string containing p, followed by any character, in turn followed by another p.
gin
^.{2}$ It matches any string containing exactly two characters.
p(hp)* It matches any string containing a p followed by zero or more instances of the sequence hp.
arn
classes, are available. Character classes specify an entire range of characters, for example, the alphabet
or an integer set:
Expression Description
w.
[[:alnum:]] It matches any string containing alphanumeric characters aA through zZ and 0 through 9.
Function Description
ereg() The ereg() function searches a string specified by string for a string specified by pattern,
returning true if the pattern is found, and false otherwise.
ereg_replace() The ereg_replace() function searches for string specified by pattern and replaces pattern
with replacement if found.
eregi() The eregi() function searches throughout a string specified by pattern for a string specified
n
by string. The search is not case sensitive.
g.i
eregi_replace() The eregi_replace() function operates exactly like ereg_replace(), except that the search
for pattern in string is not case sensitive.
n
split() The split() function will divide a string into various elements, the boundaries of each
eri
element based on the occurrence of pattern in string.
spliti() The spliti() function operates exactly in the same manner as its sibling split(), except that
e
it is not case sensitive.
gin
sql_regcase() The sql_regcase() function can be thought of as a utility function, converting each
character in the input parameter string into a bracketed expression containing two
characters.
en
Perl-style regular expressions are similar to their POSIX counterparts. The POSIX syntax can be used
almost interchangeably with the Perl-style regular expression functions. In fact, you can use any of the
quantifiers introduced in the previous POSIX section.
Le
Lets give explaination for few concepts being used in PERL regular expressions. After that we will
introduce you wih regular expression related functions.
w.
Metacharacters
A metacharacter is simply an alphabetical character preceded by a backslash that acts to give the
ww
Character Description
. a single character
n
[^aeiou] matches a single character outside the given set
g.i
(foo|bar|baz) matches any of the alternatives specified
Modifiers
n
Several modifiers are available that can make your work with regexps much easier, like case sensitivity,
eri
searching in multiple lines etc.
Modifier Description
i Makes the match case insensitive e
gin
m Specifies that if the string has newline or carriage
return characters, the ^ and $ operators will now
match against a newline boundary, instead of a
en
string boundary
o Evaluates the expression only once
arn
PHP offers following functions for searching strings using Perl-compatible regular expressions:
Function Description
ww
preg_match() The preg_match() function searches string for pattern, returning true if pattern exists,
and false otherwise.
preg_replace() The preg_replace() function operates just like ereg_replace(), except that regular
expressions can be used in the pattern and replacement input parameters.
preg_split() The preg_split() function operates exactly like split(), except that regular expressions
are accepted as input parameters for pattern.
preg_grep() The preg_grep() function searches all elements of input_array, returning all elements
matching the regexp pattern.
XML
n
XML is a markup language that looks a lot like HTML. An XML document is plain text and contains
g.i
tags delimited by < and >.There are two big differences between XML and HTML:
XML doesn't define a specific set of tags you must use.
n
XML is extremely picky about document structure.
eri
XML gives you a lot more freedom than HTML. HTML has a certain set of tags: the <a></a> tags
surround a link, the <p> startsa paragraph and so on. An XML document, however, can use any tags you
e
want. Put <rating></rating> tags around a movie rating, >height></height> tags around someone's
gin
height. Thus XML gives you option to device your own tags.
XML is very strict when it comes to document structure. HTML lets you play fast and loose with some
en
opening and closing tags. BUt this is not the case with XML.
<ul>
<li>Braised Sea Cucumber
Le
</ul>
This is not a valid XML document because there are no closing </li> tags to match up with the three
ww
opening <li> tags. Every opened tag in an XML document must be closed.
</ul>
To create a SimpleXML object from an XML document stored in a string, pass the string
to simplexml_load_string( ). It returns a SimpleXML object.
n
g.i
Example
Try out following example:
n
<?php
eri
$channel =<<<_XML_
<channel>
e
gin
<title>What's For Dinner<title>
<link>http://menu.example.com/<link>
<description>Choose what to eat tonight.</description>
en
</channel>
_XML_;
arn
$xml = simplexml_load_string($channel);
Le
?>
The What's For Dinner channel is available at http://menu.example.com/. The description is "Choose
what to eat tonight."
NOTE: You can use function simplexml_load_file( filename) if you have XML content in a file.
For a complete detail of XML parsing function check PHP Function Reference.
SimpleXML is good for parsing existing XML documents, but you can't use it to create a new one from
scratch.
The easiest way to generate an XML document is to build a PHP array whose structure mirrors that of
the XML document and then to iterate through the array, printing each element with appropriate
formatting.
Example
n
Try out following example:
g.i
<?php
n
$channel = array('title' => "What's For Dinner",
eri
'link' => 'http://menu.example.com/',
'description' => 'Choose what to eat tonight.');
print "<channel>\n"; e
gin
foreach ($channel as $element => $content) {
print " <$element>";
en
print htmlentities($content);
print "</$element>\n";
arn
}
print "</channel>";
?>
Le
<channel>
<title>What's For Dinner</title>
ww
<link>http://menu.example.com/</link>
<description>Choose what to eat tonight.</description>
</channel></html>
DOM
A DOM (Document Object Model) defines a standard way for accessing and manipulating documents.
The XML DOM defines a standard way for accessing and manipulating XML documents.
All elements can be accessed through the DOM tree. Their content (text and attributes) can be modified or
deleted, and new elements can be created. The elements, their text, and their attributes are all known as
nodes.
You can learn more about the XML DOM in our XML DOM tutorial.
n
The HTML DOM
g.i
The HTML DOM defines a standard way for accessing and manipulating HTML documents.
n
You can learn more about the HTML DOM in our JavaScript tutorial.
Example
<html>
arn
<body>
<h1>W3Schools Internal Note</h1>
<div>
<b>To:</b> <span id="to"></span><br />
Le
<script>
if (window.XMLHttpRequest)
ww
xmlDoc=xmlhttp.responseXML;
document.getElementById("to").innerHTML=
xmlDoc.getElementsByTagName("to")[0].childNodes[0].nodeValue;
document.getElementById("from").innerHTML=
xmlDoc.getElementsByTagName("from")[0].childNodes[0].nodeValue;
document.getElementById("message").innerHTML=
xmlDoc.getElementsByTagName("body")[0].childNodes[0].nodeValue;
</script>
n
</body>
g.i
</html>
n
Load an XML String - Cross-browser Example
eri
The following example parses an XML string into an XML DOM object and then extracts some info from
it with a JavaScript:
Example
e
gin
<html>
<body>
<h1>W3Schools Internal Note</h1>
<div>
en
</div>
<script>
Le
txt="<note>";
txt=txt+"<to>Tove</to>";
txt=txt+"<from>Jani</from>";
w.
txt=txt+"<heading>Reminder</heading>";
txt=txt+"<body>Don't forget me this weekend!</body>";
txt=txt+"</note>";
ww
if (window.DOMParser)
{
parser=new DOMParser();
xmlDoc=parser.parseFromString(txt,"text/xml");
}
else // Internet Explorer
{
xmlDoc=new ActiveXObject("Microsoft.XMLDOM");
xmlDoc.async=false;
xmlDoc.loadXML(txt);
}
document.getElementById("to").innerHTML=
xmlDoc.getElementsByTagName("to")[0].childNodes[0].nodeValue;
document.getElementById("from").innerHTML=
xmlDoc.getElementsByTagName("from")[0].childNodes[0].nodeValue;
document.getElementById("message").innerHTML=
n
xmlDoc.getElementsByTagName("body")[0].childNodes[0].nodeValue;
</script>
g.i
</body>
</html>
n
Document Type Definition
eri
An XML document with correct syntax is called "Well Formed".
An XML document validated against a DTD is "Well Formed" and "Valid".
e
gin
Valid XML Documents
A "Valid" XML document is a "Well Formed" XML document, which also conforms to the rules of a
DTD:
en
<to>Tove</to>
<from>Jani</from>
<heading>Reminder</heading>
Le
The DOCTYPE declaration, in the example above, is a reference to an external DTD file. The content of
w.
XML DTD
The purpose of a DTD is to define the structure of an XML document. It defines the structure with a list
of legal elements:
<!DOCTYPE note
[
<!ELEMENT note (to,from,heading,body)>
<!ELEMENT to (#PCDATA)>
!DOCTYPE note defines that the root element of the document is note
!ELEMENT note defines that the note element must contain four elements: "to, from, heading,
body"
n
!ELEMENT to defines the to element to be of type "#PCDATA"
g.i
!ELEMENT from defines the from element to be of type "#PCDATA"
!ELEMENT heading defines the heading element to be of type "#PCDATA"
!ELEMENT body defines the body element to be of type "#PCDATA"
n
eri
Using DTD for Entity Declaration
e
A doctype declaration can also be used to define special characters and character strings, used in the
gin
document:
Example
<!DOCTYPE note [
arn
<note>
<to>Tove</to>
w.
<from>Jani</from>
<heading>Reminder</heading>
<body>Don't forget me this weekend!</body>
ww
<footer>&writer; ©right;</footer>
</note>
With a DTD, independent groups of people can agree on a standard for interchanging data.
With a DTD, you can verify that the data you receive from the outside world is valid.
XSLT (eXtensible Stylesheet Language Transformations) is the recommended style sheet language for
XML.
XSLT is far more sophisticated than CSS. With XSLT you can add/remove elements and attributes to or
from the output file. You can also rearrange and sort elements, perform tests and make decisions about
which elements to hide and display, and a lot more.
XSLT Example
n
We will use the following XML document:
g.i
<?xml version="1.0" encoding="UTF-8"?>
<breakfast_menu>
n
<food>
eri
<name>Belgian Waffles</name>
<price>$5.95</price>
<description>Two of our famous Belgian Waffles with plenty of real maple syrup</description>
<calories>650</calories> e
gin
</food>
<food>
<name>Strawberry Belgian Waffles</name>
en
<price>$7.95</price>
<description>Light Belgian waffles covered with strawberries and whipped cream</description>
<calories>900</calories>
arn
</food>
<food>
Le
cream</description>
<calories>900</calories>
</food>
ww
<food>
<name>French Toast</name>
<price>$4.50</price>
<description>Thick slices made from our homemade sourdough bread</description>
<calories>600</calories>
</food>
<food>
<name>Homestyle Breakfast</name>
<price>$6.95</price>
<description>Two eggs, bacon or sausage, toast, and our ever-popular hash browns</description>
<calories>950</calories>
</food>
</breakfast_menu>
n
Example XSLT Stylesheet:
g.i
<?xml version="1.0" encoding="UTF-8"?>
<html xsl:version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<body style="font-family:Arial;font-size:12pt;background-color:#EEEEEE">
n
<xsl:for-each select="breakfast_menu/food">
eri
<div style="background-color:teal;color:white;padding:4px">
<span style="font-weight:bold"><xsl:value-of select="name"/> - </span>
<xsl:value-of select="price"/>
</div>
e
<div style="margin-left:20px;margin-bottom:1em;font-size:10pt">
gin
<p>
<xsl:value-of select="description"/>
<span style="font-style:italic"> (<xsl:value-of select="calories"/> calories per serving)</span>
en
</p>
</div>
</xsl:for-each>
arn
</body>
</html>
Le
w.
ww