112
VELTECH HIGHTECH Dr.RANGARAJAN Dr.SAKUNTHALA ENGINEERING COLLEGE DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING VELTECH HIGHTECH Dr.RANGARAJAN Dr.SAKUNTHALA ENGINEERING COLLEGE Page 1 CS6501 INTERNET PROGRAMMING UNIT I JAVA PROGRAMMING An overview of Java – Data Types – Variables and Arrays – Operators – Control Statements – Classes – Objects – Methods – Inheritance - Packages – Abstract classes – Interfaces and Inner classes – Exception handling - Introduction to Threads – Multithreading – String handling – Streams and I/O – Applets. 1.1ABSTRACT CLASSES abstract class is defined as a super class in java that does nothing, but lists out the common features of the other class “abstract” keyword is used It may contain abstract methods (methods without body) If a class has at least one abstract method, then the class must be declared as “abstract” object cannot be created To use abstract class, we have to inherit it from another class, then define the abstract methods in it. If abstract class is inherited, all the abstract methods in it should be defined in derived class. 1.1.1 ABSTRACT CLASS SYNTAX abstract class name { abstract void function name(); } class class name extends abstract class name { void function name() { } } 1.1.2 ABSTRACT CLASS EXAMPLE PROGRAM abstract class A { { abstract void absmethod(); } class B extends A { void absmethod() { System.out.println("One "); } } class C extends A { void absmethod() { System.out.println("Two "); } } class abs { public static void main(String arg[]) { B b=new B(); C c=new C(); b.absmethod(); c.absmethod(); } } O/p: one Two

CS6501 INTERNET PROGRAMMING UNIT I JAVA PROGRAMMING

  • Upload
    others

  • View
    10

  • Download
    0

Embed Size (px)

Citation preview

Page 1: CS6501 INTERNET PROGRAMMING UNIT I JAVA PROGRAMMING

VELTECH HIGHTECH Dr.RANGARAJAN Dr.SAKUNTHALA ENGINEERING COLLEGE DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING

VELTECH HIGHTECH Dr.RANGARAJAN Dr.SAKUNTHALA ENGINEERING COLLEGE Page 1

CS6501 INTERNET PROGRAMMING

UNIT I JAVA PROGRAMMING

An overview of Java – Data Types – Variables and Arrays – Operators – Control Statements – Classes – Objects – Methods – Inheritance - Packages – Abstract classes – Interfaces and Inner classes – Exception handling - Introduction to Threads – Multithreading – String handling – Streams and I/O – Applets.

1.1ABSTRACT CLASSES

➢ abstract class is defined as a super class in java that does nothing, but lists out the common features of the other class

➢ “abstract” keyword is used ➢ It may contain abstract methods

(methods without body) ➢ If a class has at least one abstract

method, then the class must be declared as “abstract”

➢ object cannot be created ➢ To use abstract class, we have to inherit it

from another class, then define the abstract methods in it.

➢ If abstract class is inherited, all the abstract methods in it should be defined in derived class.

1.1.1 ABSTRACT CLASS SYNTAX

abstract class name

{

abstract void function name();

}

class class name extends abstract class name {

void function name() { }

}

1.1.2 ABSTRACT CLASS EXAMPLE

PROGRAM

abstract class A

{

{

abstract void absmethod();

}

class B extends A

{

void absmethod() {

System.out.println("One "); }

} class C extends A {

void absmethod() {

System.out.println("Two "); }

} class abs {

public static void main(String arg[]) {

B b=new B(); C c=new C(); b.absmethod(); c.absmethod();

} } O/p: one Two

Page 2: CS6501 INTERNET PROGRAMMING UNIT I JAVA PROGRAMMING

VELTECH HIGHTECH Dr.RANGARAJAN Dr.SAKUNTHALA ENGINEERING COLLEGE DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING

VELTECH HIGHTECH Dr.RANGARAJAN Dr.SAKUNTHALA ENGINEERING COLLEGE Page 2

1.2.INTERFACE

➢ An interface is a collection of abstract methods.

➢ A class implements an interface, thereby inheriting the abstract methods of the interface

➢ An interface is not a class. ➢ Writing an interface is similar to writing a

class ➢ 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

1. 2.1 INTERFACE SYNTAX

interface interface name { } Class class name implements interface name { }

2.2 INTERFACE SAMPLE PROGRAM

interface printable

{

void print();

}

class A6 implements printable

{

public void print()

{

System.out.println("Hello");}

public static void main(String args[])

{

A6 obj = new A6();

obj.print();

}

}

O/p: Hello

1.3 INHERITANCE

➢ Inheritance in java is defined as the process of deriving a child class from a parent class.

➢ The child class acquires all the properties of the parent class.

➢ “extends” is the keyword used to inherit the properties of parent class.

INHERITANCE SYNTAX

Class parent name { ------------- ------------- }

Class child extends parent name { ------- -------

}

1.3.1 DIFFERENCES

ABSTRACT CLASS INTERFACE

We can inherit only one abstract class

We can inherit more than one interfaces

Abstract class Interface abstract class members

Interface members are only public

Page 3: CS6501 INTERNET PROGRAMMING UNIT I JAVA PROGRAMMING

VELTECH HIGHTECH Dr.RANGARAJAN Dr.SAKUNTHALA ENGINEERING COLLEGE DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING

VELTECH HIGHTECH Dr.RANGARAJAN Dr.SAKUNTHALA ENGINEERING COLLEGE Page 3

can be public, private or protected

Method may or may not have definition

No method definition (default)

Efficient Slow

1.3.2 WHY USE JAVA INTERFACE?

There are mainly three reasons to use interface. They are given below.

o It is used to achieve abstraction.

o By interface, we can support the functionality of multiple inheritance.

o It can be used to achieve loose coupling.

1.3.3 INHERITANCE TYPE

➢ Single Inheritance ➢ Multilevel Inheritance ➢ Hierarchical Inheritance

INHERITANCE ADVANTAGES ➢ Flexibility ➢ Reusability ➢ Extensibility ➢ Data hiding ➢ Overriding

1.3.4 SINGLE INHERITANCE

➢ Single inheritance in java is defined as the process of deriving a single derived class from a single base class.

➢ It is the simplest form of inheritance in Java.

SINGLE INHERITANCE EXAMPLE PROGRAM

class base

{ int a=10;

} Class derived extends base { int b=20; void add() { System.out.println(a+b); } } class single { public static void main(String bala[]) { derived d = new derived(); d.add(); } O/p : 30

1.3.5 MULTILEVEL INHERITANCE

➢ It is the process of deriving a child class from another child class.

MULTI LEVEL INHERITANCE EXAMPLE PROGRAM

class base {

int a=10; } class derived1 extends base {

int b=20; } class derived2 extends derived1 {

int c=30; void add() {

System.out.println(a+b+c); }

DERIVED 1

DERIVED 2

BASE

DERIVED

BASE

Page 4: CS6501 INTERNET PROGRAMMING UNIT I JAVA PROGRAMMING

VELTECH HIGHTECH Dr.RANGARAJAN Dr.SAKUNTHALA ENGINEERING COLLEGE DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING

VELTECH HIGHTECH Dr.RANGARAJAN Dr.SAKUNTHALA ENGINEERING COLLEGE Page 4

} Class multilevel

{ public static void main(String bala[]) {

derived2 d2 = new derived2(); d2.add();

} } 1.3.6 HIERARCHICAL INHERITANCE

➢ It is the process of deriving more than one child class from the same parent class.

➢ Two or more child classes having the same parent class.

HIERARCHICAL INHERITANCE EXAMPLE PROGRAM

class base {

int a=10; } class derived1 extends base {

int b=20; void add1() {

System.out.println(a+b); }

} class derived2 extends base { int c=30;

void add2() {

System.out.println(a+c); }

}

class hierarchical {

public static void main(String bala[]) {

derived1 d1 = new derived1(); derived2 d1 = new derived2(); d1.add1(); d2.add2();

} }

1.3.7 HYBRID INHERITANCE

➢ If more than two types of inheritance combined together in deriving child classes, it is called hybrid inheritance.

➢ It may be a combination of single-multilevel, multilevel-hierarchical, etc.

HYBRID INHERITANCE EXAMPLE PROGRAM

class base {

int a=10; } class derived1 extends base {

int b=20; } class derived2 extends derived1 {

int c=30; void add1() {

System.out.println(a+b+c); }

} class derived3 extends derived1 {

int d=40; void add2() {

System.out.println(a+b+d); }

}

DERIVED 1 DERIVED 2

BASE

Page 5: CS6501 INTERNET PROGRAMMING UNIT I JAVA PROGRAMMING

VELTECH HIGHTECH Dr.RANGARAJAN Dr.SAKUNTHALA ENGINEERING COLLEGE DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING

VELTECH HIGHTECH Dr.RANGARAJAN Dr.SAKUNTHALA ENGINEERING COLLEGE Page 5

class multilevel {

public static void main(String bala[]) {

derived2 d2 = new derived2(); derived3 d3 = new derived3(); d2.add1(); d3.add2();

} } DISADVANTAGES OF INHERITANCE ➢ Both classes (super and subclasses)

are tightly-coupled. ➢ As they are tightly coupled they

cannot work independently of each other.

➢ Changing the code in super class method also affects the subclass functionality.

➢ If super class method is deleted, the code may not work

1.4 STRING HANDLING

➢ A string in Java is defined as an object that represents a sequence of characters.

➢ char c [ ] = { ‘B’,’A’,’L’,’A’}; is equal to String s = “BALA”;

➢ String class is used to create object for it.

There are two ways to create String object: 1. By string literal 2. By new keyword 1.4.1 STRING LITERAL

➢ Java String literal is created by using double quotes. For Example:

String s="welcome"; ➢ Each time you create a string literal, the

JVM checks the string constant pool first.

➢ If the string already exists in the pool, a reference to the pooled instance is returned.

➢ If string doesn't exist in the pool, a new string instance is created and placed in the pool.

BY NEW KEYWORD ➢ String s=new String("Welcome");//creates

two objects and one reference variable

JAVA STRING EXAMPLE PROGRAM public class StringExample {

public static void main(String args[]) {

String s1="java"; char ch[]={'s','t','r','i','n','g','s'}; String s2=new String(ch); String s3= System.out.println(s1); system.out.println(s1); System.out.println(s2); System.out.println(s3); }

}

String manipulation:- class str { public static void main(String bala[ ] ) { String s = “sachin”; System.out.println(“s.concat(“SIR”)); System.out.println(s.length()); System.out.println(s+”SIR”); System.out.println(s.charAt(3)); String s2 = “BALA”; System.out.println(s.equals(s2)); String s3 = “bala”; System.out.println(s2.equalsIgnoreCase(s3)); System.out.println(s.substring(1,4)); System.out.println(s.substring(2)); String s4 = s2.replace(‘L’,’B’); System.out.println(s4);

Page 6: CS6501 INTERNET PROGRAMMING UNIT I JAVA PROGRAMMING

VELTECH HIGHTECH Dr.RANGARAJAN Dr.SAKUNTHALA ENGINEERING COLLEGE DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING

VELTECH HIGHTECH Dr.RANGARAJAN Dr.SAKUNTHALA ENGINEERING COLLEGE Page 6

System.out.println(s.toUpperCase()); System.out.println(s2.toLowerCase()); System.out.println(s3.lastIndexOf(‘a’)); } } O/P

SachinSIR 6 sachinSIR h false true ach chin BABA SACHIN Bala 3

1.5 PACKAGES

➢ A package is a collection of classes and interfaces that provides a high-level layer of access protection and name space management.

➢ To organize files when a project consists of multiple modules.

➢ It eliminates naming conflicts when different packages have classes same names.

➢ Packages access level also allows protecting data from non-authorized classes.

➢ Some of the existing packages in Java are:: java.lang - bundles the fundamental classes java.io - classes for input , output functions are bundled in this package

1.5.1 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 PACKAGE SYNTAX Package name of the package;

PACKAGE EXAMPLE PROGRAM

package letmecalculate; public class Calculator { public int add(int a, int b) { return a+b; } public static void main(String args[]){ Calculator obj = new Calculator(); System.out.println(obj.add(10, 20)); } }

import letmecalculate.Calculator; public class Demo{ public static void main(String args[]){ Calculator obj = new Calculator(); System.out.println(obj.add(100, 200)); } }

1.6 EXCEPTION HANDLING

➢ An exception is a problem that arises during the execution of a program

➢ Its breaks the normal flow of the execution.

➢ So these exceptions have to be handled efficiently in order to avoid program getting crashed.

Page 7: CS6501 INTERNET PROGRAMMING UNIT I JAVA PROGRAMMING

VELTECH HIGHTECH Dr.RANGARAJAN Dr.SAKUNTHALA ENGINEERING COLLEGE DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING

VELTECH HIGHTECH Dr.RANGARAJAN Dr.SAKUNTHALA ENGINEERING COLLEGE Page 7

REASONS FOR EXCEPTION ➢ User entered invalid input. ➢ File not found ➢ Network connection lost ➢ JVM ran out of memory BENEFITS OF EXCEPTION ➢ Avoid crashing of applications abruptly. ➢ Various types of errors grouped together. 1.6.1 TYPES OF EXCEPTION

i) Checked exception ➢ It occurs during the compile time. ➢ It cannot be ignored. ➢ Programmer should take care/handle

exceptions. ➢ Ex: FileNotFoundException ii) Unchecked exception ➢ It occurs during runtime ➢ It includes programming bugs, logical

errors, etc. ➢ It is ignored at the run time. ➢ int num[] = {1,2,3}; ➢ System.out.println(num[10]);

Error: ArrayIndexOutOfBoundsException

➢ It is not exception, but actually problems. ➢ They occur beyond the programmers’

control ➢ It is ignored, because we cannot do

anything about it. ➢ Ex: StackOverFlowError, JVM out of

memory error.

Keywords used try

Error prone block of code to be monitored for exception

catch Each corresponding ‘try’ block

finally The code that must be executed even though exception may/may

not occur. throw To throw the specific

exception from program code

throws It specifies exceptions that can be thrown by particular method

1.6.2 EXCEPTION HANDLING EXAMPLE

PROGRAM

Class sample1 {

public static void main(String bala[]) {

int a; try {

a=10/0; } catch(ArithmeticException e) {

System.out.println("Div by zero error"); }

} }

1.6.3 MULTIPLE CATCH BLOCKS FOR A

SINGLE TRY BLOCK

class sample1 {

public static void main(String bala[]) {

int a[] = new int[5]; try {

System.out.println(a[10]);

System.out.println(10/0); }

Page 8: CS6501 INTERNET PROGRAMMING UNIT I JAVA PROGRAMMING

VELTECH HIGHTECH Dr.RANGARAJAN Dr.SAKUNTHALA ENGINEERING COLLEGE DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING

VELTECH HIGHTECH Dr.RANGARAJAN Dr.SAKUNTHALA ENGINEERING COLLEGE Page 8

catch(ArrayIndexOutOfBoundsException e)

{ System.out.println(e);

} catch(ArithmeticException e) {

System.out.println(e); }

} }

O/p:- java.lang.ArrayIndexOutOfBoundsException: 10 1.6.4 FINALLY BLOCK

class sample1 {

public static void main(String bala[]) {

try {

System.out.println(10/0); } catch(ArithmeticException e) {

System.out.println(e); } finally {

System.out.println("This is from Finally block"); }

} } O/p:- java.lang.ArithmeticException: / by zero This is from Finally block

Method that throws exception class sample1 {

static void xyz(int a[]) {

try {

System.out.println(a[10]); } catch(ArrayIndexOutOfBounds

Exception e) {

System.out.println(e);

}

public static void main(String bala[])

{ int a[] = {1,2}; xyz(a);

} } O/p:- java.lang.ArrayIndexOutOfBoundsException: 10

1.7 THREAD

➢ A thread in java is defined as the smallest unit of a program that runs continuously, which is a part of a process.

➢ It is a light weight process in Java ➢ Each thread performs a certain task.

THREAD IMPLEMENTATION:- 1. By extending “Thread” class 2. By implementing “Runnable” interface

1.7.1 LIFE CYCLE OF THREAD

Page 9: CS6501 INTERNET PROGRAMMING UNIT I JAVA PROGRAMMING

VELTECH HIGHTECH Dr.RANGARAJAN Dr.SAKUNTHALA ENGINEERING COLLEGE DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING

VELTECH HIGHTECH Dr.RANGARAJAN Dr.SAKUNTHALA ENGINEERING COLLEGE Page 9

➢ 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.

STATES OF A JAVA THREAD:- ➢ New: A new thread begins its life cycle

in the new state. It remains in this state until the program starts the thread.

➢ Runnable: After a newly born thread is started, the thread becomes runnable. A thread in this state is considered to be executing its task.

➢ Waiting: Sometimes, a thread transitions to the waiting state while the thread waits for another thread to perform a task. A

➢ Timed waiting: A runnable thread can enter the timed waiting state for a specified interval of time.

➢ Terminated: A runnable thread enters the terminated state when it completes its task or otherwise terminates.

THREAD EXAMPLE PROGRAM

class ex1 extends Thread {

public void run() {

System.out.println(“Thread is running”); } public static void main(String bala[ ] ) {

ex1 e = new ex1( ); e.start( );

} }

➢ run() is the method used to tell a thread, what task it should perform while running.

➢ start() is the method used to start execution of a thread

➢ Thread scheduler handles all the thread processes.

Some popular Thread methods in Java:- class sleep extends Thread {

public void run() {

for(int i = 0; i < 2; i++) { try {

Thread.sleep(1000); } catch(InterruptedException e) {

System.out.print("Exception here"); } System.out.println(i); System.out.println(Thread.currentThr

ead) getName()); }

} public static void main(String bala[ ] ) {

sleep s1 = new sleep(); System.out.println(s1.getName() ); s1.setName("bala");

Page 10: CS6501 INTERNET PROGRAMMING UNIT I JAVA PROGRAMMING

VELTECH HIGHTECH Dr.RANGARAJAN Dr.SAKUNTHALA ENGINEERING COLLEGE DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING

VELTECH HIGHTECH Dr.RANGARAJAN Dr.SAKUNTHALA ENGINEERING COLLEGE Page 10

System.out.println(s1.getName() ); s1.start();

} } O/p:- Thread-0 name of thread1 Bala Thread name modified 0 for loop’s i value printed Bala current thread name is printed 1 for loop’s i value printed Bala current thread name is printed 1.7.2 MULTI THREADING

➢ Multithreading is the process of

executing more than one thread at a time.

➢ Each thread performs a specific task ➢ All the threads run simultaneously ➢ OS divides the processing time among

each thread ➢ Thereby the available CPU resources

are optimally used when a computer has multiple CPUs.

➢ Performing multiple activities in a program concurrently is called multithreading.

EXAMPLE MULTI THREADING PROGRAM class class1 extends Thread {

public void run() {

System.out.print("onetask");

} }

class class2 extends Thread {

public void run() {

System.out.print("twotask")

} } class MT {

public static void main(String aad[])

{ class1 c1=new class1(); class2 c2=new class2(); c1.start(); c2.start();

} }

➢ We cannot guarantee which thread is executed first

➢ Thread scheduler decides it based on optimality

ADVANTAGES OF MULTI-THREADING:- ➢ More than one task executed

simultaneously ➢ Time saving and efficient ➢ Quicker execution ➢ Less memory space occupied by each

thread ➢ It is useful in developing Gaming

applications, graphics

IO STREAM ➢ A stream is defined as a continuous

flow of objects sequentially. ➢ In Java, A stream is defined as a

channel on which data flow from sender to receiver

➢ Categories: Input stream and output stream

➢ java.io package contains all the classes required for input and output operations.

Page 11: CS6501 INTERNET PROGRAMMING UNIT I JAVA PROGRAMMING

VELTECH HIGHTECH Dr.RANGARAJAN Dr.SAKUNTHALA ENGINEERING COLLEGE DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING

VELTECH HIGHTECH Dr.RANGARAJAN Dr.SAKUNTHALA ENGINEERING COLLEGE Page 11

➢ Input Stream: Input stream is defined as an object that reads a stream of data from a file

➢ Output Stream: Output stream is defined as an object that writes stream of data to a file

➢ Nature of stream: Byte Stream and character stream

Byte Stream ➢ To give input and get output in bytes ➢ Super classes available: InputStream,

OutputStream ➢ Methods: read(), write()

InputStream classes OutputStream classes

FileInputStream PipedInputStream FilterInputStream ByteArrayInputStream

FileOuputStream PipedOuputStream FilterOuputStream ByteArrayOuputStream

Character Stream ➢ To give input and get output in

character ➢ Super classes available: Reader, Writer ➢ Methods: read(), write()

Classes in Reader Classes in Writer

FileReader PipeReader FilterReader ByteArrayreader

FileWriter PipeWriter FilterWriter ByteArrayWriter

➢ Example for FileInputStream and FileOutputStream classes import java.io.*; class fis {

public static void main(String bala[ ] ) {

int n; try {

InputStream is = new FileInputStream("bala.txt"); System.out.println("Total

Bytes = "+(n=is.available())); for(int i = 0; i <n; i++) System.out.println((char)is.rea

d()); is.close();

} catch(FileNotFoundException

e1) {

System.out.print(e1); } catch(IOException e2) {

System.out.print(e2); }

} } O/p:- Total bytes = 20

➢ This is the file content from bala.txt BufferedInputStream and BufferedOutputStream classes ➢ It is preferred over other streams for

R/W operations ➢ It is more efficient in handling files ➢ All their methods are extended from

InputStream and OutputStream class which are their parents.

➢ We can specify buffer size (default size = 512 bytes)

import java.io.*; class buf { public static void main(String bala[ ] )

Page 12: CS6501 INTERNET PROGRAMMING UNIT I JAVA PROGRAMMING

VELTECH HIGHTECH Dr.RANGARAJAN Dr.SAKUNTHALA ENGINEERING COLLEGE DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING

VELTECH HIGHTECH Dr.RANGARAJAN Dr.SAKUNTHALA ENGINEERING COLLEGE Page 12

{ try {

DataOutputStream dos = new DataOutputStream(new BufferedOutputStream(new FileOutputStream("bala.txt"))); dos.writeUTF("Bala"); dos.writeDouble(12345.67); dos.writeInt(1234); dos.writeChar('s'); dos.close(); DataInputStream dis = new DataInputStream(new BufferedInputStream(new FileInputStream("bala.txt")); System.out.println(dis.readUTF

()); System.out.println(dis.readDo

uble()); System.out.println(dis.readInt(

)); System.out.println(dis.readCha

r()); } catch(FileNotFoundException e1) {

System.out.print(e1); } catch(IOException e2) {

System.out.print(e2); }

} } APPLET ➢ Applets are small Java programs that

can be used in internet ➢ They can be transferred over internet

from one PC to another, displayed on Java enabled web browsers

Uses: To perform arithmetic operations, display graphics, play sounds, display videos, etc Situations for applet usage:- ➢ To display dynamic web pages ➢ To display special effects

(Audio/Video) ➢ To transfer an application to a user

who is located remotely Life Cycle of an Applet:

Four methods in the Applet class give you the framework on which you build any serious applet:

➢ init: This method is intended for whatever initialization is needed for your applet.

➢ ➢ start: This method is automatically

called after the browser calls the init method.

➢ ➢ stop: This method is automatically

called when the user moves off the page on which the applet sits.

➢ ➢ destroy: This method is only

called when the browser shuts down normally.

➢ paint: Invoked immediately after the start() method, and also any time the applet needs to repaint itself in the

Page 13: CS6501 INTERNET PROGRAMMING UNIT I JAVA PROGRAMMING

VELTECH HIGHTECH Dr.RANGARAJAN Dr.SAKUNTHALA ENGINEERING COLLEGE DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING

VELTECH HIGHTECH Dr.RANGARAJAN Dr.SAKUNTHALA ENGINEERING COLLEGE Page 13

browser. The paint() method is actually inherited from the java.awt.

Differences between applet and application ➢ Applet does not have main() method ➢ On loading applets, some methods of

applet are called automatically by JVM ➢ It cannot work independently ➢ They cannot read from a file, cannot

write into a file ➢ They cannot execute any program in

local PC ➢ They cannot communicate with other

server in a network ➢ They cannot use library files of other

languages ➢ They are more secured

HIERARCHY OF APPLET

Advantages Disadvantages

Simple, good GUI Java-plugin web browsers needed

Supports many platforms

GUI based programming is complex, compared to latest PHP, HTML&CSS

Supported by many Takes a lot of

browsers downloading time

Suitable for Real time apps

Slow to execute

Client-server communication is possible

Outdated as of now

APPLET SAMPLE PROGRAM

import java.awt.*; import java.applet.*; public class smiley extends Applet { public void paint(Graphics g) { g.drawOval(60,60,200,200); g.fillOval(90,120,50,20); g.fillOval(190,120,50,20); g.drawLine(165,125,165,175); g.drawArc(110,130,95,95,0,-180); } } O/p:- D:\>javac smiley.java D:\>appletviewer smiley.java

BASIC CONCEPTS OF OOPS

Java is an Object-Oriented Language. As a language that has the Object Oriented feature, Java supports the following fundamental concepts:

➢ Polymorphism

➢ Inheritance

➢ Encapsulation

➢ Abstraction

Page 14: CS6501 INTERNET PROGRAMMING UNIT I JAVA PROGRAMMING

VELTECH HIGHTECH Dr.RANGARAJAN Dr.SAKUNTHALA ENGINEERING COLLEGE DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING

VELTECH HIGHTECH Dr.RANGARAJAN Dr.SAKUNTHALA ENGINEERING COLLEGE Page 14

➢ Classes

➢ Objects

➢ Method

➢ Message Parsing

Object Any entity that has state and Behavior is known as an object. For example: chair, pen, table, keyboard, bike etc. It can be physical and logical.

Class Collection of objects is called class. It is a logical entity.

Inheritance When one object acquires all the properties and behaviours of parent object i.e. known as inheritance. It provides code reusability. It is used to achieve runtime polymorphism.

Polymorphism When one task is performed by different ways i.e. known as polymorphism. For example: to convense the customer differently, to draw something e.g. shape or rectangle etc. In java, we use method overloading and method overriding to achieve polymorphism. Another example can be to speak something e.g. cat speaks meaw, dog barks woof etc.

Abstraction Hiding internal details and showing functionality is known as abstraction. For example: phone call, we don't know the internal processing. In java, we use abstract class and interface to achieve abstraction.

Encapsulation Binding (or wrapping) code and data together into a single unit is known as encapsulation. For example: capsule, it is wrapped with different medicines. A java class is the example of encapsulation. Java bean is the fully encapsulated class because all the data members are private here.

INNER CLASS

➢ Inner class in java is defined as a

class within another class ➢ They are also called as nested class

SYNTAX OF INNER CLASS Class one { Class two { ------- ------- } }

Static inner class ➢ They are the static members of

another class ➢ Static keyword is present before the

inner class ➢ Static member of outer class are

visible to static inner class ➢ Non static members of outer lass are

invisible to static inner class EXAMPLE PROGRAM FOR STATIC INNER CLASS class outer { static class inner {

Page 15: CS6501 INTERNET PROGRAMMING UNIT I JAVA PROGRAMMING

VELTECH HIGHTECH Dr.RANGARAJAN Dr.SAKUNTHALA ENGINEERING COLLEGE DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING

VELTECH HIGHTECH Dr.RANGARAJAN Dr.SAKUNTHALA ENGINEERING COLLEGE Page 15

public void imethod() { System.out.println("Inner class"); } } public static void main(String[ ] bala) { outer o = new outer(); inner i = new inner(); i.imethod(); } } O/p:- Inner class Normal inner class ➢ They are non-static member of outer

class ➢ They can access only non-static

members of outer class EXAMPLE PROGRAM FOR NORMAL INNER CLASS class outer { class inner { public void imethod() { System.out.println("inner class"); } } void omethod() { inner i = new inner(); i.imethod(); } } public class innernormal { public static void main(String bala[ ]) { outer o = new outer(); o.omethod();

} }

O/p:- Inner class

ARRAY ➢ An array in Java is defined as a

collection of elements of similar data type

➢ which are stored in continuous memory locations.

➢ The elements are accessed by their indexes.

➢ Array index always starts from zero ➢ The size of the array is fixed. ➢ All the elements are stored under

the same name. ARRAY DECLARATION SYNTAX ✓ int a [ ] = new int [ 5 ] ; //declaration ✓ int [ ] a = new int [ 5 ]; //another way

of declaration ✓ int [ ] a = {1,2,3}; // declared and

initialized Types:- ➢ Single Dimensional array (1-D array) ➢ Multi-dimensional array (n-D array)

1-D array example:- class array { public static void main(String bala [ ] ) { int a [ ] = { 1, 2, 3 }; for(int i = 0; i < 3 ; i++) System.out.println(a[i]); } } O/p:- 3 6 9

Page 16: CS6501 INTERNET PROGRAMMING UNIT I JAVA PROGRAMMING

VELTECH HIGHTECH Dr.RANGARAJAN Dr.SAKUNTHALA ENGINEERING COLLEGE DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING

VELTECH HIGHTECH Dr.RANGARAJAN Dr.SAKUNTHALA ENGINEERING COLLEGE Page 16

2-D array example:- class array { public static void main(String bala [ ] ) { int a [ ] [ ] = { { 1, 1, 1 }, {1,1,1}, {1,1,1} } ; for(int i = 0; i < 3 ; i++) for(int j = 0; j<3; j++) System.out.println(a[ i ] [ j ] ); } } O/p:- 3 3 3

CONSTRUCTORS

➢ Constructor in java is a special type of method that is used to initialize the object.

➢ constructor is invoked at the time of object creation.

Rules for creating java constructor There are basically two rules defined for the constructor. 1.Constructor name must be same as its class name 2. Constructor must have no explicit return type Types of java constructors There are two types of constructors: 1. Default constructor (no-arg constructor) 2. Parameterized constructor Example of default constructor In this example, we are creating the no-arg constructor in the Bike class. It will be invoked at the time of object creation. class Bike1 {

Bike1() {

System.out.println("Bike is created"); }

public static void main(String args[]) {

Bike1 b=new Bike1(); }

} Output: Bike is created Java parameterized constructor A constructor that have parameters is known as parameterized constructor. Parameterized constructor is used to provide different values to the distinct objects. In this example, we have created the constructor of Student class that have two parameters. We can have any number of parameters in the constructor. class Student4

{

int id;

String name;

Student4(int i, String n)

{ id = i;

name = n; }

void display()

{

System.out.println(id+" "+name);

}

public static void main(String args[])

{Student4 s1 = new Student4(111,"Karan");

Student4 s2 = new Student4(222,"Aryan"); s1.display(); s2.display();

}}

Output: 111 Karan

Page 17: CS6501 INTERNET PROGRAMMING UNIT I JAVA PROGRAMMING

VELTECH HIGHTECH Dr.RANGARAJAN Dr.SAKUNTHALA ENGINEERING COLLEGE DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING

VELTECH HIGHTECH Dr.RANGARAJAN Dr.SAKUNTHALA ENGINEERING COLLEGE Page 17

LIST THE ACCESS SPECIFIER USED IN JAVA? Java provides a number of access modifiers to set access levels for classes, variables, methods and constructors. The four access levels are: • Visible to the package. the default. No modifiers are needed. • Visible to the class only (private). • Visible to the world (public). • Visible to the package and all subclasses (protected).

PREVIOUS YEAR UNIVERSITY 2 MARKS QUESTION

1. Give the different types of type casting in

java with example program.(NOV/DEC

2016)

2. Mention the way in which the current

state of a thread can be obtain. (NOV/DEC

2016)

3. Difference between overriding and

overloading(MAY/JUNE 2016)

4. Example of chained exception(MAY/JUNE

2016)

5. JAVA program for floating point

division(APR/MAY 2017)

6. Difference between package and

interface(APR/MAY 2017)

7. Define Abstract class(NOV/DEC 2015)

8. Features of JAVA(NOV/DEC 2015)

9. Difference between abstract class and

interface(NOV/DEC 2017)

10. Define APPLET(NOV/DEC 2017)

PREVIOUS YEAR UNIVERSITY 16 MARKS QUESTIONS

1. Explain the types of constructor (NOV/DEC 2016)

2. Explain multi level inheritance(NOV/DEC 2016)

3. Explain exception handling(NOV/DEC 2016 & 2015)

4. Explain Buffer reader (NOV/DEC 2016) 5. Explain thread(APR/MAY 2017 &

(NOV/DEC 2017)) 6. Explain APPLET(APR/MAY 2017) 7. Explain Multi threading(NOV/DEC

2015) 8. Explain interface(NOV/DEC 2017)

IMPORTANT 2 MARKS QUESTION:

1. How java is platform independent?

2. Differentiate a vector and an array in Java.

3. How to create two-dimensional array in Java

4. Is there any error in the given Java Statement? Analyze:

char [] string = “abcdef”;

5. Write down the fundamentals of Exception handling.

6. Define Multithreaded Programming.

7. What are the two ways for creating a Thread?

8. What is static in Java? Give its uses.

9. Mention the purpose of the keyword “final”.

10.Can an abstract class in Java be instantiated? Give the reason.

11.What is the difference between constructor and a method?

12. What is the difference between method overloading and overriding?

13.How do you define an interface?

14. What is finalize() and Garbage Collection?

Page 18: CS6501 INTERNET PROGRAMMING UNIT I JAVA PROGRAMMING

VELTECH HIGHTECH Dr.RANGARAJAN Dr.SAKUNTHALA ENGINEERING COLLEGE DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING

VELTECH HIGHTECH Dr.RANGARAJAN Dr.SAKUNTHALA ENGINEERING COLLEGE Page 18

15.How does a radio button in java differ from a check box?

16.Why do you need run () and start () method both.

17.What is a Stream? Which class allows you to read objects directly from a stream?

18.What is Polymorphism in Java? Explain how Polymorphism is supported in Java?

19.Mention the subclasses of the AWT Event class.

20.Code a Graphics method in Java to draw the String “Hello World” from the

coordinates (100,200).

IMPORTANT 16 MARKS QUESTION:

1 Explain the features and structure of Java Program.

2 Explain about Inheritance and Interfaces in Java.

3 Show how compile- time and run- time polymorphism are achieved in Java? Explain

with examples.

4 Explain about Packages and Abstract classes in Java.

5 Explain about Applet Lifecycle? How Applets are prepared and executed?

6 List and discuss the role of String and String Buffer classes used in Java.

7 What are the different input and output streams and their classes? Explain with

Examples?

8 Discuss about Exception handling in Java with suitable examples.

9 Discuss the different models of Threads and their states.

10 Design and Write a Java Program using Applets

Page 19: CS6501 INTERNET PROGRAMMING UNIT I JAVA PROGRAMMING

VELTECH HIGHTECH Dr.RANGARAJAN Dr.SAKUNTHALA ENGINEERING COLLEGE DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING

VELTECH HIGHTECH Dr.RANGARAJAN Dr.SAKUNTHALA ENGINEERING COLLEGE Page 19

CS6501 INTERNET PROGRAMMING

UNIT II WEBSITES BASICS, HTML 5, CSS

3, WEB 2.0 8 Web 2.0

Basics-2.1 RIA Rich Internet Applications – 2.2 Collaborations tools – 2.3 Understanding websites and web servers: 2.4 Understanding Internet – 2.5 Difference between websites and web server- 2.6 Internet technologies Overview –2.7 Understanding the difference between internet and intranet; HTML and CSS: 2.8 HTML 5.0 , 2.9 XHTML, 2.10 CSS 3

2.1 RICH INTERNET APPLICATIONS

➢ RIA (Rich Internet Application) is defined as a web application that is designed to give the same features and functions associated with desktop applications. ➢ HTML is not having much capability

and performance in web apps ➢ Users need desktop type of

interaction from web apps ➢ RIA fulfils this need, user interactivity ➢ It is the 3rd generation of web apps ➢ It runs inside a web browser and does

not need any special software installation (plug&play)

2.1.1 FEATURES OF RIA ➢ Ability to work on web

➢ Rich set of visual elements like image, video, graphics, etc

➢ It works in real-time, helps business services

➢ Users can know how to use complex apps

➢ Reduce unnecessary page navigations ➢ Responsiveness, interactivity ➢ Ex: Apache Flex, Quick PHP, .NET

framework, JavaFX

➢ GUI logic moved from server to client

Page 20: CS6501 INTERNET PROGRAMMING UNIT I JAVA PROGRAMMING

VELTECH HIGHTECH Dr.RANGARAJAN Dr.SAKUNTHALA ENGINEERING COLLEGE DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING

VELTECH HIGHTECH Dr.RANGARAJAN Dr.SAKUNTHALA ENGINEERING COLLEGE Page 20

➢ Because GUI is executed in browser ➢ GUI state is kept in browser ➢ Because GUI is separated from app logic, it is

easy to implement ➢ RIA communicate with servers by exchanging

data, not the GUI code (HTML, CSS, JS) ➢ Data exchange: XML via HTTP (or) JSON via

HTTP ➢ If server side becomes completely free, then

the app logic will become very clear to understand

2.1.2 BENEFITS OF RIA ➢ Increased productivity, new customers ➢ Reduced operational costs ➢ No installation required ➢ Easy upgrade ➢ Available through internet ➢ Client/server balance ➢ Asynchronous communication ➢ Efficiency in network

2.1.3 LIMITATIONS OF RIA ➢ Too fast in displaying contents ➢ Maintain balance between HTML and RIA ➢ GUI logic and app logic might be in

different languages ➢ Search engines are declining ➢ Complicated to develop apps, what to

cache, what not to. ➢ Breaks web page paradigm

POSSIBLE QUESTIONS FROM RIA 2 marks 1. Define RIA[APRIL/MAY 2017]

2. Features of RIA

16 marks 1. Explain rich internet application

2.2 COLLABORATION TOOLS

➢ Collaboration is a process defined by the recursive interaction of knowledge and mutual learning between two or more people who are working together

➢ Collaboration tools allow a group of

people work together virtually in real-time over the internet.

2.2.1 COLLABORATION TOOLS

FEATURE

Easy to use and set up.

Clean interface

Secure Permissions control

Ability to upload documents

File storage

Scalable Document locking

2.2.2 EXAMPLE TOOLS

Examples:- Tool

Use

Google Docs Upload/modify/retrieve files anytime

Dropbox Store/share/sync files online

Blogger Blogging site of google

Wordpress Flexible, FOSS, easy blogging tool

PDFcatch e-books, PDF search engine

SlideShare PPT, PDF share/upload/download

Youtube Upload/download/view videos

Page 21: CS6501 INTERNET PROGRAMMING UNIT I JAVA PROGRAMMING

VELTECH HIGHTECH Dr.RANGARAJAN Dr.SAKUNTHALA ENGINEERING COLLEGE DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING

VELTECH HIGHTECH Dr.RANGARAJAN Dr.SAKUNTHALA ENGINEERING COLLEGE Page 21

Facebook Upload/download/view micro contents

Twitter Upload/doenload/view thoughts

2.2.3 ADVANTAGES OF COLLABORATION TOOLS ➢ Reduces distance between employees ➢ Work in same room, together in same

documents ➢ No need to send documents back and

forth between offices ➢ Communication between employees is

improved ➢ Increases team work and transparency ➢ Easy to keep track of projects ➢ Easy to generate reports ➢ Team members can be present anywhere ➢ Online chatting ➢ IRC (Internet relay Chat) ➢ Video conferencing

POSSIBLE QUESTIONS FROM COLLABORATION TOOLS

2 marks 1. Define collaboration 2. List some of the collaboration tools

2.3 UNDERSTANDING WEBSITES AND WEB SERVERS WEB PAGE A document which can be displayed in a web browser such as Firefox, Google Chrome, Microsoft Internet Explorer or Edge, or Apple's Safari. These are also often called "web pages" or just "pages."

WEBSITE A collection of web pages which are grouped together and usually connected together in various ways. Often called a "web site" or simply a "site."

WEB SERVER A computer that hosts a website on the Internet.

2.4 INTERNET

➢ Internet is a world-wide / global system of interconnected computer networks

➢ Internet uses the standard Internet Protocol (TCP/IP)

➢ Every computer in internet is identified by a unique IP address.

➢ IP Address is a unique set of numbers (such as 110.22.33.114) which identifies a computer‘s location.

➢ A special computer DNS (Domain Name Server) is used to give name to the IP Address so that user can locate a computer by a name.

➢ For example, a DNS server will resolve a name http://www.tutorialspoint.com to a particular IP address to uniquely identify the computer on which this website is hosted. ➢ Internet is accessible to every user all over the world. ➢ Internet = Network of networks

2.4.1 ESSENTIALS FOR INTERNET CONNECTION

➢ Computer – DSL, Application software ➢ Connection – Modem, ISP ➢ Cable – TCP/IP protocol, wireless

Page 22: CS6501 INTERNET PROGRAMMING UNIT I JAVA PROGRAMMING

VELTECH HIGHTECH Dr.RANGARAJAN Dr.SAKUNTHALA ENGINEERING COLLEGE DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING

VELTECH HIGHTECH Dr.RANGARAJAN Dr.SAKUNTHALA ENGINEERING COLLEGE Page 22

2.4.2 WORKING OF INTERNET

2.4.3 EVOLUTION OF INTERNET ➢ It was introduced in 1969 at

ARPANET (Advanced research project Agency),USA

➢ It’s prime purpose was to connect among various bodies of US government

➢ Initially there were only four nodes (Hosts)

➢ In 1972, ARPANET was spread across the globe with 23 nodes

➢ All the other organizations in respective countries joined to this network

➢ Around 1990s, Tim Berners Lee and O-Reilly had developed WWW and other internet communication protocols

2.4.4 TERMINOLOGIES USED IN INTERNET

➢ Host: A computer that is connected

to internet ➢ Communication service: Protocols to

send and receive data over the internet such as FTP, HTTP, WWW, VoIP, etc.

➢ ISP: provide internet connectivity to its subscribers. Ex: BSNL ➢ Online: When a computer is

connected to internet ➢ Hyperlink: Allows an user to move

from one page to another

➢ Protocols: Set of rules for communication

➢ TCP/IP: to establish a virtual connection between source and destination.

➢ Client/Server Model: TCP/IP uses this model where a client refers to any computing device that generates HTTP request and server refers to any computer that responds to the corresponding request

➢ IP address: It is the unique address assigned to a computing device that gets connected to the internet.

➢ DNS: Domain Name Servers are used to translate the website names given by the users into machine understandable IP addresses from a database.

➢ URL: Uniform Resource Locator (URL) is defined as an unique address for the file that has to be accessed over the internet.

➢ WWW: It is a standard in which all the websites are server on the internet via HTTP

2.4.5 INTERNET WORKING STYLE ➢ From a web browser, user sends HTTP

request to a server ➢ ISP finds the corresponding site from DNS and

forwards it. ➢ The request reaches the server after a long

travel ➢ Server responds to that request and the reply

goes back ➢ Any file transmitted in internet will not be

send as a whole ➢ All the information will be chopped into

chunks (data packets) ➢ Packets have header and footer info,

useful for ordering

Page 23: CS6501 INTERNET PROGRAMMING UNIT I JAVA PROGRAMMING

VELTECH HIGHTECH Dr.RANGARAJAN Dr.SAKUNTHALA ENGINEERING COLLEGE DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING

VELTECH HIGHTECH Dr.RANGARAJAN Dr.SAKUNTHALA ENGINEERING COLLEGE Page 23

2.4.6 PROTOCOLS USED IN INTERNET

FTP (File transfer Protocol) ➢ FTP is used to share files among the

computers in the LAN ➢ It uses two connections (data

transfer and control) ➢ FTP data transfer connection uses

port 20 ➢ FTP control connection uses port 21 ➢ Some familiar commands in FTP are:

USER, PASS, QUIT, CWD, DELE, LIST, RETR, STOR, HELP

HTTP (Hyper Text Transfer protocol) ➢ Hyper Text Transfer protocol (HTTP) is a

stateless protocol for communication, to transfer information on LAN and WWW

➢ It is used to deliver files virtually and other data on WWW

➢ It takes place through TCP/IP sockets ➢ A browser is a HTTP client – sends HTTP

request ➢ A web server is a HTTP server – sends

HTTP reply ➢ It uses port no: 80 (HTTP servers listen to

this port) SNMP (Simple Network Management protocol) ➢ It is used to manage a network such as its

participants, etc ➢ Types of participants: Supervisors, Agents ➢ SNMP make use of UDP connection for

transferring the SNMP message TCP (Transmission Control Protocol ) ➢ Connection oriented (link between the

packets) ➢ ACK is available

➢ Reliable ➢ Heavy weight protocol ➢ Handshaking mechanism available ➢ Error control, flow control, congestion

control mechanisms ➢ Complex, tough to implement ➢ Ex: Telnet, SMTP, FTP, e-mail, SSH, HTTP,

HTTPS

POP3 (Post Office Protocol Version 3) ➢ It is used by local email client ➢ It uses port no 110 ➢ Popo3 protocol works only at the

receivers end ➢ The client can receive the emails from the

mailbox

UDP(User Datagram Protocol) ➢ Connectionless protocol ➢ Used for simply transmission of data ➢ It is an unreliable protocol

DIFFERENCE BETWEEN TCP AND UDP

TCP UDP

Connection oriented (link between the packets)

Connection less

ACK is available No ACK

Reliable Unreliable

Heavy weight protocol Light weight protocol

Handshaking mechanism No handshaking concept

Error control, flow control, congestion control, etc

No control mechanism

Complex, tough to implement

Simple, easy to implement

Ex: Telnet, SMTP, FTP, e-mail, SSH, HTTP, HTTP, HTTPS

Ex: VoIP, DHCP, DNS, RIP, SNMP

POSSIBLE QUESTIONS FROM INTERNET 2 marks

Page 24: CS6501 INTERNET PROGRAMMING UNIT I JAVA PROGRAMMING

VELTECH HIGHTECH Dr.RANGARAJAN Dr.SAKUNTHALA ENGINEERING COLLEGE DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING

VELTECH HIGHTECH Dr.RANGARAJAN Dr.SAKUNTHALA ENGINEERING COLLEGE Page 24

1. Define internet 2. Difference between TCP and UDP

16 marks 1. Explain internet technologies [NOV/DEC

2016] 2. Explain internet protocols

2.5 DIFFERENCE BETWEEN WEBSITE AND WEB SERVER

Website Web server

It is a collection of web pages

It is a server on which web application is executed

It is a software application that has unique domain name

It is a physical entity that has unique IP address

It can host many web pages

It can host many websites

They communicate with web server

They communicate with other servers such as DB server, File server, etc

Web server = HTML&CSS + JS+ DHTML

It receives request and gives corresponding response

Ex: https://www.google.co.in

Ex: IIS, Apache

POSSIBLE QUESTIONS FROM WEBSITE AND WEBSERVER 2 marks

1. Difference between website and webserver[APR/MAY 2017]

2.7 INTRANET ➢ An intranet is a computer network that uses Internet Protocol technology to

share information or computing services within an organization. ➢ intranets are restricted to a particular set of 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 company's Internet sites.

2.7.1 DIFFERENCES BETWEEN INTERNET AND INTRANET

INTERNET INTRANET

Network of networks, open for all

Network of computers, open for group of people

Different sources of info

Limited sources of info

Large no. of intranets

Less number of systems

Internet =LAN + WAN + MAN

Intranet = LAN | WAN | MAN

POSSIBLE QUESTIONS FROM INTERNET AND INTRANET 2 marks

1. Difference between internet and intranet[NOV/DEC 2015]

2.8 BASIC HTML TAGS

Tag Description

<!DOCTYPE> Defines the document type

<html> Defines an HTML document

Page 25: CS6501 INTERNET PROGRAMMING UNIT I JAVA PROGRAMMING

VELTECH HIGHTECH Dr.RANGARAJAN Dr.SAKUNTHALA ENGINEERING COLLEGE DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING

VELTECH HIGHTECH Dr.RANGARAJAN Dr.SAKUNTHALA ENGINEERING COLLEGE Page 25

<head> Defines information about the document

<title> Defines a title for the document

<body> Defines the document's body

<h1> to <h6> Defines HTML headings

<p> Defines a paragraph

<br> Inserts a single line break

<hr> Defines a thematic change in the content

<!--...--> Defines a comment

<form> Defines an HTML form for user input

<input> Defines an input control

<textarea> Defines a multiline input control (text area)

<button> Defines a clickable button

<select> Defines a drop-down list

<optgroup> Defines a group of related options in a drop-down list

<option> Defines an option in a drop-down list

<label> Defines a label for an <input> element

<fieldset> Groups related elements in a form

<img> Defines an image

<map> Defines a client-side image-map

2.8.1 HTML 5 ➢ HTML stands for Hyper Text Mark-up Language ➢ It is used to organize text, graphics, audio, video on a web page

➢ It is a formatting language used to design the contents of a web page ➢ Hypertext means, the text which acts as a link ➢ Mark up means symbols that are used to define structure of the text. It tells browser how to display the text (tags) ➢ Language refers to the syntax ➢ It was invented by Tim-Berners Lee at CERN ➢ HTML 1.0 (1991), HTML 2.0 (1995), HTML 3.2 (1997), HTML 4.0 (1999), XHTML (2000), HTML5 (2014)

2.8.2 FEATURES OF HTML5 ➢ HTML 5.0 is the 5th version of HTML

by W3C (Oct 2014) ➢ To support latest multimedia, more

readable ➢ <audio>, <video>, <canvas>, <svg>

tags are supported ➢ <header>, <footer>, <article>,

<section> are supported ➢ Number, date, time, calendar, range

are suooprted ➢ API available for geolocation,

drag&drop, local storage, etc. ➢ Allows Javascript to run in back side ➢ 2D and 3D drawings supported ➢ Need for flash plugin is reduced

POSSIBLE QUESTIONS FROM RIA 2 marks

1. Define HTML 5 2. Write a HTML code for draw a table

16 marks 1. Explain basic HTML tags[NOV/DEC

2017] 2. Explain Box model 3. Explain about two types of list and

frame set[NOV/ DEC 2017]

Page 26: CS6501 INTERNET PROGRAMMING UNIT I JAVA PROGRAMMING

VELTECH HIGHTECH Dr.RANGARAJAN Dr.SAKUNTHALA ENGINEERING COLLEGE DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING

VELTECH HIGHTECH Dr.RANGARAJAN Dr.SAKUNTHALA ENGINEERING COLLEGE Page 26

4. How to create form in HTML [MAY/JUNE 2016]

5. Draw a time table with using HTML and CSS technique [NOV/DEC 2016]

POSSIBLE QUESTIONS FROM HTML 5

2 marks 1. Define HTML 5

16 marks 1 Explain basic HTML tags[NOV/DEC

2017]

2.9 XHTML ➢ XHTML stands for EXtensible HyperText

Markup Language ➢ XHTML is almost identical to HTML ➢ XHTML is stricter than HTML ➢ XHTML is HTML defined as an XML

application ➢ XHTML is supported by all major browsers

2.9.1 HTML TABLE ➢ An HTML table is defined with the

<table> tag. ➢ Each table row is defined with the

<tr> tag. ➢ A table header is defined with the

<th> tag. ➢ By default, table headings are bold

and centered. ➢ A table data/cell is defined with the

<td> tag.

HTML TABLE SYNTAX <table> <tr> <th>……</th> </tr>

<tr> <td>…..</td> </tr> </table> EXAMPLE HTML TABLE PROGRAM <!DOCTYPE html> <html> <head> <style> table, th, td { border: 1px solid black; } </style> </head> <body> <table style="width:100%"> <tr> <th>First Name</th> <th>Last Name</th> </tr> <tr> <td>Jill</td> <td>Smith</td> </tr> <tr> <td>Eve</td> <td>Jackson</td> </tr> </table> </body> </html> O/P

First Name Last Name

Jill Smith

Eve Jackson

2.9.2 HTML FRAMES

Page 27: CS6501 INTERNET PROGRAMMING UNIT I JAVA PROGRAMMING

VELTECH HIGHTECH Dr.RANGARAJAN Dr.SAKUNTHALA ENGINEERING COLLEGE DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING

VELTECH HIGHTECH Dr.RANGARAJAN Dr.SAKUNTHALA ENGINEERING COLLEGE Page 27

➢ HTML frames are used to divide your browser window into multiple sections where each section can load a separate HTML document.

➢ A collection of frames in the browser window is known as a frameset.

➢ The window is divided into frames in a similar way the tables are organized: into rows and columns.

SYNTAX OF FRAME <frameset > <frame src="top.htm" name="top"/> </frameset> EXAMPLE PROGRAM <!DOCTYPE html> <html> <head> <title>HTML Frames</title> </head> <frameset rows="16%,84%"/> <frame src="top.htm" name="top"/> <frameset cols="50%,50%"/> <frame src="left.htm" name="left"/> <frame src="right.htm" name="right"/> </frameset> </frameset>

</html> O/P:

top

left

right

2.9.3 BOX MODEL ➢ The CSS box model is essentially a box that

wraps around HTML elements, and it consists of: margins, borders, padding, and the actual content. ➢ The different parts are:

• Margin • Border • Padding • Content

<!DOCTYPE >

<html lang="en"> <head>

<title>CSS Box Model Example</title> <style type="text/css">

.example1 { width:220px; background-color: yellow; } .example2 { width:220px; background-color: yellow; margin:40px; }

</style> </head> <body> <h1>Box Model Example</h1> <hr style="width: 100%; height: 1px;"> <p class="example1">My Content

Example 1</p> <hr style="width: 100%; height: 1px;

color: blue;"> <p class="example2">My Content

Example 2</p> </body>

Page 28: CS6501 INTERNET PROGRAMMING UNIT I JAVA PROGRAMMING

VELTECH HIGHTECH Dr.RANGARAJAN Dr.SAKUNTHALA ENGINEERING COLLEGE DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING

VELTECH HIGHTECH Dr.RANGARAJAN Dr.SAKUNTHALA ENGINEERING COLLEGE Page 28

</html> O/P:

Box Model Example

My Content Example 1

My Content Example 2

2.9.4 HTML FORMS ➢ HTML Forms are required, when you

want to collect some data from the site visitor.

➢ For example, during user registration yoU would like to collect information such as name, email address, credit card, etc.

➢ A form will take input from the site visitor and then will post it to a back-end application

➢ The back-end application will perform

Required processing on the passed data based on defined business logic inside the application.

There are different types of form controls

that you can use to collect data using HTML

form –

✓ Text Input Controls

✓ Checkboxes Controls

✓ Radio Box Controls

✓ Select Box Controls

✓ File Select boxes

✓ Hidden Controls

✓ Clickable Buttons

✓ Submit and Reset Button

The HTML <form> tag is used to create

an HTML form and it has following syntax – <form action = "Script URL" method =

"GET|POST"> form elements like input, textarea etc. </form> 2.9.4.1 TEXT INPUT CONTROL

➢ This control is used for items that require only one line of user input, such as search boxes or names.

➢ They are created using HTML <input> tag. PROGRAM <!DOCTYPE html> <html> <head> <title>Text Input Control</title> </head> <body> <form > First name: <input type = "text" name = "first_name" /> </form> </body> </html> O/P : First name: 2.9.4.2 MULTI LINE TEXT BOX CONTROL

Page 29: CS6501 INTERNET PROGRAMMING UNIT I JAVA PROGRAMMING

VELTECH HIGHTECH Dr.RANGARAJAN Dr.SAKUNTHALA ENGINEERING COLLEGE DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING

VELTECH HIGHTECH Dr.RANGARAJAN Dr.SAKUNTHALA ENGINEERING COLLEGE Page 29

➢ This is used when the user is required to give details that may be longer than a single sentence. ➢ Multi-line input controls are created using HTML <textarea> tag. PROGRAM <!DOCTYPE html> <html> <head> <title>Multiple-Line Input Control</title> </head> <body> <form> Description : <br /> <textarea rows = "5" cols = "50" name = "description"> Enter description here... </textarea> </form> </body> </html> O/P: Description:

2.9.4.3 CHECK BOXCONTROL ➢ Checkboxes are used when more than

one option is required to be selected. ➢ They are also created using HTML <input>

tag but type attribute is set to checkbox..

PROGRAM <!DOCTYPE html> <html> <head> <title>Checkbox Control</title> </head> <body> <form> <input type = "checkbox" name = "maths" value = "on"> Maths <input type = "checkbox" name = "physics" value = "on"> Physics </form> </body> </html> O/P:

Maths Physics

2.9.4.4 RADIO BOX CONTROL ➢ Radio buttons are used when out of

many options, just one option is required to

be selected.

➢ They are also created using HTML

<input> tag but type attribute is set to radio.

PROGRAM <!DOCTYPE html> <html> <head> <title>Radio Box Control</title> </head> <body> <form> <input type = "radio" name = "subject" value = "maths"> Maths <input type = "radio" name = "subject" value = "physics"> Physics </form> </body>

Page 30: CS6501 INTERNET PROGRAMMING UNIT I JAVA PROGRAMMING

VELTECH HIGHTECH Dr.RANGARAJAN Dr.SAKUNTHALA ENGINEERING COLLEGE DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING

VELTECH HIGHTECH Dr.RANGARAJAN Dr.SAKUNTHALA ENGINEERING COLLEGE Page 30

</html> O/P:

Maths Physics 2.9.4.5 SELECT BOX CONTROL ➢ A select box, also called drop down box ➢ which provides option to list down various

options in the form of drop down list, from where a user can select one or more options.

PROGRAM <!DOCTYPE html> <html> <head> <title>Select Box Control</title> </head> <body> <form> <select name = "dropdown"> <option value = "Maths" selected>Maths</option> <option value = "Physics">Physics</option> </select> </form> </body> </html> O/P:

Maths

2.9.4.6 FILE BOX CONTROL ➢ If you want to allow a user to upload a file

to your web site, you will need to use a file upload box, also known as a file select box.

➢ This is also created using the <input> element but type attribute is set to file.

PROGRAM <!DOCTYPE html> <html> <head> <title>File Upload Box</title> </head> <body> <form>

<input type = "file" name =

"fileupload" accept = "image/*" />

</form> </body> </htm>

2.9.5 HTML LISTS HTML offers web authors three ways for specifying lists of information. All lists must contain one or more list elements. Lists may contain − ➢ <ul> − An unordered list. This will list

items using plain bullets. ➢ <ol> − An ordered list. This will use

different schemes of numbers to list your items.

➢ <dl> − A definition list. This arranges your items in the same way as they are arranged in a dictionary.

2.9.5.1HTML UNORDERED LISTS

Page 31: CS6501 INTERNET PROGRAMMING UNIT I JAVA PROGRAMMING

VELTECH HIGHTECH Dr.RANGARAJAN Dr.SAKUNTHALA ENGINEERING COLLEGE DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING

VELTECH HIGHTECH Dr.RANGARAJAN Dr.SAKUNTHALA ENGINEERING COLLEGE Page 31

➢ An unordered list is a collection of related

items that have no special order or

sequence.

➢ This list is created by using

HTML <ul> tag. Each item in the list is

marked with a bullet.

PROGRAM <!DOCTYPE html> <html> <head> <title>HTML Unordered List</title> </head> <body> <ul> <li>Beetroot</li> <li>Ginger</li> <li>Potato</li> <li>Radish</li> </ul> </body> </html> O/P:

• Beetroot • Ginger • Potato • Radish

2.9.5.2 HTML ORDERED LISTS ➢ If you are required to put your items in a

numbered list instead of bulleted, then HTML ordered list will be used.

➢ This list is created by using <ol> tag. ➢ The numbering starts at one and is

incremented by one for each successive ordered list element tagged with <li>.

PROGRAM <!DOCTYPE html>

<html> <head> <title>HTML Ordered List</title> </head> <body> <ol> <li>Beetroot</li> <li>Ginger</li> <li>Potato</li> <li>Radish</li> </ol> </body> </html> O/P:

2. Beetroot 3. Ginger 4. Potato 5. Radish

2.9.5.3 HTML DEFINITION LISTS

➢ HTML and XHTML supports a list style

which is called definition lists where

entries are listed like in a dictionary

or encyclopedia.

➢ The definition list is the ideal way to

present a glossary, list of terms, or

other name/value list.

Definition List makes use of following three

tags.

• <dl> − Defines the start of the list

• <dt> − A term

Page 32: CS6501 INTERNET PROGRAMMING UNIT I JAVA PROGRAMMING

VELTECH HIGHTECH Dr.RANGARAJAN Dr.SAKUNTHALA ENGINEERING COLLEGE DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING

VELTECH HIGHTECH Dr.RANGARAJAN Dr.SAKUNTHALA ENGINEERING COLLEGE Page 32

• <dd> − Term definition

• </dl> − Defines the end of the list

PROGRAM <!DOCTYPE html> <html> <head> <title>HTML Definition List</title> </head> <body> <dl> <dt><b>HTML</b></dt> <dd>This stands for Hyper Text Markup Language</dd> <dt><b>HTTP</b></dt>

<dd>This stands for Hyper Text Transfer Protocol</dd>

</dl> </body> </html> O/P: HTML

This stands for Hyper Text Markup Language

HTTP This stands for Hyper Text Transfer Protocol

POSSIBLE QUESTIONS FROM RIA 2 marks 1. Write a HTML code for draw a table 16 marks

1. Explain Box model 2. Explain about two types of list and frame

set[NOV/ DEC 2017] 3. How to create form in HTML [MAY/JUNE

2016]

4. Draw a time table with using HTML and CSS technique [NOV/DEC 2016]

2.10 CASCADING STYLE SHEET(CSS) ➢ Cascading style sheet is defined as a

style sheet in which, all the style information of a web page can be defined. ➢ 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 XHTML.

2.10.1 TYPES ➢ Inline style sheets ➢ Embedded style sheets ➢ External style sheet ➢ Imported style sheets

2.10.2 EXAMPLE FOR EMBEDDED CSS <HTML> <HEAD> <STYLE TYPE="TEXT/CSS"> P{FONT-FAMILY:CALIBRI; }

H3.A{COLOR:BLUE; } H3.B{FONT-SIZE:40PX} </STYLE> </HEAD> <BODY> <P>SELECTOR</P> <H3 CLASS="A">CLASS SELECTOR 1</H3> <H3 CLASS="B">CLASS SELECTOR 2</H3>

Page 33: CS6501 INTERNET PROGRAMMING UNIT I JAVA PROGRAMMING

VELTECH HIGHTECH Dr.RANGARAJAN Dr.SAKUNTHALA ENGINEERING COLLEGE DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING

VELTECH HIGHTECH Dr.RANGARAJAN Dr.SAKUNTHALA ENGINEERING COLLEGE Page 33

</BODY> </HTML>

O/P : CLASS SELECTOR 1 CLASS SELECTOR 2

2.10.4 EXAMPLE FOR EXTERNAL STYLE SHEET EXTERNALCSS.HTML <HTML> <HEAD> <LINK REL="STYLESHEET TYPE="TEXT/CSS" HREF="EX.CSS"> </HEAD> <BODY>

<P CLASS="FORMAT">FORMATTING</P> <P CLASS="WEIGHT">WEIGHT</P>

</BODY> </HTML>

EX.CSS P.FORMAT {

FONT-FAMILY:ARIAL; FONT-SIZE:25PX;

} P.WEIGHT {

FONT-WEIGHT:BOLD; FONT-STYLE:ITALIC;

} O/P : FORMATTING WEIGHT

2.10.5 EXAMPLE FOR INLINE STYLE SHEET <html> <head> </head> <body> <h2>INLINE CSS</h2>

</body> </html> O/P INLINE CSS

POSSIBLE QUESTIONS FROM CSS 2 marks

1.Define CSS 16 marks

1. Explain CSS [NOV/DEC 2017 & APRIL/MAY 2015 & NOV/DEC 2016]

2.11 WEB 2.0 ➢ Internet has revolutionized the computer

and communications, undergoing extreme make-over

➢ In 1990s, it was used to retrieve information (Read-Only)

➢ Around 2004, new web tools came up, to add contents to web

➢ People with no programming knowledge can publish an article, photo, video, ppt, pdf, etc.

➢ Web has become 2-way communication medium (R/W)

➢ This is called Web 2.0 (bidirectional data traffic)

➢ It is not the second version of Web ➢ It is also called Participatory web (or)

Read/Write Web ➢ Web 2.0 refers to the transition of static

HTML pages to dynamic web ➢ XML is used ➢ It offers freedom for everybody to

contribute to the web ➢ Ex: Wikipedia, FB, YouTube, Twitter, etc.

2.10.1 COMPONENTS OF WEB 2.0

Page 34: CS6501 INTERNET PROGRAMMING UNIT I JAVA PROGRAMMING

VELTECH HIGHTECH Dr.RANGARAJAN Dr.SAKUNTHALA ENGINEERING COLLEGE DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING

VELTECH HIGHTECH Dr.RANGARAJAN Dr.SAKUNTHALA ENGINEERING COLLEGE Page 34

➢ Blogs ➢ Wikis ➢ Web services

2.10.2 FEATURES OF WEB 2.0 ➢ Classify and find required info ➢ Get dynamic contents from the web ➢ Information is shared among all users on

the web ➢ Information is used and reused ➢ Mass participation in discussion forum

2.10.3 TECHNOLOGIES USED IN WEB 2.0 ➢ At client side: client side scripting

languages (AJAX, java script) ➢ At server side: server side scripting languages

(PHP, PYTHON, RUBY, etc)

2.10.4 ADVANTAGES OF WEB 2.0 ➢ Equal chance to all to

post/view/comment/share ➢ Latest/updated contents ➢ Social networking sites are useful to be in

contact ➢ Write reviews about a product ➢ Digital advertisement

2.10.5 DISADVANTAGES OF WEB 2.0 ➢ Increased spam ➢ Information overloaded (everybody posts) ➢ Negative feedback may cause bad

effect on business

POSSIBLE QUESTIONS FROM web 2.0 2 marks

1.Define web 2.0 16 marks

1. Explain web 2.0 [NOV/DEC 2017 ]

Page 35: CS6501 INTERNET PROGRAMMING UNIT I JAVA PROGRAMMING

VELTECH HIGHTECH Dr.RANGARAJAN Dr.SAKUNTHALA ENGINEERING COLLEGE DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING

VELTECH HIGHTECH Dr.RANGARAJAN Dr.SAKUNTHALA ENGINEERING COLLEGE Page 35

CS6501 INTERNET PROGRAMMING

UNIT III CLIENT SIDE AND SERVER SIDE PROGRAMMING

Java Script: 3.1 An introduction to JavaScript–

3.2JavaScript DOM Model-3.3 Date and

Objects,-3.4 Regular Expressions- 3.5

Exception Handling-3.6 Validation-3.7 Built-in

objects-3.8 Event Handling- 3.9 DHTML with

JavaScript. 3.10 Servlets: Java Servlet

Architecture- Servlet Life Cycle- 3.11 Form

GET and POST actions- 3.12 Session Handling-

3.13 Understanding Cookies- 3.14 Installing

and Configuring Apache Tomcat Web Server,

3.15 DATABASE CONNECTIVITY: JDBC

perspectives, JDBC program example – 3.16

JSP: Understanding Java Server Pages- 3.17

JSP Standard Tag Library(JSTL)- 3.18 Creating

HTML forms by embedding JSP code.

3.1 JAVA SCRIPT

➢ JavaScript is a programming language

that can be included on web pages to

make them more interactive.

➢ It is a client-side scripting language developed by Netscape Communications Corp. and Sun Microsystems.

3.1.1 DIFFERENCE BETWEEN JAVA AND

JAVA SCRIPT

JAVA JAVA SCRIPT

Java is an object JavaScript is not

oriented programming language.

an object based programming language.

Java creates application that can run in a virtual machine or browser.

JavaScript code run on browser only.

Objects of Java are class based.

Objects of JavaScript are prototype based.

Java program has file extension “.Java”

JavaScript file has file extension “.js”.

Java program uses more memory

This requires less memory

Page 36: CS6501 INTERNET PROGRAMMING UNIT I JAVA PROGRAMMING

VELTECH HIGHTECH Dr.RANGARAJAN Dr.SAKUNTHALA ENGINEERING COLLEGE DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING

VELTECH HIGHTECH Dr.RANGARAJAN Dr.SAKUNTHALA ENGINEERING COLLEGE Page 36

3.1.2 FEATURES OF JAVASCRIPT

➢ It is useful for page designers ➢ Light weight, interpreted, embedded in

HTML ➢ Network centric apps ➢ JS = JAVA + HTML ➢ To develop dynamic and interactive

pages ➢ To validate data, create cookies

1.2 DOM MODEL

➢ Document Object Model (DOM) is a set of platform independent and language neutral application interface (API) ➢ Its describes how to access and manipulate the information stored in XML, XHTML and javascript documents.

3.2.1 DOM USES

➢ To identify interface and object for representing and manipulating a document ➢ To find behaviour and attributes of interface & object ➢ To find relation between interface and object

3.2.2 LEVELS OF DOM

➢ Level 0 : To access few html elements (by Netscape in 1990s)

➢ Level 1: To change entire web page (1998)

3.2.3 DOM TREE

➢ Documents in DOM are represented using

a tree like structure

➢ Every element is represented as a node

➢ This tree structure is called as DOM tree

3.2.4 METHODS OF DOCUMENT OBJECT

➢ We can access and change the

contents of document by its methods.

➢ The important methods of document

object are as follows:

➢ Level 2:Platform independent, language independent

➢ Level 3: Platform independent, language independent .To access dynamically, update contents, structure, style

POSSIBLE QUESTIONS FROM JAVA SCRIPT

2 MARKS 1. Define java script 2. Difference between java and java

script 3. Uses or features of java script

Page 37: CS6501 INTERNET PROGRAMMING UNIT I JAVA PROGRAMMING

VELTECH HIGHTECH Dr.RANGARAJAN Dr.SAKUNTHALA ENGINEERING COLLEGE DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING

VELTECH HIGHTECH Dr.RANGARAJAN Dr.SAKUNTHALA ENGINEERING COLLEGE Page 37

Method

Description

write("string")

writes the given string on the doucment.

writeln("string

")

writes the given string on the

doucment with newline

character at the end.

getElementBy

Id()

returns the element having the given id value.

getElementsB

yName()

returns all the elements having the given name value.

getElementsB

yTagName()

returns all the elements having

the given tag name.

getElementsB

yClassName()

returns all the elements having

the given class name.

Accessing field value by document object

➢ In this example, we are going to get

the value of input text by user. Here, we are

using document.form1.name.value to get the

value of name field.

Here, document →The root element that

represents the html document.

name →The attribute name of the input text.

value →The property, that returns the value of the input text.

3.2.5 EXAMPLE OF DOCUMENT OBJECT

THAT PRINTS NAME WITH WELCOME

MESSAGE.

<script type="text/javascript">

function printvalue()

{

var name=document.form1.name.value;

alert("Welcome: "+name);

}

</script>

<form name="form1">

Enter Name:<input type="text"

name="name"/>

<input type="button"

onclick="printvalue()" value="print name"/>

</form>

O/P:

POSSIBLE QUESTIONS FROM DOM 2 MARKS

1. Define DOM 2. Draw the structure of DOM tree 3. Levels of DOM

16 MARKS

1. Explain DOM and levels DOM with

example program

Page 38: CS6501 INTERNET PROGRAMMING UNIT I JAVA PROGRAMMING

VELTECH HIGHTECH Dr.RANGARAJAN Dr.SAKUNTHALA ENGINEERING COLLEGE DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING

VELTECH HIGHTECH Dr.RANGARAJAN Dr.SAKUNTHALA ENGINEERING COLLEGE Page 38

3.4 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.

3.4.1 METHODS OF REGULAR

EXPRESSION

Methods that use regular expressions

Method Description

exec A RegExp method that executes

a search for a match in a string.

It returns an array of

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 information or

null on a mismatch.

search A String method that tests for a

match in a string. It returns the

index of the match, or -1 if the

search fails.

replace A String method that executes a

search for a match in a string,

and replaces the matched

substring with a replacement

substring.

split A String method that uses a

regular expression or a fixed

string to break a string into an

array of substrings.

3.4.2 USE OF OBJECT RegExp

➢ Javascript allows to search the desired pattern from the given text using object RegExp

EXAMPLE PROGRAM

<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Transitional//EN” http://www.w3.org/1999/xhtml11.dtd>

<html xmlns = http://www.w3.org/1999/xhtml>

<head>

<script type=”text/javascript”>

Function test(str)

{

Document.write(str);

Var i= new RegExp(“like”);

If(i.test(str))

alert(“word is found”);

else

alert(“sorry”);

}

</script>

</head>

<body>

<script type=”text/javascript”>

Test(“I like programming”);

</script>

</body>

</html>

O/P:

I like programming

Page 39: CS6501 INTERNET PROGRAMMING UNIT I JAVA PROGRAMMING

VELTECH HIGHTECH Dr.RANGARAJAN Dr.SAKUNTHALA ENGINEERING COLLEGE DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING

VELTECH HIGHTECH Dr.RANGARAJAN Dr.SAKUNTHALA ENGINEERING COLLEGE Page 39

Word is found

3.4.3 USE OF SEARCH METHOD

➢ The search method is used to search

for the desired pattern in the given

input text

EXAMPLE PROGRAM

<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Transitional//EN” http://www.w3.org/1999/xhtml11.dtd>

<html xmlns = http://www.w3.org/1999/xhtml>

<head>

<script type=”text/javascript”>

Function test(str)

{

Document.write(str);

Var i= new RegExp(“/like/”);

return i;

}

</script>

</head>

<body>

<script type=”text/javascript”>

Var x=Test(“I like programming”);

If(x>0)

Document.write(“the word is found at”+x);

else

document.write(“not found”);

</script>

</body>

</html>

O/P:

the word is found at 2

3.5EXCEPTION HANDLING ➢ An exception is a problem that arises

during the execution of a program ➢ Its breaks the normal flow of the

execution. ➢ So these exceptions have to be handled

efficiently in order to avoid program getting crashed.

REASONS FOR EXCEPTION ➢ User entered invalid input. ➢ File not found ➢ Network connection lost ➢ JVM ran out of memory BENEFITS OF EXCEPTION ➢ Avoid crashing of applications abruptly. ➢ Various types of errors grouped together.

3.5.1 THE TRY...CATCH...FINALLY

STATEMENT

➢ The latest versions of JavaScript added

exception handling capabilities.

POSSIBLE QUESTIONS FROM JAVA SCRIPT 2 MA

RKS 1. Def

ine Regular Expression 16 marks

1. Exp

lain Regular Expression with example

program

Page 40: CS6501 INTERNET PROGRAMMING UNIT I JAVA PROGRAMMING

VELTECH HIGHTECH Dr.RANGARAJAN Dr.SAKUNTHALA ENGINEERING COLLEGE DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING

VELTECH HIGHTECH Dr.RANGARAJAN Dr.SAKUNTHALA ENGINEERING COLLEGE Page 40

➢ JavaScript implements the

try...catch...finally construct as well as

the throw operator to handle

exceptions.

SYNTAX

<script type="text/javascript">

<!--

try

{

}

catch ( e )

{

}

finally

{

}

//-->

</script>

EXAMPLE PROGRAM

<!DOCTYPE html> <html>

<body> <p id="demo"></p> <script> try {

adddlert("Welcome guest!"); } catch(err) {

document.getElementById("demo"); innerHTML = err.message;

} </script>

</body> </html> O/P: Welcome guest!

3.6 VALIDATION

➢ JavaScript, provides a way to validate

form's data on the client's computer

before sending it to the web server.

➢ Form validation generally performs two

functions.

✓ Basic Validation − First of all, the

form must be checked to make

sure all the mandatory fields are

filled in.

✓ Data Format Validation −

Secondly, the data that is entered

must be checked for correct form

and value.

VALIDATION EXAMPLE PROGRAM

<html>

<body>

<script>

function validateform(){

var name=document.myform.name.value;

var

password=document.myform.password.value

;

if (name==null || name==""){

alert("Name can't be blank");

return false;

Page 41: CS6501 INTERNET PROGRAMMING UNIT I JAVA PROGRAMMING

VELTECH HIGHTECH Dr.RANGARAJAN Dr.SAKUNTHALA ENGINEERING COLLEGE DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING

VELTECH HIGHTECH Dr.RANGARAJAN Dr.SAKUNTHALA ENGINEERING COLLEGE Page 41

}

else if(password.length<6){

alert("Password must be at least 6

characters long.");

return false;

}

}

</script>

<body>

<form name="myform" method="post"

action="http://www.javatpoint.com/javascrip

tpages/valid.jsp" onsubmit="return

validateform()" >

Name: <input type="text"

name="name"><br/>

Password: <input type="password"

name="password"><br/>

<input type="submit" value="register">

</form>

</body>

</html>

O/P

Name:

Password:

register

3.7 BUILT IN OBJECTS

➢ In javascript object is a collection of

properties.

➢ built-in objects that create the essential

functionality of the language.

➢ JavaScript has many intrinsic objects that

define it as a language.

✓ Math object

✓ Number object

✓ Date object

✓ Boolean object

3.7.1 NUMBER OBJECT

➢ The JavaScript Number object is a

wrapper for numeric values.

SYNTAX

var myNumber = new Number(numeric

value);

Four properties are included in the Number object:

• MAX_VALUE • MIN_VALUE • NEGATIVE_INFINITY • POSITIVE_INFINITY

EXAMPLE PROGRAM

<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Transitional//EN” http://www.w3.org/1999/xhtml11.dtd>

<html xmlns = http://www.w3.org/1999/xhtml>

<head>

</head>

<body>

<script type=”text/javascript”>

Document.write(Number.NEGATIVE_INFI

NITY);

Page 42: CS6501 INTERNET PROGRAMMING UNIT I JAVA PROGRAMMING

VELTECH HIGHTECH Dr.RANGARAJAN Dr.SAKUNTHALA ENGINEERING COLLEGE DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING

VELTECH HIGHTECH Dr.RANGARAJAN Dr.SAKUNTHALA ENGINEERING COLLEGE Page 42

</script>

</body>

</html>

O/P

Infinity

3.7.2 MATH OBJECT

➢ The JavaScript Math object is

used to perform mathematical functions.

SYNTAX

var pi = Math.PI;

➢ commonly used methods from math

object

✓ sqrt(num)

✓ abs(num)

✓ ceil(num)

✓ floor(num)

✓ log(num)

✓ pow(a,b)

EXAMPLE PROGRAM

<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Transitional//EN” http://www.w3.org/1999/xhtml11.dtd>

<html xmlns = http://www.w3.org/1999/xhtml>

<head>

</head>

<body>

<script type=”text/javascript”>

Var num=100;

Document.write(Math.surt(num));

</script>

</body>

</html>

O/P

10

3.7.3 DATE OBJECTS

➢ The JavaScript Date object provides a

way to work with dates and times.

SYNTAX

var myDate = new Date();

➢ commonly used methods from date

object

➢ getDate ➢ getDay ➢ getFullYear ➢ getHours ➢ getMilliseconds ➢ getMinutes ➢ getMonth ➢ getSeconds ➢ getTime ➢ getTimezoneOffset

EXAMPLE PROGRAM

<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Transitional//EN” http://www.w3.org/1999/xhtml11.dtd>

<html xmlns = http://www.w3.org/1999/xhtml>

<head>

</head>

Page 43: CS6501 INTERNET PROGRAMMING UNIT I JAVA PROGRAMMING

VELTECH HIGHTECH Dr.RANGARAJAN Dr.SAKUNTHALA ENGINEERING COLLEGE DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING

VELTECH HIGHTECH Dr.RANGARAJAN Dr.SAKUNTHALA ENGINEERING COLLEGE Page 43

<body>

<script type=”text/javascript”>

Var my_date = new Date();

Document.write(my_date.getDate());

Document.write(my_date.getHours());

Document.write(my_date.getSeconds(

));

</script>

</body>

</html>

O/P

18

5

32

3.7.4 BOOLEAN OBJECT

➢ The Boolean object is necessary when

attempting to create any sort of logic in

JavaScript.

➢ A Boolean is an object that represents a true

or a false value.

SYNTAX

var myBoolean = true;

EXAMPLE PROGRAM

<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Transitional//EN” http://www.w3.org/1999/xhtml11.dtd>

<html xmlns = http://www.w3.org/1999/xhtml>

<head>

</head>

<body>

<script type=”text/javascript”>

Var temp = new Boolean(false);

Document.write(false);

</script>

</body>

</html>

O/P

false

3.8 EVENT HANDLING

➢ An event handler executes a segment of a

code based on certain events occurring

within the application

➢ JavaScript event handers can be divided

into two parts:

✓ interactive event handlers

✓ 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, onMouseOver

➢ non-interactive event handler would be

onLoad, because this event handler would

automatically execute JavaScript code

➢ following event handlers available in

JavaScript

on Abort image

on Blur select, text, text area

on Change select, text, textarea

unclick button, checkbox, radio,

link, reset, submit, area

on Error image

on Focus select, text, testarea

onLoad windows, image

onMouseOver link, area

onMouseOut link, area

Page 44: CS6501 INTERNET PROGRAMMING UNIT I JAVA PROGRAMMING

VELTECH HIGHTECH Dr.RANGARAJAN Dr.SAKUNTHALA ENGINEERING COLLEGE DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING

VELTECH HIGHTECH Dr.RANGARAJAN Dr.SAKUNTHALA ENGINEERING COLLEGE Page 44

onSelect text, textarea

onSubmit form

onUnload window

3.8.1 on Abort EVENT

➢ An on Abort event handler executes

JavaScript code when the user aborts

loading an image.

EXAMPLE PROGRAM

<html>

< <head>

</head>

<body>

<IMG SRC="reaz.gif" on Abort="alert('You

stopped the loading the image!')">

</body>

</html>

O/P

You stopped the loading the image

3.8.2 onBlur EVENT

➢ 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 JavaScript

code when the window loses focus.

EXAMPLE PROGRAM

<html>

<head>

<script language="javascript">

function valid(form){ var input=0;

input=document.myform.data.value;

if (input<0){

alert("please input a value that is less than

0");

}

}

</script>

</head>

<body>

<form name="myform">

<input type="text" name="data" value=""

size=10 onblur="valid(this.form)">

</form>

</body>

</html>

O/P

Please input a value that is less than 0

3.8.3 on Change EVENT

➢ The on Change event handler executes

JavaScript code when input focus exits the

field after the user modifies its text.

EXAMPLE PROGRAM

<html>

<head>

<script language="javascript">

function valid(form)

Page 45: CS6501 INTERNET PROGRAMMING UNIT I JAVA PROGRAMMING

VELTECH HIGHTECH Dr.RANGARAJAN Dr.SAKUNTHALA ENGINEERING COLLEGE DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING

VELTECH HIGHTECH Dr.RANGARAJAN Dr.SAKUNTHALA ENGINEERING COLLEGE Page 45

{

var input=0;

input=document.myform.data.value;

alert("you have changed the value from 10 to

" + input );

}

</script>

</head>

<body>

<input type="text" name="data" value="10"

size=10 on change="valid(this.form)">

</form>

</body>

</html>

O/P

You have changed the value from 10 to 0

3.9 DHTML WITH JAVASCRIPT

➢ DHTML stands for Dynamic HTML ➢ DHTML is NOT a language or a web

standard. ➢ DHTML is a TERM used to describe the

technologies used to make web pages dynamic and interactive.

➢ To most people DHTML means the combination of HTML, JavaScript, DOM, and CSS.

3.9.1 DIFFERENCE BETWEEN HTML AND

DHTML

HTML DHTML

Hypertext Markup Language

Dynamic HTML

Static web pages Dynamic web pages

It works slowly upon client-server technology

It works faster on client-server technology

No CSS, and no dynamic contents

Use CSS, events, methods to create dynamic pages

No processing at browser

Script is processed at browser

Contents will not be changed

Contents can be changed

Simple, less interactive

Complex, more interactive

Only HTML contents DHTML = HTML+CSS+JS

3.10 SERVLET

➢ Servlets are defined as simple java programs

that are dynamically loaded and run on JVM of web servers, to respond to the requests from the clients

➢ It acts as middle layer between browser and server

➢ To develop sites with secure access, interact with DB, maintain unique session info of each client

➢ Used with HTTP, hence called HttpServlet ➢ It makes use of two packages:

✓ Javax.servlet

SERVLET CONTAINER ➢ The server that executes a servlet is called as

servlet container or servlet engine ➢ Browsers send an HTTP request to server,

which in turn sends to servlet container ➢ Servlet container receives the request from

the server, processes appropriate servlet,

Page 46: CS6501 INTERNET PROGRAMMING UNIT I JAVA PROGRAMMING

VELTECH HIGHTECH Dr.RANGARAJAN Dr.SAKUNTHALA ENGINEERING COLLEGE DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING

VELTECH HIGHTECH Dr.RANGARAJAN Dr.SAKUNTHALA ENGINEERING COLLEGE Page 46

✓ javax.servlet.http

sends back request

3.10.1 SERVLET API LIFE CYCLE METHODS

Servlet API life cycle methods –

➢ init() The web container calls the init method only once after creating the servlet instance. The init method is used to initialize the servlet

➢ service(): method called directly by server when an HTTP request is received;

➢ destroy(): called when server shuts down

Fig: servlet life cycle

3.10.2 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.

Fig servlet architecture

ADVANTAGES 1. better performance: because it creates a thread for each request not process. 2. Portability: because it uses java language. 3. Robust: Servlets are managed by JVM so we don't need to worry about memory leak, garbage collection etc. 4. Secure: because it uses java language. EXAMPLE PROGRAM import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class HelloWorld extends HttpServlet { public void init() { } public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException

Page 47: CS6501 INTERNET PROGRAMMING UNIT I JAVA PROGRAMMING

VELTECH HIGHTECH Dr.RANGARAJAN Dr.SAKUNTHALA ENGINEERING COLLEGE DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING

VELTECH HIGHTECH Dr.RANGARAJAN Dr.SAKUNTHALA ENGINEERING COLLEGE Page 47

{ response.setContentType("text/html"); PrintWriter out = response.getWriter(); out.println("<html><body>helloworld</body></html>"); } public void destroy() { }

}

O/P

helloworld

3.10.3 COMPILING SERVLET

➢ Let us put above code if HelloWorld.java file and put this file in C:\ServletDeveloper

➢ add these directories as well in CLASSPATH.

➢ Assuming your environment is setup properly, go in ServletDeveloper directory and compile HelloWorld.java as follows: $ javac HelloWorld.java

➢ If the servlet depends on any other libraries, you have to include those JAR files on your CLASSPATH as well.

➢ I have included only servlet-api.jar JAR file because I'm not using any other library in Hello World program.

➢ This command line uses the built-in javac compiler that comes with the Sun Microsystems Java Software Development Kit (JDK).

➢ For this command to work properly, you have to include the location of the Java SDK that you are using in the PATH environment variable.

➢ If everything goes fine, above compilation would produce

HelloWorld.class file in the same directory.

3.11 GET AND POST METHOD

➢ HTTP request makes use of two

commonly used methods such as GET and

POST

3.11.1 DIFFERENCE BETWEEN DO GET

AND DO POST METHODS

HTTP GET request HTTP POST request

doGet() method is used

doPost() method is used

URL string displays request submitted by the user

URL string does not display request submitted by user

To download info from server

To upload info from server

No effect on data Has effect on data

Page can be bookmarked

Page cannot be bookmarked

page can be cached, saved in history

Page cannot be cached, cannot be saved in history

Only ASCII characters allowed

Any character is allowed

Unsafe More secure

3.11.2 HTTP GET

➢ Query string is part of URL

➢ Length of query string may be limited

Page 48: CS6501 INTERNET PROGRAMMING UNIT I JAVA PROGRAMMING

VELTECH HIGHTECH Dr.RANGARAJAN Dr.SAKUNTHALA ENGINEERING COLLEGE DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING

VELTECH HIGHTECH Dr.RANGARAJAN Dr.SAKUNTHALA ENGINEERING COLLEGE Page 48

HTML PROGRAM Login.html <html> <body> <form action="login" method="get"> <table> <tr> <td>User</td> <td><input name="user" /></td> </tr> <tr> <td>password</td> <td><input name="password" /></td> </tr> </table> <input type="submit" /> </form> </body> </html> ➢ create a Servlet which receives the request

in /login , which is the indicated direction in the action attribute of the tag <form> of login.html

SERVLET PROGRAM import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class LoginServlet extends HttpServlet { protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { String user = req.getParameter("user"); String pass = req.getParameter("password"); if ("balamurugan".equals(user) && "bala1234".equals(pass)) { response(resp, "login ok"); } else { response(resp, "invalid login"); } } private void response(HttpServletResponse resp, String msg) throws IOException

{ PrintWriter out = resp.getWriter(); out.println("<html><body>"); out.println(msg); out.println("</body></html>"); } }

➢ We compilate this Servlet and we include LoginServlet.class in the folder /WEB-INF/classes. We modify web.xml to link /login with this Servlet.

WEB.XML <web-app> <servlet> <servlet-name>hello</servlet-name> <servlet-class> hello </servlet-class> </servlet> <servlet-mapping> <servlet-name>login-servlet</servlet-name> <url-pattern>/login</url-pattern> </servlet-mapping> </web-app>

O/P

3.11.3 HTTP POST

Page 49: CS6501 INTERNET PROGRAMMING UNIT I JAVA PROGRAMMING

VELTECH HIGHTECH Dr.RANGARAJAN Dr.SAKUNTHALA ENGINEERING COLLEGE DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING

VELTECH HIGHTECH Dr.RANGARAJAN Dr.SAKUNTHALA ENGINEERING COLLEGE Page 49

➢ Query string is sent as body of HTTP

request

➢ Length of query string is unlimited

➢ Most browsers will warn you if they are

about to resubmit POST data to avoid

duplicate updates

HTML PROGRAM

<html>

<body>

<form action="login" method="post">

<table>

<tr><td>User</td> <td><input

name="user" /></td></tr>

<tr><td>password</td> <td>

<input name="password" /></td></tr>

</table>

<input type="submit" />

</form>

</body>

</html>

SERVLET PROGRAM

import java.io.*;

import javax.servlet.*;

import javax.servlet.http.*;

public class LoginServlet extends

HttpServlet

{

protected void

doPost(HttpServletRequest req,

HttpServletResponse resp) throws

ServletException, IOException

{

String user = req.getParameter("user");

String pass =

req.getParameter("password");

if ("balamurugan".equals(user) &&

"bala1234".equals(pass))

{

response(resp, "login ok");

}

else

{

response(resp, "invalid login");

}

}

private void

response(HttpServletResponse resp,

String msg) throws IOException

{

PrintWriter out = resp.getWriter();

out.println("<html><body>");

out.println(msg);

out.println("</body></html>");

}

O/P

3.12 SESSION HANDLING

➢ Session simply means a particular interval of time.

➢ Session Tracking is a way to maintain state (data) of an user. It is also known as session management in servlet.

➢ Http protocol is a stateless so we need to maintain state using session tracking techniques.

Page 50: CS6501 INTERNET PROGRAMMING UNIT I JAVA PROGRAMMING

VELTECH HIGHTECH Dr.RANGARAJAN Dr.SAKUNTHALA ENGINEERING COLLEGE DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING

VELTECH HIGHTECH Dr.RANGARAJAN Dr.SAKUNTHALA ENGINEERING COLLEGE Page 50

➢ Each time user requests to the server, server treats the request as the new request.

➢ So we need to maintain the state of an user to recognize to particular user.

HTTP is stateless that means each request is considered as the new request. It is shown in the figure given below:

3.12.1 Session Tracking Techniques

There are four techniques used in Session tracking:

1. Cookies

2. Hidden Form Field

3. URL Rewriting

4. HttpSession

3.12.2 Cookies in Servlet

➢ A cookie is a small piece of information that is persisted between the multiple client requests.

➢ A cookie has a name, a single value, and optional attributes such as a comment, path and domain qualifiers, a maximum age, and a version number.

How Cookie works ➢ By default, each request is considered as a new

request. ➢ In cookies technique, we add cookie with

response from the servlet. ➢ So cookie is stored in the cache of the browser. ➢ After that if request is sent by the user, cookie is

added with request by default. Thus, we recognize the user as the old user.

Types of Cookie There are 2 types of cookies in servlets. 1. Non-persistent cookie 2. Persistent cookie Advantage of Cookies 1. Simplest technique of maintaining the state. 2. Cookies are maintained at client side. Disadvantage of Cookies 1. It will not work if cookie is disabled from the browser. 2. Only textual information can be set in Cookie object. Gmail uses cookie technique for login. If you disable the cookie, gmail won't work. Hidden Form Fields

3.12.3 URL Rewriting

Page 51: CS6501 INTERNET PROGRAMMING UNIT I JAVA PROGRAMMING

VELTECH HIGHTECH Dr.RANGARAJAN Dr.SAKUNTHALA ENGINEERING COLLEGE DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING

VELTECH HIGHTECH Dr.RANGARAJAN Dr.SAKUNTHALA ENGINEERING COLLEGE Page 51

➢ You can append some extra data on the

end of each URL that identifies the

session, and the server can associate that

session identifier with data it has stored

about that session.

➢ URL rewriting is a better way to maintain

sessions and works for the browsers when

they don't support cookies

➢ but here drawback is that you would have

generate every URL dynamically to assign

a session ID though page is simple static

HTML page.

THE HTTP SESSION OBJECT

➢ Apart from the above mentioned three

ways, servlet provides HttpSession

Interface which provides a way to identify

a user across more than one page request

or visit to a Web site and to store

information about that user.

➢ The servlet container uses this interface

to create a session between an HTTP

client and an HTTP server.

➢ You would get HttpSession object by

calling the public method getSession() of

HttpServletRequest, as below:

SYNTAX

HttpSession session =

request.getSession();

EXAMPLE PROGRAM

import java.io.*;

import javax.servlet.*;

import javax.servlet.http.*;

import java.util.*;

public class SessionTracker extends

HttpServlet

{

public void doGet(HttpServletRequest

request, HttpServletResponse response)

throws ServletException, IOException

{

Page 52: CS6501 INTERNET PROGRAMMING UNIT I JAVA PROGRAMMING

VELTECH HIGHTECH Dr.RANGARAJAN Dr.SAKUNTHALA ENGINEERING COLLEGE DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING

VELTECH HIGHTECH Dr.RANGARAJAN Dr.SAKUNTHALA ENGINEERING COLLEGE Page 52

HttpSession session =

request.getSession(true);

Date createTime = new

Date(session.getCreationTime());

Date lastAccessTime=new

Date(session.getLastAccessedTime());

String title = "Welcome Back to my

website";

Integer visitCount = new Integer(0);

String visitCountKey = new

String("visitCount");

String userIDKey = new String("userID");

String userID = new String("ABCD");

if (session.isNew())

{

title = "Welcome to my website";

session.setAttribute(userIDKey, userID);

}

else

{

visitCount =

(Integer)session.getAttribute(visitCountKe

y);

visitCount = visitCount + 1;

userID =

(String)session.getAttribute(userIDKey);

}

session.setAttribute(visitCountKey,

visitCount);

response.setContentType("text/html");

PrintWriter out = response.getWriter();

out.println("<html><body><center>");

out.println("Session Information");

out.println("<table border=\"1\"><tr>");

out.println("<th>Session

info</th><th>value</th></tr>");

out.println("<tr><td>Session ID</td><td>

+ session.getId() + </td></tr>");

out.println("<tr><td>Creation

Time</td><td> + createTime +

</td></tr>");

Page 53: CS6501 INTERNET PROGRAMMING UNIT I JAVA PROGRAMMING

VELTECH HIGHTECH Dr.RANGARAJAN Dr.SAKUNTHALA ENGINEERING COLLEGE DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING

VELTECH HIGHTECH Dr.RANGARAJAN Dr.SAKUNTHALA ENGINEERING COLLEGE Page 53

out.println("<tr><td>Time of Last

Access</td><td> + lastAccessTime+

</td></tr>");

out.println("<tr><td>User ID</td><td> +

userID+ </td></tr>");

out.println("<tr><td>Number of

visits</td><td> + visitCount+ </td></tr>");

out.println("</table></body></html>");

}

}

O/P

3.13 COOKIES

➢ By default, each request is considered as a new request.

➢ In cookies technique, we add cookie with response from the servlet.

➢ So cookie is stored in the cache of the browser.

➢ After that if request is sent by the user, cookie is added with request by default. Thus, we recognize the user as the old user.

Types of Cookie There are 2 types of cookies in servlets. 1. Non-persistent cookie 2. Persistent cookie Advantage of Cookies 1. Simplest technique of maintaining the state. 2. Cookies are maintained at client side. Disadvantage of Cookies 1. It will not work if cookie is disabled from the browser. 2. Only textual information can be set in Cookie object. Gmail uses cookie technique for login. If you disable the cookie, gmail won't work. Hidden Form Fields

3.13.1 HTML PROGRAM

<html>

<head>

<title>Cookies Example in Servlets</title>

</head>

<body bgcolor=wheat>

Page 54: CS6501 INTERNET PROGRAMMING UNIT I JAVA PROGRAMMING

VELTECH HIGHTECH Dr.RANGARAJAN Dr.SAKUNTHALA ENGINEERING COLLEGE DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING

VELTECH HIGHTECH Dr.RANGARAJAN Dr.SAKUNTHALA ENGINEERING COLLEGE Page 54

<center>

<h1>Cookies Example in Java</h1>

<form

action="http://localhost:8080/cookies/co"

method="Post">

First name: <input type="text"

name="fname">

Last name: <input type="text"

name="lname">

<input type="submit"value="SUBMIT">

</form>

</center>

</body>

</html>

3.13.2 SERVLET PROGRAMS

COOKIEEXAMPLE.JAVA

import javax.servlet.*;

import javax.servlet.http.*;

import java.io.*;

public class CookieExample extends

HttpServlet

{

public void doPost(HttpServletRequest

req,HttpServletResponse res) throws

ServletException,IOException

{

String fname=req.getParameter("fname");

String lname=req.getParameter("lname");

Cookie f=new Cookie("first_name",fname);

Cookie l=new Cookie("last_name",lname);

res.addCookie(f);

res.addCookie(l);

res.sendRedirect("http://localhost:8080/cook

ies/st");

}

}

GETCOOKIE.JAVA

import javax.servlet.*;

import javax.servlet.http.*;

import java.io.*;

public class GetCookie extends HttpServlet

{

public void doGet(HttpServletRequest

req,HttpServletResponse res) throws

ServletException,IOException

{

PrintWriter pw=res.getWriter();

pw.println("<h1>");

Page 55: CS6501 INTERNET PROGRAMMING UNIT I JAVA PROGRAMMING

VELTECH HIGHTECH Dr.RANGARAJAN Dr.SAKUNTHALA ENGINEERING COLLEGE DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING

VELTECH HIGHTECH Dr.RANGARAJAN Dr.SAKUNTHALA ENGINEERING COLLEGE Page 55

Cookie[] c=req.getCookies();

for(Cookie k:c)

{

pw.println(k.getValue());

}

pw.println("</h1>");

}

}

O/P

Click on the SUBMIT then,

3.14 APACHE TOMCAT

➢ It is an application server or web server

or servlet container developed by the

Apache Software Foundation (ASF) and

released under the Apache License

version 2.

➢ HTTP web servers provide an

environment for Java code to run in.

➢ It includes tools for configuration and

management, but can also be configured

by editing XML configuration files.

➢ Most of the modern Java web

frameworks are based on servlets and

JavaServer Pages and can run on Apache

Tomcat, for example Struts, JavaServer

Faces, Spring, etcetera.

How to Install Tomcat 7

There are certain steps we must follow for

configuring Apache Tomcat 7.

Step 1

Download and Install Tomcat

Go to

http://tomcat.apache.org/download-

70.cgi then go to the Binary

Distribution/Core/ and download the

"zip" package

Step 2

Check the installed directory to ensure it

contains the following sub-directories:

Page 56: CS6501 INTERNET PROGRAMMING UNIT I JAVA PROGRAMMING

VELTECH HIGHTECH Dr.RANGARAJAN Dr.SAKUNTHALA ENGINEERING COLLEGE DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING

VELTECH HIGHTECH Dr.RANGARAJAN Dr.SAKUNTHALA ENGINEERING COLLEGE Page 56

bin folder

logs folder

webapps folder

work folder

temp folder

conf folder

lib folder

Step 3

Now, we need to create an Environment

Variable JAVA_HOME.

We need to create an environment

variable called "JAVA_HOME" and set it to

our JDK installed directory.

To create the JAVA_HOME environment

variable in Windows XP/Vista/7 we need

to push the "Start" button then select

"Control Panel" / "System" / "Advanced

system settings". Then switch to the

"Advanced" tab and select "Environment

Variables" / "System Variables" then

select "New" (or "Edit" for modification).

In "Variable Name", enter "JAVA_HOME".

In "Variable Value", enter your JDK

installed directory (e.g., "c:\Program

Files\Java\jdk1.7.0_{xx}").

For ensuring that it is set correctly, we

need to start a command shell (to refresh

the environment) and issue:

set JAVA_HOME

JAVA_HOME=c:\Program

Files\Java\jdk1.7.0_{xx} <== Check that

this is OUR JDK installed directory

Sometimes we need to set JRE_HOME

also. So for creating JRE_HOME we need

to use the same procedure. Push the

"Start" buttonthen select "Control Panel"

/ "System" / "Advanced system settings".

Then switch to the "Advanced" tab and

select "Environment Variables" / "System

Variables" then select "New" (or "Edit" for

modification). In "Variable Name", enter

"JRE_HOME". In "Variable Value", enter

your JRE installed directory (e.g.,

"C:\Program Files\Java\jre7\").

Step 4

Configure Tomcat Server

The configuration files of the Apache

Tomcat Server are located in the "conf"

sub-directory of our Tomcat installed

directory, for example

"E:\myserver\tomcat7.0.40\conf". There

are 4 configuration XML files:

context.xml file

tomcat-users.xml file

server.xml file

web.xml file

Before proceeding, make a BACKUP of the

configuration files.

Step 4(a) "conf\web.xml"; Enabling a

Directory Listing

Page 57: CS6501 INTERNET PROGRAMMING UNIT I JAVA PROGRAMMING

VELTECH HIGHTECH Dr.RANGARAJAN Dr.SAKUNTHALA ENGINEERING COLLEGE DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING

VELTECH HIGHTECH Dr.RANGARAJAN Dr.SAKUNTHALA ENGINEERING COLLEGE Page 57

Open the configuration file "web.xml".

We shall enable the directory listing by

changing "listings" from "false" to "true"

for the "default" servlet.

<param-value>true</param-value> like:

Step 4(b) "conf\server.xml file"; set the

TCP Port Number

Open the file "server.xml" in a text editor.

The default port number of Tomcat is

8080. Now we need to change the TCP

port number for Tomcat, since the same

port number can be used by other servers

like SQL Server. We may choose any

number between 1024 and 65535. We

shall choose 9999 in this article.

Locate the following lines, and change

port="8080" to port="9999". Like:

<Connector port="9999"

protocol="HTTP/1.1" Like

Step 4(c) "conf\context.xml"; Enabling

Automatic Reload

In that we set reloadable="true" to the

<Context> element to enable automatic

reload after code changes.

Add reloadable="true" as in the following:

<Context reloadable="true">

......

</Context> Like

Step 4(d) (Optional) "conf\tomcat-

users.xml"

It is used to manage Tomcat by adding the

highlighted lines, inside the <tomcat-

users> elements.

In that we can add a password and

username as an optional step.

Step 5

Now, start the tomcat server

Executable programs and scripts are kept

in the "bin" sub-directory of the Tomcat

installed directory, e.g.,

"E:\myserver\tomcat7.0.40\bin".

Step 5(a)

Page 58: CS6501 INTERNET PROGRAMMING UNIT I JAVA PROGRAMMING

VELTECH HIGHTECH Dr.RANGARAJAN Dr.SAKUNTHALA ENGINEERING COLLEGE DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING

VELTECH HIGHTECH Dr.RANGARAJAN Dr.SAKUNTHALA ENGINEERING COLLEGE Page 58

Start Server

Launch a command shell. Set the current

directory to "<TOMCAT_HOME>\bin" like

E:\myserver\tomcat7.0.40\bin, and run

"startup.bat" as follows:

After that a new Tomcat console window

appears. Read the messages on the

console. Look out for the Tomcat's port

number (double check that Tomcat is

running on port 9999).......

We saw a figure like:

Step 5(b) Access the Server

Open a browser then enter the URL

"http://localhost:9999" to access the

Tomcat server's welcome page.

If we get this type of page then it means

we are done.

Fig-7.jpg

Now try the URL

http://localhost:9999/examples to view

JSP and servlet examples.

Step 5(c) How to Shutdown Server

We can stop the server using one of the

following:

Press ctrl-c on the Tomcat console; or

Run

"<TOMCAT_HOME>\bin\shutdown.bat"

script:

// Change the current directory to

Tomcat's "bin"

> e: // Change the current drive

e:\> cd E:\myserver\tomcat7.0.40\bin //

Change Directory to YOUR Tomcat's "bin"

directory

// Shutdown the server

E:\myserver\tomcat7.0.40\bin> shutdown

Page 59: CS6501 INTERNET PROGRAMMING UNIT I JAVA PROGRAMMING

VELTECH HIGHTECH Dr.RANGARAJAN Dr.SAKUNTHALA ENGINEERING COLLEGE DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING

VELTECH HIGHTECH Dr.RANGARAJAN Dr.SAKUNTHALA ENGINEERING COLLEGE Page 59

3.15 JDBC

➢ JDBC is defined as an API that provides

industry standard and database

connectivity between java apps and

database servers

➢ It is a framework that contains many

classes, interfaces, exceptions, using

which java apps can send SQL statement

to database to store and retrieve data

Uses

➢ It helps client to store and retrieve data

to databases

➢ It helps client to update databases

Types

➢ JDBC-ODBC bridge driver

➢ Partial java driver

➢ Pure java driver for accessing

middleware

➢ Pure java driver for direct DB access

3.15.1 JDBC ARCHITECTURE

The JDBC API supports both two-tier and three-tier processing models for database access but in general, JDBC Architecture consists of two layers − ➢ JDBC API: This provides the application-

to-JDBC Manager connection. ➢ JDBC Driver API: This supports the JDBC

Manager-to-Driver Connection.

➢ The JDBC API uses a driver manager and database-specific drivers to provide transparent connectivity to heterogeneous databases.

Following is the architectural diagram,

which shows the location of the driver

manager with respect to the JDBC drivers

and the Java application

3.15.2 COMMON JDBC COMPONENTS

The JDBC API provides the following interfaces and classes − ➢ DriverManager: This class manages a list of

database drivers. establish a database

Connection. ➢ Driver: This interface handles the

communications with the database server.

You will interact directly with Driver objects very rarely.

➢ Connection: This interface with all methods for contacting a database. The connection object represents communication context, i.e., all communication with database is through connection object only.

➢ Statement: You use objects created from this interface to submit the SQL statements to

the database. ➢ ResultSet: These objects hold data retrieved

from a database after you execute an SQL query using Statement objects.

➢ SQLException: This class handles any errors that occur in a database application.

➢ Structured Query Language (SQL) is a standardized language that allows you to perform operations on a database, such as creating entries, reading content, updating content, and deleting entries.

➢ SQL is supported by almost any database you

Page 60: CS6501 INTERNET PROGRAMMING UNIT I JAVA PROGRAMMING

VELTECH HIGHTECH Dr.RANGARAJAN Dr.SAKUNTHALA ENGINEERING COLLEGE DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING

VELTECH HIGHTECH Dr.RANGARAJAN Dr.SAKUNTHALA ENGINEERING COLLEGE Page 60

will likely use, and it allows you to write database code independently of the underlying database.

➢ Create Database The CREATE DATABASE statement is used for creating a new database. The syntax is − CREATE DATABASE DATABASE_NAME; Example The following SQL statement creates a Database named EMP − CREATE DATABASE EMP;

➢ Drop Database The DROP DATABASE statement is used for deleting an existing database. The syntax is − SQL> DROP DATABASE DATABASE_NAME; Note: To create or drop a database you should have administrator privilege on your database server. Be careful, deleting a database would loss all the data stored in the database. The DROP TABLE statement is used for deleting an existing table. The syntax is − DROP TABLE table_name; Example The following SQL statement deletes a table named Employees − DROP TABLE Employees;

➢ INSERT Data

The syntax for INSERT, looks similar to the following, where column1, column2, and so on represents the new data to appear in the respective columns − SQL> INSERT INTO table_name VALUES (column1, column2, ...); Example The following SQL INSERT statement inserts a new row in the Employees database created earlier − SQL> INSERT INTO Employees VALUES (100, 18, 'Zara', 'Ali');

➢ SELECT Data The SELECT statement is used to retrieve data from a database. The syntax for SELECT is −

SQL> SELECT column_name, column_name, ... FROM table_name Example The following SQL statement selects the age, first and last columns from the Employees table, where id column is 100 − SQL> SELECT first, last, age FROM Employees WHERE id = 100;

➢ UPDATE Data The UPDATE statement is used to update data. The syntax for UPDATE is − SQL> UPDATE table_name SET column_name = value, column_name = value, ... Example The following SQL UPDATE statement changes the age column of the employee whose id is 100 − SQL> UPDATE Employees SET age=20 WHERE id=100; DELETE Data The DELETE statement is used to delete data from tables. The syntax for DELETE is − SQL> DELETE FROM table_name WHERE conditions; SQL> DELETE FROM Employees WHERE id=100;

3.15.3 BUILDING A JDBC

➢ Import the packages: Requires that you include the packages containing the JDBC classes needed for database programming. Most often, using import java.sql.* will suffice.

➢ Register the JDBC driver: Requires that you initialize a driver so you can open a communication channel with the database.

➢ Open a connection: Requires using the DriverManager.getConnection() method to create a Connection object, which represents a physical connection with the database.

➢ Execute a query: Requires using an object of type Statement for building and submitting an

Page 61: CS6501 INTERNET PROGRAMMING UNIT I JAVA PROGRAMMING

VELTECH HIGHTECH Dr.RANGARAJAN Dr.SAKUNTHALA ENGINEERING COLLEGE DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING

VELTECH HIGHTECH Dr.RANGARAJAN Dr.SAKUNTHALA ENGINEERING COLLEGE Page 61

SQL statement to the database. ➢ Extract data from result set: Requires that you

use the appropriate ResultSet.getXXX() method to retrieve the data from the result set.

➢ Clean up the environment: Requires explicitly closing all database resources versus relying on the JVM's garbage collection.

➢ EXAMPLE PROGRAM import java.sql.*; public class FirstExample { static final String JDBC_DRIVER = "com.mysql.jdbc.Driver"; static final String DB_URL = "jdbc:mysql://localhost/EMP"; static final String USER = "username"; static final String PASS = "password"; public static void main(String[] args) { Connection conn = null; Statement stmt = null; try { Class.forName("com.mysql.jdbc.Driver"); System.out.println("Connecting to database..."); conn = DriverManager.getConnection(DB_URL,USER,PASS); System.out.println("Creating statement..."); stmt = conn.createStatement(); String sql; sql = "SELECT id, first, last, age FROM Employees"; ResultSet rs = stmt.executeQuery(sql); while(rs.next() { int id = rs.getInt("id"); int age = rs.getInt("age"); String first = rs.getString("first"); String last = rs.getString("last");

System.out.print("ID: " + id); System.out.print(", Age: " + age); System.out.print(", First: " + first); System.out.println(", Last: " + last); } rs.close(); stmt.close(); conn.close(); } catch(SQLException se) { se.printStackTrace(); } catch(Exception e) { e.printStackTrace(); } finally { try { if(stmt!=null) stmt.close(); } catch(SQLException se2) { } try { if(conn!=null) conn.close(); } catch(SQLException se) { se.printStackTrace(); } } System.out.println("Goodbye!"); } } O/P C:\>javac FirstExample.java Connecting to database... Creating statement... ID: 100, Age: 18, First: Zara, Last: Ali

Page 62: CS6501 INTERNET PROGRAMMING UNIT I JAVA PROGRAMMING

VELTECH HIGHTECH Dr.RANGARAJAN Dr.SAKUNTHALA ENGINEERING COLLEGE DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING

VELTECH HIGHTECH Dr.RANGARAJAN Dr.SAKUNTHALA ENGINEERING COLLEGE Page 62

ID: 101, Age: 25, First: Mahnaz, Last: Fatma ID: 102, Age: 30, First: Zaid, Last: Khan ID: 103, Age: 28, First: Sumit, Last: Mittal

3.16 JSP

➢ Java Server Pages is a kind of server side scripting language that enables user to embed java code with HTML elements for the creation of dynamic, platform-independent method for building web apps

➢ JSP = Java + HTML + servlet ➢ JavaServer Pages (JSP) is a server-side

programming technology that enables the creation of dynamic, platform-independent method for building Web-based applications.

➢ JSP have access to the entire family of Java APIs, including the JDBC API to access enterprise databases

➢ JavaServer Pages (JSP) is a technology for developing web pages that support dynamic content which helps developers insert java code in HTML pages by making use of special JSP tags, most of which start with <% and end with %>.

➢ JSP, you can collect input from users through web page forms, present records from a database or another source, and create web pages dynamically.

DIFFERENCE BETWEEN JSP AND SERVLET

JSP Servlet JSP = Java inside HTML

Servlet = HTML inside Java

It generates dynamic web contents

It generates dynamic web pages

In MVC, JSP acts as a view

In MVC, servlet acts as controller

JSP makes use of custom tags

No custom tags

3.16.1 ARCHITECTURE

➢ The web server needs a JSP engine ie.

container to process JSP pages.

➢ The JSP container is responsible for

intercepting requests for JSP pages

➢ A JSP container works with the Web

server to provide the runtime

environment and other services a JSP

needs.

➢ It knows how to understand the special

elements that are part of JSPs.

3.16.2 JSP PROCESSING

The following steps explain how the web

server creates the web page using JSP:

➢ As with a normal page, your browser

sends an HTTP request to the web server.

➢ The web server recognizes that the HTTP

request is for a JSP page and forwards it

to a JSP engine. This is done by using the

URL or JSP page which ends with .jsp

instead of .html.

➢ The JSP engine loads the JSP page from

disk and converts it into a servlet content.

➢ This conversion is very simple in which all

template text is converted to println( )

Page 63: CS6501 INTERNET PROGRAMMING UNIT I JAVA PROGRAMMING

VELTECH HIGHTECH Dr.RANGARAJAN Dr.SAKUNTHALA ENGINEERING COLLEGE DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING

VELTECH HIGHTECH Dr.RANGARAJAN Dr.SAKUNTHALA ENGINEERING COLLEGE Page 63

statements and all JSP elements are

converted to Java code that implements

the corresponding dynamic behavior of

the page

➢ The JSP engine compiles the servlet into an executable class and forwards the original request to a servlet engine.

➢ A part of the web server called the servlet engine loads the Servlet class and executes it. During execution, the servlet produces an output in HTML format, which the servlet engine passes to the web server inside an HTTP response.

➢ The web server forwards the HTTP response to your browser in terms of static HTML content.

➢ Finally web browser handles the dynamically generated HTML page inside the HTTP response exactly as if it were a static page.

The following are the paths followed by a JSP

✓ Compilation

✓ Initialization

✓ Execution

✓ Cleanup

The four major phases of JSP life cycle are

very similar to Servlet Life Cycle and they are

as follows:

3.16.3 LIFE CYCLE OF A JSP PAGE

The JSP pages follows these phases:

➢ Translation of JSP Page

➢ Compilation of JSP Page

➢ Classloading (class file is loaded by the

classloader)

➢ Instantiation (Object of the Generated

Servlet is created).

➢ Initialization ( jspInit() method is invoked

by the container).

➢ Reqeust processing ( _jspService() method

is invoked by the container).

➢ Destroy ( jspDestroy() method is invoked

by the container).

3.16.4 RUNNING JSP PAGE

Follow the following steps to execute this JSP page: ➢ Start the server ➢ put the jsp file in a folder and deploy on the

server ➢ visit the browser by the url

http://localhost:portno/contextRoot/jspfile e.g. http://localhost:8888/myapplication/index.jsp

Page 64: CS6501 INTERNET PROGRAMMING UNIT I JAVA PROGRAMMING

VELTECH HIGHTECH Dr.RANGARAJAN Dr.SAKUNTHALA ENGINEERING COLLEGE DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING

VELTECH HIGHTECH Dr.RANGARAJAN Dr.SAKUNTHALA ENGINEERING COLLEGE Page 64

➢ MVC stands for Model View and Controller. It is a design pattern that separates the business logic, presentation logic and data.

➢ Controller acts as an interface between View and Model. Controller intercepts all the incoming requests.

➢ Model represents the state of the application i.e. data. It can also have business logic.

➢ View represents the presentaion i.e. UI(User Interface).

3.17 JSTL

➢ Java Standard Tags Library represents set of

tags to simplify JSP development

➢ J2EE is used for server side programming using

JAVA and JSTL (a compoment of J2EE web app

development

➢ It is useful in performing condition execution,

loop execution, data procession, etc

➢ Embed logic in JSP page without java code

Advantage of JSTL

➢ Fast Developement JSTL provides many tags

that simplifies the JSP.

➢ Code Reusability We can use the JSTL tags in

various pages.

➢ No need to use scriptlet tag It avoids the use

of scriptlet tag.

3.17.1 JSTL TAGS

➢ The syntax used for including JSTL core library

in your JSP is:

<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>

<%@ taglib

uri="http://java.sun.com/jsp/jstl/core"

prefix="c" %>

<html>

<head>

<title>Tag Example</title>

</head>

<body>

<c:out value="${'Welcome to

javaTpoint'}"/>

</body>

</html>

O/P

Page 65: CS6501 INTERNET PROGRAMMING UNIT I JAVA PROGRAMMING

VELTECH HIGHTECH Dr.RANGARAJAN Dr.SAKUNTHALA ENGINEERING COLLEGE DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING

VELTECH HIGHTECH Dr.RANGARAJAN Dr.SAKUNTHALA ENGINEERING COLLEGE Page 65

JSTL Function Tags

➢ The JSTL function provides a number of

standard functions, most of these

functions are common string

manipulation functions.

<%@ taglib

uri="http://java.sun.com/jsp/jstl/function

s" prefix="fn" %>

fn:contains()

It is used to test if an input string

containing the specified substring in a

program.

fn:indexOf()

It returns an index within a string of first

occurrence of a specified substring.

fn:trim()

It removes the blank spaces from both the

ends of a string.

fn:split()

It splits the string into an array of

substrings.

fn:toLowerCase()

It converts all the characters of a string to

lower case.

fn:toUpperCase()

It converts all the characters of a string to

upper case.

fn:substring()

It returns the subset of a string according

to the given start and end position.

fn:substringAfter()

It returns the subset of string after a

specific substring.

fn:substringBefore()

It returns the subset of string before a

specific substring.

fn:length()

It returns the number of characters inside

a string, or the number of items in a

collection.

fn:replace()

It replaces all the occurrence of a string

with another string sequence.

PROGRAM

<%@ taglib

uri="http://java.sun.com/jsp/jstl/core"

prefix="c" %>

<%@ taglib

uri="http://java.sun.com/jsp/jstl/function

s" prefix="fn" %>

<html>

<head>

<title>JSTL fn:length()

example</title>

</head>

<body>

<c:set var="str1" value="This is first

string"/>

<c:set var="str2" value="Hello"/>

Length of the String-1 is:

${fn:length(str1)}<br>

Length of the String-2 is: ${fn:length(str2)}

</body>

</html>

Page 66: CS6501 INTERNET PROGRAMMING UNIT I JAVA PROGRAMMING

VELTECH HIGHTECH Dr.RANGARAJAN Dr.SAKUNTHALA ENGINEERING COLLEGE DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING

VELTECH HIGHTECH Dr.RANGARAJAN Dr.SAKUNTHALA ENGINEERING COLLEGE Page 66

JSTL Formatting tags

➢ The formatting tags provide support for

message formatting, number and date

formatting etc.

➢ The url for the formatting tags is

http://java.sun.com/jsp/jstl/fmt and

prefix is fmt.

➢ The JSTL formatting tags are used for

internationalized web sites to display and

format text, the time, the date and

numbers.

<%@ taglib

uri="http://java.sun.com/jsp/jstl/fmt"

prefix="fmt" %> Formatting Tags

Descriptions fmt:timeZone

It specifies a parsing action nested in its

body or the time zone for any time

formatting. fmt:formatNumber

It is used to format the numerical value

with specific format or precision.

fmt:parseDate

It parses the string representation of a

time and date. fmt:formatDate

It formats the time and/or date using the

supplied pattern and styles.

<%@ taglib prefix="c"

uri="http://java.sun.com/jsp/jstl/core"%>

<%@ taglib prefix="fmt"

uri="http://java.sun.com/jsp/jstl/fmt"%>

<html>

<head> <title>fmt:formatDate</title>

</head>

<body>

<h2>Different Formats of the

Date</h2>

<c:set var="Date" value="<%=new

java.util.Date()%>" />

<p> Formatted Time :

<fmt:formatDate type="time"

value="${Date}" />

</p>

<p> Formatted Date :

<fmt:formatDate type="date"

value="${Date}" />

</p>

<p> Formatted Date and Time :

<fmt:formatDate type="both"

value="${Date}" />

</p>

</body></html>

JSTL XML tags

➢ The JSTL XML tags are used for providing a

JSP-centric way of manipulating and

creating XML documents.

➢ XML Tags Descriptions x:out

Similar to <%= ... > tag, but for XPath

expressions.

➢ x:parser It is used for parse the XML data

specified either in the tag body or an

attribute.

➢ x:set

Page 67: CS6501 INTERNET PROGRAMMING UNIT I JAVA PROGRAMMING

VELTECH HIGHTECH Dr.RANGARAJAN Dr.SAKUNTHALA ENGINEERING COLLEGE DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING

VELTECH HIGHTECH Dr.RANGARAJAN Dr.SAKUNTHALA ENGINEERING COLLEGE Page 67

It is used to sets a variable to the value of

an XPath expression.

➢ x:if It is used for evaluating the test XPath

expression and if it is true, it will

processes its body content.

➢ x:transform

It is used in a XML document for providing

the XSL(Extensible Stylesheet Language)

transformation.

<%@ taglib prefix="c"

uri="http://java.sun.com/jsp/jstl/core"

%>

<%@ taglib prefix="x"

uri="http://java.sun.com/jsp/jstl/xml" %>

<html>

<body>

<h2>Vegetable Information:</h2>

<c:set var="vegetable">

<vegetables>

<vegetable>

<name>onion</name>

<price>40/kg</price>

</vegetable>

<vegetable>

<name>Potato</name>

<price>30/kg</price>

</vegetable>

<vegetable>

<name>Tomato</name>

<price>90/kg</price>

</vegetable>

</vegetables>

</c:set>

<x:parse xml="${vegetable}"

var="output"/>

<b>Name of the vegetable is</b>:

<x:out

select="$output/vegetables/vegetable[1]/

name" /><br>

<b>Price of the Potato is</b>:

<x:out

select="$output/vegetables/vegetable[2]/

price" />

</body> </html>

JSTL SQL TAG

➢ The JSTL sql tags provide SQL support.

➢ The url for the sql tags is

http://java.sun.com/jsp/jstl/sql and prefix

is sql. SQL Tags Descriptions

sql:setDataSource

It is used for creating a simple data source

suitable only for prototyping. sql:query

It is used for executing the SQL query

defined in its sql attribute or the body.

sql:update

It is used for executing the SQL update

defined in its sql attribute or in the tag

body. sql:transaction

It is used to provide the nested database

action with a common connection.

<%@ page

import="java.io.*,java.util.*,java.sql.*"%>

<%@ page

import="javax.servlet.http.*,javax.servlet.

*" %>

Page 68: CS6501 INTERNET PROGRAMMING UNIT I JAVA PROGRAMMING

VELTECH HIGHTECH Dr.RANGARAJAN Dr.SAKUNTHALA ENGINEERING COLLEGE DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING

VELTECH HIGHTECH Dr.RANGARAJAN Dr.SAKUNTHALA ENGINEERING COLLEGE Page 68

<%@ taglib

uri="http://java.sun.com/jsp/jstl/core"

prefix="c"%>

<%@ taglib

uri="http://java.sun.com/jsp/jstl/sql"

prefix="sql"%>

<html>

<body>

<sql:setDataSource var="db"

driver="com.mysql.jdbc.Driver"

url="jdbc:mysql://localhost/test"

user="root" password="1234"/>

<sql:query dataSource="${db}" var="rs">

SELECT * from Students;

</sql:query>

<table border="2" width="100%">

<tr>

<th>Student ID</th>

<th>First Name</th>

<th>Last Name</th>

<th>Age</th>

</tr>

<c:forEach var="table"

items="${rs.rows}">

<tr>

<td><c:out value="${table.id}"/></td>

<td><c:out

value="${table.First_Name}"/></td>

<td><c:out

value="${table.Last_Name}"/></td>

<td><c:out value="${table.Age}"/></td>

</tr>

</c:forEach>

</table>

</body></html>

O/P

3.18 CREATING HTML FORMS BY

EMBEDDING JSP CODE

JSP Scripting elements

➢ Scripting elements provides the ability to

insert java code inside the jsp.

✓ scriptlet tag

✓ expression tag

✓ declaration tag

3.18.1 JSP SCRIPTLET TAG

A scriptlet tag is used to execute java source

code in JSP

Example

In this example, we have created two files

index.html and welcome.jsp. The index.html

file gets the username from the user and the

welcome.jsp file prints the username with the

welcome message.

File: index.html

<html>

<body>

<form action="welcome.jsp">

<input type="text" name="uname">

Page 69: CS6501 INTERNET PROGRAMMING UNIT I JAVA PROGRAMMING

VELTECH HIGHTECH Dr.RANGARAJAN Dr.SAKUNTHALA ENGINEERING COLLEGE DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING

VELTECH HIGHTECH Dr.RANGARAJAN Dr.SAKUNTHALA ENGINEERING COLLEGE Page 69

<input type="submit" value="go"><br/>

</form>

</body>

</html>

File: welcome.jsp

<html>

<body>

<%

String

name=request.getParameter("uname");

out.print("welcome "+name);

%>

</form>

</body>

</html>

3.18.2 JSP EXPRESSION TAG

The code placed within JSP expression tag is

written to the output stream of the response.

So you need not write out.print() to write

data. It is mainly used to print the values of

variable or method.

Example of JSP expression tag that prints the

user name

In this example, we are printing the username

using the expression tag. The index.html file

gets the username and sends the request to

the welcome.jsp file, which displays the

username.

File: index.jsp

<html>

<body>

<form action="welcome.jsp">

<input type="text"

name="uname"><br/>

<input type="submit" value="go">

</form>

</body>

</html>

File: welcome.jsp

<html>

<body>

<%= "Welcome

"+request.getParameter("uname") %>

</body>

</html>

3.18.3 JSP DECLARATION TAG

➢ The JSP declaration tag is used to declare

fields and methods.

➢ The code written inside the jsp

declaration tag is placed outside the

service() method of auto generated

servlet.

➢ So it doesn't get memory at each request.

<html>

<body>

<%! int data=50; %>

<%= "Value of the variable is:"+data %>

</body>

Page 70: CS6501 INTERNET PROGRAMMING UNIT I JAVA PROGRAMMING

VELTECH HIGHTECH Dr.RANGARAJAN Dr.SAKUNTHALA ENGINEERING COLLEGE DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING

VELTECH HIGHTECH Dr.RANGARAJAN Dr.SAKUNTHALA ENGINEERING COLLEGE Page 70

CS6501 INTERNET PROGRAMMING

UNIT IV PHP and XML

An introduction to PHP: 4.1 PHP- 4.2 Using PHP-4.3 Variables-4.4 Program control- 4.5 Built-in functions-4.6 Connecting to Database – 4.7 Using Cookies-4.8 Regular Expressions;

XML:4.9 Basic XML- 4.10 Document Type Definition- 4.11 XML Schema 4.12 DOM and Presenting XML,4.13 XML Parsers and Validation, 4.14 XSL and XSLT Transformation, 4.15 News Feed (RSS and ATOM).

4.1 PHP

➢ PHP is defined as a server side scripting

language that is mainly used for form

handling and database access.

➢ PHP stands for Hypertext Pre Processor

➢ It was invented in 1994 by Rasmus

Lerdorf

➢ It is the most popular scripting language

in web

➢ It is free to download and use

4.1.1 FEATURES OF PHP

➢ Embedded inside HTML, easy to develop

➢ Easy to manage dynamic content,

database, session tracking

➢ Supports many protocols such as IMAP,

POP3

➢ Supports many databases such as MS SQL

server, Oracle, SyBase etc

➢ Simple like C and HTML

4.2 USING PHP

➢ To perform system functions such as file

create, open, close, read, write, etc

➢ To handle forms, gather data from files,

save data to a file, send email, etc

➢ To add, delete, modify database contents

➢ To access and set cookies and variables

➢ To restrict users from page access

➢ To encrypt data

4.2.1 RULES IN PHP

➢ White space insensitive

➢ Case sensitive

➢ Each statement ends with semi colon

➢ Expressions are combination of tokens

➢ $ is used before variables

➢ Save file as .php and access it from

localhost server

4.3 VARIABLES

➢ Variables ate entities that are used for

storing the values

➢ All PHP variable names must be pre-fixed

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.

➢ Values are assigned to variables using the

PHP assignment operator.

➢ Finally the line, as with all PHP code

statements, is terminated with a semi-

colon (;)

SYNTAX

Page 71: CS6501 INTERNET PROGRAMMING UNIT I JAVA PROGRAMMING

VELTECH HIGHTECH Dr.RANGARAJAN Dr.SAKUNTHALA ENGINEERING COLLEGE DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING

VELTECH HIGHTECH DR.RANGARAJAN Dr.SAKUNTHALA ENGINEERING COLLEGE Page 71

$variable name = value;

EXAMPLE

$A = 10;

4.4 PROGRAM CONTROL

➢ PHP supports following three decision

making statements.

➢ The if, elseif ...else and switch statements

are used to take decision based on the

different condition.

➢ You can use conditional statements in

your code to make your decisions.

4.4.1 IF…ELSE STATEMENT

➢ If you want to execute some code if a

condition is true and another code if a

condition is false, use the if....else

statement.

SYNTAX

If(condition)

{ }

else

{ }

EXAMPLE PROGRAM

<htmal>

<head>

</head>

<body>

<?php

$a=10;

if ($a == 10)

echo "a value is 10";

else

echo "a value is not 10";

?>

</body>

</html>

O/P

a value is 10

4.4.2 IF…ELSEIF…ELSE STATEMENT

➢ If one of the several conditions are true,

then use elseif

Page 72: CS6501 INTERNET PROGRAMMING UNIT I JAVA PROGRAMMING

VELTECH HIGHTECH Dr.RANGARAJAN Dr.SAKUNTHALA ENGINEERING COLLEGE DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING

VELTECH HIGHTECH DR.RANGARAJAN Dr.SAKUNTHALA ENGINEERING COLLEGE Page 72

statement

SYNTAX

If (condition)

{ }

elseif( condition )

{ }

else

{ }

EXAMPLE PROGRAM

<head>

</head>

<body>

<?php

$a=10;

if ($a > 0)

echo "a is positive";

elseif ($a< 0)

echo "a is negative";

else

echo "a is zero";

?>

</body>

</html>

O/P

a is positive

4.4.3 SWITCH STATEMENT

➢ If you want to select one of many

blocks of code to be executed, use the

Switch statement.

➢ The value of the expression is then

compared with the values for each case in

the structure.

➢ If there is a match, the block of code

associated with that case is executed.

➢ Use break to prevent the code from

running into the next case automatically.

➢ The default statement is used if no

match is found.

Page 73: CS6501 INTERNET PROGRAMMING UNIT I JAVA PROGRAMMING

VELTECH HIGHTECH Dr.RANGARAJAN Dr.SAKUNTHALA ENGINEERING COLLEGE DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING

VELTECH HIGHTECH DR.RANGARAJAN Dr.SAKUNTHALA ENGINEERING COLLEGE Page 73

SYNTAX

Switch(condition)

{

Case :

………….

………

default :

}

EXAMPLE PROGRAM

<head>

</head>

<body>

<?php

$fav = "green";

switch ($fav)

{

case "red":

echo "Your favorite color is red!";

break;

case "green":

echo "Your favorite color is green!";

break;

default:

echo "Your favorite color is

neither red, blue, nor green!";

?>

</body>

</html>

O/P

Your favorite color is green!

4.5 BUILT IN FUNCTIONS

➢ PHP functions are similar to other

programming languages.

➢ A function is a piece of code which takes

one more input in the form of parameter

and does some processing and returns a

value.

➢ PHP has more than 1000 built-in

functions.

➢ Two types of function

✓ User define function

✓ Built in function

SYNTAX

function name_of_function(parameter)

{

………………

}

Page 74: CS6501 INTERNET PROGRAMMING UNIT I JAVA PROGRAMMING

VELTECH HIGHTECH Dr.RANGARAJAN Dr.SAKUNTHALA ENGINEERING COLLEGE DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING

VELTECH HIGHTECH DR.RANGARAJAN Dr.SAKUNTHALA ENGINEERING COLLEGE Page 74

4.5.1 USER DEFINE FUNCTION

➢ User define function in PHP , we can

create our own functions.

➢ A function will not execute immediately

when a page loads.

➢ A function will be executed by a call to

the function.

EXAMPLE PROGRAM

<?php

function writeMsg()

{

echo "Hello world!";

}

writeMsg();

?>

O/P

HelloWorld

4.5.2 BUILT IN FUNCTION

➢ PHP Array Functions

➢ PHP Calender Functions

➢ PHP Class/Object Functions

➢ PHP Character Functions

➢ PHP Date & Time Functions

➢ PHP Directory Functions

➢ PHP Error Handling Functions

➢ PHP File System Functions

➢ PHP MySQL Functions

➢ PHP Network Functions

➢ PHP ODBC Functions

➢ PHP String Functions

➢ PHP SimpleXML Functions

➢ PHP XML Parsing Functions

ARRAY FUNCTIONS

<?php

$a = array("a"=>"Dog", "b"=>"Cat",

"c"=>"Horse");

print_r($a);

?>

o/p

Array ( [a] => Dog [b] => Cat [c] => Horse )

array_fill()

➢ Fills an array with num entries of the value of the valueparameter, keys starting at the start_index parameter.

<?php

$a = array_fill(5, 6, 'apple');

print_r($a);

?>

o/p

Array ( [5] => apple [6] => apple [7] => apple

[8] => apple [9] => apple [10] => apple )

array_keys() and array_values()<?php

<?php

$array = array("a"=>"green", "b"=>"brown",

"c"=>"blue", "red");

print_r(array_values($array));

echo "<br>";

print_r(array_keys($array));

?>

O/P

Array ( [0] => green [1] => brown [2] => blue

[3] => red ) Array ( [0] => a [1] => b [2] => c [3]

=> 0 )

Page 75: CS6501 INTERNET PROGRAMMING UNIT I JAVA PROGRAMMING

VELTECH HIGHTECH Dr.RANGARAJAN Dr.SAKUNTHALA ENGINEERING COLLEGE DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING

VELTECH HIGHTECH DR.RANGARAJAN Dr.SAKUNTHALA ENGINEERING COLLEGE Page 75

CALENDER FUNCTION

➢ The calendar extension presents a series

of functions to simplify converting

between different calendar formats.

➢ The intermediary or standard it is based

on is the Julian Day Count.

➢ To convert between calendar systems,

you must first convert to Julian Day

Count, then to the calendar system of

your choice.

cal_days_in_month() ➢ This function will return the number of days in

the month of year for the specified calendar ➢ This function returns the day of the week. It can

return a string or an integer depending on the mode.

<?php $num =

cal_days_in_month(CAL_GREGORIAN,10, 2016);

echo "There are $num days in October 2016"; ?> O/p:- There are 31 days in October 2016

CHARACTER FUNCTIONS

➢ The functions provided by this extension

check whether a character or string falls

into a certain character class according to

the current locale.

➢ Checks if all of the characters in the

provided string, text, are alphabetical.

Checks if all of the characters in the

provided string, text, are numerical. It

checks only 1...9

➢ This function checks if all of the characters

in the provided string, text, are lowercase

letters.

➢ This function checks if all of the

characters in the provided string, text, are

uppercase characters.

EXAMPLE PROGRAM

<?php

$strings = array('AB','cd','123','#');

foreach ($strings as $check)

{

if (ctype_alnum($check)) echo "$check

consists of letters or digits"; echo "<br>";

?>

O/p:-

AB consists of letters or digits

4.6 CONNECTING TO DATABASE

➢ Before you can get content out of your MySQL database, you must know how to establish a connection to MySQL from inside a PHP script.

➢ To perform basic queries from within MySQL is very easy.

➢ The first thing to do is connect to the database. The function to connect to MySQL is called mysql_connect.

➢ This function returns a resource which is a pointer to the database connection.

<?php $username = "your_name"; $password = "your_password"; $hostname = "localhost"; //connection to the database $dbhandle = mysql_connect($hostname, $username, $password) or die("Unable to connect to MySQL"); echo "Connected to MySQL<br>";

Page 76: CS6501 INTERNET PROGRAMMING UNIT I JAVA PROGRAMMING

VELTECH HIGHTECH Dr.RANGARAJAN Dr.SAKUNTHALA ENGINEERING COLLEGE DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING

VELTECH HIGHTECH DR.RANGARAJAN Dr.SAKUNTHALA ENGINEERING COLLEGE Page 76

?> ➢ All going well, you should see "Connected

to MySQL" when you run this script. ➢ Once you've connected, you're going to

want to select a database to work with. ➢ Let's assume the database is ca

'examples'. To start working in this database, you'll need the mysql_select_db() function: <?php //select a database to work with $selected = mysql_select_db("examples",$dbhandle) or die("Could not select examples"); ?>

➢ Now that you're connected, let's try and run some queries. The function used to perform queries is named - my The function returns a resource that contains the results of the query, called the result set.

➢ A convenient way to access all the rows is with a while loop. Let's add the code to our script:

➢ <?php //execute the SQL query and return records $result = mysql_query("SELECT id, model, year FROM cars"); //fetch the data from the database while ($row = mysql_fetch_array($result)) { echo "ID:".$row{'id'}." Name:".$row{'model'}." ".$row{'year'}."<br>"; } ?> EXAMPLE PROGRAM <?php //close the connection mysql_close($dbhandle); ?> Here is a code in full: <?php $username = "your_name";

$password = "your_password"; $hostname = "localhost"; //connection to the database $dbhandle = mysql_connect($hostname, $username, $password) or die("Unable to connect to

MySQL"); echo "Connected to MySQL<br>"; //select a database to work with $selected = mysql_select_db("examples",$dbhandle) or die("Could not select examples"); //execute the SQL query and return records $result = mysql_query("SELECT id, model,year FROM cars"); //fetch the data from the database while ($row = mysql_fetch_array($result)) { echo "ID:".$row{'id'}." Name:".$row{'model'}."Year: ". //display the results $row{'year'}."<br>"; } //close the connection mysql_close($dbhandle); ?> To create 'examples' database on your MySQL server you should run the following script: CREATE DATABASE `examples`; USE `examples`; CREATE TABLE `cars` ( `id` int UNIQUE NOT NULL, `name` varchar(40), `year` varchar(50), PRIMARY KEY(id) ); INSERT INTO cars VALUES(1,'Mercedes','2000'); INSERT INTO cars VALUES(2,'BMW','2004');

4.7 COOKIES ➢ A cookie is a name-value pair that is

stored on client computer for tracking

purpose

➢ It is created by some software on the

server

➢ In every HTTP communication

between client and server, there is a

header, within that, cookies are

present

➢ PHP supports cookies

➢ Server puts cookie into client machine

on first visit.

➢ When that client machine sends request

to that server next time, server identifies

which user it is, from where the request

arrives, from what device the request

comes

Page 77: CS6501 INTERNET PROGRAMMING UNIT I JAVA PROGRAMMING

VELTECH HIGHTECH Dr.RANGARAJAN Dr.SAKUNTHALA ENGINEERING COLLEGE DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING

VELTECH HIGHTECH DR.RANGARAJAN Dr.SAKUNTHALA ENGINEERING COLLEGE Page 77

4.7.1 CREATE COOKIES WITH PHP

➢ A cookie is created with the setcookie() function. Syntax setcookie(name, value, expire, path, domain, secure, httponly);

➢ Only the name parameter is required. All other parameters are optional.

EXAMPLE PROGRAM <html> <body> <?php if(!isset(“Myname”])) echo "welcome “.$+COOKIE[“Myname”]”; . $else “welcome guest”; ?>

</body>

</html>

O/P

Welcome cse

4.8 REGULAR EXPRESSION

➢ Regular Expressions, commonly known as

"regex" or "RegExp", are a specially

formatted text strings used to find

patterns in text.

➢ Regular expressions are one of the most

powerful tools available today for

effective and efficient text processing and

manipulations.

➢ For example, it can be used to verify

whether the format of data i.e. name,

email, phone number, etc.

➢ PHP (version 5.3 and above) supports

Perl style regular expressions via its preg_

family of functions.

4.8.1 REGULAR EXPRESSION FUNCTION

Function What it Does

preg_match() Perform a regular expression

match.

preg_match_all Perform a global regular

expression match.

preg_replace() Perform a regular expression

search and replace.

preg_grep() Returns the elements of the

input array that matched the

pattern.

preg_split() Splits up a string into

substrings using a regular

expression.

preg_quote() Quote regular expression

characters found within a

string.

4.8.2 Regular Expression Syntax

Regular expression syntax includes the use of special characters (do not confuse with the HTML special characters). The characters that are given special meaning within a regular expression, are: . * ? + [ ] ( ) { } ^ $ | \.

EXAMPLE PROGRAM

<?php

$pattern = "/ca[kf]e/";

$text = "He was eating cake in the cafe.";

if(preg_match($pattern, $text)){

Page 78: CS6501 INTERNET PROGRAMMING UNIT I JAVA PROGRAMMING

VELTECH HIGHTECH Dr.RANGARAJAN Dr.SAKUNTHALA ENGINEERING COLLEGE DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING

VELTECH HIGHTECH DR.RANGARAJAN Dr.SAKUNTHALA ENGINEERING COLLEGE Page 78

echo "Match found!";

} else{

echo "Match not found.";

}

?>

O/P

Match found!

4.9 XML

➢ Xtensible Markup language

➢ XML is defined as a text based mark up

language derived from Standard

Generalised Markup Language

➢ Developed by W3C in Feb 1998 to

overcome HTML

➢ A web script that contains XML tags is

called XML document

➢ It is a mark up language that defines set of

rules for encoding documents in a format

that is both human readable and machine

readable

➢ It is not a programming language

4.9.1MENTION THE FEATURES OF XML

➢ Extensible: user defined tags

➢ Secure: Carries data, but does not shows

it

➢ Public standard: developed by W3C

➢ Simplifies HTML for large websites

➢ To offload and reload databases

➢ To store and arrange data

➢ Can be merged with CSS

➢ Any data can be expressed in XML

4.9.2 RULES IN XML DECLARATION

➢ If XML declaration is present, it should be

placed 1st

➢ If XML declaration is present, it must

contain version no

➢ Parameter name and parameter value is

case sensitive

➢ Correct order is: version, encoding,

standalone

➢ Either ‘ or “ can be used

➢ XML declaration has no close tag </?xml>

is wrong

4.9.3 DIFFERENCE BETWEEN XML AND

HTML

XML HTML

To transport and store data

To display data

Focus on what data it is

Focus on how the data looks

Provides framework for defining mark up languages

It is mark up language itself

It is neither a programming language, nor a presentation language

It is a presentation language

Case sensitive Case insensitive

User defined tags No user defined tags

Closing of each tag is mandatory

Not necessary of closing all the opened tags

Preserve white space Does not.

4.9.4 ADVANTAGES OF XML

➢ Human readable, easy to understand

Page 79: CS6501 INTERNET PROGRAMMING UNIT I JAVA PROGRAMMING

VELTECH HIGHTECH Dr.RANGARAJAN Dr.SAKUNTHALA ENGINEERING COLLEGE DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING

VELTECH HIGHTECH DR.RANGARAJAN Dr.SAKUNTHALA ENGINEERING COLLEGE Page 79

➢ Language neutral

➢ Tree structured, understood in simpler

manner

➢ Independent of hardware, software and

OS

➢ User defined tags

4.9.5 MENTION THE USES OF XML

➢ To display meta contents

➢ To exchange data between applications

and databases

➢ To store any kind of complex data in

simpler way

➢ A java program can generate XML and can

be parsed by Perl

4.9.6 BUILDING BLOCKS OF XML

➢ Elements (start and end tags)

➢ Attributes (flag type=”true”)

➢ CDATA (Character DATA, parsed by XML

parser)

➢ PCDATA ( Parsed Character DATA, i.e.,

text)

➢ XML declaration < ? xml version = “1.0” ?> “xml” should be in lower case Every XML document should begin with <?xml…>

It must be the root element in all XML files Tags and elements Tags are the building blocks of XML document It is also called XML nodes <name>Bala</name> <person>

<name>Bala</name> <phone>1234</phone> </person> Attributes o To specify a property of an element o It is a “name-value” pair o An element can have more than 1

attributes o <phone available=”yes”>1234</phone> References o To add additional information

o Begin with & o Entity reference o Character Reference Text

XML elements and attributes are case sensitive

Start and end tag needs to be in same case

To avoid encoding problems, use UTF-8 or UTF-16

It is whitespace insensitive Example:- <?xml version=”1.0”?> <person> <name>Bala</name> <cell>1234</cell> <company>TCS</company> </person> Rules for XM

4.10 DOCUMENT TYPE DECLARATION

➢ Document Type Definition

➢ To define the type of the document

➢ A DTD is attached to a document

➢ To describe the XML

Syntax:-

Page 80: CS6501 INTERNET PROGRAMMING UNIT I JAVA PROGRAMMING

VELTECH HIGHTECH Dr.RANGARAJAN Dr.SAKUNTHALA ENGINEERING COLLEGE DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING

VELTECH HIGHTECH DR.RANGARAJAN Dr.SAKUNTHALA ENGINEERING COLLEGE Page 80

➢ The DTD starts with <!DOCTYPE delimiter.

➢ An element tells the parser to parse the

document from the specified root

element

➢ DTD identifier is an identifier for the

document type definition, which may be

the path to a file on the system or URL to

a file on the internet. If the DTD is

pointing to external path, it is called

External Subset.

➢ The square brackets [ ] enclose an

optional list of entity declarations called

Internal Subset.

4.10.1 INTERNAL DTD

➢ Elements are declared within XML

➢ DTD is stored within the XML file itself.

➢ Set stand alone attribute = “yes”

sample.xml

<? xml version = “1.0” encoding = “utf-8”

standalone=”yes”?>

< ! DOCTYPE address

[

< ! ELEMENT address(name, phone,

company)>

< ! ELEMENT name(#PCDATA)>

< ! ELEMENT phone(#PCDATA)>

< ! ELEMENT company(#PCDATA)>

]

>

<address>

<name>Bala</name>

<phone>1234</phone>

<company>TCS</company>

</address>

Note:-

CDATA -Character Data, this data is parsed by

the XML parser

PCDATA -Parsed Character Data, plain text

# -Delimiter

4.10.2 EXTERNAL DTD

➢ DTD is stored in a separate file called

“sample.dtd”

➢ Set stand alone attribute = “no”

sample.xml

<? xml version = “1.0” encoding = “utf-8”

standalone=”yes”?>

< ! DOCTYPE address SYSTEM “address.dtd”>

<address>

<name>Bala</name>

<phone>1234</phone>

<company>TCS</company>

</address>

Page 81: CS6501 INTERNET PROGRAMMING UNIT I JAVA PROGRAMMING

VELTECH HIGHTECH Dr.RANGARAJAN Dr.SAKUNTHALA ENGINEERING COLLEGE DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING

VELTECH HIGHTECH DR.RANGARAJAN Dr.SAKUNTHALA ENGINEERING COLLEGE Page 81

address.dtd

< ! DOCTYPE address

[

< ! ELEMENT address(name, phone,

company)>

< ! ELEMENT name(#PCDATA)>

< ! ELEMENT phone(#PCDATA)>

< ! ELEMENT company(#PCDATA)>

]

>

Advantages of DTD

➢ XML processor enforces structure, as

defined in DTD

➢ Application is accessed easily in document

structure

➢ DTD gives hint to XML processor

➢ Reduces size of document

4.11 XML SCHEMA

➢ It is also known as XML schema Definition

(XSD) ➢ To represent structure of XML document ➢ To describe and validate structure and

content of XML ➢ Defines elements, attributes and data

types ➢ To define building blocks of XML Ex: <xs:schema xmlns:xs=http://www.w3.org/2001/XMLSchema> 4.11.1 PURPOSE OF XML SCHEMA

➢ The schemas are more specific and provide the support for data types.

➢ The schema is aware of namespace ➢ The XML Schema is written in XML

itself and has a large number of built-in and derived types.

➢ The xml schema is the W3C

➢ recommendation. Hence it is

supported by various XML validator and XML Processors.

What are the disadvantages of schema? The XML

schema is complex to design and hard to learn The

XML document cannot be if the corresponding schema

file is absent. Maintaining the schema for large and

complex operations sometimes slows down the

processing of XML document

4.11.2 DISADVANTAGES OF SCHEMA

➢ The XML schema is complex to design and hard to learn

➢ The XML document cannot be if the corresponding schema file is absent.

➢ Maintaining the schema for large and complex operations sometimes slows down the processing of XML document

Simple Type - Simple type element is used only in the context of the text. Some of predefined simple types are: xs:integer, xs:boolean, xs:string, xs:date. For example: <xs:element name="phone_number" type="xs:int" /> ii) Complex Type - A complex type is a container for other element definitions. This allows you to specify which child elements an element can contain and to provide some

Page 82: CS6501 INTERNET PROGRAMMING UNIT I JAVA PROGRAMMING

VELTECH HIGHTECH Dr.RANGARAJAN Dr.SAKUNTHALA ENGINEERING COLLEGE DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING

VELTECH HIGHTECH DR.RANGARAJAN Dr.SAKUNTHALA ENGINEERING COLLEGE Page 82

structure within your XML documents. For example: <xs:element name="Address"> <xs:complexType> <xs:sequence> <xs:element name="name" type="xs:string" /> <xs:element name="company" type="xs:string" /> <xs:element name="phone" type="xs:int" /> </xs:sequence> </xs:complexType> </xs:element> iii) Global Types - With global type, you can define a single type in your document, which can be used by all other references. For example, suppose you want to generalize the person and company for different addresses of the company. In such case, you can define a general type as below: <xs:element name="AddressType"> <xs:complexType> <xs:sequence> <xs:element name="name" type="xs:string" /> <xs:element name="company" type="xs:string" /> </xs:sequence> </xs:complexType> </xs:element> Now let us use this type in our example as below: <xs:element name="Address1"> <xs:complexType> <xs:sequence> <xs:element name="address" type="AddressType" /> <xs:element name="phone1" type="xs:int" /> </xs:sequence> </xs:complexType> </xs:element>

<xs:element name="Address2"> <xs:complexType> <xs:sequence> <xs:element name="address" type="AddressType" /> <xs:element name="phone2" type="xs:int" /> </xs:sequence> </xs:complexType> </xs:element>

1. Instead of having to define the name and the company twice (once for Address1 and once for Address2), we now have a single definition.

2. This makes maintenance simpler, i.e., if you decide to add "Postcode" elements to the address, you need to add them at just one place. Step 2: student.xml <?xml version="1.0" encoding="UTF-8"?> <contact xmlns:xs="http://www.w3.org/2001/XMLSchema-instance” SchemaLocation=”student.xsd”> <name>Bala></name> <company>TCS</company> <phone>1234</phone> <contact> Step 3: Open the Xml file in browser o/p:- <contact> <name>Bala></name> <company>TCS</company> <phone>1234</phone> <contact> 4.11.3 XML SCHEMA DATA TYPES

➢ String ➢ Numeric

➢ Date

➢ Boolean

Page 83: CS6501 INTERNET PROGRAMMING UNIT I JAVA PROGRAMMING

VELTECH HIGHTECH Dr.RANGARAJAN Dr.SAKUNTHALA ENGINEERING COLLEGE DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING

VELTECH HIGHTECH DR.RANGARAJAN Dr.SAKUNTHALA ENGINEERING COLLEGE Page 83

<xs:string> data type ➢ The <xs:string> data type can take

characters, line feeds, carriage returns, and tab characters.

➢ The XML processor does not replace line feeds, carriage returns, and tab characters in the content with space and keep them intact.

➢ For example, multiple spaces or tabs are preserved during display.

Example:- Step 1: string.xsd <?xml version="1.0" encoding="UTF-8"?> <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"> <xs:element name=”contact” type=”xs:string”/> </xs:schema>

Step 2: string.xml <?xml version="1.0" encoding="UTF-8"?> <contact xmlns:xs="http://www.w3.org/2001/XMLSchema-instance” SchemaLocation=”string.xsd”> Balamurugan </contact> Step 3: Validate in Xml validator o/p:- This XML document is valid ii) <xs:date> data type The <xs:date> data type is used to represent date in YYYY-MM-DD format. * YYYY − represents year * MM − represents month * DD − represents day Step 1: date.xsd <?xml version="1.0" encoding="UTF-8"?> <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"> <xs:element name=”contact” type=”xs:date”/> </xs:schema> Step 2: date.xml <?xml version="1.0" encoding="UTF-8"?> <contact xmlns:xs="http://www.w3.org/2001/XMLSchema-instance” SchemaLocation=”date.xsd”> 2016-10-17 </contact> Step 3: Validate in Xml validator o/p:- This XML document is valid iii) <xs:numeric> data type

The <xs:decimal> data type is used to represent numeric values.

It supports decimal numbers up to 18 digits. The <xs:integer> data type is used to represent

integer values. Step 1: numeric.xsd <?xml version="1.0" encoding="UTF-8"?> <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"> <xs:element name=”contact” type=”xs:decimal”/>

Page 84: CS6501 INTERNET PROGRAMMING UNIT I JAVA PROGRAMMING

VELTECH HIGHTECH Dr.RANGARAJAN Dr.SAKUNTHALA ENGINEERING COLLEGE DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING

VELTECH HIGHTECH DR.RANGARAJAN Dr.SAKUNTHALA ENGINEERING COLLEGE Page 84

</xs:schema> Step 2: numeric.xml <?xml version="1.0" encoding="UTF-8"?> <contact xmlns:xs="http://www.w3.org/2001/XMLSchema-instance” SchemaLocation=”numeric.xsd”> 93.5 </contact> Step 3: Validate in Xml validator o/p:- This XML document is valid

4.13 XML Parsers and Validation

➢ XML parser is a software library or a

package that gives interface for client

apps to work with XML

➢ It checks for proper format of XML

document and validate XML documents

➢ To parse the given XML document

DOM API SAX API

Document Object Model

Simple API for XML

Tree based parsing

Event based parsing

Entire XML is stored in

Part of Xml is stored in

memory memory

Requires less memory space

Requires more memory space

Useful for small apps

Uesful for large apps

Traverse in any direction

Top-down traversing

4.13.1 DOM BASED PARSING:- dom.java import java.io.*; import javax.xml.parsers.*; import org.w3c.dom.*; import org.xml.sax.*; public class dom { public static void main(String bala[]) { try { System.out.println(“Enter XML document name”); BufferedReader input = new BufferedReader( new InuptStreamReader(System.in)); String filename = input.readLine(); File fp = new File(filename); if(fp.exists()) { try { DocumentBuilderFactory dbf = new DocumentBuilderFactory.newInstance(); DocumentBuilder db = dbf.new DocumentBuilder(); InputSource ips = new InputSource(filename); Document doc = db.parse(ips); System.out.println(filename + “is well formed”); } catch(Exception e) { System.out.println(“Not well formed”);

Page 85: CS6501 INTERNET PROGRAMMING UNIT I JAVA PROGRAMMING

VELTECH HIGHTECH Dr.RANGARAJAN Dr.SAKUNTHALA ENGINEERING COLLEGE DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING

VELTECH HIGHTECH DR.RANGARAJAN Dr.SAKUNTHALA ENGINEERING COLLEGE Page 85

System.exit(1); } } else { System.out.println(“File not Found”); } } catch(IOException ioe) { ioe.printStackTrace(); } } } User.xml <?xml version="1.0"?> <userdata> <user1> <userno>001</userno> <username>Bala</username> <phonenumner>123456789</phonenumber> <address>Chennai</Chennai> </user1> <user2> <userno>002</userno> <username>Suresh</username> <phonenumner>987654321</phonenumber> <address>madurai</Chennai> </user2> <user3> <userno>003</userno> <username>arul</username> <phonenumner>1122334455</phonenumber> <address>Vellore</Chennai> </user3> </userdata> o/p:- C:> javac dom.java C:> java dom Enter file name dom.xml dom.xml is well formed

4.13.2 SAX BASED PARSING

import java.io.*; import org.xml.sax.*; import org.xml.sax.helpers.*; public class dom { public static void main(String bala[]) { try { System.out.println(“Enter XML document name”); BufferedReader input = new BufferedReader( new InuptStreamReader(System.in)); String filename = input.readLine(); File fp = new File(filename); if(fp.exists()) { try { XMLReader reader = XMLReaderFactory.CreateXMLReader(); reader.parse(filename); System.out.println(“filename + “is well formed”); } catch(Exception e) { System.out.println(“filename + “is not well formed”); System.exit(1); }

else

{

System.out.println(“file not found”);

}

catch(IOException ioe)

{

ioe.printStackTrace();

}

}

}

Page 86: CS6501 INTERNET PROGRAMMING UNIT I JAVA PROGRAMMING

VELTECH HIGHTECH Dr.RANGARAJAN Dr.SAKUNTHALA ENGINEERING COLLEGE DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING

VELTECH HIGHTECH DR.RANGARAJAN Dr.SAKUNTHALA ENGINEERING COLLEGE Page 86

o/p:-

C:> javac sax.java

C:> java sax

Enter file name

data.xml

data.xml is well formed

4.14 XSL and XSLT Transformation

➢ XML concentrates on structure of

information

➢ W3C has published 2 recommendations for

style sheets

a) CSS

b) XSL

➢ XSL = XML Style sheet Language

➢ To transform a document before display

➢ For advanced style information

PARTS OF XSL

➢ XSLT: XSL Transformation, to

transform XML

➢ XPath: a language for navigating XML

➢ XSL-FO: XSL-Formatting Objects, for

formatting XML

XSLT

➢ XSLT is a language to specify

transformation of XML documents

➢ It takes XML document, transforms it

into another XML document

➢ It is XML related technology to

manipulate and transform XML

documents

➢ To define XML transformations and

presentations

➢ The Extensible Stylesheet Language

(XSL) is an XML vocabulary typically

used to transform XML documents

from one form to another for

4.15 NEWS FEED

➢ On the World Wide Web, a web feed (or

news feed) is a data format used for

providing users with frequently updated

content.

➢ Content distributors syndicate a web feed,

thereby allowing users to subscribe to it.

➢ Making a collection of web feeds accessible

in one spot is known as aggregation, which

is performed by a news aggregator.

➢ A web feed is also sometimes referred to as

a syndicated feed.

4.15.1 ADVANTAGES OF WEB FEEDS

➢ Users do not disclose their email address

when subscribing to a feed and so are not

increasing their exposure to threats

Page 87: CS6501 INTERNET PROGRAMMING UNIT I JAVA PROGRAMMING

VELTECH HIGHTECH Dr.RANGARAJAN Dr.SAKUNTHALA ENGINEERING COLLEGE DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING

VELTECH HIGHTECH DR.RANGARAJAN Dr.SAKUNTHALA ENGINEERING COLLEGE Page 87

associated with email: spam, viruses,

phishing, and identity theft.

➢ Users do not have to send an unsubscribe

request to stop receiving news. They simply

remove the feed from their aggregator.

➢ The feed items are automatically sorted in

that each feed URL has its own sets of

entries

➢ News websites and blogs are common

sources for web feeds, but feeds are also

used to deliver structured information

ranging from weather data to top-ten lists

of hit tunes to search results.

➢ The two main web feed formats are

1) RSS

2) Atom.

➢ Web feeds are designed to be machine-

readable rather than human-readable

4.15.2 RSS

➢ RSS stand for: It depends on what version of

RSS you are using.

o RSS Version 0.9 - Rich Site Summary

o RSS Version 1.0 - RDF Site Summary

o RSS Versions 2.0, 2.0.1, and 0.9x -

Really Simple Syndication

➢ RSS is a protocol that provides an open

method of syndicating and aggregating web

content.

➢ RSS is a standard for publishing regular

updates to web-based content.

➢ RSS is an XML application, which conforms

to the W3C's RDF specification and is

extensible via XML.

WORKING OF RSS

➢ A website willing to publish its content using

RSS creates one RSS Feed and keeps it on a

web server.

➢ RSS Feeds can be created manually or with

software.

➢ A website visitor will subscribe to read your

RSS Feed.

➢ An RSS Feed will be read by an RSS Feed

reader.

➢ The RSS Feed Reader reads the RSS Feed

file and displays it.

➢ The RSS Reader displays only new items

from the RSS Feed.

<?xml version="1.0" ?>

<rss version="2.0">

<channel>

<title>Ajax and XUL</title>

<link>http://www.xul.fr/en/</link>

<description>XML graphical interface

etc...</description>

<image>

<url>http://www.xul.fr/xul-icon.gif</url>

<link>http://www.xul.fr/en/index.php</link

Page 88: CS6501 INTERNET PROGRAMMING UNIT I JAVA PROGRAMMING

VELTECH HIGHTECH Dr.RANGARAJAN Dr.SAKUNTHALA ENGINEERING COLLEGE DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING

VELTECH HIGHTECH DR.RANGARAJAN Dr.SAKUNTHALA ENGINEERING COLLEGE Page 88

>

</image>

<item>

<title>News of today</title>

<link>http://www.xul.fr/en-xml-

rss.html</link>

<description>All you need to know about

RSS</description>

</item>

<item>

<title>News of tomorrows</title>

<link>http://www.xul.fr/en-xml-

rdf.html</link>

<description>And now, all about

RDF</description>

</item>

</channel>

4.15.3 ATOM FEED

➢ Atom is the name of an XML-based Web

content and metadata syndication format,

and an application-level protocol for

publishing and editing Web resources

belonging to periodically updated websites.

➢ Atom is a relatively recent spec and is much

more robust and feature-rich than RSS.

➢ All Atom Feeds must be well-formed XML

documents, and are identified with the

application/atom+xml media type.

STRUCTURE OF AN ATOM 1.0 FEED

<?xml version="1.0"?>

<feed

xmlns="http://www.w3.org/2005/Atom">

<title>...</title>

<link>...</link>

<updated>...</updated>

<author>

<name>...</name>

</author>

<id>...</id>

<entry>

<title>...</title>

<link>...</link>

<id>...</id>

<updated>...</updated>

<summary>...</summary>

</entry>

</feed>

EXAMPLE:-

<?xml version="1.0" encoding="utf-8"?>

<feed

xmlns="http://www.w3.org/2005/Atom">

<title>Example Feed</title>

Page 89: CS6501 INTERNET PROGRAMMING UNIT I JAVA PROGRAMMING

VELTECH HIGHTECH Dr.RANGARAJAN Dr.SAKUNTHALA ENGINEERING COLLEGE DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING

VELTECH HIGHTECH DR.RANGARAJAN Dr.SAKUNTHALA ENGINEERING COLLEGE Page 89

<subtitle>Insert witty or insightful remark

here</subtitle>

<link href="http://example.org/"/>

<updated>2003-12-

13T18:30:02Z</updated>

<author>

<name>Mohtashim</name>

<email>[email protected]</em

ail>

</author>

<id>urn:uuid:60a76c80-d399-11d9-

b93C-0003939e0af6</id>

<entry>

<title>Tutorial on Atom</title>

<link

href="http://example.org/2003/12/13/

atom03"/>

<id>urn:uuid:1225c695-cfb8-4ebb-aaaa-

80da344efa6a</id>

<updated>2003-12-

13T18:30:02Z</updated>

<summary>Some text.</summary>

</entry>

</feed>

RSS ATOM

Contains either plain text or escaped sequence as payload

Contains html, xml, dhtml, documents, audio, video, etc as payload

Shows timestamp of data when feed was last created or updated

Shows timestamp of data when it was last updated

Uses blogger and meta weblog protocols

It has only one standard protocols

Loose approach on data

Strict approach on data

More complicated process

Easier process

Not a standard feature

Standard feature

Less robust, scalable, efficient

More robust, scalable, efficient

Page 90: CS6501 INTERNET PROGRAMMING UNIT I JAVA PROGRAMMING

VELTECH HIGHTECH Dr.RANGARAJAN Dr.SAKUNTHALA ENGINEERING COLLEGE DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING

VELTECH HIGHTECH DR.RANGARAJAN Dr.SAKUNTHALA ENGINEERING COLLEGE Page 90

CS6501 INTERNET PROGRAMMING

UNIT V INTRODUCTION TO AJAX and WEB

SERVICES

AJAX: 5.1 Ajax Client Server Architecture- 5.2 XML Http Request Object-5.3 Call Back Methods; Web Services: 5.4 Introduction- 5.5 Java web services Basics – 5.6 Creating, Publishing ,Testing and Describing a Web services (WSDL)- 5.8 Consuming a web service, 5.9 Database Driven web service from an application – 5.10 SOAP.

5.1 AJAX

➢ AJAX is an acronym for asynchronous

JavaScript and XML

➢ It is a set of web development techniques

using many web technologies on the

client-side to create asynchronous Web

applications.

➢ HTML and CSS can be used in

combination to mark up and style

information.

➢ The DOM is accessed with JavaScript to

dynamically display and allow the user to

interact with the information presented.

➢ JavaScript and the XMLHttpRequest

object provide a method for exchanging

data asynchronously between browser

and server to avoid full page reloads.

ADVANTAGES OF AJAX ➢ Using Ajax are asynchronous

communication, minimal data transfer and server is not overloaded with unnecessary load.

TECHNOLOGIES ARE BEING USED IN AJAX ✓ JavaScript ✓ XMLHttpRequest ✓ Document Object Model (DOM ✓ Extensible HTML (XHTML) ✓ Cascading Style Sheets (CSS)

5.1.1 AJAX CLIENT SEVER ARCHITECTURE

RIA TECHNOLOGY

➢ AJAX is the most viable Rich Internet

Application (RIA) technology

➢ It is getting tremendous industry

momentum and several tool kit and

frameworks are emerging.

➢ But at the same time, AJAX has browser

incompatibility and it is supported by

JavaScript, which is hard to maintain and

debug.

Page 91: CS6501 INTERNET PROGRAMMING UNIT I JAVA PROGRAMMING

VELTECH HIGHTECH Dr.RANGARAJAN Dr.SAKUNTHALA ENGINEERING COLLEGE DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING

VELTECH HIGHTECH DR.RANGARAJAN Dr.SAKUNTHALA ENGINEERING COLLEGE Page 91

5.1.2 STEPS OF PROCESSING IN AJAX

➢ An event occurs in a web page (the page

is loaded, a button is clicked)

➢ An XMLHttpRequest object is created by

JavaScript

➢ The XMLHttpRequest object sends a

request to a web server

➢ The server processes the request

➢ The server sends a response back to the

web page

➢ The response is read by JavaScript

➢ Proper action (like page update) is

performed by JavaScript

EXAMPLE FOR AJAX: Google maps, Gmail, cricket update websites, stock markets websites, etc EXAMPLE PROGRAM <!DOCTYPE html> <html> <body> <div id="demo"> <h1>The XMLHttpRequest Object</h1> <button type="button" onclick="loadDoc()"> Change Content </button> </div> <script> function loadDoc() { var xhttp = new XMLHttpRequest(); xhttp.onreadystatechange = function() { if (this.readyState == 4 && this.status == 200) { document.getElementById("demo").innerHTML = this.responseText; } }; xhttp.open("GET", "ajax_info.txt", true); xhttp.send(); } </script> </body> </html> O/P

Page 92: CS6501 INTERNET PROGRAMMING UNIT I JAVA PROGRAMMING

VELTECH HIGHTECH Dr.RANGARAJAN Dr.SAKUNTHALA ENGINEERING COLLEGE DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING

VELTECH HIGHTECH DR.RANGARAJAN Dr.SAKUNTHALA ENGINEERING COLLEGE Page 92

SERVER SIDE

CLIENT SIDE

5.2 XML HTTP REQUEST OBJECT

➢ The XMLHttpRequest object can be used

to request data from a web server

➢ Update a web page without reloading the

page

➢ Request data from a server - after the

page has loaded

➢ Receive data from a server - after the

page has loaded

➢ Send data to a server - in the background

➢ The XMLHttpRequest object is the key to

AJAX. It has been available ever since

Internet Explorer 5.5 was released in July

2000

➢ XMLHttpRequest (XHR) is an API that can

be used by JavaScript, JScript, VBScript,

and other web browser scripting

languages to transfer and manipulate XML

data to and from a webserver using HTTP

5.2.1 XMLHTTPREQUEST METHODS

➢ abort() : Cancels the current request. ➢ getAllResponseHeaders() : Returns the

complete set of HTTP headers as a string.

Page 93: CS6501 INTERNET PROGRAMMING UNIT I JAVA PROGRAMMING

VELTECH HIGHTECH Dr.RANGARAJAN Dr.SAKUNTHALA ENGINEERING COLLEGE DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING

VELTECH HIGHTECH DR.RANGARAJAN Dr.SAKUNTHALA ENGINEERING COLLEGE Page 93

➢ getResponseHeader( headerName ) : Returns the value of the specified HTTP header.

➢ open(): method, URL

5.2.2 XMLHTTPREQUEST PROPERTIES

➢ onreadystatechange : An event handler

for an event that fires at every state

change.

➢ readyState : The readyState property

defines the current state of the

XMLHttpRequest object.

State Description

0 The request is not initialized.

1 The request has been set up.

2 The request has been sent.

3 The request is in process.

4 The request is completed

➢ readyState = 0 After you have created the

XMLHttpRequest object, but before you

have called the open() method

➢ readyState = 1 After you have called the

open() method, but before you have

called send().

➢ readyState = 2 After you have called

send().

➢ readyState = 3 After the browser has

established a communication with the

server, but before the server has

completed the response.

➢ readyState = 4 After the request has been

completed, and the response data has

been completely received from the

server.

➢ responseText :Returns the response as a

string.

➢ responseXML :Returns the response as

XML.

➢ status : Returns the status as a number

(e.g., 404 for "Not Found" and 200 for

"OK").

➢ statusText :Returns the status as a string

(e.g., "Not Found" or "OK")

EXAMPLE PROGRAM

<!DOCTYPE html>

<html>

<body>

<h2>Using the XMLHttpRequest

Object</h2>

<div id="demo">

<button type="button"

onclick="loadXMLDoc()">Change Content

</button>

</div>

<script>

function loadXMLDoc()

{

var xhttp = new XMLHttpRequest();

xhttp.onreadystatechange =

function()

{

if (this.readyState == 4 &&

this.status == 200)

Page 94: CS6501 INTERNET PROGRAMMING UNIT I JAVA PROGRAMMING

VELTECH HIGHTECH Dr.RANGARAJAN Dr.SAKUNTHALA ENGINEERING COLLEGE DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING

VELTECH HIGHTECH DR.RANGARAJAN Dr.SAKUNTHALA ENGINEERING COLLEGE Page 94

{

document.getElementById("demo").inner

HTML = this.responseText;

}

};

xhttp.open("GET", "xmlhttp_info.txt",

true);

xhttp.send();

}

</script>

</body>

</html>

O/P

➢ The onreadystatechange property

specifies a function to be executed every

time the status of the XMLHttpRequest

object changes.

➢ When readyState property is 4 and the

status property is 200, the response is

ready.

➢ responseText property returns the server

response as a text string.

➢ The text string can be used to update a

web page

5.3 CALL BACK METHODS

➢ The ajaxSuccess( callback ) method

attaches a function to be executed

whenever an AJAX request completes

successfully.

➢ This is an Ajax Event.

5.3.1 JQUERY CALLBACK FUNCTIONS

➢ JavaScript statements are executed line

by line. However, with effects, the next

line of code can be run even though the

effect is not finished. This can create

errors.

➢ To prevent this, you can create a callback

function.

➢ A callback function is executed after the

current effect is finished.

SYNTAX

$(selector).hide(speed,callback);

EXAMPLE PROGRAM

<html>

<head>

<script src=”jquery.min.js”>

</script>

<script>

$(document).ready(function()

{

$(“button”).click(

function()

{

$(“p”.hide();

}

);

});

</script>

</head>

<body>

<h3>call back</h3>

<button>CLICK ME</button>

</body>

</html>

Page 95: CS6501 INTERNET PROGRAMMING UNIT I JAVA PROGRAMMING

VELTECH HIGHTECH Dr.RANGARAJAN Dr.SAKUNTHALA ENGINEERING COLLEGE DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING

VELTECH HIGHTECH DR.RANGARAJAN Dr.SAKUNTHALA ENGINEERING COLLEGE Page 95

O/P

CALL BACK

5.4 WEB SERVICES

➢ Web services are open standard (XML,

SOAP, HTTP etc.) based Web applications

that interact with other web applications

for the purpose of exchanging data.

➢ It is OS and language independent

➢ Web Services can convert your existing

applications into Web-applications.

➢ A web service is a collection of open

protocols and standards used for

exchanging data between applications or

systems.

➢ ➢

CHARACTERISTICS OF WEB SERVICE ➢ Machine-to-machine interactions ➢ Loose coupling ➢ Interoperability ➢ Platform-independence ➢ Operating system-independence ➢ Language-independence COMPONENTS OF WEB SERVICES ➢ The basic web services platform is

XML + HTTP. ➢ SOAP (Simple Object Access

Protocol) ➢ UDDI (Universal Description,

Discovery and Integration) ➢ WSDL (Web Services Description

Language) ADVANTAGES OF WEB SERVICE

➢ Exposing the Existing Function on

the network ➢ Interoperability ➢ Standardized protocol ➢ Low Cost of Communication

5.5 JAVA WEB SERVICES BASICS

➢ Two main java web services api:

JAX-WS and JAX-RS.

➢ The java web service application

can be accessed by other

programming languages such as

.Net and PHP.

➢ Java web service application

perform communication through

WSDL (Web Services Description

Language).

➢ There are two ways to write java

web service application code: SOAP

and RESTful.

5.5.1 CONCEPT OF RPC

➢ Remote Procedure Call (RPC) is a

powerful technique for

constructing distributed, client-

server based applications.

➢ It is based on extending the

conventional local procedure

calling, so that the called procedure

need not exist in the same address

space as the calling procedure.

➢ The two processes may be on the

same system

CLICK ME

Page 96: CS6501 INTERNET PROGRAMMING UNIT I JAVA PROGRAMMING

VELTECH HIGHTECH Dr.RANGARAJAN Dr.SAKUNTHALA ENGINEERING COLLEGE DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING

VELTECH HIGHTECH DR.RANGARAJAN Dr.SAKUNTHALA ENGINEERING COLLEGE Page 96

Fig. Principle of RPC between a client and

server program

5.6 DESCRIBING A WEB SERVICES

(WSDL)

➢ WSDL stands for Web Services Description Language.

➢ It is the standard format for describing a web service.

➢ WSDL was developed jointly by Microsoft and IBM.

➢ To exchange information in a distributed environment.

➢ WSDL is used to describe web services

➢ WSDL is written in XML ➢ WSDL is a W3C recommendation

from 26. June 2007 5.7.1 ELEMENTS of WSDL?

➢ Types– a container for data type definitions using some type system (such as XSD).

➢ Message– an abstract, typed definition of the data being communicated.

➢ Operation– an abstract description of

an action supported by the service. ➢ Port Type–an abstract set of

operations supported by one or more endpoints.

➢ Binding– a concrete protocol and data format specification for a particular port type.

➢ Port– a single endpoint defined as a combination of a binding and a network address.

➢ Service– a collection of related endpoints.

4.7.2FEATURES OF WSDL

➢ WSDL is an XML-based protocol for information exchange in decentralized and distributed environments.

➢ WSDL definitions describe how to access a web service and what operations it will perform.

➢ WSDL is a language for describing how to interface with XML-based services.

➢ WSDL is an integral part of Universal Description, Discovery, and Integration (UDDI), an XML-based worldwide business registry.

➢ WSDL is the language that UDDI uses. WSDL is pronounced as 'wiz-dull' and spelled out as 'W-S-D-L'.

Page 97: CS6501 INTERNET PROGRAMMING UNIT I JAVA PROGRAMMING

VELTECH HIGHTECH Dr.RANGARAJAN Dr.SAKUNTHALA ENGINEERING COLLEGE DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING

VELTECH HIGHTECH DR.RANGARAJAN Dr.SAKUNTHALA ENGINEERING COLLEGE Page 97

4.7.3 THE WSDL DOCUMENT

STRUCTURE

<definitions> <types> definition of types........ </types> <message> definition of a message.... </message> <portType> <operation> definition of a operation....... </operation> </portType> <binding> definition of a binding……

</binding> <service> definition of a service.... </service>

</definitions> EXAMPLE PROGRAM <message name="getTermRequest"> <part name="term" type="xs:string"/> </message> <message name="getTermResponse">

<part name="value" type="xs:string"/> </message> <portType name="glossaryTerms"> <operation name="getTerm"> <input message="getTermRequest"/> <output message="getTermResponse"/> </operation> </portType> In this example the

➢ <portType> element defines

"glossaryTerms" as the name of a port, and "getTerm" as the name of an operation.

➢ The "getTerm" operation has an input message called "getTermRequest" and an output message called "getTermResponse".

➢ The <message> elements define the parts of each message and the associated data types.

5.8 DATABASE DRIVEN WEB SERVICE

FROM AN APPLICATION

➢ In this tutorial we will develop a simple user registration Webservices. The user registration/account registration form will be presented to the user.

➢ Once user fills in the form and clicks on the "OK" button, the serverside JSP will call the webservice to register the user.

➢ The MySQL database is used to save the user registration data. Software required to develop and run this example: • JDK 1.6 • NetBeans 6.1 • MySQL Database 5 or above

Let's get started with the development of the applicaton

Page 98: CS6501 INTERNET PROGRAMMING UNIT I JAVA PROGRAMMING

VELTECH HIGHTECH Dr.RANGARAJAN Dr.SAKUNTHALA ENGINEERING COLLEGE DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING

VELTECH HIGHTECH DR.RANGARAJAN Dr.SAKUNTHALA ENGINEERING COLLEGE Page 98

MySql Database Configuration In NetBeans Let's configure MySQL database in the NetBeans IDE and then create the required table into database. Step 1:

• Click on the service tab in NetBeans as shown below in Fig 1

Fig. 1 Step 2:

• Right Click on the Databases • Select New Connection as shown

below in Fig 2.

Fig. 2.

Step 3:

• It opens a dialog box for the mysql configuration.

• Type the driver name, url , user name and password as shown below in Fig. 3.

Fig. 3 Step 4:

• Click on the Ok button . • Now expand the Newly created

database connection. • It shows the all the tables of the

database test as shown below in Fig 4.

Page 99: CS6501 INTERNET PROGRAMMING UNIT I JAVA PROGRAMMING

VELTECH HIGHTECH Dr.RANGARAJAN Dr.SAKUNTHALA ENGINEERING COLLEGE DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING

VELTECH HIGHTECH DR.RANGARAJAN Dr.SAKUNTHALA ENGINEERING COLLEGE Page 99

Fig. 4 Step 5:

• Create a table named login. • Right Click on the Tables and

select Create table as shown below in Fig 5

Fig. 5 Step 6:

• It opens a dialog box for giving the

fields name of the table • Now give the field name and data

type as shown below in Fig 6.

Fig. 6 Step 7:

• Click on the Ok • It creates the table login in the

test database. Creating the WebService program for Account creation Step 8:

• Open the netbeans 6.1 • Creat a new web project as shown

below in Fig 7.

Page 100: CS6501 INTERNET PROGRAMMING UNIT I JAVA PROGRAMMING

VELTECH HIGHTECH Dr.RANGARAJAN Dr.SAKUNTHALA ENGINEERING COLLEGE DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING

VELTECH HIGHTECH DR.RANGARAJAN Dr.SAKUNTHALA ENGINEERING COLLEGE Page 100

Fig. 7 Step 9:

• Type the project Name as MyAccount

• Click on the next button as shown below in Fig 8.

Fig. 8 Step 10:

• Select the server as Glassfish • Click on the Next and then finish

button as shown below in Fig 9.

Fig. 9 Step 11:

• It creates a Web Project named MyAccount. Creating the WebService Step 12:

• Right Click on the project MyAccount

• Select New-->WebService as shown below in Fig 10.

Fig. 10 Step 13:

• Type the name of the WebService as myaccount with the package as mypack.

• Click on the Finish button as shown below in Fig 11.

Page 101: CS6501 INTERNET PROGRAMMING UNIT I JAVA PROGRAMMING

VELTECH HIGHTECH Dr.RANGARAJAN Dr.SAKUNTHALA ENGINEERING COLLEGE DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING

VELTECH HIGHTECH DR.RANGARAJAN Dr.SAKUNTHALA ENGINEERING COLLEGE Page 101

Fig. 11 Step 14:

• It creates a WebService application in design view

• Click on the Add operation as shown below in Fig 12.

Fig. 12 Step 15:

• In the dialog box type all parameter names.

• Also select the appropriate data type.

• Click on Ok as shown below in Fig 13.

Fig. 13 Step 16:

• It creates a WebService application

• Click on the source tab as shown below in the Fig 14.

Page 102: CS6501 INTERNET PROGRAMMING UNIT I JAVA PROGRAMMING

VELTECH HIGHTECH Dr.RANGARAJAN Dr.SAKUNTHALA ENGINEERING COLLEGE DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING

VELTECH HIGHTECH DR.RANGARAJAN Dr.SAKUNTHALA ENGINEERING COLLEGE Page 102

Fig. 14 Step 17:

• Now create the database source • Right Click in the source code of

myaccount.java • Select the Enterprise Resources--

>Use Database as shown below in Fig 15.

Fig. 15 Step 18:

• In the choose database select the

Add button as shown below in Fig

Fig. 16

Step 19: • It opens a Add Data Source

Reference. • Type the Reference Name as

data1 • For Project Data Sources Click on

the Add button as shown below in Fig 17.

Fig. 17

Page 103: CS6501 INTERNET PROGRAMMING UNIT I JAVA PROGRAMMING

VELTECH HIGHTECH Dr.RANGARAJAN Dr.SAKUNTHALA ENGINEERING COLLEGE DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING

VELTECH HIGHTECH DR.RANGARAJAN Dr.SAKUNTHALA ENGINEERING COLLEGE Page 103

Step 20:

• In the Crea Data Source type thye jndi name as jndi1

• In the database connection select the newly created database connction for the mysql. as shown below in Fig 18.

Fig. 18 Step 21:

• Click on the Ok button • It creates the database connection

gives the dialog box as shown below.

• Click on the Ok button as shown below in Fig 19.

Fig. 19 Step 22:

• It creates the datasource data1 with the resource name as data1 in the code

• Edit the code and give the database connection, statement for the mysql connectivity as shown below.

package mypack; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import javax.annotation.Resource; import javax.jws.WebMethod; import javax.jws.WebParam; import javax.jws.WebService; import javax.sql.DataSource; @WebService() public class myaccount { @Resource(name = "data1")

Page 104: CS6501 INTERNET PROGRAMMING UNIT I JAVA PROGRAMMING

VELTECH HIGHTECH Dr.RANGARAJAN Dr.SAKUNTHALA ENGINEERING COLLEGE DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING

VELTECH HIGHTECH DR.RANGARAJAN Dr.SAKUNTHALA ENGINEERING COLLEGE Page 104

private DataSource data1; @WebMethod(operationName = "insert") public String insert(@WebParam(name = "uname") String uname, @WebParam(name = "fname") String fname, @WebParam(name = "lname") String lname, @WebParam(name = "location") String location, @WebParam(name = "phone") String phone, @WebParam(name = "credit") String credit, @WebParam(name = "dl") String dl) { try { Class.forName("com.mysql.jdbc.Driver"); Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/test", "root", ""); PreparedStatement st = con.prepareStatement("insert into login values(?,?,?,?,?,?,?)"); st.setString(1, uname); st.setString(2, fname); st.setString(3, lname); st.setString(4, location); int ph = Integer.parseInt(phone); st.setInt(5, ph); int cr = Integer.parseInt(credit); st.setInt(6, cr); int d1 = Integer.parseInt(dl); st.setInt(7, d1); st.executeUpdate(); } catch (Exception e) { System.out.println(e.getMessage()); } return "record inserted";

} } Step 23:

• Now deploy the project • Right click on the project • Select Undeploy and Deploy as

shown below in Fig 20. • It builds and deploys the

MyAccount Web project on the glassfish server.

Fig. 20 Step 24:

• After deploying now we can test the Web Service created

• Right click on the myaccount webservice

• Select Test Web Service as shown below in Fig 21.

Page 105: CS6501 INTERNET PROGRAMMING UNIT I JAVA PROGRAMMING

VELTECH HIGHTECH Dr.RANGARAJAN Dr.SAKUNTHALA ENGINEERING COLLEGE DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING

VELTECH HIGHTECH DR.RANGARAJAN Dr.SAKUNTHALA ENGINEERING COLLEGE Page 105

• Fig. 21 Step 25:

• It runs the deployed webservice in the firefox browser.

• Type the value and click on the insert button as shown below in Fig 22.

Fig. 22 Step 26:

• After clicking on the insert button it insert the values into the login table

• It open new window and displays the Method parameters, SOAP request and response as shown below in Fig 23.

Step 27: Check the data in the database table

• In the service tab select the mysql connection

• In its table node right click on the table login

• Select the view data as shown below in Fig 24.

Fig. 24

Step 27:

Page 106: CS6501 INTERNET PROGRAMMING UNIT I JAVA PROGRAMMING

VELTECH HIGHTECH Dr.RANGARAJAN Dr.SAKUNTHALA ENGINEERING COLLEGE DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING

VELTECH HIGHTECH DR.RANGARAJAN Dr.SAKUNTHALA ENGINEERING COLLEGE Page 106

• It opens a new window • Then display the data as shown

below in Fig. 25.

Fig. 25 Making the client of the WebService Step 28:

• Create a new Web Project • Type the name as

MyAccountClient as shown below in Fig.26.

Fig. 26

Step 29: • Click on the next button • Select the server as glassfish as

shown below in Fig. 27.

Fig. 27 Step 30:

• Click on the finish button • It creates a web project with a

index.jsp file • In the index.jsp design it with

form and all its fields • Give the form action as Client.jsp

as shown below in Fig 28. Create WebService Client Step 1:

• Right Click on the MyAccountClient

• Select WebService Client as shown below in Fig.28.

Page 107: CS6501 INTERNET PROGRAMMING UNIT I JAVA PROGRAMMING

VELTECH HIGHTECH Dr.RANGARAJAN Dr.SAKUNTHALA ENGINEERING COLLEGE DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING

VELTECH HIGHTECH DR.RANGARAJAN Dr.SAKUNTHALA ENGINEERING COLLEGE Page 107

Fig. 28 Step 2:

• In the dialog box click on the browse button as shown below in Fig 29.

Fig. 29 Step 3:

• Select the myaccount webservice. • Click on the OK button as shown

below in Fig 30.

Fig. 30 Step 4:

• Now project is containing the WSDL file url.

• Click on the Ok button as shown below in Fig 31.

Fig. 31 Step 5:

• Right Click in the Client.jsp

Page 108: CS6501 INTERNET PROGRAMMING UNIT I JAVA PROGRAMMING

VELTECH HIGHTECH Dr.RANGARAJAN Dr.SAKUNTHALA ENGINEERING COLLEGE DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING

VELTECH HIGHTECH DR.RANGARAJAN Dr.SAKUNTHALA ENGINEERING COLLEGE Page 108

• Select Web Service Client Resources-->Call WebService Operation as shown below in Fig 32.

Fig. 32 Step 5:

• Select the insert operation as shown below in Fig .33.

Fig. 33 Step 6:

• After insert operation the code becomes like as shown below in Fig 34.

Fig. 34 Step 7:

• Deploy the MyAccountClient • Right Click and select Undeplo and

Deploy as shown below in Fig.35.

Page 109: CS6501 INTERNET PROGRAMMING UNIT I JAVA PROGRAMMING

VELTECH HIGHTECH Dr.RANGARAJAN Dr.SAKUNTHALA ENGINEERING COLLEGE DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING

VELTECH HIGHTECH DR.RANGARAJAN Dr.SAKUNTHALA ENGINEERING COLLEGE Page 109

Fig. 35 Step 8:

• After deployment run the project. • Right Click and select the run as

shown below in Fig 36.

Fig. 36 Step 9:

• It runs the index.jsp in the browser as shown below in Fig 37.

• Put the data and click on the ok button

Fig. 37 Step 10:

• After this click values get inserted in the database table

• The message comes as record inserted as shown below in Fig.38

Fig. 38 Step 11:

• See the data inserted in the table. • In the service tab select the

connection created for mysql. • In the table node select the login • Right Click and select the view

data as shown below in Fig. 39.

Page 110: CS6501 INTERNET PROGRAMMING UNIT I JAVA PROGRAMMING

VELTECH HIGHTECH Dr.RANGARAJAN Dr.SAKUNTHALA ENGINEERING COLLEGE DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING

VELTECH HIGHTECH DR.RANGARAJAN Dr.SAKUNTHALA ENGINEERING COLLEGE Page 110

Fig. 39

Step 12:

• It displays the record inserted as

shown below in Fig 40.

5.10 SOAP ➢ SOAP is an acronym for Simple Object

Access Protocol.

➢ It is an XML-based messaging protocol for

exchanging information among

computers.

➢ SOAP is an application of the XML

specification.

➢ SOAP is an application communication

protocol

➢ SOAP is a format for sending and

receiving messages

➢ SOAP is platform independent

➢ SOAP is based on XML

➢ SOAP is a W3C recommendation

5.10.1 FEATURES OF SOAP.

➢ SOAP is a communication protocol

designed to communicate via Internet.

➢ SOAP can extend HTTP for XML

messaging.

➢ SOAP provides data transport for Web

services.

➢ SOAP can exchange complete documents

or call a remote procedure.

➢ SOAP can be used for broadcasting a

message.

➢ SOAP is platform- and language-

independent.

➢ SOAP is the XML way of defining what

information is sent and how.

➢ SOAP enables client applications to easily

connect to remote services and invoke

remote methods.

5.10.2 ELEMENTS OF SOAP

➢ An Envelope element that identifies the

XML document as a SOAP message

➢ A Header element that contains header

Page 111: CS6501 INTERNET PROGRAMMING UNIT I JAVA PROGRAMMING

VELTECH HIGHTECH Dr.RANGARAJAN Dr.SAKUNTHALA ENGINEERING COLLEGE DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING

VELTECH HIGHTECH DR.RANGARAJAN Dr.SAKUNTHALA ENGINEERING COLLEGE Page 111

information

➢ A Body element that contains call and

response information

➢ A Fault element containing errors and status

information

5.10.4 ADVANTAGES OF SOAP

➢ Simplicity

➢ Portability

➢ Firewall

➢ Scalable

➢ Flexible

➢ Interoperability

5.10.5 RULES

➢ A SOAP message MUST be encoded using

XML

➢ A SOAP message MUST use the SOAP

Envelope namespace

➢ A SOAP message MUST use the SOAP

Encoding namespace

➢ A SOAP message must NOT contain a DTD

reference

➢ A SOAP message must NOT contain XML

Processing Instructions

<?xml version="1.0"?>

<soap:Envelope

xmlns:soap="http://www.w3.org/2003/05/s

oap-envelope/"

soap:encodingStyle="http://www.w3.org/2

003/05/soap-encoding">

<soap:Header> ... </soap:Header>

<soap:Body> ...

<soap:Fault> ... </soap:Fault>

</soap:Body>

</soap:Envelope>

SOAP REQUEST

POST /Quotation HTTP/1.0

Host: www.xyz.org

Content-Type: text/xml; charset=utf-8

Content-Length: nnn

<?xml version="1.0"?>

<SOAP-ENV:Envelope xmlns:SOAP-

ENV="http://www.w3.org/2001/12/soap-

envelope" SOAP-

ENV:encodingStyle="http://www.w3.org/20

01/12/soap-encoding" >

<SOAP-ENV:Body

xmlns:m="http://www.xyz.org/quotations"

>

<m:GetQuotation>

<m:QuotationsName>MiscroSoft</m:Quota

tionsName>

</m:GetQuotation>

</SOAP-ENV:Body>

Page 112: CS6501 INTERNET PROGRAMMING UNIT I JAVA PROGRAMMING

VELTECH HIGHTECH Dr.RANGARAJAN Dr.SAKUNTHALA ENGINEERING COLLEGE DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING

VELTECH HIGHTECH DR.RANGARAJAN Dr.SAKUNTHALA ENGINEERING COLLEGE Page 112

</SOAP-ENV:Envelope>

SOAP RESPONSE

HTTP/1.0 200 OK

Content-Type: text/xml; charset=utf-8

Content-Length: nnn

<?xml version="1.0"?>

<SOAP-ENV:Envelope xmlns:SOAP-

ENV="http://www.w3.org/2001/12/soap-

envelope" SOAP-

ENV:encodingStyle="http://www.w3.org/20

01/12/soap-encoding" >

<SOAP-ENV:Body

xmlns:m="http://www.xyz.org/quotation" >

<m:GetQuotationResponse>

<m:Quotation>Here is the

quotation</m:Quotation>

</m:GetQuotationResponse>

</SOAP-ENV:Body>

</SOAP-ENV:Envelope>