Download JAVA

Document related concepts
no text concepts found
Transcript
JAVA
 Java is a programming language originally developed by




James Gosling at Sun Microsystems and released in 1995
as a core component of Sun Microsystems' Java platform.
The language derives much of its syntax from C and C++
but has a simpler object model and fewer low-level
facilities than either C or C++.
JAVA is Platform Independent Pure object oriented
Programming Language. It is also called Write Once Run
Anywhere(WORA).
Java is CASE SENSITIVE!!
Java applications are typically compiled to bytecode (class
file) that can run on any Java Virtual Machine (JVM)
regardless of computer architecture.
Sunil Kumar Sahu, Lecturer RCET
1
 Definition of Java (As per Sun MicroSystem)
A simple, Object Oriented, distributed, interpreted,
robust, secure architecture, neutral, protable, high
performance, mutithread, and dynamic language.
 In Java, comments are preceded by two
slashes (//) in a line, or enclosed
between /* and */ in one or multiple
lines.
Sunil Kumar Sahu, Lecturer RCET
2
History
 James Gosling began developing Java





beginning in 1991
It was first called “Project Green” and ‘Oak”
First developed for remote cable TV boxes
Sun Microsystems released to a select group
on the Website wicked.neato.org as Java 1.0 in
1995
James Naughton creates “HotJava” in 1995. it’s
a web,browser that lets you run “Applets”. The
entire browser is writteninJava.
Java currently released version JDK7 or Java
SE 7.0
Sunil Kumar Sahu, Lecturer RCET
3
History...
 1. JDK 1.0 (January 23, 1996)
 2. JDK 1.1 (February 19, 1997)
 3. J2SE 1.2 (December 8, 1998)
 4. J2SE 1.3 (May 8, 2000)
 5. J2SE 1.4 (February 6, 2002)
 6. J2SE 5.0 (September 30, 2004)
 7. Java SE 6 (December 11, 2006)
 8. Java SE 7 (July 28, 2011)
Sunil Kumar Sahu, Lecturer RCET
4
Version of java
Java Language vs Java Platform
- Current version of the language is JKD7
- Core language plus additional APIs is called the Java 2 platform
- Three versions of the Java 2 Platform, targeted at different uses
Java 2 Micro Edition (J2ME)
- Very small Java environment for smart cards, pages, phones,
and set-top boxes
- Subset of the standard Java libraries aimed at limited size and
processing power
Java 2 Standard Edition (J2SE)
- The basic platform, which this course will cover
Java 2 Enterprise Edition (J2EE)
- For business applications, web services, mission-critical systems
- Transaction processing, databases, distribution, replication
Sunil Kumar Sahu, Lecturer RCET
5
Java Basic Tools
Tool Name
javac
language.
Java
javadoc
Appletviewer
jar
Jdb
javah
javap
extcheck
Brief Description
The compiler for the Java programming
The launcher for Java applications.
API documentation generator.
Run and debug applets without a web browser.
Create and manage Java Archive (JAR) files.
The Java Debugger.
C header and stub generator. Used to write
native methods.
Class file disassembler
Utility to detect Jar conflicts.
Sunil Kumar Sahu, Lecturer RCET
6
JAVA vs JAVA SCRIPT
Java
 A complete programming language developed by Sun
 Can be used to develop either web based or stand-alone
software
 Many pre-created code libraries available
 For more complex and powerful programs
Java Script
 A small language that’s mostly used for web-based
applications (run through a web browser like Internet
Explorer, Firefox, Safari, Chrome)
 Good for programming simple special effects for your web
page e.g., roll-overs
Sunil Kumar Sahu, Lecturer RCET
7
How it works
Sunil Kumar Sahu, Lecturer RCET
8
Characteristics of Java
 Java Is Simple
 Java Is Object-Oriented
 Java Is Distributed
 Java Is Interpreted
Java is partially modeled on C++, but
greatly simplified and improved. Some
people refer to Java as "C++--" because it is
like C++ but with more functionality and
fewer negative aspects.
 Java Is Robust
 Java Is Secure
 Java Is Architecture



Neutral
Java Is Portable
Java's Performance
Java Is Multithreaded
Java Is Dynamic
Sunil Kumar Sahu, Lecturer RCET
9
Characteristics of Java
 Java Is Simple
 Java Is Object-Oriented
 Java Is Distributed
 Java Is Interpreted
 Java Is Robust
 Java Is Secure
 Java Is Architecture



Neutral
Java Is Portable
Java's Performance
Java Is Multithreaded
Java Is Dynamic
Java is inherently object-oriented.
Although many object-oriented
languages began strictly as procedural
languages, Java was designed from the
start to be object-oriented. Objectoriented programming (OOP) is a
popular programming approach that is
replacing traditional procedural
programming techniques.
One of the central issues in software
development is how to reuse code.
Object-oriented programming provides
great flexibility, modularity, clarity, and
reusability through encapsulation,
inheritance, and polymorphism.
Sunil Kumar Sahu, Lecturer RCET
10
Characteristics of Java
 Java Is Simple
 Java Is Object-Oriented
 Java Is Distributed
 Java Is Interpreted
 Java Is Robust
 Java Is Secure
 Java Is Architecture



Distributed computing involves several
computers working together on a
network. Java is designed to make
distributed computing (e.g. Web
Services) easy. Since networking
capability is inherently integrated into
Java, writing network programs is like
sending and receiving data to and from
a file.
Neutral
Java Is Portable
Java's Performance
Java Is Multithreaded
Java Is Dynamic
Sunil Kumar Sahu, Lecturer RCET
11
Characteristics of Java
 Java Is Simple
 Java Is Object-Oriented
 Java Is Distributed
 Java Is Interpreted
 Java Is Robust
 Java Is Secure
You need an interpreter to run Java
programs. The programs are compiled
into the Java Virtual Machine code
called bytecode. The bytecode is
machine-independent and can run on
any machine that has a Java interpreter,
which is part of the Java Virtual
Machine (JVM).
 Java Is Architecture



Neutral
Java Is Portable
Java's Performance
Java Is Multithreaded
Java Is Dynamic
Sunil Kumar Sahu, Lecturer RCET
12
Characteristics of Java
 Java Is Simple
 Java Is Object-Oriented
Java compilers can detect many
problems that would first show up at
execution time in other languages.
 Java Is Distributed
 Java Is Interpreted
 Java Is Robust
 Java Is Secure
 Java Is Architecture



Neutral
Java Is Portable
Java's Performance
Java Is Multithreaded
Java Is Dynamic
Java has eliminated certain types of
error-prone programming constructs
found in other languages.
Java has a runtime exception-handling
feature to provide programming
support for robustness.
Sunil Kumar Sahu, Lecturer RCET
13
Characteristics of Java
 Java Is Simple
 Java Is Object-Oriented
 Java Is Distributed
 Java Is Interpreted
 Java Is Robust
 Java Is Secure
Java implements several security
mechanisms to protect your system
against harm caused by stray programs.
 Java Is Architecture



Neutral
Java Is Portable
Java's Performance
Java Is Multithreaded
Java Is Dynamic
Sunil Kumar Sahu, Lecturer RCET
14
Characteristics of Java
 Java Is Simple
 Java Is Object-Oriented
 Java Is Distributed
 Java Is Interpreted
 Java Is Robust
 Java Is Secure
 Java Is Architecture



Neutral
Java Is Portable
Java's Performance
Java Is Multithreaded
Java Is Dynamic
Write once, run anywhere
With a Java Virtual Machine (JVM),
you can write one program that will
run on any platform.
Sunil Kumar Sahu, Lecturer RCET
15
Characteristics of Java
 Java Is Simple
 Java Is Object-Oriented
 Java Is Distributed
 Java Is Interpreted
 Java Is Robust
 Java Is Secure
 Java Is Architecture



Neutral
Java Is Portable
Java's Performance
Java Is Multithreaded
Java Is Dynamic
Because Java is architecture neutral,
Java programs are portable. They can
be run on any platform without being
recompiled.
Sunil Kumar Sahu, Lecturer RCET
16
Characteristics of Java
 Java Is Simple
 Java Is Object-Oriented
 Java Is Distributed
 Java Is Interpreted
 Java Is Robust
 Java Is Secure
 Java Is Architecture



Neutral
Java Is Portable
Java's Performance
Java Is Multithreaded
Java Is Dynamic
Because Java is architecture neutral,
Java programs are portable
(moveable). They can be run on any
platform without being recompiled.
Sunil Kumar Sahu, Lecturer RCET
17
Characteristics of Java
 Java Is Simple
 Java Is Object-Oriented
 Java Is Distributed
 Java Is Interpreted
 Java Is Robust
 Java Is Secure
 Java Is Architecture



Neutral
Java Is Portable
Java's Performance
Java Is Multithreaded
Java Is Dynamic
Multithread programming is smoothly
integrated in Java, whereas in other
languages you have to call procedures
specific to the operating system to enable
multithreading.
Sunil Kumar Sahu, Lecturer RCET
18
Characteristics of Java
 Java Is Simple
 Java Is Object-Oriented
 Java Is Distributed
 Java Is Interpreted
 Java Is Robust
 Java Is Secure
 Java Is Architecture



Neutral
Java Is Portable
Java's Performance
Java Is Multithreaded
Java Is Dynamic
Java was designed to adapt to an evolving
environment. New code can be loaded on the
fly without recompilation. There is no need for
developers to create, and for users to install,
major new software versions. New features can
be incorporated transparently as needed.
Sunil Kumar Sahu, Lecturer RCET
19
Creating ,Compiling and Executing Programs
On command line
javac file.java
Executing
Applications
java classname
Create/Modify Source Code
Source Code
Compile Source Code
i.e. javac Welcome.java
If compilation errors
Bytecode
Run Byteode
i.e. java Welcome
Result
If runtime errors or incorrect result
Sunil Kumar Sahu, Lecturer RCET
20
Simple Java Program
public class hello
{
public static void main (String args[])
{
System.out.println(“This is first java program“);
}
}
 Save as hello.java
Sunil Kumar Sahu, Lecturer RCET
21
How to compile and run java
Program
 Save java program with .java(dot java) extension
 Compile java program-
- javac hello.java
 Run java program- java hello
Output-
Sunil Kumar Sahu, Lecturer RCET
22
Writing Java Applet
 An applet is a Java program that runs in a Web browser and
embedded within an HTML page.
 All applets are subclass of APPLET,thus all applets must import
java.applet. Applets also import java.awt.
 Applets are not executed by the console-based java run time
interpreter,rather they are executed by either a web browser or
an applet viewer.
 There are some important differences between an applet and a
standalone Java application, including the following:
1.An applet is a Java class that extends the java.applet.Applet
class.
2.A main() method is not invoked on an applet, and an applet class
will not define main().
Sunil Kumar Sahu, Lecturer RCET
23
3.Applets are designed to be embedded within an HTML
page.
4.When a user views an HTML page that contains an applet,
the code for the applet is downloaded to the user's
machine.
5.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.
6.The JVM on the user's machine creates an instance of the
applet class and invokes various methods during the
applet's lifetime.
Sunil Kumar Sahu, Lecturer RCET
24
Example of Applet (SimpleApplet.java)
import java.awt.*;
import java.applet.*;
/*<applet code=“SimpleApplet” width=200 height=60>
</applet> */
public class SimpleApplet extends Applet
{
public void paint (Graphics g)
{
g.drawString("Hello World", 25, 50);
g.setColor(Color.red);
g.drawRect(80,100, 100, 50);
g.setColor(Color.blue);
g.drawOval(100,120, 90,95);
g.fillOval(200,90,30,35);
g.fillRect(300,120, 100, 150); }
}
Sunil Kumar Sahu, Lecturer RCET
25
 Description of Example-
This applet begins with two import statements.
 1)The first imports the Abstract Window Toolkit(AWT)
