JAVA

105
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

description

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. - PowerPoint PPT Presentation

Transcript of JAVA

Slide 1

JAVAJava 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 RCET1Definition 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 RCET2History

James Gosling began developing Java beginning in 1991 It was first called Project Green and OakFirst developed for remote cable TV boxesSun Microsystems released to a select group on the Website wicked.neato.org as Java 1.0 in 1995James Naughton creates HotJava in 1995. its 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 RCET3

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 RCET4Version 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 powerJava 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, replicationSunil Kumar Sahu, Lecturer RCET5Java Basic Tools

Tool Name Brief Descriptionjavac The compiler for the Java programming language.Java The launcher for Java applications.javadoc API documentation generator.Appletviewer Run and debug applets without a web browser.jar Create and manage Java Archive (JAR) files.Jdb The Java Debugger.javah C header and stub generator. Used to write native methods.javap Class file disassemblerextcheck Utility to detect Jar conflicts.Sunil Kumar Sahu, Lecturer RCET6JAVA vs JAVA SCRIPTJavaA complete programming language developed by SunCan be used to develop either web based or stand-alone softwareMany pre-created code libraries availableFor more complex and powerful programs

Java Script A small language thats 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 RCET7How it worksSunil Kumar Sahu, Lecturer RCET8

Characteristics of JavaJava 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 Sunil Kumar Sahu, Lecturer RCET9Java 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.Characteristics of JavaJava 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 Sunil Kumar Sahu, Lecturer RCET10Java is inherently object-oriented. Although many object-oriented languages began strictly as procedural languages, Java was designed from the start to be object-oriented. Object-oriented 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. Characteristics of JavaJava 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 Sunil Kumar Sahu, Lecturer RCET11Distributed 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. Characteristics of JavaJava 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 Sunil Kumar Sahu, Lecturer RCET12You 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). Characteristics of JavaJava 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 Sunil Kumar Sahu, Lecturer RCET13Java compilers can detect many problems that would first show up at execution time in other languages.

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. Characteristics of JavaJava 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 Sunil Kumar Sahu, Lecturer RCET14Java implements several security mechanisms to protect your system against harm caused by stray programs. Characteristics of JavaJava 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 Sunil Kumar Sahu, Lecturer RCET15Write once, run anywhere

With a Java Virtual Machine (JVM), you can write one program that will run on any platform.Characteristics of JavaJava 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 Sunil Kumar Sahu, Lecturer RCET16Because Java is architecture neutral, Java programs are portable. They can be run on any platform without being recompiled. Characteristics of JavaJava 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 Sunil Kumar Sahu, Lecturer RCET17Because Java is architecture neutral, Java programs are portable (moveable). They can be run on any platform without being recompiled. Characteristics of JavaJava 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 Sunil Kumar Sahu, Lecturer RCET18Multithread programming is smoothly integrated in Java, whereas in other languages you have to call procedures specific to the operating system to enable multithreading.Characteristics of JavaJava 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 Sunil Kumar Sahu, Lecturer RCET19Java 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. Creating ,Compiling and Executing Programs

Sunil Kumar Sahu, Lecturer RCET20On command linejavac file.javaExecuting Applications java classname

Simple Java Program

public class hello{public static void main (String args[]){System.out.println(This is first java program);}}Save as hello.javaSunil Kumar Sahu, Lecturer RCET21How to compile and run java Program

Save java program with .java(dot java) extensionCompile java program- - javac hello.javaRun java program- - java hello

Output-Sunil Kumar Sahu, Lecturer RCET22

Writing Java AppletAn 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 RCET233.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 RCET24Example of Applet (SimpleApplet.java)import java.awt.*;import java.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 RCET25Description 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 RCET26The 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 RCET27After 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-

Sunil Kumar Sahu, Lecturer RCET28After 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

Sunil Kumar Sahu, Lecturer RCET29

Command Promptb)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 like-C:\>appletviewer SimpleApplet.java

Sunil Kumar Sahu, Lecturer RCET30

Applet Window Sunil Kumar Sahu, Lecturer RCET31

Applet Window Command Prompt

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 RCET32public void init( )This is the first method to executeIt is an ideal place to initialize variablesIt is the best place to define the GUI Components (buttons, text fields, scrollbars, etc.), lay them out, and add listeners to themAlmost every applet you ever write will have an init() method.public void start( )Not always neededCalled after init()Called each time the page is loaded and restartedUsed mostly in conjunction with stop( )start() and stop( ) are used when the Applet is doing time-consuming calculations that you dont want to continue when the page is not in front

Sunil Kumar Sahu, Lecturer RCET33public void stop( )Not always neededCalled when the browser leaves the pageCalled just before destroy( )Use stop( ) if the applet is doing heavy computation that you dont want to continue when the browser is on some other pageUsed mostly in conjunction with start()public void destroy( )Seldom neededCalled after stop( )Use to explicitly release system resources (like threads)System resources are usually released automatically