classes(import java.awt.*;).Applets interacts with the user
through the AWT not through the console based I/O based
classes.
 The AWT contains support for a window-based graphical
interface.
2)The second import statement (import java.applet.*;)
imports the applet package which contains the class
Applet.Every applet that you create must be a subclass of
Applet.
Sunil Kumar Sahu, Lecturer RCET
26
 The next line in the the program declares the class
SimpleApplet which is declared as public class,because
it will be accessed by the code outside the program.
 paint() method is defined by AWT and must be
overridden by the applet. Paint() is called each time that
the applet must redisplay its output.
 paint() method has one parameter of type Graphics that
contains graphics context,which describes the graphics
environment in which the applet is running.This context
is used whenever output to the applet is required.
 Inside paint() is a call to drawstring(),which is a
member of the Graphics class.This method outputs a
string beginning at the specified X,Y location.It has
following form..
void drawString(String message,int x,int y)
Sunil Kumar Sahu, Lecturer RCET
27
 After you enter the source code for SimpleApplet, compile
in the same way that you have been compiling
programs.However running SimpleApplet involves a
different process.
 There are two ways in which you can run an applet:
1)Using Java compatible web browser.
 To execute an applet in a web browser you need to write a
short HTML file that contains the appropriate APPLET
tag.
Example<applet code=“SimpleApplet” width=200 height=60>
</applet>
Sunil Kumar Sahu, Lecturer RCET
28
 After you create this file you can execute your browser
and then load this file,which causes SimpleApplet to be
executed.
2)Using an appletviewer such as standard SDK tool.
a)To Execute SimpleApplet with appletviewer, you may
also execute the HTML file shown earlier.
 For example if the preceding HTML file is called
Simple.html then the following command line will run
SimpleApplet:
C:\>appletviewer Simple.html
Command Prompt
Sunil Kumar Sahu, Lecturer RCET
29
Applet Window
b)The simple method is that you can include a comment
at the head of java source code file that contains
APPLET tag and run with appletviewer likeC:\>appletviewer SimpleApplet.java
Sunil Kumar Sahu, Lecturer RCET
30
Command Prompt
Applet Window
Sunil Kumar Sahu, Lecturer RCET
31
Life Cycle of Applet
 The Life Cycle of an applet consist of Four
methods and one method from
AWT(Abstract Window Toolkit)
1)init()
2)start()
3)stop()
4)destroy()
5)paint()
Sunil Kumar Sahu, Lecturer RCET
32
public void init( )
 This is the first method to execute
 It is an ideal place to initialize variables
 It is the best place to define the GUI Components (buttons,
text fields, scrollbars, etc.), lay them out, and add listeners to
them
 Almost every applet you ever write will have an init() method.
public void start( )





Not always needed
Called after init()
Called each time the page is loaded and restarted
Used mostly in conjunction with stop( )
start() and stop( ) are used when the Applet is doing timeconsuming calculations that you don’t want to continue when
the page is not in front
Sunil Kumar Sahu, Lecturer RCET
33
public void stop( )
 Not always needed
 Called when the browser leaves the page
 Called just before destroy( )
 Use stop( ) if the applet is doing heavy computation that
you don’t want to continue when the browser is on some
other page
 Used mostly in conjunction with start()
public void destroy( )
 Seldom needed
 Called after stop( )
 Use to explicitly release system resources (like threads)
 System resources are usually released automatically