Sunil Kumar Sahu, Lecturer RCET34public 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 RCET35init and destroy are only called once eachstart and stop are called whenever the browser enters and leaves the pagedo some work is code called by your listenerspaint is called when the applet needs to be repaintedinit()start()stop()destroy()do some workMethods are called in this orderSunil Kumar Sahu, Lecturer RCET36Example-import java.awt.*; import java.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 RCET37Output-Sunil Kumar Sahu, Lecturer RCET38

Applet WindowCommand PromptDOM(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 RCET39convert 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 RCET40The 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 CoreDOM Level3 Load and SaveDOM Level3 XpathDOM Level3 Views and FormattingDOM Level3 RequirmentsDOM Level3 Validation

Sunil Kumar Sahu, Lecturer RCET41HTML DOMThe HTML DOM defines a standard way for accessing and manipulating HTML documents.The DOM presents an HTML document as a tree-structure.

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 RCET42HTML DOM presents an HTML document as a tree structure as shown below-

Sunil Kumar Sahu, Lecturer RCET43DocumentRoot Element

ElementbodyElementheadElement

AttributehrefElementtitleElement

TextMy HeaderTextMy linkTextMy TextFig. Displaying Html document as Tree StructureNodes: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 nodes-1)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 RCET44Objects: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 RCET45HTML DOM Example

function changeImage() { element=document.getElementById('myimage') if (element.src.match("bulbon")) { element.src="pic_bulboff.gif"; } else { element.src="pic_bulbon.gif"; } } Click to turn on/off the light Sunil Kumar Sahu, Lecturer RCET46

After Clicking

OUTPUT-Sunil Kumar Sahu, Lecturer RCET47innerHTMLThe 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 is- document.getElementById({ID of element}).innerHTML={content} Sunil Kumar Sahu, Lecturer RCET48TheinnerHTMLpropertyis used to get or set the HTMLcontentof anelementnode.Example-1)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 RCET493)Change an HTML Attribute

document.getElementById(image).src=Sunset.jpg;

4)Change an HTML Element Old Header

Document.getElementById(header).innerHTML=New Header;

Sunil Kumar Sahu, Lecturer RCET50Example 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 RCET51XML DOMThe 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 RCET52In 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 RCET53

pen this is pen which is used to write something on paper. $30 50 pencil this is pen which is used to write something on paper. $10 100

Sunil Kumar Sahu, Lecturer RCET54XML DOM tree for product.xml

Sunil Kumar Sahu, Lecturer RCET55Root Element

Element

AttributeidElement

Element

Element

Element

Text50Text30Textthis is pen which is used to write something on paper.

TextPenThe DOM tree structure shown in fig has the root node containing the child node named . node contains the four element nodes and an Attribute node.Each Element node has the respective text node. Sunil Kumar Sahu, Lecturer RCET56XML parser or XML processorParsing is the process of reading and validating a program written in a one format and converting it into the desired format.XML file XML parser

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 RCET57application programmersomething useful forThe 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 RCET58When 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 RCET59Using a DOM TreeSunil Kumar Sahu, Lecturer RCET60

DOM ParserDOM TreeXML FileAPIApplication60 SAX Parser DOM Parser1.It read an xml file as 1.It stores the entire xml Node by node. Document in memory before parsing.2.It detects an event(eg. 2.It builds an in-memoryStart element). Tree representation on xml document.3.It informs of the event 3.It hands over the treeto our application to our application program. program. (Cont)Sunil Kumar Sahu, Lecturer RCET614.In SAX, application 4.In DOM, applicationprogram acts up on the programs handles the xml Event. tree like structures as appropriate.5.Parsing continues till all 5.It parses the whole xml The events or end of the document at a time.Xml file is parsed.

6.It uses less amount of 6.It uses more amount ofmemory. memory. Sunil Kumar Sahu, Lecturer RCET62XML file--

Israel 6,199,008 Jerusalem Ashdod France 60,424,213

Sunil Kumar Sahu, Lecturer RCET6363The DOM TreeSunil Kumar Sahu, Lecturer RCET64