Sunil Kumar Sahu, Lecturer RCET
34
public void 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.
Sunil Kumar Sahu, Lecturer RCET
35
Methods are called in this order
init()
start()
do some work
stop()
destroy()
• init and destroy are only
called once each
• start and stop are called
whenever the browser enters
and leaves the page
• do some work is code called
by your listeners
• paint is called when the
applet needs to be repainted
Sunil Kumar Sahu, Lecturer RCET
36
Exampleimport java.awt.*;
import java.applet.*;
/*<applet code="SimpleApplet 1" width=200 height=60> </ applet>*/
public class SimpleApplet1 extends Applet{
String out;
Public void init() {
setBackground(Color.blue);
setForeground(Color.yellow);
out=“init_”; }
public void start() {
out+=“start_”; }
public void stop() { }
public void destroy() { }
public void paint (Graphics g) {
out+=“paint_”;
g.drawString (out, 100, 10);
}}
Sunil Kumar Sahu, Lecturer RCET
37
OutputCommand Prompt
Applet Window
Sunil Kumar Sahu, Lecturer RCET
38
DOM(Document Object Model)
 The DOM defines a standard for accessing HTML and
XML documents.It is a platform and language neutral
interface that will allow programs and scripts to
dynamically access and update the content,structure
and style of documents.
 The document can be further processed and the
results of that processing can be incorporated back
into the presented page.
 DOM supports navigation in any direction that means
you can navigate to the parent,sibling,or the child
nodes from the current node.
 DOM is useful in cases where you need to access a
document multiple times.
Sunil Kumar Sahu, Lecturer RCET
39
 convert XML into a tree of objects .
 “random access” protocol(User accesses data by traversing
the tree)
 Can update XML document (insert/delete nodes).
 The API allows for constructing, accessing and
manipulating the structure and content of XML
documents.
DOM is divided into 3 parts:
1.The Core DOM:Includes objects that are present in both
XML and HTML documents.
2.The HTML DOM:Includes the HTML Objects.
3.The XML DOM:Includes the XML Objects.
Sunil Kumar Sahu, Lecturer RCET
40
 The following are levels of DOM:
Level 0: Supports an intermediate DOM,which existed
before the creation of DOM Level1.
For eg. the DHTML Object Model or the Netscape
intermediate DOM.
Level1: Includes the navigation of DOM document and
allows content manipulation.
Level2: Supports xml namespace,filtered views and events.
Level3: consist of the following 6 specification DOM Level3 Core
 DOM Level3 Load and Save
 DOM Level3 Xpath
 DOM Level3 Views and Formatting
 DOM Level3 Requirments
 DOM Level3 Validation
Sunil Kumar Sahu, Lecturer RCET
41
HTML DOM
 The HTML DOM defines a standard way for accessing and
manipulating HTML documents.
 The DOM presents an HTML document as a treestructure.
 The HTML DOM is W3C standard object model that
defines the objects and properties of all HTML elements
and the methods to access them.
 The HTML DOM is a standard for how to get,change,add
or delete HTML elements.
Sunil Kumar Sahu, Lecturer RCET
42
 HTML DOM presents an HTML document as a tree –
structure as shown belowDocument
Root Element
<html>
Element
head
Element
title
Element
body
Attribute
“href”
Text
“My Text”
Element
<a>
Text
“My link”
Element
<h1>
Text
“My Header”
Fig. Displaying Html document as Tree Structure
Sunil Kumar Sahu, Lecturer RCET
43
Nodes:
 Every element in an Html page represents a DOM node. The
nodes are related to each other through the parent child
relationship.
 All nodes in a document make a DOM tree which describes
the relationship among elements.
 There are several types of nodes1)Element node -Represents the basic building blocks of
documents known as elements.These elements can contain
other elements such as HTML,HEAD,BODY,A,H1 etc.
2)Text Node -Represents the content contained in element
nodes such as title1, link1 and header1 etc.
3)Attribute nodes -Provides more information about
elements.Attribute node are always contained in Element
nodes.eg href is an Attribute node which is contained within
the BODY element.
Sunil Kumar Sahu, Lecturer RCET
44
Objects:
 When an html document is loaded into a web browser it
becomes a document object.In the same way Element
object represents an html element.
 Html elements have attributes which are represented bt
Attr objects.
Events: HTML DOM also contains events that allow JavaScript to
register different event handlers on elements in an html
document.These events can be mouse events,keyboard
events,frame events,object events,or form events.
 Html DOM events are initiated by the event object which
various constants,properties and methods.
Sunil Kumar Sahu, Lecturer RCET
45
HTML DOM Example
<!DOCTYPE html>
<html>
<body>
<script>
function changeImage()
{
element=document.getElementById('myimage')
if (element.src.match("bulbon"))
{
element.src="pic_bulboff.gif";
}
else
{
element.src="pic_bulbon.gif";
}
}
</script>
<img id="myimage" onclick="changeImage()" border="0" src="pic_bulboff.gif"
width="100" height="180">
<p>Click to turn on/off the light</p>
</body>
</html>
Sunil Kumar Sahu, Lecturer RCET
46
OUTPUT-
After Clicking
Sunil Kumar Sahu, Lecturer RCET
47
innerHTML
 The term innerHTML is a property that is used to modify
an HTML document.
 This propertyis used to modify HTML pages content
without refreshing the page,so that your website becomes
quicker and responsive to user input.
 The innerHTML property is used along with the
getElementById() method in JavaScript to refer an HTML
page and modify its content.
 The syntax isdocument.getElementById(‘{ID of element}’).innerHTML=‘{content}’
Sunil Kumar Sahu, Lecturer RCET
48
 The innerHTML property is used to get or set the
HTML content of an element node.
Example1)Get the element with the "someElement" id, and give it
new content.
document.getElementById('someElement').innerHTML = "new content";
2)Retrieve the content from an element.
var content = document.getElementById('someElement').innerHTML;
alert( content );
Sunil Kumar Sahu, Lecturer RCET
49
3)Change an HTML Attribute
<html> <body>
<img id=“image” src=“Winter.jpg”>
<script type=“text/javascript”>
document.getElementById(“image”).src=“Sunset.jpg”;
</script>
</body> </html>
4)Change an HTML Element
<html> <body>
<h1 id=“header”>Old Header</h1>
<script type=“text/javascript”>
Document.getElementById(“header”).innerHTML=“New
Header”;
<script>
</body> </html>
Sunil Kumar Sahu, Lecturer RCET
50
Example Explained:
 The HTML document contains a header with
id=“header”.
 The DOM is used to get the element with
id=“header”.
 A javascript is used to change the HTML
content(innerHTML).
Sunil Kumar Sahu, Lecturer RCET
51
XML DOM
 The XML DOM defines a standard way for accessing and
manipulating XML documents.It is a technique to
represent an XML document in a tree format containing
the root and child nodes.
 The root node is the parent element whereas the
elements,attributes and text are defined as child nodes.
 In an XML document,DOM defines the standard way to
access and manipulate the XML nodes.
 In other words you can add or delete any no.of child nodes
from the DOM tree of an XML document,whereas the
root will always remain the same.
Sunil Kumar Sahu, Lecturer RCET
52
 In the DOM structure the entire document is
considered as the Document node.
 The XML tag or XML element is recognized as the
Element node.
 The text in XML elements is referred to as the Text
node,the XML Attributes are considered as Attribute
nodes and the comments are considered as Comment
node.
 Consider given example(product.xml) of an XML
file and there DOM tree-structure-
Sunil Kumar Sahu, Lecturer RCET
53
<?xml version=“1.0 “encoding=“UTF-8”>
<product data>
<product id=p001>
<proname>pen</proname>
<description>this is pen which is used to write something
on paper.</description>
<price>$30</price>
<quantity>50</quantity>
</product>
<product id=p002>
<proname> pencil </pencil>
<description>this is pen which is used to write something
on paper.</description>
<price>$10</price> <quantity>100</quantity>
</product>
</product data>
Sunil Kumar Sahu, Lecturer RCET
54
 XML DOM tree for product.xml
Root Element
<Product data>
Element
<productl>
Element
<proname>
Text
Pen
Attribute
“id”
Element
<description>
Element
<price>
Element
<quantity>
Text
Text
30
Text
50
this is pen which is used to
write something on paper.
Sunil Kumar Sahu, Lecturer RCET
55
 The DOM tree structure shown in fig has the root node
<Product data> containing the child node named
<product>.
 <product> node contains the four element nodes and an
Attribute node.
 Each Element node has the respective text node.
Sunil Kumar Sahu, Lecturer RCET
56
XML parser or XML processor
 Parsing is the process of reading and validating a program
written in a one format and converting it into the desired
format.
something
XML file
XML parser
useful for
application programmer
 The program that does this job is is called a parser or
processor.
 The parser has to access the xml file and bring it into main
memory.
 Then parser converts this file into an object where this
object is accessed by the application program and finally
the program produces the desired output.
Sunil Kumar Sahu, Lecturer RCET
57
 The parsing process follows the below steps-
1.The xml parser reads the xml file from the disk and
validates it.
2.The xml parser converts the xml file into an object.
3.This object is accessed by the application program.
4.Finally the application program produces the desired
output.
Sunil Kumar Sahu, Lecturer RCET
58
 When an XML document is presented to a java program as
an object there are two possibilities 1)SAX parser-the first approach where it goes through the
xml document item by item till the end of the XML file is
called SIMPLE API for XML(SAX).
 2)DOM parser -the second approach where the entire xml
document is read in the memory as an object and parse its
contents as per the requirement is called DOM(Document
Object Model).
Sunil Kumar Sahu, Lecturer RCET
59
Using a DOM Tree
XML File
DOM Parser
DOM Tree
Sunil Kumar Sahu, Lecturer RCET
A
P
I
Application
60
SAX Parser
1.It read an xml file as
Node by node.
2.It detects an event(eg.
Start element).
3.It informs of the event
to our application
program.
DOM Parser
1.It stores the entire xml
Document in memory
before parsing.
2.It builds an in-memory
Tree representation on
xml document.
3.It hands over the tree
to our application
program.
(Cont…)
Sunil Kumar Sahu, Lecturer RCET
61
4.In SAX, application
program acts up on the
Event.
5.Parsing continues till all
The events or end of the
Xml file is parsed.
6.It uses less amount of
memory.
4.In DOM, application
programs handles the xml
tree like structures as
appropriate.
5.It parses the whole xml
document at a time.
6.It uses more amount of
memory.
Sunil Kumar Sahu, Lecturer RCET
62
XML file-<?xml version="1.0"?>
<!DOCTYPE countries SYSTEM "world.dtd">
<countries>
<country continent="&as;">
<name>Israel</name>
<population year="2001">6,199,008</population>
<city capital="yes"><name>Jerusalem</name></city>
<city><name>Ashdod</name></city>
</country>
<country continent="&eu;">
<name>France</name>
<population year="2004">60,424,213</population>
</country>
</countries>
Sunil Kumar Sahu, Lecturer RCET
63
The DOM Tree
Document
countries
country
continent
name
city
Asia
Israel
population
year
2001
capital
city
capital
name
name
country
population
no Ashdod
6,199,008
year
yes
continent
Jerusalem
Europe
Sunil Kumar Sahu, Lecturer RCET
name
France 2004
60,424,213
64
DHTML(Dynamic HTML)
 DHTML combines the HTML,JavaScript,CSS,and DOM.
 DHTML is not a scripting language whereas it is a browser