64DHTML(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 RCET65The 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 RCET66Features 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 itselfFont 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 RCET67How DHTML worksThe web page here uses simple DHTML to change the style of links to be red and underlined when the mouse is rolled over them

Rollover Style Changesa {text-decoration: none;}function turnOn(currentLink) {currentLink.style.color = #990000;currentLink.style.textDecoration = underline;}function turnOff(currentLink) {currentLink.style.color = #0000FF;currentLink.style.textDecoration = none;}

Sunil Kumar Sahu, Lecturer RCET68 Home
Contact

Sunil Kumar Sahu, Lecturer RCET69Advantages:File sizes are small: DHTML files are small compared to other interactive media like Flash, Shockwave, and JavaIts supported by major browser manufacturersDHTML is a standardNo plug-ins, ActiveX controls, or Java is necessaryThere are fewer calls to the serverDisadvantages:Only newer browsers support the DHTML standardNetscape and MS have different DHTML implementationsDHTML creation has a fairly steep learning curve

Sunil Kumar Sahu, Lecturer RCET70CGI(Common Gateway Interface)

Sunil Kumar Sahu, Lecturer RCET71It 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 RCET72Sunil Kumar Sahu, Lecturer RCET73Fig.Communications and computation using CGI

How CGI WorksSunil Kumar Sahu, Lecturer RCET74Web 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.

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 RCET756. 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 computers file system and reads, writes, and/or edits files.10. The CGI software then sends the result it wants the Web surfers 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 surfers browser.Sunil Kumar Sahu, Lecturer RCET76Example1- First.cgiSunil Kumar Sahu, Lecturer RCET77

Sunil Kumar Sahu, Lecturer RCET78

Example2 simple.cgiSunil Kumar Sahu, Lecturer RCET79

OUTPUT-Sunil Kumar Sahu, Lecturer RCET80

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 RCET81Perl(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 dont need to write main function.# Symbol is used for Comments.Example- print Hello world; #It prints Hello worldSunil Kumar Sahu, Lecturer RCET82WindowsDownload ActivePerl from ActiveStateJust run the script from a 'Command Prompt' windowUNIX CygwinPut the following in the first line of your script#!/usr/bin/perlRun the script% perl script_name

Sunil Kumar Sahu, Lecturer RCET83Running Perl ScriptsExample of Perl Program:print Enter your name:;$name=;print Hello, ${name}welcome to Rungta College!!!!!!!;Save it with .pl(dot pl) extension like Hello.plAfter 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 RCET84

Using Scalar Variables and Operators in PerlPerl has three types of variables :1)Scalars2)Arrays3)Lists4)Hashes1)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 RCET85

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 newline\r carriage return\t tab\b backspaceSpecial escape sequencesSome 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 RCET86The 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 testThese 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 RCET872)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 RCET88

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 RCET89

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 RCET90

Perl has following Operators-1)Arithmatic Operators(+, -, *, /, %,**.)2)Assignment Operators(=, +=, -+, *=, /=, .=.)3)Logical Operators(&&, ||, !.)4) Comparison Operators5)String Operators6)Relational operations7)Increment/decrement operators: (++, --)

Sunil Kumar Sahu, Lecturer RCET91Sunil Kumar Sahu, Lecturer RCET92

Sunil Kumar Sahu, Lecturer RCET93

StringOperationArithmeticltless than

eqequal to==leless than or equal to=nenot equal to!=cmpcompare, return 1, 0, -1

Sunil Kumar Sahu, Lecturer RCET94Comparison OperatorsOperatorOperation||, orlogical or&&, andlogical and!, notlogical notxorlogical xorSunil Kumar Sahu, Lecturer RCET95Logical OperatorsOperatorOperation.string concatenationxstring repetition.=concatenation and assignment$string1 = "potato";$string2 = "head";

$newstring = $string1 . $string2; #"potatohead"$newerstring = $string1 x 2; #"potatopotato"$string1 .= $string2; #"potatohead"Sunil Kumar Sahu, Lecturer RCET96String OperatorsControl StructuresIf /else control structure looks like:if(condition){ If body}else{ Else body}Example:if ($gas_money < 10) { print "You dont have enough money!"; } else { print "You have enough money."; }

Sunil Kumar Sahu, Lecturer RCET97For loop has the following C-based formula: for (initialize;condition; increment){ code to repeat } For Example: for ($count=1; $countperl w c program name.plSunil Kumar Sahu, Lecturer RCET100Testing a Script-Example(hello.pl)-print "Enter your name";$name=;print "Hello,${name} Welcome to Rungta College!!!!!!!";1. Open shell or DOS prompt2. Go to path where the Perl script is locatedExample: cd Sunil3. perl -c filename OR perl -w filenamefilename = the name of the Perl scriptExample: perl -c hello.pl or perl w hello.pl

Sunil Kumar Sahu, Lecturer RCET101-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 RCET102

Additionally, can test a Perl/CGI script with a Web browserOn a UNIX machine, change the file permissions of the script so that it can be executedchmod 755 filenameIn the browser, type in the URL of the script:http://yourservername/cgi-bin/chap01/first.cgi

Sunil Kumar Sahu, Lecturer RCET103

Debugging a Perl ScriptWhen you use the -c or -w switches with Perl, the line number of the error will be shownEdit the Perl script, and go to that line numberExamine that line, and the line directly above itMake the corrections, resave the file, and try testing the script againLook for simple errors, such as:Missing semicolons at the end of linesUppercase commands or functions (remember that Perl is case-sensitive)Missing quotation marks at the beginning or end of print statements

Sunil Kumar Sahu, Lecturer RCET104There is no. of Tips that is taken while testing and debugging the CGI Perl scipt-1)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 RCET105

Create/Modify Source Code

Source Code

If compilation errors

Result

Compile Source Code

i.e. javac Welcome.java

Bytecode

Run Byteode

i.e. java Welcome

If runtime errors or incorrect result

DocumentcountriescontinentAsianameIsraelpopulationyear20016,199,008countrycitycapitalyesnameJerusalemcitycapitalnonameAshdodcountryEuropecontinentFrancenameyear200460,424,213population