feature that gives your browser the ability to be dynamic.
 DHTML is a new way of controlling and looking the HTML
codes and commands. You can get more controls in
dynamic HTML over standard HTML.
 With DHTML you can add various effects to your web
pages,such as hiding the content,animating the text,and
images in your document and so on.
 javaScript and ActiveX are the scripting language which are
most commonly used to activate DHTML.
Sunil Kumar Sahu, Lecturer RCET
65
The following components are a part of DHTML:
 HTML:Specifies a markup language that defines the
structure of a web page with the help of basic elements
which includes headings,forms,tables,paragraph and
links.
 CSS:Specifies a style sheet that controls the formatting of
HTML elements.
 Scripting:Specifies a mechanism that provides
animations and effects in an HTML page.
 DOM:Specifies an interface that outlines Web page
content in such a way that HTML elements,style sheet and
scripting language can interact with each other.
Sunil Kumar Sahu, Lecturer RCET
66
Features of DHTML: Dynamic Content: internet Explorer support, With
DHTML, you can change the content of the page after it
is loaded.
 Positioning and Animation: is the ability to place an
HTML element at a specific point on a page, relative to
another element or the browser window itself
 Font Download :Internet Explorer can dynamically
download fonts for use in a Web page.
 Data Binding: is a DHTML feature that lets you easily
bind individual elements in your document to data from
another source, such as a database or comma-delimited
text file.
 Dynamic Styles :are a key feature of DHTML. By using
CSS, you can quickly change the appearance and
formatting of elements in a document without adding or
removing elements.
Sunil Kumar Sahu, Lecturer RCET
67
How DHTML works
 The web page here uses simple DHTML to change the style of links
to be red and underlined when the mouse is rolled over them
<html>
<head>
<title>Rollover Style Changes</title>
<style>
a {text-decoration: none;}
</style>
<script>
function turnOn(currentLink) {
currentLink.style.color = “#990000”;
currentLink.style.textDecoration = “underline”;
}
function turnOff(currentLink) {
currentLink.style.color = “#0000FF”;
currentLink.style.textDecoration = “none”;
}
</script>
</head>
Sunil Kumar Sahu, Lecturer RCET
68
<body bgcolor=“#FFFFFF”>
<a href=“#home”onMouseOver=“turnOn(this);”
onMouseOut=“turnOff(this);”>Home</a>
<br>
<a href=“#contact”
onMouseOver=“turnOn(this);”
onMouseOut=“turnOff(this);”>Contact</a>
<br>
</body>
</html>
Sunil Kumar Sahu, Lecturer RCET
69
 Advantages:
 File sizes are small: DHTML files are small compared to




other interactive media like Flash, Shockwave, and Java
It’s supported by major browser manufacturers
DHTML is a standard
No plug-ins, ActiveX controls, or Java is necessary
There are fewer calls to the server
 Disadvantages:
 Only newer browsers support the DHTML “standard”
 Netscape and MS have different DHTML implementations
 DHTML creation has a fairly steep learning curve
Sunil Kumar Sahu, Lecturer RCET
70
CGI(Common Gateway Interface)
Sunil Kumar Sahu, Lecturer RCET
71
 It is a standard protocol for interfacing external




application software with the web server. It developed in
1993 at NCSA (National Center for Supercomputing
Applications)
It is a Protocol that allows communication between web
server and CGI scripts.
CGI scripts are executables that will execute on the server
to produce dynamic and interactive web pages.
You need to first configure the web server to support the
CGI applications.Different web servers can be configured
in different manner according to their configuratuion
settings.
Some of the web servers are Apache,Google Web
Serve(GWS),Sum Java System Web Server and IIS(Internet
Information Server).
Sunil Kumar Sahu, Lecturer RCET
72
Fig.Communications and computation using CGI
Sunil Kumar Sahu, Lecturer RCET
73
How CGI Works
• Web browser requests CGI script from web server
using HTTP protocol.
• Web server sees that it is a CGI script and runs the
script.
• The CGI script sends output back to the web server
which sends the output to the browser.
Sunil Kumar Sahu, Lecturer RCET
74
 1. The Web surfer fills out a form and clicks, “Submit.”




The information in the form is sent over the Internet to
the Web server.
2. The Web server “grabs” the information from the form
and passes it to the CGI software.
3. The CGI software performs whatever validation of this
information that is required. For instance, it might
check to see if an e-mail address is valid. If this is a
database program, the CGI software prepares a database
statement to either add, edit, or delete information from
the database.
4. The CGI software then executes the prepared database
statement, which is passed to the database driver.
5. The database driver acts as a middleman and performs
the requested action on the database itself.
Sunil Kumar Sahu, Lecturer RCET
75
 6. The results of the database action are then passed back





to the database driver.
7. The database driver sends the information from the
database to the CGI software.
8. The CGI software takes the information from the
database and manipulates it into the format that is
desired.
9. If any static HTML pages need to be created, the CGI
program accesses the Web server computer’s file system
and reads, writes, and/or edits files.
10. The CGI software then sends the result it wants the
Web surfer’s browser to see back to the Web server.
11. The Web server sends the result it got from the CGI
software back to the Web surfer’s browser.
Sunil Kumar Sahu, Lecturer RCET
76
Example1- First.cgi
Sunil Kumar Sahu, Lecturer RCET
77
Sunil Kumar Sahu, Lecturer RCET
78
Example2– simple.cgi
Sunil Kumar Sahu, Lecturer RCET
79
OUTPUT-
Sunil Kumar Sahu, Lecturer RCET
80
Advantage of CGI:
 CGI is simple to learn and use.
 Programs developed in CGI supports good web browsers
compatibility.
 CGI is rich in libraries which are sufficient for developing the
programs. Therefore no need to use any library other than CGI
libraries.
Limitation of CGI: CGI is slow.
 Every time a process is launched.,it starts from the
beginning thereby taking lots of time.
 Every time a process executes ,the resources such as
database connections must be created and reloaded.
 The state is not persistent.On every request,everything is
built again.
Sunil Kumar Sahu, Lecturer RCET
81
Perl(Practical Extraction and Report Language)
 It is a Scripting Language that is used for scanning the text






files,extacting information and displaying the report on
the basis of the extracted information.
This language is easy to use and contains some features of
C and other languages.
Perl was created by Larry Wall in 1986 to enhance the
functionality of csh shell Script notation of unix.
Perl program contains one or more statements,which are
ended with semicolon.
In Perl you don’t need to write main function.
# Symbol is used for Comments.
Exampleprint “Hello world”; #It prints Hello world
Sunil Kumar Sahu, Lecturer RCET
82
Running Perl Scripts
 Windows
 Download ActivePerl from ActiveState
 Just run the script from a 'Command Prompt' window
 UNIX – Cygwin
 Put the following in the first line of your script
#!/usr/bin/perl
 Run the script
% perl script_name
Sunil Kumar Sahu, Lecturer RCET
83
Example of Perl Program:
print “Enter your name:”;
$name=<STDIN>;
print “Hello, ${name}welcome to Rungta College!!!!!!!”;
 Save it with .pl(dot pl) extension like Hello.pl
 After installing ActivePerl in your computer open
command prompt and go to the location of that file.
 Now type perl program name.pl and press enter key like:
Sunil Kumar Sahu, Lecturer RCET
84
Using Scalar Variables and Operators in Perl
 Perl has three types of variables :
1)Scalars
2)Arrays
3)Lists
4)Hashes
1)Scalar variable:Numeric Scalar Variables A scalar variable represents a single value.
 A variable declared as scalar starts with $ sign.
 following code shows an example of the scalar type variables.
$var =‘hello Sunil’;
$num=100;
print $var;
print $num;
Sunil Kumar Sahu, Lecturer RCET
85
 Here we declared two scalar variables var and num.
 We have initialized the var variable with string hello Sunil and
num variable with number 100.
Strings String types in Perl are like those in other programming
language. Strings are treated literally when enclosed in
quotation marks (either single or double). Escape sequences can
be used with Perl strings. These are the most common:




\n
\r
\t
\b
newline
carriage return
tab
backspace
Special escape sequences
 Some escape sequences for strings have special meaning to Perl:
 \l
change next character to lower case
 \u change next character to upper case
 \’
literal single quotation mark
 \”
literal double quotation mark
 \\
backslash
Sunil Kumar Sahu, Lecturer RCET
86
The q and qq operators Perl allows you to use the these structures:
 q( ) and qq( )
 Instead of single and double quotes, respectively. So,
qq(This is a test)
 is the same as
“This is a test”
 These can be handy when embedding marks that would otherwise
need escaping:
qq(He said “Help!” then “Now!”)
Single and double quotes Double quotation marks allow expansion of variables within them.
Single quotes do not.
 For example:
“This is from $name1”;
is not the same as
‘This is from $name1’;
as the second will literally display ‘$name1” which the first will
substituted the value in the variable name1.
Sunil Kumar Sahu, Lecturer RCET
87
2)Array Variable: An Array represents a list of values.
 A variable declared as array starts with the @sign.
 Following code shows an example of Array type variables@var=(“Appel”,”Banana”,”Orange”,”Grapes”,”Mango”);
print @var;
 In which have declared a variable var of array type.
 We have initialized the var with multiple scalar values
Sunil Kumar Sahu, Lecturer RCET
88
3)List Variable They are like arrays. It can be considered as a group of scalar
variables.
 They are always preceded by the @symbol.
Example@names = (“Shiv",“Ram“,” Shyam",“);
print $names[1];
Output-
Sunil Kumar Sahu, Lecturer RCET
89
4)Hash Variable: A hash type of variable stores multiple scalar values similar to
the array type.However the hash type variable does not store
the value on the basis of the index number.
 It uses sting values as index and stores the value on the basis of
these indexed values.
 A variable declared as hash starts with % sign with the index
value in the square brackets([ ]).
Example:
%var=(one=>”Apple”,two=>”Mango”,three=>”Orange”);
print “ $var{‘two’}”;
Sunil Kumar Sahu, Lecturer RCET
90
 Perl has following Operators-
1)Arithmatic Operators(+, -, *, /, %,**.)
2)Assignment Operators(=, +=, -+, *=, /=, .=.)
3)Logical Operators(&&, ||, !.)
4) Comparison Operators
5)String Operators
6)Relational operations
7)Increment/decrement operators: (++, --)
Sunil Kumar Sahu, Lecturer RCET
91
Sunil Kumar Sahu, Lecturer RCET
92
Sunil Kumar Sahu, Lecturer RCET
93
Comparison Operators
String
Operation
Arithmetic
lt
less than
<
gt
greater than
>
eq
equal to
==
le
less than or equal to
<=
ge
greater than or equal to
>=
ne
not equal to
!=
cmp
compare, return 1, 0, -1
<=>
Sunil Kumar Sahu, Lecturer RCET
94
Logical Operators
Operator
Operation
||, or
logical or
&&, and
logical and
!, not
logical not
xor
logical xor
Sunil Kumar Sahu, Lecturer RCET
95
String Operators
Operator
Operation
.
string concatenation
x
string repetition
.=
concatenation and assignment
$string1 = "potato";
$string2 = "head";
$newstring = $string1 . $string2; #"potatohead"
$newerstring = $string1 x 2; #"potatopotato"
$string1 .= $string2; #"potatohead"
Sunil Kumar Sahu, Lecturer RCET
96
Control Structures
 If /else control structure looks like:
if(condition){
If body
}
else{
Else body
}
 Example:
if ($gas_money < 10) {
print "You don’t have enough money!";
}
else {
print "You have enough money.";
}
Sunil Kumar Sahu, Lecturer RCET
97
 For loop has the following C-based formula:
for (initialize;condition; increment){
code to repeat
}
For Example:
for ($count=1; $count<11; $count++){
print "cool\n";
}
 While loop has also the following C-based
formula:
while (test condition)
{
code to repeat
}
Sunil Kumar Sahu, Lecturer RCET
98
While Example:
$count=1;
while ($count < 11){
print "$count\n"; $count++;
}
 foreach has the following formula:
foreach variable_name (array_name)
{
code to repeat
}
Foreach Example:
foreach $item(@inventory)
{
print “$item\n”;
}
Sunil Kumar Sahu, Lecturer RCET
99
Testing and debugging Perl CGI Script
 The most common error that is encounterd while running




a CGI application is “Internal Server Error”.
This is due to not properly configuring of Web server to
run CGI programs.
When a CGI application has some error the web server
return a web page with the “Error 500:Internal Server”
message.
Most of the time error 500problems come due to synatax
error in the Script.
An easy way to check a perl CGI script syntax is to execute
the following command at command prompt:
E:\>perl –w –c program name.pl
Sunil Kumar Sahu, Lecturer RCET
100
Testing a ScriptExample(hello.pl)print "Enter your name";
$name=<STDIN>;
print "Hello,${name} Welcome to Rungta
College!!!!!!!";
1. Open shell or DOS prompt
2. Go to path where the Perl script is located
Example: cd Sunil
3. perl -c filename OR perl -w filename
filename = the name of the Perl script
Example: perl -c hello.pl or perl –w hello.pl
Sunil Kumar Sahu, Lecturer RCET
101
 -c option or switch will check for syntax errors but will not
execute the script.
 -w option or switch will check for execution errors and will
execute the script
Sunil Kumar Sahu, Lecturer RCET
102
 Additionally, can test a Perl/CGI script with a Web
browser
 On a UNIX machine, change the file permissions of the
script so that it can be executed

chmod 755 filename
 In the browser, type in the URL of the script:
 http://yourservername/cgi-bin/chap01/first.cgi
Sunil Kumar Sahu, Lecturer RCET
103
Debugging a Perl Script
 When you use the -c or -w switches with Perl, the line
number of the error will be shown
 Edit the Perl script, and go to that line number
 Examine that line, and the line directly above it
 Make the corrections, resave the file, and try testing the
script again
 Look for simple errors, such as:
 Missing semicolons at the end of lines
 Uppercase commands or functions (remember that Perl is
case-sensitive)
 Missing quotation marks at the beginning or end of print
statements
Sunil Kumar Sahu, Lecturer RCET
104
 There is no. of Tips that is taken while testing and
debugging the CGI Perl scipt1)A CGI applications that is written in Perl CGI script must
contain a line that begins with #! Symbol. This symbol is
called as sharp-bang.
2)If this symbol is not used the server will not know about
interpreter that has to execute the script.
3)You need to isolate a program from other progarms in
order to test it.
4)You can add print statements to make it more clear which
programs is executing error free.
Sunil Kumar Sahu, Lecturer RCET
105