Escolar Documentos
Profissional Documentos
Cultura Documentos
1
DETAILED LESSON PLAN
TEXT BOOKS
1. Deitel and Deitel and Nieto, Internet and World Wide Web - How to Program,
Prentice Hall, 5th Edition, 2011.
2. Herbert Schildt, Java-The Complete Reference, Eighth Edition, Mc Graw Hill
Professional, 2011.
REFERENCES
1. Stephen Wynkoop and John Burke Running a Perfect Website, QUE, 2nd
Edition,1999.
2. Chris Bates, Web Programming Building Intranet Applications, 3rd Edition, Wiley
Publications, 2009.
3. Jeffrey C and Jackson, Web Technologies A Computer Science Perspective, Pearson
Education, 2011.
4. Gopalan N.P. and Akilandeswari J., Web Technology, Prentice Hall of India, 2011.
5. Paul Dietel and Harvey Deitel, Java How to Program, , 8th Edition Prentice Hall of
India.
6. Mahesh P. Matha, Core Java A Comprehensive Study, Prentice Hall of India, 2011.
7. Uttam K.Roy, Web Technologies, Oxford University Press, 2011.
Hours Cumulative
Sl. Book No
Topics Required Hrs
No. ( Page No)
/ Planned
UNIT I JAVA PROGRAMMING
1 T2(73-95,96-
1 An Overview of java, Data Types 1
107)
2 T2(107-
2 Variables and Arrays , Operators 1
125,126-147)
3 T2(148-
3 Control Statements , Classes 1
180,181-206)
Objects , 4 T2(185-189,
4 1
Methods 189-206)
5 Java T(1) 5 NPTEL
6 T2(244-
6 Inheritance, Packages 1
271,272-282)
7 T2(265-
Abstract classes, Interfaces and
7 1 269,282-
Inner classes
294,229-233)
8 Inheritance T(1) 8 PPT
Exception handling , Introduction 9
T2(295-
9 1
to Threads 316,318-330)
10 T2(330-
10 Multithreading , String handling 1
357,491-520)
11 T2(724-
11 Streams and I/O, Applets 1
767,415-418)
12 Applets T(1) 12 T2(832-854)
UNIT II WEBSITES BASICS, HTML 5, CSS 3, WEB 2.0
2
Hours Cumulative
Sl. Book No
Topics Required Hrs
No. ( Page No)
/ Planned
RIA Rich Internet Applications - 14 T1(80-
14 1
Collaborations tools - 82)WEB
Understanding websites and
15 web servers: Understanding 1 15 R3(1-44)
Internet
Difference between websites and
16 web server- Internet technologies 1 16 WEB
Overview
17 Internet technologies Overview 1 17 R3(1-44)
Understanding the difference
WEB,R3(56-
18 between internet and intranet; 1 18
107)
HTML and CSS
19 HTML 5.0, XHTML 1 19 WEB,
T1(118-
20 XHTML, CSS 3. 1 20
151,159-190)
21 HTML 5.0 T(1) 21 NPTEL
22 XHTML T(1) 22 WEB
23 CSS T(1) 23 PPT
3
Hours Cumulative
Sl. Book No
Topics Required Hrs
No. ( Page No)
/ Planned
Exceptions JSP: Understanding
R3(433-
35 Java Server Pages-JSP Standard 1 35
457,463-466)
Tag Library(JSTL)
Creating HTML forms by
36 1 36 WEB
embedding JSP code
T1(1123-
37 JSP T(1) 37
1166)
UNIT IV PHP and XML
An introduction to PHP: PHP- T1(906-
38 1 38
Using PHP 907),WEB
39 Using PHP- Variables 1 39 T1(907-917)
Program control- Built-in
40 1 40 PPT
functions
41 PHP T(1) 41 WEB
Connecting to Database Using T1(929-
42 1 42
Cookies 933,933-939)
43 Connecting to Database T(1) 43 NPTEL
Regular Expressions; XML: Basic WEB,
44 1 44
XML T1(516-519)
- Document Type Definition, T1(529-
45 XML Schema DOM and 1 45 533,533-
Presenting XML 540,553-570)
46 XML T(1) 46 R3(364-370)
47 XML Parsers and Validation 1 47 R3(383-396)
T1(544-
XSL and XSLT Transformation,
48 1 48 553,570-
News Feed (RSS and ATOM).
578),WEB
UNIT V INTRODUCTION TO AJAX and WEB SERVICES
AJAX: Ajax Client Server
49 1 49 T1(588-627)
Architecture
50 AJAX T(1) 50 NPTEL
51 XML Http Request Object 1 51 R3(390-395)
52 XML Http Request Object T(1) 52 PPT
53 Call Back Methods 1 53 WEB
T1(1226-
54 Web Services: Introduction 1 54
1228)
55 Java web services Basics 1 55 T1(1228)
Creating, Publishing, Testing and
T1(1228-
56 Describing a Webservices 1 56
1239)
(WSDL)
T1(1239-
57 Consuming a web service, 1 57
1248)
Database Driven web service from T1(1265-
58 1 58
an application 1273)
4
Hours Cumulative
Sl. Book No
Topics Required Hrs
No. ( Page No)
/ Planned
59 Web Services T(1) 59 R3(486-502)
T1(1248-
60 SOAP. 1 60
1249,
5
Unit I
JAVA PROGRAMMING
PART A (2 marks)
1. Define an abstract class. Give example. [Nov/Dec 2015]
A class that is declared with abstract keyword, is known as abstract class in java. It
can have abstract and non-abstract methods (method with body).
Example
abstract class Bike
{
abstract void run();
}
class Honda4 extends Bike
{
void run(){System.out.println("running safely..");
}
public static void main(String args[])
{
Bike obj = new Honda4();
obj.run();
}
2. Expand DOM, AJAX, AWT, JDBC. [Nov/Dec 2015]
DOM Document Object Model
AJAX - Asynchronous JavaScript and XML
AWT - Abstract Window Toolkit
JDBC - Java Database Connectivity
3. Differentiate Method overriding and Overloading?
When a method in a subclass has the same name & type signature as a method in the
subclass is said to override the method in the super class. When an overridden method is
called from within a subclass it will always refer to the version of that method defined by
the subclass.
class A{
.
void show(){
System.out.println(Super class)
}
class B extends A{
.
Void show(){
System.out.println(sub class)
}
class override{
B sub = new B( );
Sub. show( );
}
Method Overloading is the nothing but function overloading. It is the process of
having same name to more than one function but differing in the number of arguments or
the type of arguments.
4. Give two examples for Java Modifiers.
Access Control Modifiers
o private
6
o public
o protected
o default
Non Access Modifiers
o static
o final
o abstract
o synchronized and volatile
5. How do we allocate an array dynamically in Java?
An array can be created dynamically with an initializer.
For example
int numbers[] = {1, 2, 4, 8, 16, 32, 64, 128};
This syntax dynamically creates an array and initializes its elements to the specified
values.
6. What are the advantages of Packages?
Java package is used to categorize the classes and interfaces so that they can be
easily maintained.
Java package provides access protection.
Java package removes naming collision.
7. Define interface.
An interface is nothing but a class which has some distinct features. An interface is
denoted by the keyword interface. Interface can contain final (constant) variables and
Function declaration. The class which implements the interface must define the function.
8. Define Exception. List out its types.
A java exception is an object that describes an exceptional condition that has occurred in
a piece of code. The types are
User Defined
Pre Defined Exception
Java includes the import statements to bring certain classes ,or entire packages in to
visibility. import statements occur immediately following the package statements &
before any class definitions.
Syntax: import pkg1[.pkg2].( class name| *);
Pkg1 _name of the Top level package.
pkg2 _name of the subordinate package inside the outer package separated by a dot.
7
11. States of Thread?
Newborn state
Runnable state
Running state
Blocked state
Dead state
12. What is Java API package?
An Application Programming Interface (API), in the context of Java, is a collection of
prewritten packages, classes, and interfaces with their respective methods
Eg
java.io
java.net
13. Define Multithreaded Programming?
A Multithreaded program contains two or more parts that can run concurrently. Each part
of such a program is called a thread and each thread defines a separate path of execution.
Thus Multi threading is a specialized form of multitasking.
It can be implemented
By implementing the runnable interface.
Class Newthread implements Runnable
By Extending the Thread class
Class Newthread extends Thread
14. Explain about Strings in Java?
Strings can be created using
String class
String s= new String(Hello);
StringBuffer class
StringBuffer s= new StringBuffer(Hello);
String arrays
String methods
8
Waiting state - Another thread is executing
Timed Waiting state - Waiting for some time
Blocked state - I/O Request
Terminated State - Finished
Thread Class
The main class must extend the thread class. A thread is created in the constructor.
It must me initialized in the constructor using super() call. Then override the run()
method
Eg
class ThreadDemo extends Thread
{
String str="";
ThreadDemo(String s)
{
super(s);
str=s;
start();
}
public void run()
{
System.out.println(str);
}
}
class Main
{
public static void main(String []args)
{
ThreadDemo t=new ThreadDemo("ONE");
}
}
Runnable Interface
The main class must implement the runnable interface and overide the run()
method.
Eg
class ThreadDemo implements Runnable
9
{
Thread t;
String str="";
ThreadDemo(String s)
{
t=new Thread(this);
str=s;
t.start();
}
public void run()
{
System.out.println(str);
}
}
class Main
{
public static void main(String []args)
{
ThreadDemo t=new ThreadDemo("ONE");
}
}
Multiple Threads
Thread Class
The main class must extend the thread class. A thread is created in the constructor.
It must me initialized in the constructor using super() call. Then override the run()
method
Example
class ThreadDemo extends Thread
{
String str="";
ThreadDemo(String s)
{
super(s);
str=s;
start();
}
public void run()
{
for(int i=0;i<3;i++)
System.out.println(str);
}
}
class Main
{
public static void main(String []args)
{
ThreadDemo t=new ThreadDemo("ONE");
ThreadDemo t=new ThreadDemo("TWO");
ThreadDemo t=new ThreadDemo("THREE");
}
10
}
Output: (Order can change)
ONE
ONE
TWO
TWO
TWO
THREE
THREE
THREE
ONE
(ii) Exception handling in java [Nov/Dec 2015]
Exceptions are runtime anomalies or unusual conditions that a program may
encounter while executing. It is caused due to run time error in the program
Example Divide by zero
Array Index out of Bounds
Steps involved in Exception Handling
1. Find the problem (Hit the Exception)
2. Inform that an error occurred (Throw the Exception)
3. Receive the error information (Catch the Exception)
4. Take corrective action (Handle the Exception)
Try
The syntax is
try
{
......
throw exception;
}
catch(type arg)
{
.....
.....
}
The catch block must be present immediately after the try block.
Try is used to group the statements which may generate Exception.
If no exception is generated the catch block won't get executed.
11
When an exception occurs it is thrown from try block.
The thrown exception is caught by the catch block and handles it.
class Exception
{
public static void main(String []args)
12
{
int a;
Scanner obj=new Scanner(System.in);
a=obj.nextInt();
try
{
if(a==0)
throw a;
else if(a==1)
throw 1.0;
else
throw 'a';
}
catch(int a)
{
System.out.println("Integer catch");
}
catch(float a)
{
System.out.println("Floating catch");
}
catch(char a)
{
System.out.println("Character catch");
}
}
}
Finally
Finally block gets executed after try block. It is assured of execution of some important
code that must be executed after the try block.
The syntax is
finally
{
//statements
}
class sample
{
public static void main(String []s)
{
int a=10,b=0,c;
try
{
c=a/b;
}
catch(ArithmeticException e)
{
System.out.println("Divide by 0");
}
finally
13
{
System.out.println("Exiting..");
}
}
}
User Defined Exception
We can throw our own exception using the keyword throw
throw new classname
Eg
import java.lang.Exception
class MyOwnException extends Exception
{
MyOwnException(String s)
{
super(s);
}
}
class Demo
{
public static void main(String []args)
{
try
{
throw new MyOwnException("Exception");
}
catch(MyOwnException e)
{
System.out.println(e.getMessage());
}
}
}
Output
Exception
2. (i) Write a java program to draw smiley using applet. [Nov/Dec 2015]
import java.awt.*;
import java.applet.*;
public class Smiley extends Applet
{
public void paint(Graphics g)
{
Font f = new Font("Helvetica", Font.BOLD,20);
g.setFont(f);
g.drawString("Keep Smiling!!!", 50, 30);
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);
}
}
14
(ii) Compare Overloading and Overriding in Java [Nov/Dec 2015]
Overloading example
//A class for adding upto 5 numbers
class Sum
{
int add(int n1, int n2)
{
return n1+n2;
}
int add(int n1, int n2, int n3)
{
return n1+n2+n3;
}
int add(int n1, int n2, int n3, int n4)
{
return n1+n2+n3+n4;
}
int add(int n1, int n2, int n3, int n4, int n5)
{
return n1+n2+n3+n4+n5;
}
public static void main(String args[])
{
Sum obj = new Sum();
System.out.println("Sum of two numbers: "+obj.add(20, 21));
System.out.println("Sum of three numbers: "+obj.add(20, 21, 22));
System.out.println("Sum of four numbers: "+obj.add(20, 21, 22, 23));
System.out.println("Sum of five numbers: "+obj.add(20, 21, 22, 23, 24));
15
}
}
Output
Sum of two numbers: 41
Sum of three numbers: 63
Sum of four numbers: 86
Sum of five numbers: 110
Overriding example
package beginnersbook.com;
class CarClass
{
public int speedLimit()
{
return 100;
}
}
class Ford extends CarClass
{
public int speedLimit()
{
return 150;
}
public static void main(String args[])
{
CarClass obj = new Ford();
int num= obj.speedLimit();
System.out.println("Speed Limit is: "+num);
}
}
Output
Speed Limit is: 150
3 (i) Write short notes about data types in java.
(or)
How do you represent the data in java? Explain with example
There are two data types available in Java:
Primitive Data Types
Reference/Object Data Types
Primitive Data Types
There are eight primitive data types supported by Java. Primitive data types are
predefined by the language and named by a keyword. Let us now look into detail about
the eight primitive data types.
Byte
Byte data type is an 8-bit signed two's complement integer.
Minimum value is -128 (-2^7)
Maximum value is 127 (inclusive)(2^7 -1)
Default value is 0
Byte data type is used to save space in large arrays, mainly in place of integers,
since a byte is four times smaller than an int.
Example: byte a = 100 , byte b = -50
short
Short data type is a 16-bit signed two's complement integer.
Minimum value is -32,768 (-2^15)
16
Maximum value is 32,767 (inclusive) (2^15 -1)
Short data type can also be used to save memory as byte data type. A short is 2
times smaller than an int
Default value is 0.
Example: short s = 10000, short r = -20000
int
Int data type is a 32-bit signed two's complement integer.
Minimum value is - 2,147,483,648.(-2^31)
Maximum value is 2,147,483,647(inclusive).(2^31 -1)
Int is generally used as the default data type for integral values unless there is a
concern about memory.
The default value is 0.
Example: int a = 100000, int b = -200000
long
Long data type is a 64-bit signed two's complement integer.
Minimum value is -9,223,372,036,854,775,808.(-2^63)
Maximum value is 9,223,372,036,854,775,807 (inclusive). (2^63 -1)
This type is used when a wider range than int is needed.
Default value is 0L.
Example: long a = 100000L, long b = -200000L
float
Float data type is a single-precision 32-bit IEEE 754 floating point.
Float is mainly used to save memory in large arrays of floating point numbers.
Default value is 0.0f.
Float data type is never used for precise values such as currency.
Example: float f1 = 234.5f
double
double data type is a double-precision 64-bit IEEE 754 floating point.
This data type is generally used as the default data type for decimal values,
generally the default choice.
Double data type should never be used for precise values such as currency.
Default value is 0.0d.
Example: double d1 = 123.4
boolean
boolean data type represents one bit of information.
There are only two possible values: true and false.
This data type is used for simple flags that track true/false conditions.
Default value is false.
Example: boolean one = true
char
char data type is a single 16-bit Unicode character.
Minimum value is '\u0000' (or 0).
Maximum value is '\uffff' (or 65,535 inclusive).
Char data type is used to store any character.
Example: char letterA ='A'
Reference Data Types
Reference variables are created using defined constructors of the classes. They are
used to access objects. These variables are declared to be of a specific type that
cannot be changed. For example, Employee, Puppy etc.
Class objects, and various type of array variables come under reference data type.
17
Default value of any reference variable is null.
A reference variable can be used to refer to any object of the declared type or any
compatible type.
Example: Animal animal = new Animal("giraffe");
Syntax
dataType[] arrayRefVar;
Example
double[] myList;
Creating Arrays
We can create an array by using the new operator with the following syntax:
18
// Summing all elements
double total =0;
for(int i =0; i < myList.length; i++)
{
total += myList[i];
}
System.out.println("Total is "+ total);
// Finding the largest element
double max = myList[0];
for(int i =1; i < myList.length; i++)
{
if(myList[i]> max) max = myList[i];
}
System.out.println("Max is "+ max);
}
}
Output
1.9
2.9
3.4
3.5
Total is11.7
Max is3.5
3(iii) Explain in detail about the inheritance mechanism in java with an example
programs.
(or)
Describe in detail about the method of deriving the properties of one class from
another class
(or)
Explain about the base and derived class mechanism used in java with suitable
programs.
(or)
Describe in detail about the types of inheritance in java.
It is a process by which the object of one class acquires the properties of objects of
another class. The new class is called as derived class whereas the already existing one is
called as base class.
The various types of inheritance are
Single Inheritance
Multilevel Inheritance
The syntax is
class derivedclassname extends baseclassname
{
//STS;
}
Single Inheritance
It is an inheritance where a derived class has only one base class.
A BASE CLASS
19
Example B DERIVED CLASS
class A
{
public:
int a;
void seta(int i)
{
a=i;
}
void puta()
{
System.out.println(a);
}
}
class B extends A
{
public:
int b;
void setb(int i)
{
b=i;
}
void putb()
{
System.out.println(b);
}
}
class Demo
{
public static void main(String []s)
{
B obj=new B();
obj.seta(10);
obj.setb(15);
obj.puta();
obj.putb();
}
}
Here the variable 'a' and puta() in class A are inherited to class B with public visibility
mode.
Multilevel Inheritance
Here the derived class is derived from intermediate base class which is already
derived from a base class.
A
Example
class A
C
20
{
public:
int a;
void seta(int i)
{
a=i;
}
void puta()
{
System.out.println(a);
}
}
class B extends A
{
public:
int b;
void setb(int i)
{
b=i;
}
void putb()
{
System.out.println(b);
}
}
class C extends B
{
public:
int c;
void setc(int i)
{
c=i;
}
void putc()
{
System.out.println(c);
}
}
class demo
{
public static void main(String []s)
{
C obj=new C();
obj.seta(10);
obj.setb(15);
obj.setc(20);
obj.puta();
obj.putb();
obj.putc();
}
21
}
Here the variables 'a' from class A is inherited to class B. Then variable 'a' and 'b' from
class B are inherited to class C with public visibility mode.
4(i) Explain the various types of operators in Java and explain with suitable
examples.
(or)
What are all the various types of operators used in Java?
OPERATORS AND EXPRESSIONS
An expression is a sequence of operators and operands that specifies computation of a
value, or that designates an object or a function, or that generates side effects, or that
performs a combination.
ARITHMETIC OPERATORS:
import java.io.*;
class sample
{
public static void main(String []args)
{
int sum = 50;
float rem;
rem = sum % 10;
System.out.println("The Remainder is: "+rem);
}
}
PRE means do the operation first followed by any assignment operation. POST means do
the operation after any assignment operation. Consider the following statements
Example
import java.io.*;
class sample
{
public static void main(String []args)
{
22
int count = 0, loop;
loop = ++count; /* same as count = count + 1; loop = count; */
System.out.println("Loop:"+loop+"\nCount:"+count);
loop = count++; /* same as loop = count; count = count + 1; */
System.out.println("Loop:"+loop+"\nCount:"+count);
}
}
If the operator is on the left hand side of the variable, the operation is performed first, so
the statements loop = ++count; really means increment count first, then assign the new
value of count to loop.
Example
import java.io.*;
class sample
{
public static void main(String []args)
{
int count;
for( count = 1; count <= 10; count = count + 1 )
System.out.println(count);
}
}
These allow the testing of more than one condition as part of selection statements. The
symbols are
LOGICAL OR ||
LOGICAL NOT !
logical not negates (changes from TRUE to FALSE, vice versa) a condition.
LOGICAL EOR ^
Logical eor will be executed if either condition is TRUE, but NOT if they are all true.
23
Example
The following program uses an if statement with logical AND to validate the users input
to be in the range 1-10.
import java.io.*;
class sample
{
public static void main(String []args)
{
int number, valid = 0;
Scanner cin=new Scanner(System.in);
while( valid == 0 )
{
System.out.println("Enter a number between 1 and 10 -->");
number=cin.nextInt();
if( (number < 1 ) || (number > 10) )
{
System.out.println("Number is outside range 1-10. Please re-enter\n");
valid = 0;
}
else
valid = 1;
}
System.out.println("The number is "+number );
}
}
Example: NEGATION
class sample
{
public static void main(String []args)
{
int flag = 0;
if( ! flag )
{
System.out.println("The flag is not set.\n");
flag = ! flag;
}
System.out.println("The value of flag is "+ flag);
}
}
THE CONDITIONAL EXPRESSION OPERATOR or TERNARY OPERATOR
The two symbols used to denote this operator are the ? and the :.
The first operand is placed before the ?, the second operand between the ? and the :
, and the third after the : . The general format is,
24
If the result of condition is TRUE ( non-zero ), expression1 is evaluated and the
result of the evaluation becomes the result of the operation.
If the condition is FALSE (zero), then expression2 is evaluated and its result
becomes the result of the operation. An example will help,
s = ( x < 0 ) ? -1 : x * x;
BIT OPERATIONS
C has the advantage of direct bit manipulation and the operations available are,
25
4. private
A private member variable or function cannot be accessed, or even viewed from outside
the class. Only the class and friend functions can access private members.
A public member is accessible from anywhere outside the class but within a program.
You can set and get the value of public variables without any member function.
A protected member variable or function is very similar to a private member but it
provided one additional benefit that they can be accessed in child classes which are called
derived classes.
4(iii) Explain about Packages in detail.
Or
Illustrate the concept of user defined package with the syntax and example.
Packages
It is a mechanism in which a group of classes and interfaces can be grouped
together. The main advantage of packages are
The classes in one package can be reused by a different program
Two classes of two different packages can have the same name
It provides separation of design and coding. It also provides possibility of hiding
classes
import java.io.
Importing all the classes in a package
import java.util.*;
Creating User Defined Packages
Create a folder with the name as package name. For eg if the package name is
my_package then create a folder named my_package. Write the coding of the classes and
interface and save it in it.
Syntax
Package packagename;
{
/*Classes
Sub packages
Block of statements*/
}
26
Example
package mypackage;
public class A
{
int a;
void seta(int i)
{
a=i;
}
void showa()
{
System.out.println("A="+a);
}
}
class Main
{
public static void main(String []args)
{
A obj=new A();
obj.seta(10);
obj.showa();
}
}
Save the above coding as Main.java in the mypackage folder.
To run
Move into the package folder - cd mypackage;
Compile the java file - javac Main.java
Move one folder back - cd ..
Run the java file - java mypackage.Main
Another way of using a package is using import statement. Create a package named
mypackage and save the file in it. Create the Main class in bin and use the import
statement to use it.
Example
package mypackage;
public class A
{
int a;
void seta(int i)
{
a=i;
}
void showa()
{
System.out.println("A="+a);
}
}
27
Save the above file as A.java in the mypackage folder. To use this in another program
then.
import mypackage.A;
class Main
{
public static void main(String []args)
{
A obj=new A();
obj.seta(10);
obj.showa();
}
}
Example
interface A
{
static final int val=10;
}
interface B extends A
{
void display();
28
}
The contents of interface A will be transferred to interface B.
Implementing an Interface
Class can implement an interface using the keyword implements. Once it has
implemented then the class must define the function declared in the interface.
class classname implements interface1,interface2,...
{
...
...
}
For Example
public interface myinterface
{
void disp(int i);
}
class A implements myinterface
{
public void disp(int i)
{
System.out.println("Value is:"+i);
}
}
class Main
{
public static void main(String []args)
{
A obj=new A();
(or)
myinterface obj= new A();
obj.disp(10);
}
}
Multiple Inheritance using Interface
It is a kind of inheritance in which more than one super class exists for a subclass.
A B
C
In java it is made possible using interface.
Example
class A
{
int v;
void setv(int i)
{
v=i;
}
29
}
interface B
{
public void showv();
}
class C extends A implements B
{
public void showv()
{
System.out.println("V="+v);
}
}
30
s1.equals(s2);
Sub String
We can derive a substring from a given string using substring method.
Syntax
s.substring(start_pos,end_pos);
Example String s="Algorithm";
s.substring(2,3);
will produce "go"
Replace
We can replace a character in a string but some character.
Syntax
s.replace(old_char,new_char)
Example String s="Hai";
s.replace('a','i');
will produce "Hii"
Upper Case & Lower Case
It converts the character of the string to uppercase and lower case respectively.
s.toLowerCase(); - Small Letters
s.toUpperCase(); - Capital Letters
String Buffer
It is more flexible than the String class. It has some additional methods like
append(str) - Joins the string
capacity - Return the capacity of the buffer
insert(pos,ch) - Insert the character 'ch' at position pos
delete(start,end) - Deletes the character from start to end
31
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.
It is called after the param tags inside the applet tag have been processed.
start: This method is automatically called after the browser calls the init method.
It is also called whenever the user returns to the page containing the applet after
having gone off to other pages.
stop: This method is automatically called when the user moves off the page on
which the applet sits. It can, therefore, be called repeatedly in the same applet.
destroy: This method is only called when the browser shuts down normally.
Because applets are meant to live on an HTML page, you should not normally
leave resources behind after a user leaves the page that contains the applet.
paint: Invoked immediately after the start() method, and also any time the applet
needs to repaint itself in the browser. The paint() method is actually inherited
from the java.awt.
32
Fetch an image
Fetch an audio clip
Play an audio clip
Resize the applet
Additionally, the Applet class provides an interface by which the viewer or browser
obtains information about the applet and controls the applet's execution. The viewer
may:
request information about the author, version and copyright of the applet
request a description of the parameters the applet recognizes
initialize the applet
destroy the applet
start the applet's execution
stop the applet's execution
The Applet class provides default implementations of each of these methods. Those
implementations may be overridden as necessary.
The "Hello, World" applet is complete as it stands. The only method overridden is the
paint method.
Invoking an Applet
An applet may be invoked by embedding directives in an HTML file and viewing the
file through an applet viewer or Java-enabled browser.
The <applet> tag is the basis for embedding an applet in an HTML file. Below is an
example that invokes the "Hello, World" applet:
<html>
<title>The Hello, World Applet</title>
<hr>
<applet code="HelloWorldApplet.class" width="320" height="120">
If your browser was Java-enabled, a "Hello, World"
message would appear here.
</applet>
<hr>
</html>
The code attribute of the <applet> tag is required.
It specifies the Applet class to run.
Width and height are also required to specify the initial size of the panel in which an
applet runs.
The applet directive must be closed with a </applet> tag.
If an applet takes parameters, values may be passed for the parameters by adding
<param> tags between <applet> and </applet>.
The browser ignores text and other tags between the applet tags.
Non-Java-enabled browsers do not process <applet> and </applet>.
Therefore, anything that appears between the tags, not related to the applet, is visible in
non-Java-enabled browsers.
Getting Applet Parameters
The following applet displays a checkerboard pattern of black and a second
color.
The second color and the size of each square may be specified as parameters to
the applet within the document.
CheckerApplet gets its parameters in the init() method.
It may also get its parameters in the paint() method.
The applet viewer or browser calls the init() method of each applet it runs.
33
The viewer calls init() once, immediately after loading the applet. (Applet.init() is
implemented to do nothing.)
Override the default implementation to insert custom initialization code.
The Applet.getParameter() method fetches a parameter given the parameter's
name (the value of a parameter is always a string).
If the value is numeric or other non-character data, the string must be parsed.
The following is a skeleton of CheckerApplet.java:
import java.applet.*;
import java.awt.*;
public class CheckerApplet extends Applet
{
int squareSize = 50;// initialized to default size
public void init () {}
private void parseSquareSize (String param) {}
private Color parseColor (String param) {}
public void paint (Graphics g) {}
}
Here are CheckerApplet's init() and private parseSquareSize() methods:
public void init ()
{
String squareSizeParam = getParameter ("squareSize");
parseSquareSize (squareSizeParam);
String colorParam = getParameter ("color");
Color fg = parseColor (colorParam);
setBackground (Color.black);
setForeground (fg);
}
private void parseSquareSize (String param)
{
if (param == null) return;
try {
squareSize = Integer.parseInt (param);
}
catch (Exception e) {
// Let default value remain
}
}
The applet calls parseSquareSize() to parse the squareSize parameter.
parseSquareSize() calls the library method Integer.parseInt(), which parses a
string and returns an integer.
Integer.parseInt() throws an exception whenever its argument is invalid.
Therefore, parseSquareSize() catches exceptions, rather than allowing the applet
to fail on bad input.
The applet calls parseColor() to parse the color parameter into a Color value.
parseColor() does a series of string comparisons to match the parameter value to
the name of a predefined color.
Specifying Applet Parameters
The following is an example of an HTML file with a CheckerApplet embedded in it.
The HTML file specifies both parameters to the applet by means of the <param> tag.
<html>
<title>Checkerboard Applet</title>
<hr>
<applet code="CheckerApplet.class" width="480" height="320">
<param name="color" value="blue">
<param name="squaresize" value="30">
</applet>
<hr>
34
</html>
Application Conversion to Applets
It is easy to convert a graphical Java application (that is, an application that uses the
AWT and that you can start with the java program launcher) into an applet that you can
embed in a web page.
Here are the specific steps for converting an application to an applet.
Make an HTML page with the appropriate tag to load the applet code.
Supply a subclass of the JApplet class. Make this class public. Otherwise, the
applet cannot be loaded.
Eliminate the main method in the application. Do not construct a frame window
for the application. Your application will be displayed inside the browser.
Move any initialization code from the frame window constructor to the init
method of the applet. You don't need to explicitly construct the applet object.the
browser instantiates it for you and calls the init method.
Remove the call to setSize; for applets, sizing is done with the width and height
parameters in the HTML file.
Remove the call to setDefaultCloseOperation. An applet cannot be closed; it
terminates when the browser exits.
If the application calls setTitle, eliminate the call to the method. Applets cannot
have title bars. (You can, of course, title the web page itself, using the HTML title
tag.)
Don't call setVisible(true). The applet is displayed automatically.
Event Handling
Applets inherit a group of event-handling methods from the Container class. The
Container class defines several methods, such as process KeyEvent and process
MouseEvent, for handling particular types of events, and then one catch-all method
called process Event.
In order to react an event, an applet must override the appropriate event-specific method.
import java.awt.event.MouseListener;
import java.awt.event.MouseEvent;
import java.applet.Applet;
import java.awt.Graphics;
StringBuffer strBuffer;
35
void addItem(String word) {
System.out.println(word);
strBuffer.append(word);
repaint();
}
36
UNIT II
WEBSITES BASICS, HTML 5, CSS 3, WEB 2.0
Part-A (2marks)
1. What is XHTML?
XHTML stands for "Extensible HyperText Markup Language".
It was developed by the World Wide Web Consortium (W3C) and is now a W3C
Recommendation.
XHTML is a reformulation of HTML 4 in XML 1.0.
This means that the benefits provided by XML will be available to XHTML.
2. How is XHTML different from HTML?
XHTML is case-sensitive, HTML is not. All tags and attributes must be lowercase in
XHTML.
XHTML, being XML, must be well-formed. Every element must have an end tag, or
use the self-closing tag syntax. HTML allows some end tags and even some start tags to
be omitted.
If an XML parser encounters a well-formedness error, it must abort. An SGML or
HTML parser is expected to try to salvage what it can and keep going.
All attributes must have a value in XHTML. HTML allows some attributes (e.g.,
selected) to be minimised.
All attribute values must be surrounded by double or single quotes. HTML allows
quotes to be omitted if the value contains only alphanumeric characters (and some
others).
The comment syntax is more limited in XHTML, but that's rarely an issue for most
designers/developers.
3. What is the need for DOCTYPE declaration?
The DOCTYPE declaration serves two purposes: it tells a validator against which
DTD the document claims conformance, and it is used by browsers to determine
the rendering mode to use.
Browsers that support XHTML use the 'strict standards' rendering mode for
XHTML documents, provided that they are served as such.
4.Why we use XHTML?
We use XHTML because of some important reasons those are given below:
XHTML can run on all new browsers.
It is a combination of HTML and XML so, it support many important features of them.
XHTML also gives us facility to write well formed document.
XHTML has facility to extend. We perform this task with use of extra modules to do
things without pages where as this facility not provided by HTML.
5.What are the rules essential for XHTML Syntax?
Rule1: Write attribute names only in lower case letters.
Rule2: Assigned attribute values must be quoted.
Rule3: Attribute minimization must be prohibited.
Rule4: In XHTML name attribute is replaced by id attribute.
Rule5: In XHTML DTD must set mandatory elements.
6.How you define DTD in XHTML?
DTD: Its stand for Document Type Declaration. It specifies the syntax of web page in
SGML. We use DTD on SGML applications like: HTML, XML etc.
In XHTML we can say that DTD is an computer readable language which is used to
allow syntax of XHTML.
In XHTML we use These three DTD's,
1.STRICT
37
2.TRANSITIONAL
3.FRAMESET
7. What are Cascading Style Sheets (CSS)?
CSS allows document authors to specify the presentation of elements on a web page
(fonts, spacing, margins etc.) separately from the structure of the document (section
header, body, links etc.). It is used to give same look and feel to the displayed text and
background elements.
8. List down the ways of including style information in a document.
1. Linked Styles -Style information is read from a separate .css file that is specified in
the tag
2. Embedded Styles -Style information is defined in the document head using the tags.
3. Inline Styles -Style information is placed inside an HTML tag and applies to all
content between that tag and it companion closing tag.
9. What is the precedence in CSS to avoid conflicting styles?
The precedence order is author > user > user agent.
The styles defined by child element take more precedence than styles defined by parent
element.
10. What are Text Flow and Box Model in CSS?
Text Model allows to move an element to one side of the screen ant the other content in
the document flows around the floated element.
Box Model draws a virtual box around each element. The properties of the box can be
adjusted to control the amount of padding inside the element and the margins outside the
element.
11. Difference between Internet and Intranet.
Intranet Internet
Localized Network. Worldwide Network
Doesn't have access to Intranet Have access to Internet.
More Expensive Less Expensive
More Safe Less Safe
More Reliability Less Reliability
12. How does RIA different from traditional web applications?(May/Jun2016)
RIA (Rich Internet Applications) are a special breed of web applications where the user
interface has much richer functionality than what the first and second generation web
applications
13. What is dynamic positioning?
We can change an elements style dynamically. Most HTML elements have a style object
as a property. Suppose an elements CSS position property is declared to be either
absolute or relative. Then we can move it by manipulating any of the top, left, right, or
bottom CSS properties of its style object. This is dynamic positioning
14. State the difference between absolute and relative positioning.
Absolute positioning
An element which is positioned absolute does not obtain any space in the document.
This means that it does not leave an empty space after being positioned.
To position an element absolutely, the position property is set as absolute. You can
subsequently use the properties left, right, top, and bottom to place the box.
Relative positioning
To position an element relatively, the property position is set as relative. The difference
between absolute and relative positioning is how the position is being calculated.
38
The position for an element which is relatively positioned is calculated from the original
position in the document. That means that you move the element to the right, to the left,
up or down. This way, the element still obtains a space in the document after it is
positioned.
15. Define HTML.
It is a simple page description language, which enables document creation for the web.
PART B
1. Explain about Rich Internet Applications in detail (May / June 2016)
Rich Internet Applications
RIA (Rich Internet Applications) are a special breed of web applications
where the user interface has much richer functionality than what the first
and second generation web applications.
They look and feel more like desktop applications. RIA user interfaces are
typically developed using HTML5 + JavaScript + CSS3, Flex (Flash),
JavaFX, GWT, Dart or some other RIA tool.
The richer GUI client of RIA user interfaces also results in a somewhat
different internal architecture and design of the web applications.
RIA user interfaces and their back ends are typically more cleanly
separated than for first and second generation web applications. This makes
the RIA GUI more independent of the server side, and also makes it easier
for GUI and server developers to work in parallel.
First Generation Web Applications
First generation web applications were page oriented. We would include all
GUI logic and application logic inside the same web page.
The web page would be a script which was executed by the web server,
when requested by the browser.
GUI logic and application logic were mixed up inside the same page script.
Here is an illustration of this architecture and design:
Being page oriented every action the application allowed was typically embedded
in its own web page script.
Each script was like a separate transaction which executed the application logic,
and generated the GUI to be sent back to the browser after the application logic
was executed.
The GUI was pretty dumb. The browser showed a page.
When the user clicked something in the page, the browser was typically redirected
to a new page (script).
First generation web page technologies include Servlets (Java), JSP (JavaServer
Pages), ASP, PHP and CGI scripts in Perl etc.
GUI logic and application logic was interleaved, making it hard to locate either
one when we needed to make changes to either the GUI or application logic.
39
Code reuse was low, because the code was spread over a large amount of web
page scripts.
GUI state (like pressed down buttons) which had to be maintained across multiple
pages, had to be kept either in the session data on the server, or be sent along to
each page and back to the browser again.
If we wanted to change the programming language of the web page scripts (like
from PHP to Java Server Pages (JSP)), that would often require a complete rewrite
of the web application. It was a nightmare.
Second Generation Web Applications
In second generation web applications developers found ways to separate the GUI
logic from the application logic on the server.
Web applications also became more object oriented than they had been when the
code was spread over multiple pages.
Often, web page scripts were used for the GUI logic, and real classes and objects
were used for the application logic.
40
Additionally, due to the limits of second generation web application technologies,
the GUIs developed were often more primitive than what people were used to
from desktop applications.
RIA Web Applications
RIA (Rich Internet Applications) web applications are the third generation of web
applications.
RIA web applications were first and foremost known for having a user interface
that looked much closer to desktop applications.
To achieve these more advanced user interfaces, RIA technologies are typically
executed in the browser using either JavaScript, Flash, JavaFX or Silverlight.
As we can see, the GUI logic is now moved from the web server to the browser.
This complete split from the server logic has some positive and negative
consequences for the design and architecture of the application.
First of all, the GUIs can become much more advanced with RIA technologies.
That by itself is an advantage.
Second, because the GUI logic is executed in the browser, the CPU time needed to
generate the GUI is lifted off the server, freeing up more CPU cycles for executing
application logic.
Third, GUI state can be kept in the browser, thus further cleaning up the server
side of RIA web applications.
Fourth, the GUI logic completely separated from the application logic, it becomes
easier to develop reusable GUI components, which can be reused no matter what
server side programming language is used for the application logic.
Fifth, RIA technologies typically communicate with the web server by exchanging
data, not GUI code (HTML, CSS and JavaScript). The data exchange is typically
XML sent via HTTP, or JSON sent via HTTP. This changes the server side from
being "pages" to being "services" that perform some part of the application logic
(create user, login, store task etc.).
Sixth, the GUI and application logic on the server typically communicate via
HTTP + JSON, or HTTP + XML, the GUI is 100% independent of programming
language that is used on the server. The GUI logic's interface to the server is just
HTTP calls.
Seventh, GUI logic and application logic are completely separated, and the only
interface between them is HTTP + JSON / XML, the GUI and application logic
can also be developed independently of each other. The application logic
developer can implement the services and test them independently of the GUI.
Eighth, because the back end just consists of services that send and receive data, it
is much easier add a different type of client in the future, if needed. For instance,
we might want to add a native mobile iOS or Android application client, which
also interacts with your back end services.
Ninth, the back end now consist of simple services receiving and sending data, our
web application is naturally prepared for the "open application" trend, where web
41
applications can be accessed both via a GUI and via an API (in case your users
need to write a program to interact with your web application).
Tenth, the GUI and back end services only exchange data, the traffic load is often
smaller than if the back end had to send both the data and HTML, CSS and
JavaScript.
The complete split of GUI logic from application logic sometimes means that the
GUI logic is implemented using a different programming language than the
application logic.
GUI logic might be implemented in JavaScript, ActionScript (Flash) or Dart, and
the application logic in Java, C# or PHP.
Java developers can use Google Web Toolkit (GWT) to program JavaScript GUIs
using Java.
The new RIA technologies mean that the developer team must master more
technologies.
RIA Technologies
Here is a list of a few well-known RIA technologies:
HTML5 + CSS3 + JavaScript + JavaScript frameworks
o jQuery
o jQuery Mobile
o AngularJS
o Sencha EXT-JS
o SmartClient
o D3
o Dart
GWT (Google Web Toolkit)
JavaFX
Flex (Flash)
Silverlight
Silverlight
JavaFx
42
JavaFX (is) replacing Swing as the new client UI library for Java which is why it makes
sense as Java developers that we start taking JavaFx seriously and start embracing it as
the best way to build applications in Java.
Main features of JavaFx
New and improved interface tools that way beyond our standard buttons,
checkboxes, etc. (Think bar and pie charts and cool things you can find using
JQuery like date-pickers, accordion panes, tabbed panes etc.). This includes new
media player and web rendering controls.
A new language called FXML, which like HTML is used only to define the
interface of an application, keeping it completely separate from the code logic.
An outstanding application called Scene Builder which can be integrated into
NetBeans and Eclipse to allow you to create and generate FXML documents using
a drag-and-drop design interface .
A new powerful way to control the design of your application with CSS-like
syntax and precision.
An integrated library for graphics (both 2D and 3D) as well as animation tools that
rival Flash, JQuery and CSS animations
Mobile platform development tools. There is an open-source project
called JavaFx ports that helps bridge the path to mobile application development
with JavaFx
Flex
Flex is a highly productive, open source application framework for building and
maintaining expressive web applications that deploy consistently on all major browsers,
desktops, and devices. It provides a modern, standards-based language and programming
model that supports common design patterns suitable for developers from many
backgrounds.
Enterprise-class programming model
Use constructs like strong typing, inheritance, and interfaces to program more efficiently.
Extensive mobile and traditional components help speed development. Flex applications
can access device capabilities such as GPS, accelerometer, camera, and local database.
Cross-platform and native experience
Create applications that run consistently across Android, BlackBerry Tablet OS, and
iOS devices, as well as inside the browser and on traditional desktop computers.
Although cross platform, with Flex we get an uncompromised native experience on each
platform.
End-to-end tooling
Build Flex applications more easily using Adobe Flash Builder software, an
enterprise-class Eclipse based IDE. Productivity features include on-device debugging
and mobile simulators for testing across screen sizes and resolutions.
43
Another collaboration tool is a conference call, during which multiple people get
together over the phone to hash out an issue.
Collaboration tools allow people to work on a common project wherever they are.
44
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 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.
Advantages
Internet covers almost every aspect of life, one can think of.
o Facebook
o Twitter
o Yahoo
o Google+
o Flickr
o Orkut
One can surf for any kind of information over the internet. Information regarding
various topics such as Technology, Health & Science, Social Studies,
Geographical Information, Information Technology, Products etc can be surfed
with help of a search engine.
o Online Television
o Online Games
o Songs
o Videos
o Social Networking Apps
45
o Internet Banking
o Matrimonial Services
o Online Shopping
o Online Ticket Booking
o Online Bill Payment
o Data Sharing
o E-mail
Internet provides concept of electronic commerce, that allows the business deals
to be conducted on electronic systems
Disadvantages
Internet has proved to be a powerful source of information in almost every field, yet
there exists many disadvantages discussed below:
There are always chances to lose personal information such as name, address,
credit card number. Therefore, one should be very careful while sharing such
information.
Virus can easily be spread to the computers connected to internet. Such virus
attacks may cause your system to crash or your important data may get deleted.
There are various websites that do not provide the authenticated information. This
leads to misconception among many people.
Intranet
Intranet is defined as private network of computers within an organization with its own
server and firewall. Moreover we can define Intranet as:
46
Benefits
Intranet is very efficient and reliable network system for any organization. It is
beneficial in every aspect such as collaboration, cost-effectiveness, security, productivity
and much more.
Communication
Intranet offers easy and cheap communication within an organization. Employees can
communicate using chat, e-mail or blogs.
Time Saving
Information on Intranet is shared in real time.
Collaboration
Information is distributed among the employees as according to requirement and it can
be accessed by the authorized users, resulting in enhanced teamwork.
Platform Independency
Intranet can connect computers and other devices with different architecture.
Cost Effective
Employees can see the data and other documents using browser rather than printing
them and distributing duplicate copies among the employees, which certainly decreases
the cost.
Workforce Productivity
Data is available at every time and can be accessed using company workstation. This
helps the employees work faster.
Business Management
It is also possible to deploy applications that support business operations.
Security
47
Since information shared on intranet can only be accessed within an organization,
therefore there is almost no chance of being theft.
Specific Users
Intranet targets only specific users within an organization therefore, once can exactly
know whom he is interacting.
Immediate Updates
Any changes made to information are reflected immediately to all the users.
Issues
Apart from several benefits of Intranet, there also exist some issues.. These issues are
shown in the following diagram:
Applications
Intranet applications are same as that of Internet applications. Intranet applications are
also accessed through a web browser. The only difference is that, Intranet applications
reside on local server while Internet applications reside on remote server. Here, we've
discussed some of these applications:
48
Support for Internet Applications
Intranet offers an environment to deploy and test applications before placing them on
Internet.
Intranet Internet
Localized Network. Worldwide Network
Doesn't have access to Intranet Have access to Internet.
More Expensive Less Expensive
More Safe Less Safe
More Reliability Less Reliability
The new standard incorporates features like video playback and drag-and-drop that have
been previously dependent on third-party browser plug-ins such as Adobe Flash,
Microsoft Silverlight, and Google Gears.
New Features
HTML5 introduces a number of new elements and attributes that helps in building a
modern website. Following are great features introduced in HTML5.
New Semantic Elements These are like <header>, <footer>, and <section>.
Forms 2.0 Improvements to HTML web forms where new attributes have been
introduced for <input> tag.
Persistent Local Storage To achieve without resorting to third-party plugins.
WebSocket A a next-generation bidirectional communication technology for
web applications.
Server-Sent Events HTML5 introduces events which flow from web server to
the web browsers and they are called Server-Sent Events (SSE).
Canvas This supports a two-dimensional drawing surface that you can program
with JavaScript.
Audio & Video We can embed audio or video on our web pages without
resorting to third-party plugins.
Geolocation Now visitors can choose to share their physical location with your
web application.
Microdata This lets us create our own vocabularies beyond HTML5 and extend
your web pages with custom semantics.
Drag and drop Drag and drop the items from one location to another location
on a the same webpage.
But HTML5 is coming with lots of flexibility and would support the followings
Uppercase tag names.
Quotes are optional for attributes.
49
Attribute values are optional.
Closing empty elements are optional.
The DOCTYPE
DOCTYPEs in older versions of HTML were longer because the HTML language was
SGML based and therefore required a reference to a DTD.
Simple syntax to specify DOCTYPE as follows
<!DOCTYPE html>
Character Encoding
Simple syntax to specify Character Encoding as follows
<meta charset="UTF-8">
The <script> tag
It's common practice to add a type attribute with a value of "text/javascript" to script
elements as follows
<script type="text/javascript" src="scriptfile.js"></script>
HTML 5 removes extra information required and we can use simply following syntax
<script src="scriptfile.js"></script>
The <link> tag
So far we were writing <link> as follows
<link rel="stylesheet" type="text/css" href="stylefile.css">
HTML 5 removes extra information required and we can use simply following syntax
<link rel="stylesheet" href="stylefile.css">
HTML5 Elements
HTML5 elements are marked up using start tags and end tags. Tags are delimited using
angle brackets with the tag name in between.
The difference between start tags and end tags is that the latter includes a slash before
the tag name.
Following is the example of an HTML5 element
<p>...</p>
HTML5 tag names are case insensitive and may be written in all uppercase or mixed
case, although the most common convention is to stick with lower case.
Most of the elements contain some content like <p>...</p> contains a paragraph. For
example, br, hr, link and meta etc.
HTML5 Attributes
Elements may contain attributes that are used to set various properties of an
element.
Some attributes are defined globally and can be used on any element, while
others are defined for specific elements only.
All attributes have a name and a value and look like as shown below in the
example.
The example of attributes which illustrates how to mark up a div element with an
attribute named class using a value of "example"
<div class="example">...</div>
Attributes may only be specified within start tags and must never be used in end
tags.
HTML5 attributes are case insensitive and may be written in all upper case or
mixed case, although the most common convention is to stick with lower case.
HTML5 Document
The following tags have been introduced for better structure
50
section This tag represents a generic document or application section. It can be
used together with h1-h6 to indicate the document structure.
article This tag represents an independent piece of content of a document, such
as a blog entry or newspaper article.
aside This tag represents a piece of content that is only slightly related to the
rest of the page.
header This tag represents the header of a section.
footer This tag represents a footer for a section and can contain information
about the author, copyright information, etc.
nav This tag represents a section of the document intended for navigation.
dialog This tag can be used to mark up a conversation.
figure This tag can be used to associate a caption together with some embedded
content, such as a graphic or video.
The markup for an HTML 5 document would look like the following
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>...</title>
</head>
<body>
<header>...</header>
<nav>...</nav>
<article>
<section>
...
</section>
</article>
<aside>...</aside>
<figure>...</figure>
<footer>...</footer>
</body>
</html>
Example
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>...</title>
</head>
<body>
<header role="banner">
<h1>HTML5 Document Structure Example</h1>
<p>This page should be tried in safari, chrome or Mozila.</p>
</header>
<nav>
<ul>
<li><a href="#">HTML Tutorial</a></li>
<li><a href="#">CSS Tutorial</a></li>
<li><a href="#">JavaScript Tutorial</a></li>
51
</ul>
</nav>
<article>
<section>
<p>Once article can have multiple sections</p>
</section>
</article>
<aside>
<p>This is aside part of the web page</p>
</aside>
<figure align="right">
<img src="/html5/images/logo.png" alt="SCAD" width="200" height="100">
</figure>
<footer>
<p>Created by <a href="#">SCAD Group</a></p>
</footer>
</body>
</html>
This will produce following result
HTML Tutorial
CSS Tutorial
JavaScript Tutorial
Some attributes are defined globally and can be used on any element, while
others are defined for specific elements only. All attributes have a name and a
value and look like as shown below in the example.
Following is the example of an HTML5 attributes which illustrates how to mark up a div
element with an attribute named class using a value of "example"
<div class="example">...</div>
Attributes may only be specified within start tags and must never be used in end
tags.
HTML5 attributes are case insensitive and may be written in all uppercase or
mixed case, although the most common convention is to stick with lowercase.
Standard Attributes
The attributes listed below are supported by almost all the HTML 5 tags.
52
element.
contenteditable true, false Specifies if the user can edit the element's content
or not.
spellcheck true, false Specifies if the element must have it's spelling or
grammar checked.
valign top, middle, bottom Vertically aligns tags within an HTML element.
Type Description
datetime A date and time (year, month, day, hour, minute, second, fractions of a
second) encoded according to ISO 8601 with the time zone set to UTC.
53
datetime- A date and time (year, month, day, hour, minute, second, fractions of a
local second) encoded according to ISO 8601, with no time zone information.
month A date consisting of a year and a month encoded according to ISO 8601.
week A date consisting of a year and a week number encoded according to ISO
8601.
time A time (hour, minute, seconds, fractional seconds) encoded according to ISO
8601.
number This accepts only numerical value. The step attribute specifies the precision,
defaulting to 1.
range The range type is used for input fields that should contain a value from a
range of numbers.
email This accepts only email value. This type is used for input fields that should
contain an e-mail address. If you try to submit a simple text, it forces to enter
only email address in email@example.com format.
url This accepts only URL value. This type is used for input fields that should
contain a URL address. If you try to submit a simple text, it forces to enter
only URL address either in http://www.example.com format or in
http://example.com format.
Image Size - Width and Height
We can use the style attribute to specify the width and height of an image.
The values are specified in pixels (use px after the value):
Example
<img src="html5.gif" alt="HTML5 Icon" style="width:128px;height:128px;">
The <output> element
The element <output> which is used to represent the result of different types of output,
such as output written by a script.
We can use the for attribute to specify a relationship between the output element and
other elements in the document that affected the calculation (for example, as inputs or
parameters). The value of the for attribute is a space-separated list of IDs of other
elements.
<!DOCTYPE HTML>
<html>
<head>
<script type="text/javascript">
function showResult()
{
x = document.forms["myform"]["newinput"].value;
document.forms["myform"]["result"].value=x;
}
</script>
54
</head>
<body>
<form action="/cgi-bin/html5.cgi" method="get" name="myform">
Enter a value : <input type="text" name="newinput" />
<input type="button" value="Result" onclick="showResult();" />
<output name="result"></output>
</form>
</body>
</html>
55
<p>Try to submit using Submit button</p>
<input type="submit" value="submit" />
</form>
</body>
</html>
56
Example
<!DOCTYPE html>
<html>
<head>
<style>
body {background-color:lightgrey;}
h1 {color:blue;}
p {color:green;}
</style>
</head>
<body>
<h1>This is a heading</h1>
<p>This is a paragraph.</p>
</body>
</html>
External Styling (External CSS)
An external style sheet is used to define the style for many pages.
With an external style sheet, we can change the look of an entire web site by changing
one file!
To use an external style sheet, add a link to it in the <head> section of the HTML page:
Example
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<h1>This is a heading</h1>
<p>This is a paragraph.</p>
</body>
</html>
An external style sheet can be written in any text editor. The file should not contain any
html tags. The style sheet file must be saved with a .css extension.
Here is how the "styles.css" looks:
body {
background-color: lightgrey;
}
h1 {
color: blue;
}
p{
color:green;
}
CSS Fonts
The CSS color property defines the text color to be used for the HTML element.
The CSS font-family property defines the font to be used for the HTML element.
The CSS font-size property defines the text size to be used for the HTML element.
57
Example
<!DOCTYPE html>
<html>
<head>
<style>
h1 {
color: blue;
font-family: verdana;
font-size: 300%;
}
p {
color: red;
font-family: courier;
font-size: 160%;
}
</style>
</head>
<body>
<h1>This is a heading</h1>
<p>This is a paragraph.</p>
</body>
</html>
The CSS Box Model
Every HTML element has a box around it, even if you cannot see it.
The CSS border property defines a visible border around an HTML element:
Example
p{
border: 1px solid black;
}
The CSS padding property defines a padding (space) inside the border:
Example
p{
border: 1px solid black;
padding: 10px;
}
The CSS margin property defines a margin (space) outside the border:
Example
p{
border: 1px solid black;
padding: 10px;
margin: 30px;
}
The id Attribute
To define a special style for one special element, first add an id attribute to the element:
<p id="p01">I am different</p>
then define a style for the element with the specific id:
Example
#p01 {
color: blue;
}
58
The class Attribute
To define a style for a special type (class) of elements, add a class attribute to the
element:
<p class="error">I am different</p>
We can also define a different style for elements with the specific class:
Example
p.error {
color: red;
}
3. Explain about XHTML in detail.
What Is 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
Need of XHTML
Many pages on the internet contain "bad" HTML.
This HTML code works fine in most browsers (even if it does not follow the HTML
rules):
<html>
<head>
<title>This is bad HTML</title>
<body>
<h1>Bad HTML
<p>This is a paragraph
</body>
XML is a markup language where documents must be marked up correctly (be "well-
formed").
By combining the strengths of HTML and XML, XHTML was developed.
XHTML is HTML redesigned as XML.
The Most Important Differences from HTML
Document Structure
XHTML DOCTYPE is mandatory
The xmlns attribute in <html> is mandatory
<html>, <head>, <title>, and <body> are mandatory
XHTML Elements
XHTML elements must be properly nested
XHTML elements must always be closed
XHTML elements must be in lowercase
XHTML documents must have one root element
XHTML Attributes
Attribute names must be in lower case
Attribute values must be quoted
Attribute minimization is forbidden
<!DOCTYPE ....> Is Mandatory
An XHTML document must have an XHTML DOCTYPE declaration.
The <html>, <head>, <title>, and <body> elements must also be present, and the xmlns
attribute in <html> must specify the xml namespace for the document.
59
This example shows an XHTML document with a minimum of required tags:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Title of document</title>
</head>
<body>
some content
</body>
</html>
60
<tagname>content</tagname>
The HTML element is everything from the start tag to the end tag:
<p>My first HTML paragraph.</p>
Start tag Element content End tag
<br>
Nested HTML Elements
HTML elements can be nested (elements can contain elements).
All HTML documents consist of nested HTML elements.
Example
<!DOCTYPE html>
<html>
<body>
<h1>My First Heading</h1>
<p>My first paragraph.</p>
</body>
</html>
Explanation
The <html> element defines the whole document.
It has a start tag <html> and an end tag </html>.
The element content is another HTML element (the <body> element).
<html>
<body>
<h1>My First Heading</h1>
<p>My first paragraph.</p>
</body>
</html>
The <body> element defines the document body.
It has a start tag <body> and an end tag </body>.
The element content is two other HTML elements (<h1> and <p>).
<body>
</body>
The <h1> element defines a heading.
It has a start tag <h1> and an end tag </h1>.
The element content is: My First Heading.
<h1>My First Heading</h1>
The <p> element defines a paragraph.
It has a start tag <p> and an end tag </p>.
The element content is: My first paragraph.
<p>My first paragraph.</p>
Example
61
<html>
<body>
<p>This is a paragraph
<p>This is a paragraph
</body>
</html>
Empty HTML Elements
HTML elements with no content are called empty elements.
<br> is an empty element without a closing tag (the <br> tag defines a line
break).
Empty elements can be "closed" in the opening tag like this: <br />.
HTML5 does not require empty elements to be closed. But if you want
stricter validation, or you need to make your document readable by XML
parsers, you should close all HTML elements.
HTML Tip: Use Lowercase Tags
HTML tags are not case sensitive: <P> means the same as <p>.
The HTML5 standard does not require lowercase tags, but
W3C recommends lowercase in HTML4, and demands lowercase for
stricter document types like XHTML.
HTML Formatting Elements
HTML also defines special elements for defining text with a special meaning.
HTML uses elements like <b> and <i> for formatting output, like bold or italic text.
Formatting elements were designed to display special types of text:
Bold text
Important text
Italic text
Emphasized text
Marked text
Small text
Deleted text
Inserted text
Subscripts
Superscripts
HTML Bold and Strong Formatting
The HTML <b> element defines bold text, without any extra importance.
Example
<p>This text is normal.</p>
62
<p>This text is normal.</p>
63
4(ii). Explain about the links in HTML
HTML Links - Hyperlinks
HTML links are hyperlinks.
A hyperlink is a text or an image you can click on, and jump to another document.
HTML Links - Syntax
In HTML, links are defined with the <a> tag:
<a href="url">link text</a>
Example
<a href="http://www.w3schools.com/html/">Visit our SCAD Group</a>
The href attribute specifies the destination address.
The link text is the visible part.
Local Links
The example above used an absolute URL (A full web address).
A local link (link to the same web site) is specified with a relative URL (without
http://www....).
Example
<a href="html_images.asp">HTML Images</a>
HTML Links - Colors
When we move the mouse over a link, two things will normally happen:
The mouse arrow will turn into a little hand
The color of the link element will change
By default, a link will appear like this (in all browsers):
An unvisited link is underlined and blue
A visited link is underlined and purple
An active link is underlined and red
We can change the default colors, by using styles:
Example
<style>
a:link {color:green; background-color:transparent; text-decoration:none}
a:visited {color:pink; background-color:transparent; text-decoration:none}
a:hover {color:red; background-color:transparent; text-decoration:underline}
a:active {color:yellow; background-color:transparent; text-decoration:underline}
</style>
HTML Links - The target Attribute
The target attribute specifies where to open the linked document.
This example will open the linked document in a new browser window or in a new tab:
Example
<a href="http://www.w3schools.com/" target="_blank">Visit W3Schools!</a>
Target Description
Value
_self Opens the linked document in the same frame as it was clicked (this is
default)
_top Opens the linked document in the full body of the window
64
framename Opens the linked document in a named frame
If your webpage is locked in a frame, you can use target="_top" to break out of the
frame:
Example
<a href="http://www.w3schools.com/html/" target="_top">HTML5 </a>
HTML Links - Image as Link
It is common to use images as links
Example
<a href="default.asp">
<img src="smiley.gif" alt="HTML tutorial" style="width:42px;height:42px;border:0">
</a>
HTML Links - Create a Bookmark
HTML bookmarks are used to allow readers to jump to specific parts of a Web page.
Bookmarks are practical if the website has long pages.
To make a bookmark, we must first create the bookmark, and then add a link to it.
When the link is clicked, the page will scroll to the location with the bookmark.
Example
First, create a bookmark with the id attribute:
<h2 id="tips">Useful Tips Section</h2>
Then, add a link to the bookmark ("Useful Tips Section"), from within the same page:
<a href="#tips">Visit the Useful Tips Section</a>
Or, add a link to the bookmark ("Useful Tips Section"), from another page:
Example
<a href="html_tips.html#tips">Visit the Useful Tips Section</a>
HTML Images
In HTML, images are defined with the <img> tag.
The <img> tag is empty, it contains attributes only, and does not have a closing tag.
The src attribute specifies the URL (web address) of the image:
<img src="url" alt="some_text">
The alt Attribute
The alt attribute specifies an alternate text for an image, if the image cannot be displayed.
The alt attribute provides alternative information for an image if a user for some reason
cannot view it (because of slow connection, an error in the src attribute, or if the user uses
a screen reader).
If a browser cannot find an image, it will display the alt text:
Example
<img src="wrongname.gif" alt="HTML5 Icon" style="width:128px;height:128px;">
The alt attribute is required. A web page will not validate correctly without it.
HTML Screen Readers
A screen reader is a software program that can read what is displayed on a screen.
Screen readers are useful to people who are blind, visually impaired, or learning disabled.
Image Size - Width and Height
We can use the style attribute to specify the width and height of an image.
The values are specified in pixels (use px after the value):
Example
<img src="html5.gif" alt="HTML5 Icon" style="width:128px;height:128px;">
Alternatively, we can use width and height attributes. Here, the values are specified in
pixels by default:
Example
<img src="html5.gif" alt="HTML5 Icon" width="128" height="128">
65
It prevents styles sheets from changing the original size of images:
Example
<!DOCTYPE html>
<html>
<head>
<style>
img {
width:100%;
}
</style>
</head>
<body>
</body>
</html>
Images in Another Folder
If not specified, the browser expects to find the image in the same folder as the web page.
However, it is common to store images in a sub-folder. We must then include the folder
name in the src attribute:
Example
<img src="/images/html5.gif" alt="HTML5 Icon" style="width:128px;height:128px;">
Images on Another Server
Some web sites store their images on image servers.
Actually,we can access images from any web address in the world:
Example
<img src="http://www.w3schools.com/images/w3schools_green.jpg" alt="W3Schools.co
m">
Animated Images
The GIF standard allows animated images:
Example
<img src="programming.gif" alt="Computer Man" style="width:48px;height:48px;">
Using an Image as a Link
To use an image as a link, simply nest the <img> tag inside the <a> tag:
Example
<a href="default.asp">
<img src="smiley.gif" alt="HTML tutorial" style="width:42px;height:42px;border:0;">
</a>
Image Floating
Use the CSS float property to let the image float.
The image can float to the right or to the left of a text:
Example
<p>
<img src="smiley.gif" alt="Smiley face" style="float:right;width:42px;height:42px;">
The image will float to the right of the text.
</p>
<p>
<img src="smiley.gif" alt="Smiley face" style="float:left;width:42px;height:42px;">
66
The image will float to the left of the text.
</p>
Image Maps
Use the <map> tag to define an image-map. An image-map is an image with clickable
areas.
The name attribute of the <map> tag is associated with the <img>'s usemap attribute and
creates a relationship between the image and the map.
The <map> tag contains a number of <area> tags, that defines the clickable areas in the
image-map:
Example
<img src="planets.gif" alt="Planets" usemap="#planetmap" style="width:145px;height:1
26px;">
<map name="planetmap">
<area shape="rect" coords="0,0,82,126" alt="Sun" href="sun.htm">
<area shape="circle" coords="90,58,3" alt="Mercury" href="mercur.htm">
<area shape="circle" coords="124,58,8" alt="Venus" href="venus.htm">
</map>
HTML Image Tags
Tag Description
67
Example
<table border="1" style="width:100%">
<tr>
<td>Jill</td>
<td>Smith</td>
<td>50</td>
</tr>
<tr>
<td>Eve</td>
<td>Jackson</td>
<td>94</td>
</tr>
</table>
To add borders, use the CSS border property:
Example
table, th, td {
border: 1px solid black;
}
An HTML Table with Collapsed Borders
If we want the borders to collapse into one border, add CSS border-collapse:
Example
table, th, td {
border: 1px solid black;
border-collapse: collapse;
}
An HTML Table with Cell Padding
Cell padding specifies the space between the cell content and its borders.
If we do not specify a padding, the table cells will be displayed without padding.
To set the padding, use the CSS padding property:
Example
table, th, td {
border: 1px solid black;
border-collapse: collapse;
}
th, td {
padding: 15px;
}
HTML Table Headings
Table headings are defined with the <th> tag.
By default, all major browsers display table headings as bold and centered:
Example
<table style="width:100%">
<tr>
<th>Firstname</th>
<th>Lastname</th>
<th>Points</th>
</tr>
<tr>
<td>Eve</td>
<td>Jackson</td>
<td>94</td>
68
</tr>
</table>
To left-align the table headings, use the CSS text-align property:
Example
th {
text-align: left;
}
An HTML Table with Border Spacing
Border spacing specifies the space between the cells.
To set the border spacing for a table, use the CSS border-spacing property:
Example
table {
border-spacing: 5px;
}
Table Cells that Span Many Columns
To make a cell span more than one column, use the colspan attribute:
Example
<table style="width:100%">
<tr>
<th>Name</th>
<th colspan="2">Telephone</th>
</tr>
<tr>
<td>Bill Gates</td>
<td>555 77 854</td>
<td>555 77 855</td>
</tr>
</table>
Table Cells that Span Many Rows
To make a cell span more than one row, use the rowspan attribute:
Example
<table style="width:100%">
<tr>
<th>Name:</th>
<td>Bill Gates</td>
</tr>
<tr>
<th rowspan="2">Telephone:</th>
<td>555 77 854</td>
</tr>
<tr>
<td>555 77 855</td>
</tr>
</table>
An HTML Table With a Caption
To add a caption to a table, use the <caption> tag:
Example
<table style="width:100%">
<caption>Monthly savings</caption>
<tr>
<th>Month</th>
69
<th>Savings</th>
</tr>
<tr>
<td>January</td>
<td>$100</td>
</tr>
<tr>
<td>February</td>
<td>$50</td>
</tr>
</table>
A Special Style for One Table
To define a special style for a special table, add an id attribute to the table:
Example
<table id="t01">
<tr>
<th>Firstname</th>
<th>Lastname</th>
<th>Points</th>
</tr>
<tr>
<td>Eve</td>
<td>Jackson</td>
<td>94</td>
</tr>
</table>
Now we can define a special style for this table:
table#t01 {
width: 100%;
background-color: #f1f1c1;
To add more styles:
table#t01 tr:nth-child(even) {
background-color: #eee;
}
table#t01 tr:nth-child(odd) {
background-color: #fff;
}
table#t01 th {
color: white;
background-color: black;
}
HTML Table Tags
Tag Description
70
<caption> Defines a table caption
<col> Specifies column properties for each column within a <colgroup> element
71
UNIT III
CLIENT SIDE AND SERVER SIDE PROGRAMMING
Part A (2 marks)
1. What are the primitive data types in javascript?
JavaScript supports five primitive data types: number, string, Boolean,
undefined, and null. These types are referred to as primitive types because they are
the basic building blocks from which more complex types can be built. Of the five,
only number, string, and Boolean are real data types in the sense of actually
storing data. Undefined and null are types that arise under special circumstances.
2. Justify JavaScript is an event-driven programming
Javascript supports event driven programming. When user clicks the mouse
or hit the keys on the keyboard or if user submits the form then these events and
response to them can be handled using javascript. Hence javascript is mainly used
in web programming for validating the data provided by the user.
3. How to create arrays in Javascript?
We can declare an array like this Var scripts = new Array();
We can add elements to this array like this scripts[0] = "PHP";
scripts[1] = "ASP";
scripts[2] = "JavaScript";
scripts[3] = "HTML";
Now our array scripts have 4 elements inside it and we can print or access
them by using their index number. Note that index number starts from 0. To get
the third element of the array we have to use the index number 2. Here is the way
to get the third element of an array. document.write (scripts [2]);
We also can create an array like this
var no_array = new Array(21, 22, 23, 24, 25);
4. Write short notes on JDBC.
JDBC standard is intented for people developing industrial-strength
database applications. JDBC makes java effective for developing enterprise
information system.java.sql is the JDBC package that contains classes &
interfaces that enable a java program to interact with a database.
5. Write short notes on JDBC drivers.
A JDBC driver is basically an implementation of the function calls
specified in the JDBC API for a particular vendors RDBMS. Hence, a java
program with JDBC function calls can access any RDBMS that has a JDBC driver
available. A driver manager is used to keep track of all the installed drivers on the
system. The operations of driver manager are getDriver, registerDriver,
deregisterDriver.
6. What is the difference between CGI and servlets?
Performance is significantly better, servlet execute within the address space
of a web server.
Servlets are platform independent
The java security manager on the server enforces a set of restrictions to
protect the resources on a server machine.
The full functionality of java class libraries is available to a servlet.
7. Define Servlet Life Cycle?
init( ) method - invoked when the servlet is first loaded into memory
service( ) - called for each HTTP request (for processing)
destroy( ) - unloads the servlet from its memory.
72
8. Write down the methods of servlet interface
void destroy() called when the servlet is unloaded.
ServletConfig getServletConfig() returns a ServletConfig
object that contains any initialization parameters.
String get ServletInfo() returns a string describing the servlet.
void init(ServletConfig sc) throws ServletException called
when the servlet is initialized. Initialization parameters for servlet
can be obtained from sc. An unavailable exception should be thrown if the
servlet is not initialized.
Void Service(ServletRequest req, ServletResponse res) throws
ServletException, IOException - Called to process a request from a client. The
request from the client can be read from req. response to the client can be
written to res. An exception is generated if a servlet or IO problem occurs.
9. Define event bubbling.
Suppose, there is an element present inside another element. Then during
the event handling, if the event which is present in the inner element is handled
and then the event of the outer element is handled. This process of event handling
is called event bubbling
10. What is meant by cookies? List out its types. (Nov/Dec 2015)
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.
There are 2 types of cookies in servlets.
Non-persistent cookie
Persistent cookie
Non-persistent cookie
It is valid for single session only. It is removed each time when user closes
the browser.
Persistent cookie
It is valid for multiple session . It is not removed each time when user
closes the browser. It is removed only if user logout or signout.
73
onClick=calc.display.value+=3>
<input class=button three type=button value=C
onClick=Resetfunction(this.form)>
<input class=button three type=button value=<- onClick=backspace(this.form)>
<input class=button three type=button value== onClick=evaluation(this.form)>
<br>
<input class=button number type=button value=4
onClick=calc.display.value+=4>
<input class=button number type=button value=5
onClick=calc.display.value+=5>
<input class=button number type=button value=6
onClick=calc.display.value+=6>
<input class=button opps type=button value=- onClick=calc.display.value+=->
<input class=button opps type=button value=%
onClick=calc.display.value+=%>
<input class=button type=button value=cos onClick=cos_function()>
<br>
<input class=button number type=button value=7
onClick=calc.display.value+=7>
<input class=button number type=button value=8
onClick=calc.display.value+=8>
<input class=button number type=button value=9
onClick=calc.display.value+=9>
<input class=button opps type=button value=*
onClick=calc.display.value+=*>
<input class=button type=button value=n! onClick=fact_function()>
<input class=button type=button value=sin onClick=sin_function()>
<br>
<input class=button opps type=button value=. onClick=calc.display.value+=.>
<input class=button number type=button value=0
onClick=calc.display.value+=0>
<input class=button opps type=button value=, onClick=calc.display.value+=,>
<input class=button opps type=button value=+
onClick=calc.display.value+=+>
<input class=button opps type=button value=/ onClick=calc.display.value+=/>
<input class=button type=button value=tan onClick=tan_function()>
<br>
<input class=button type=button value=E onClick=calc.display.value+=2.718>
<input class=button type=button value=pi onClick=calc.display.value+=3.141>
<input class=button type=button value=x^y onClick=power_function()>
<input class=button type=button value=( onClick=openpara(this.value)>
<input class=button type=button value=) onClick=closepara(this.value)>
<input class=button type=button value=log onClick=log_function()>
<br>
<input class=button type=button value=sqrt onClick=sqrt_function()>
<input class=button type=button value=LN2
onClick=calc.display.value+=0.693>
<input class=button type=button value=LN10
onClick=calc.display.value+=2.302>
<input class=button type=button value=log2E
74
onClick=calc.display.value+=1.442>
<input class=button type=button value=log10E
onClick=calc.display.value+=0.434>
<input class=button type=button value=EXP onClick=exp_function>
</form>
</div>
</div>
</body>
At this point we should get an output like this,
75
function cos_function()
{
flag+=1;
calc.display.value+=Math.cos(;
}
function sin_function()
{
flag+=1;
calc.display.value+=Math.sin(;
}
function tan_function()
{
flag+=1;
calc.display.value+=Math.tan(;
}
function log_function()
{
flag+=1;
calc.display.value+=Math.log(;
}
function sqrt_function()
{
flag+=1;
calc.display.value+=Math.sqrt(;
}
function exp_function()
{
flag+=1;
calc.display.value+=Math.exp(;
}
function fact(x)
{
factvar=1;
for (i=1;i<=x;i++)
{
factvar=factvar*i;
}
return factvar;
}
function fact_function(x)
{
flag+=1;
calc.display.value+=fact(;
}
function power_function(x)
{
flag+=1;
calc.display.value+=Math.pow(x,y;
}
function evaluation(calc)
76
{
n = calc.display.value;
var size = calc.display.value.length;
var lastchar = calc.display.value.charAt(size)
if(isNaN(lastchar) && lastchar!=) && lastchar!=!)
{calc.display.value=syntax error;}
else if(flag!=0){calc.display.value=error:paranthesis;}
else {
result=eval(n);
calc.display.value=result;}
}
</script>
Step-3: Making the calculator look pretty
Now that the important part of our calculator is over, it is all up to css to make it look
beautiful. You can also toss in some of your own ideas to make it look even better.
<style>
*{padding:0;
margin:0;
}
body {text-align:center;
background-color:#637ACB;
}
#heading {margin-top:30px;}
#form_wrapper {width:405px;
height:450px;
margin:30px auto auto 420px;
background-color:#000;
text-align:center;
border-radius:10px;
border-right:2px groove #333;
box-shadow:4px 4px 2px #666666;}
#formone{padding-top:10px;}
#display {width:380px;
height:40px;
font-size:18px;
color:black;
margin:4px;
border:2px inset black;
border-bottom:1px inset #FFF;
border-right:1px inset #FFF;
background-color:#D5F192;}
.button {width:60px;
height:60px;
margin:1px;}
.number {font-size:16px;
font-weight:bold;}
.opps {font-size:18px;}
.three {font-weight:bold;
background-color:#FBB9A8;
}
77
.three:hover{background-color:#F66;}
</style>
78
In the Document Object Model, documents have a logical structure which is very
much like a tree; to be more precise, it is like a "forest" or "grove" which can
contain more than one tree.
The object model specifies the logical model for the programming interface, and
this logical model may be implemented in any way that a particular
implementation finds convenient.
In this specification, we use the term structure model to describe the tree-like
representation of a document; we specifically avoid terms like "tree" or "grove" in
order to avoid implying a particular implementation. One important property of
DOM structure models is structural isomorphism: if any two Document Object
Model implementations are used to create a representation of the same document,
they will create the same structure model, with precisely the same objects and
relationships.
The name "Document Object Model" was chosen because it is an "object model"
is used in the traditional object oriented design sense: documents are modeled
using objects, and the model encompasses not only the structure of a document,
but also the behavior of a document and the objects of which it is composed. As an
object model, the Document Object Model identifies:
the interfaces and objects used to represent and manipulate a document
the semantics of these interfaces and objects - including both behavior and
attributes
the relationships and collaborations among these interfaces and objects
The structure of SGML documents has traditionally been represented by an
abstract data model, not by an object model. In an abstract data model, the model
is centered around the data.
In object oriented programming languages, the data itself is encapsulated in
objects which hide the data, protecting it from direct external manipulation.
The functions associated with these objects determine how the objects may be
manipulated, and they are part of the object model.
The Document Object Model currently consists of two parts, DOM Core and
DOM HTML.
The DOM Core represents the functionality used for XML documents, and also
serves as the basis for DOM HTML.
All DOM implementations must support the interfaces listed as "fundamental" in
the Core specification; in addition, XML implementations must support the
interfaces listed as "extended" in the Core specification.
The Level 1 DOM HTML specification defines additional functionality needed for
HTML documents.
79
3. Explain about database connectivity. [Nov/ Dec 15]
(or)
Explain how the database is connected using JBDC.
Java Database Connectivity (JDBC) is an application programming interface
(API) for the programming language Java, which defines how a client may access
adatabase.
It is part of the Java Standard Edition platform, from Oracle Corporation.
There are 5 steps to connect any java application with the database in java using JDBC.
They are as follows:
Register the driver class
Creating connection
Creating statement
Executing queries
Closing connection
80
System.out.println(rs.getInt(1)+" "+rs.getString(2));
}
5) Close the connection object
By closing connection object statement and ResultSet will be closed automatically. The
close() method of Connection interface is used to close the connection.
Syntax of close() method
public void close()throws SQLException
Example to close connection
con.close();
4 (i). How do you write Javascript? What are its advantages and limitations?
JavaScript is a lightweight, interpreted programming language. It is designed for creating
network-centric applications. It is complimentary to and integrated with Java. JavaScript
is very easy to implement because it is integrated with HTML. It is open and cross-
platform.
Sample Code
<html>
<body>
<script language="javascript" type="text/javascript">
<!--
document.write("Hello World!")
//-->
</script>
</body>
</html>
CLIENT-SIDE JAVASCRIPT
Client-side JavaScript is the most common form of the language.
The script should be included in or referenced by an HTML document for the
code to be interpreted by the browser.
It means that a web page need not be a static HTML, but can include programs
that interact with the user, control the browser, and dynamically create HTML
content.
The JavaScript client-side mechanism provides many advantages over traditional
CGI server-side scripts. For example, you might use JavaScript to check if the
user has entered a valid e-mail address in a form field.
The JavaScript code is executed when the user submits the form, and only if all
the entries are valid, they would be submitted to the Web Server.
JavaScript can be used to trap user-initiated events such as button clicks, link navigation,
and other actions that the user initiates explicitly or implicitly.
ADVANTAGES OF JAVASCRIPT
The merits of using JavaScript are
Less server interaction We can validate user input before sending the page off
to the server. This saves server traffic, which means less load on your server.
Immediate feedback to the visitors They don't have to wait for a page reload
to see if they have forgotten to enter something.
Increased interactivity We can create interfaces that react when the user
hovers over them with a mouse or activates them via the keyboard.
Richer interfaces We can use JavaScript to include such items as drag-and-
drop components and sliders to give a Rich Interface to your site visitors.
81
LIMITATIONS OF JAVASCRIPT
We cannot treat JavaScript as a full-fledged programming language. It lacks the
following important features
Client-side JavaScript does not allow the reading or writing of files. This has been
kept for security reason.
JavaScript cannot be used for networking applications because there is no such
support available.
JavaScript doesn't have any multithreading or multiprocessor capabilities.
A simple syntax of your JavaScript will appear as follows.
<script ...>
JavaScript code
</script>
JavaScript can be implemented using JavaScript statements that are placed within
the <script>... </script> HTML tags in a web page.
We can place the <script> tags, containing your JavaScript, anywhere within you
web page, but it is normally recommended that you should keep it within
the <head> tags.
The <script> tag alerts the browser program to start interpreting all the text
between these tags as a script. The script tag takes two important attributes.
Language This attribute specifies what scripting language you are using.
Typically, its value will be javascript. Although recent versions of HTML (and
XHTML, its successor) have phased out the use of this attribute.
Type This attribute is what is now recommended to indicate the scripting
language in use and its value should be set to "text/javascript".
So our JavaScript segment will look like
<script language="javascript" type="text/javascript">
JavaScript code
</script>
<html>
<body>
<script language="javascript" type="text/javascript">
<!--
document.write("Hello World!")
//-->
</script>
</body>
</html>
This code will produce the following result
Hello World!
4(ii). Explain in detail about Date object method in Javascript.
The Date object is used to work with dates and times.
Date objects are created with new Date().
There are four ways of instantiating a date:
var d = new Date();
var d = new Date(milliseconds);
var d = new Date(dateString);
var d = new Date(year, month, day, hours, minutes, seconds, milliseconds);
DATE OBJECT PROPERTIES
Property Description
constructor Returns the function that created the Date object's prototype
82
prototype Allows you to add properties and methods to an object
getTime() Returns the number of milliseconds since midnight Jan 1 1970, and
a specified date
getTimezoneOffset() Returns the time difference between UTC time and local time, in
minutes
getUTCDate() Returns the day of the month, according to universal time (from 1-
31)
getUTCDay() Returns the day of the week, according to universal time (from 0-
6)
REGEXP OBJECT
A regular expression is an object that describes a pattern of characters.
Regular expressions are used to perform pattern-matching and "search-and-replace"
functions on text.
Syntax
/pattern/modifiers;
Example
var patt = /w3schools/i
Example explained:
/w3schools/i is a regular expression.
w3schools is a pattern (to be used in a search).
83
i is a modifier (modifies the search to be case-insensitive).
MODIFIERS
Modifiers are used to perform case-insensitive and global searches:
Modifier Description
METACHARACTERS
Metacharacters are characters with a special meaning:
Metacharacter Description
\d Find a digit
84
\xxx Find the character specified by an octal number xxx
QUANTIFIERS
Quantifier Description
85
test() Tests for a match in a string. Returns true or false
<script type="text/javascript">
<!--
function sayHello() {
alert("Hello World")
}
//-->
</script>
</head>
<body>
<p>Click the following button and see result</p>
<form>
<input type="button" onclick="sayHello()" value="Say Hello" />
</form>
</body>
</html>
OUTPUT
onsubmit Event type
onsubmit is an event that occurs when you try to submit a form. You can put your form
validation against this event type.
EXAMPLE
The following example shows how to use onsubmit. Here we are calling
avalidate() function before submitting a form data to the webserver.
Ifvalidate() function returns true, the form will be submitted, otherwise it will not
submit the data.
86
<html>
<head>
<script type="text/javascript">
<!--
function validation() {
all validation goes here
.........
return either true or false
}
//-->
</script>
</head>
<body>
</body>
</html>
ONMOUSEOVER AND ONMOUSEOUT
These two event types will help us create nice effects with images or even with text as
well. The onmouseover event triggers when we bring your mouse over any element and
the onmouseout triggers when our move your mouse out from that element. Try the
following example.
<html>
<head>
<script type="text/javascript">
<!--
function over() {
document.write ("Mouse Over");
}
function out() {
document.write ("Mouse Out");
}
//-->
</script>
</head>
<body>
<p>Bring your mouse inside the division to see the result:</p>
</body>
</html>
87
OUTPUT
HTML 5 STANDARD EVENTS
The standard HTML events are listed here.
Attribute Description
oncanplay Triggers when media can start play, but might has to stop for
buffering
8. Explain in detail about Java servlet architecture and its life cycle.
88
Java Servlets are programs that run on a Web or Application server and act as a
middle layer between a request coming from a Web browser or other HTTP client
and databases or applications on the HTTP server.
Using Servlets, you can collect input from users through web page forms, present
records from a database or another source, and create web pages dynamically.
Java Servlets often serve the same purpose as programs implemented using the
Common Gateway Interface (CGI). But Servlets offer several advantages in
comparison with the CGI.
Performance is significantly better.
Servlets execute within the address space of a Web server. It is not necessary to
create a separate process to handle each client request.
Servlets are platform-independent because they are written in Java.
Java security manager on the server enforces a set of restrictions to protect the
resources on a server machine. So servlets are trusted.
The full functionality of the Java class libraries is available to a servlet. It can
communicate with applets, databases, or other software via the sockets and RMI
mechanisms that you have seen already.
SERVLETS ARCHITECTURE
Following diagram shows the position of Servelts in a Web Application.
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.
SERVLETS TASKS
Servlets perform the following major tasks:
89
Read the explicit data sent by the clients (browsers). This includes an HTML form
on a Web page or it could also come from an applet or a custom HTTP client
program.
Read the implicit HTTP request data sent by the clients (browsers). This includes
cookies, media types and compression schemes the browser understands, and so
forth.
Process the data and generate the results. This process may require talking to a
database, executing an RMI or CORBA call, invoking a Web service, or
computing the response directly.
Send the explicit data (i.e., the document) to the clients (browsers). This
document can be sent in a variety of formats, including text (HTML or XML),
binary (GIF images), Excel, etc.
Send the implicit HTTP response to the clients (browsers). This includes telling
the browsers or other clients what type of document is being returned (e.g.,
HTML), setting cookies and caching parameters, and other such tasks.
SERVLETS PACKAGES
Java Servlets are Java classes run by a web server that has an interpreter that
supports the Java Servlet specification.
Servlets can be created using the javax.servlet and javax.servlet.http
packages, which are a standard part of the Java's enterprise edition, an expanded
version of the Java class library that supports large-scale development projects.
These classes implement the Java Servlet and JSP specifications. At the time of
writing this tutorial, the versions are Java Servlet 2.5 and JSP 2.1.
Java servlets have been created and compiled just like any other Java class. After
you install the servlet packages and add them to our computer's Classpath, we
can compile servlets with the JDK's Java compiler or any other current compiler.
LIFE CYCLE OF THE SERVLET
The web container maintains the life cycle of a servlet instance.
1. Servlet class is loaded.
2. Servlet instance is created.
3. init method is invoked.
4. service method is invoked.
5. destroy method is invoked.
90
As displayed in the above diagram, there are three states of a servlet: new, ready and end.
The servlet is in new state if servlet instance is created. After invoking the init() method,
Servlet comes in the ready state. In the ready state, servlet performs all the tasks. When
the web container invokes the destroy() method, it shifts to the end state.
The classloader is responsible to load the servlet class. The servlet class is loaded when
the first request for the servlet is received by the web container.
The web container creates the instance of a servlet after loading the servlet class. The
servlet instance is created only once in the servlet life cycle.
The web container calls the init method only once after creating the servlet instance.
The init method is used to initialize the servlet. It is the life cycle method of the
javax.servlet.Servlet interface. Syntax of the init method is given below:
public void init(ServletConfig config) throws ServletException
The web container calls the service method each time when request for the servlet is
received. If servlet is not initialized, it follows the first three steps as described above
then calls the service method. If servlet is initialized, it calls the service method. Notice
that servlet is initialized only once. The syntax of the service method of the Servlet
interface is given below:
The web container calls the destroy method before removing the servlet instance from the
service. It gives the servlet an opportunity to clean up any resource for example memory,
thread etc. The syntax of the destroy method of the Servlet interface is given below:
91
Types of Cookie
There are 2 types of cookies in servlets.
1. Non-persistent cookie
2. Persistent cookie
Non-persistent cookie
It is valid for single session only. It is removed each time when user closes the browser.
Persistent cookie
It is valid for multiple session . It is not removed each time when user closes the
browser. It is removed only if user logout or signout.
Advantage of Cookies
1. Simplest technique of maintaining the state.
2. Cookies are maintained at client side.
Disadvantage of Cookies
1. It will not work if cookie is disabled from the browser.
2. Only textual information can be set in Cookie object.
COOKIE CLASS
javax.servlet.http.Cookie class provides the functionality of using cookies. It provides a
lot of useful methods for cookies.
Constructor of Cookie class
Constructor Description
Cookie() constructs a cookie.
Cookie(String name, String value) constructs a cookie with a specified name
and value.
92
to return all the cookies from the browser.
Creation of Cookie
Let's see the simple code to create cookie.
1. Cookie ck=new Cookie("user","sonoo jaiswal");//creating cookie object
2. response.addCookie(ck);//adding cookie in the response
Deletion of Cookie
Let's see the simple code to delete cookie. It is mainly used to logout or signout the user.
1. Cookie ck=new Cookie("user","");//deleting value of cookie
2. ck.setMaxAge(0);//changing the maximum age to 0 seconds
3. response.addCookie(ck);//adding cookie in the response
6b. How to Install and Configuring Apache Tomcat Web Server?
STEP 1: Download and Install Tomcat
NOTE: At the time of writing, Tomcat 9 is at the alpha stage, not stable release. We shall
install Tomcat 8.0.30.
For Windows
Goto http://tomcat.apache.org Downloads Tomcat 8.0 "8.0.{xx}"
(where {xx} is the latest upgrade number) Binary Distributions Core
"ZIP" package (e.g., "apache-tomcat-8.0.{xx}.zip", about 8 MB).
Create our project directory, say "d:\myProject" or "c:\myProject". UNZIP the
downloaded file into your project directory. Tomcat will be unzipped into
directory "d:\myProject\apache-tomcat-8.0.{xx}".
For ease of use, we shall shorten and rename this directory to
"d:\myProject\tomcat".
Take note of our Tomcat Installed Directory. Tomcat installed directory
as <TOMCAT_HOME>.
STEP 2: Create an Environment Variable JAVA_HOME (For Windows)
We need to create an environment variable called "JAVA_HOME" and set it to
our JDK installed directory.
First, find your JDK installed directory. The default is "c:\Program
Files\Java\jdk1.8.0_{xx}", where {xx} is the upgrade number. Take note of your
JDK installed directory.
To set the environment variable JAVA_HOME in Windows 7/8/10: Start "Control
Panel" System Advanced system settings Switch to "Advanced" tab
Environment Variables System Variables "New" In "Variable Name",
enter "JAVA_HOME" In "Variable Value", enter your JDK installed directory
as noted in Step 1.
To verify, RE-START a CMD shell (restart needed to refresh the environment)
and issue:
SET JAVA_HOME
JAVA_HOME=c:\Program Files\Java\jdk1.8.0_{xx} <== Verify that this is
YOUR JDK installed directory
STEP 3: Configure Tomcat Server
The Tomcat configuration files are located in the "conf" sub-directory of your Tomcat
installed directory, e.g. "d:\myProject\tomcat\conf" (for Windows) or
"/Applications/tomcat/conf" (for Mac OS X). There are 4 configuration XML files:
1. server.xml
93
2. web.xml
3. context.xml
4. tomcat-users.xml
Make a BACKUP of the configuration files before we proceed.
Step 3(a) "conf\server.xml" - Set the TCP Port Number
Use a programming text editor (e.g., NotePad++, TextPad for Windows; or gEdit,
jEdit for Mac OS X) to open the configuration file "server.xml", under the "conf"
sub-directory of Tomcat installed directory.
The default TCP port number configured in Tomcat is 8080, you may choose any
number between 1024 and 65535, which is not used by an existing application.
We shall choose 9999 in this article. (For production server, you should use port
80, which is pre-assigned to HTTP server as the default port number.)
Locate the following lines (around Line 69) that define the HTTP connector, and
change port="8080" to port="9999".
<!-- A "Connector" represents an endpoint by which requests are received
and responses are returned. Documentation at :
Java HTTP Connector: /docs/config/http.html (blocking & non-blocking)
Java AJP Connector: /docs/config/ajp.html
APR (HTTP/AJP) Connector: /docs/apr.html
Define a non-SSL HTTP/1.1 Connector on port 8080
-->
<Connector port="9999" protocol="HTTP/1.1"
connectionTimeout="20000"
redirectPort="8443" />
Step 3(b) "conf\web.xml" - Enabling Directory Listing
Again, use a programming text editor to open the configuration file "web.xml", under the
"conf" sub-directory of Tomcat installed directory.
We shall enable directory listing by changing "listings" from "false" to "true" for the
"default" servlet. This is handy for test system, but not for production system for security
reasons.
Locate the following lines (around Line 103) that define the "default" servlet; and change
the "listings" from "false" to "true".
<!-- The default servlet for all web applications, that serves static -->
<!-- resources. It processes all requests that are not mapped to other -->
<!-- servlets with servlet mappings. -->
<servlet>
<servlet-name>default</servlet-name>
<servlet-class>org.apache.catalina.servlets.DefaultServlet</servlet-class>
<init-param>
<param-name>debug</param-name>
<param-value>0</param-value>
</init-param>
<init-param>
<param-name>listings</param-name>
<param-value>true</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
Step 3(c) "conf\context.xml" - Enabling Automatic Reload
We shall add the attribute reloadable="true" to the <Context> element to enable
automatic reload after code changes. Again, this is handy for test system but not for
production, due to the overhead of detecting changes.
94
Locate the <Context> start element (around Line 19), and change it to <Context
reloadable="true">.
<Context reloadable="true">
......
......
</Context>
Step 3(d) (Optional) "conf\tomcat-users.xml"
Enable the Tomcat's manager by adding the highlighted lines, inside the <tomcat-
users> elements:
<tomcat-users>
<role rolename="manager-gui"/>
<user username="manager" password="xxxx" roles="manager-gui"/>
</tomcat-users>
This enables the manager GUI app for managing Tomcat server.
STEP 4: Start Tomcat Server
The Tomcat's executable programs and scripts are kept in the "bin" sub-directory of the
Tomcat installed directory, e.g., "d:\myProject\tomcat\bin" (for Windows) or
"/Applications/tomcat/bin" (for Mac OS X).
Step 4(a) Start Server
For Windows
Launch a CMD shell. Set the current directory to "<TOMCAT_HOME>\bin", and run
"startup.bat" as follows:
// Change the current directory to Tomcat's "bin"
// Assume that Tomcat is installed in "d:\myProject\tomcat"
d: // Change the current drive
cd \myProject\tomcat\bin // Change Directory to YOUR Tomcat's "bin" directory
95
Press Ctrl-C on the Tomcat console; OR
Run "<TOMCAT_HOME>\bin\shutdown.bat" script. Open a new "cmd" and
issue:
// Change the current directory to Tomcat's "bin"
d: // Change the current drive
cd \myProject\tomcat\bin // Change Directory to YOUR Tomcat's "bin" directory
// Shutdown the server
shutdown
96
6c. Explain about JSP Standard Tag Library.
The JavaServer Pages Standard Tag Library (JSTL) is a collection of useful JSP
tags which encapsulates core functionality common to many JSP
applications.JSTL has support for common, structural tasks such as iteration and
conditionals, tags for manipulating XML documents, internationalization tags,
and SQL tags. It also provides a framework for integrating existing custom tags
with JSTL tags.
The JSTL tags can be classified, according to their functions, into following JSTL
tag library groups that can be used when creating a JSP page:
Core Tags
Formatting tags
SQL tags
XML tags
JSTL Functions
Tag Description
<c:catch> Catches any Throwable that occurs in its body and optionally
exposes it.
<c:if> Simple conditional tag which evalutes its body if the supplied
condition is true.
<c:when> Subtag of <choose> that includes its body if its condition evalutes
to 'true'.
<c:otherwise > Subtag of <choose> that follows <when> tags and runs only if all
of the prior conditions evaluated to 'false'.
97
Formatting tags
The JSTL formatting tags are used to format and display text, the date, the time, and
numbers for internationalized Web sites. Following is the syntax to include Formatting
library in your JSP:
<fmt:formatDate> Formats a date and/or time using the supplied styles and pattern
<fmt:timeZone> Specifies the time zone for any time formatting or parsing
actions nested in its body.
<fmt:setTimeZone> Stores the given time zone in the time zone configuration
variable
SQL tags
The JSTL SQL tag library provides tags for interacting with relational databases
(RDBMSs) such as Oracle, mySQL, or Microsoft SQL Server.
Following is the syntax to include JSTL SQL library in your JSP:
<%@ taglib prefix="sql"
uri="http://java.sun.com/jsp/jstl/sql" %>
<sql:query> Executes the SQL query defined in its body or through the sql
attribute.
<sql:update> Executes the SQL update defined in its body or through the sql
attribute.
98
XML tags
The JSTL XML tags provide a JSP-centric way of creating and manipulating XML
documents. Following is the syntax to include JSTL XML library in your JSP.
The JSTL XML tag library has custom tags for interacting with XML data. This
includes parsing XML, transforming XML data, and flow control based on XPath
expressions.
<%@ taglib prefix="x"
uri="http://java.sun.com/jsp/jstl/xml" %>
Before you proceed with the examples, you would need to copy following two XML and
XPath related libraries into your <Tomcat Installation Directory>\lib:
XercesImpl.jar: Download it fromhttp://www.apache.org/dist/xerces/j/
xalan.jar: Download it from http://xml.apache.org/xalan-j/index.html
Following is the list of XML JSTL Tags:
Tag Description
<x:parse> Use to parse XML data specified either via an attribute or in the tag
body.
<x:if > Evaluates a test XPath expression and if it is true, it processes its body.
If the test condition is false, the body is ignored.
Function Description
99
UNIT IV
PHP and XML
PART - A
1. What is XML parse tree? [Nov/Dec 15]
XML documents form a tree structure that starts at "the root" and branches to "the
leaves".
XML documents are formed as element trees.
An XML tree starts at a root element and branches from the root to child
elements.
All elements can have sub elements (child elements)
<root>
<child>
<subchild>.....</subchild>
</child>
</root>
2. Why is XSLT an important tool in development of web applications?
[May/June 16]
The original document is not changed; rather, a new document is created based on
the content of an existing one.Typically, input documents are XML files, but
anything from which the processor can build an XQuery and XPath Data
Model can be used, for example relational database tables, or geographical
information systems.
3. When should the super global arrays in PHP be used? Which super global
array in PHP would contain a HTML forms POST data? [May/June 16]
100
array() - Creates an array
cal_days_in_month() - Returns the number of days in a month for a specified year
and calendar
date.timezone - The default timezone (used by all date/time functions)
chdir() - Changes the current directory
5. Define XML.
Extensible Markup Language (XML) is a markup language that defines a set of
rules for encoding documents in a format that is both human-
readable and machine-readable. It is defined by the W3C's XML 1.0
Specification and by several other related specifications, all of which are free open
standards.
The basic building block of an XML document is an element, defined by tags. An
element has a beginning and an ending tag. All elements in an XML document are
contained in an outermost element known as the root element.
6. Define DTD.
A document type definition (DTD) is a set of markup declarations that define a
document type for an SGML-family markup language (SGML, XML, and
HTML). A Document Type Definition (DTD) defines the legal building blocks
of an XML document. It defines the document structure with a list of legal
elements and attributes.
7. What are the XML rules for distinguishing between the content of a
document and the XML markup element?
The start of XML markup elements is identified by either the less than
symbol (<) or the ampersand (&) character.
Three other characters, the greater than symbol (>), the apostrophe or single
quote () and the double quotation marks () are used by XML for markup.
To use these special characters as content within your document, you must
use the corresponding general XML entity.
8. What is DOM?
The DOM is a W3C (World Wide Web Consortium) standard. The DOM defines
a standard for accessing documents: "The W3C Document Object Model (DOM)
is a platform and language-neutral interface that allows programs and scripts to
dynamically access and update the content, structure, and style of a document."
9. What is XSLT?
XSLT (ExtensibleStylesheet Language Transformations) is a language
for transforming XML documents into other XML documents, or other formats
such as HTML for web pages, plain text or into XSL Formatting Objects, which
may subsequently be converted to other formats, such
as PDF, PostScript and PNG.
10. What is metadata?
Metadata is simply data about data, or, to put it another way, data that describes
other data. Take, for example, an XML document. An XML document contains
markup, which is a form of metadata. Consider this fragment:
<p>The <library-name>foobar</library-name> library contains the routines
<routine-name>foo()</routine-name> and <routine-name>bar()</routine-
name>.</p>
The <p> tag is metadata that tells us that the string it contains is a paragraph. The
<library-name> and <routine-name> tags are metadata that tell us that the strings
they contain are library names and routine names respectively.
101
11. What are the uses of XLink,Xpath,Xquery?.
XLink is used to create hyperlinks in XML documents.
XPath: provides a common syntax and semantics for functionality shared between
XSLT and XPointer.
XQuery: query language. It facilitates the data extraction from XML documents.
12. Define PHP.
PHP: Hypertext Preprocessor is a server-side scripting language designed for web
development but also used as a general-purpose programming language. PHP code
may be embedded into HTML code, or it can be used in combination with
various web template systems, web content management systems and web
frameworks.
PHP code is usually processed by a PHP interpreter implemented as a module in
the web server or as a Common Gateway Interface (CGI) executable.
13. What are the rules to write variables in PHP?
A variable can have a short name (like x and y) or a more descriptive name (age,
carname, total_volume).
Rules for PHP variables:
A variable starts with the $ sign, followed by the name of the variable
A variable name must start with a letter or the underscore character
A variable name cannot start with a number
A variable name can only contain alpha-numeric characters and
underscores (A-z, 0-9, and _ )
Variable names are case-sensitive ($age and $AGE are two different
variables)
14. What is meant by RSS and ATOM?
RSS stands for both Rich Site Summary and Really Simple Syndication but it
always refers to the same technology. It is a mean of transmitting and updating
news in an automated way. Most news sites (including virtually all blogs) will
publish what is called an RSS feed which is regularly updated with the latest
available headlines and/or articles.
The RSS feed is not human readable. It is an XML format which is designed to be
read by machines rather than humans.
The name Atom applies to a pair of related Web standards. The Atom Syndication
Format is an XML language used for web feeds, while the Atom Publishing
Protocol (AtomPub or APP) is a simple HTTP-based protocol for creating and
updating web resources. A feed contains entries, which may be headlines, full-text
articles, excerpts, summaries, and/or links to content on a website, along with
various metadata. The Atom format was developed as an alternative to RSS.
15. How to connect a database in PHP?
We should establish a connection to the MySQL database. This is an extremely
important step because if our script cannot connect to its database, our queries to
the database will fail. A good practice when using databases is to set the username,
the password and the database name values at the beginning of the script code. If
we need to change them later, it will be an easy task.
$username="our_username";$password="our_password";$database="our_databas
e";
We should replace "our_username", "our_password" and "our_database" with the
MySQL username, password and database that will be used by our script.
102
Next we should connect our PHP script to the database. This can be done with the
mysql_connect PHP function:
mysql_connect(localhost,$username,$password);
Part B (16 marks)
1. Write a PHP program to do string manipulations. [Nov/Dec15]
Following are valid examples of string
$string_1 = "This is a string in double quotes";
$string_2 = "This is a somewhat longer, singly quoted string";
$string_39 = "This string has thirty-nine characters";
$string_0 = ""; // a string with zero characters
Singly quoted strings are treated almost literally, whereas doubly quoted strings replace
variables with their values as well as specially interpreting certain character sequences.
<?php
$variable = "name";
$literally = 'My $variable will not print!\\n';
print($literally);
print "<br />";
$literally = "My $variable will print!\\n";
print($literally);
?>
This will produce the following result
My $variable will not print!\n
My name will print
String Concatenation Operator
To concatenate two string variables together, use the dot (.) operator
<?php
$string1="Hello World";
$string2="1234";
echo $string1 . " " . $string2;
?>
This will produce the following result
Hello World 1234
strlen() function
The strlen() function is used to find the length of a string.
Let's find the length of our string "Hello world!":
<?php
echo strlen("Hello world!");
?>
This will produce the following result
12
strpos() function
The strpos() function is used to search for a string or character within a string. If a match
is found in the string, this function will return the position of the first match. If no match
is found, it will return FALSE. Let's see if we can find the string "world" in our string
<?php
echo strpos("Hello world!","world");
?>
This will produce the following result
6
103
To ensure all the letters in a specific string were uppercase, we can use
the strtoupper()function as follows:
<?php
$str = "Like a puppet on a string.";
$cased = strtoupper($str);
// Displays: LIKE A PUPPET ON A STRING.
echo $cased;
It is perhaps obvious but still worth noting that numbers and other non-alphabet
characters will not be converted.
The strtolower() function does the exact opposite of strtoupper() and converts a string
into all lowercase letters:
<?php
$str = "LIKE A PUPPET ON A STRING.";
$cased = strtolower($str);
// Displays: like a puppet on a string.
echo $cased;
Likewise when we want to ensure certain words, such as names or titles, just have the
first letter of each word capitalized. For this we can use the ucwords() function:
<?php
$str = "a knot";
$cased = ucwords($str);
// Displays: A Knot
echo $cased;
It is also possible to manipulate the case of just the first letter of a string using
the lcfirst() and ucfirst() functions. If we want the first letter to be lowercase, use lcfirst().
If we want the first letter to be uppercase, use ucfirst(). The ucfirst() function is probably
the most useful since we can use it to ensure a sentence always starts with a capital letter.
<?php
$str = "how long is a piece of string?";
$cased = ucfirst($str);
//Displays: How long is a piece of string?
echo $cased;
2(i).Explain in detail about i) XML Schema [Nov / Dec 15]
Let's have a look at this XML document called "shiporder.xml"
<?xml version="1.0" encoding="UTF-8"?>
<shiporder orderid="889923"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="shiporder.xsd">
<orderperson>JohnSmith</orderperson>
<shipto>
<name>OlaNordmann</name>
<address>Langgt23</address>
<city>4000Stavanger</city>
<country>Norway</country>
</shipto>
<item>
<title>EmpireBurlesque</title>
<note>SpecialEdition</note>
<quantity>1</quantity>
<price>10.90</price>
104
</item>
<item>
<title>Hideyourheart</title>
<quantity>1</quantity>
<price>9.90</price>
</item>
</shiporder>
The XML document above consists of a root element, "shiporder", that contains a
required attribute called "orderid".
The "shiporder" element contains three different child elements: "orderperson",
"shipto" and "item".
The "item" element appears twice, and it contains a "title", an optional "note"
element, a "quantity", and a "price" element.
The line above: xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" tells
the XML parser that this document should be validated against a schema.
The line: xsi:noNamespaceSchemaLocation="shiporder.xsd" specifies WHERE
the schema resides (here it is in the same folder as "shiporder.xml").
Create an XML Schema
Now we want to create a schema for the XML document above.
We start by opening a new file that we will call "shiporder.xsd".
To create the schema we could simply follow the structure in the XML document
and define each element as we find it.
We will start with the standard XML declaration followed by the xs:s element that
defines a schema:
<?xml version="1.0" encoding="UTF-8" ?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
...
</xs:schema>
In the schema above we use the standard namespace (xs), and the URI associated
with this namespace is the Schema language definition, which has the standard
value of http://www.w3.org/2001/XMLSchema.
Next, we have to define the "shiporder" element.
This element has an attribute and it contains other elements, therefore we consider
it as a complex type.
The child elements of the "shiporder" element is surrounded by a xs:sequence
element that defines an ordered sequence of sub elements:
<xs:element name="shiporder">
<xs:complexType>
<xs:sequence>
...
</xs:sequence>
</xs:complexType>
</xs:element>
2(ii) List at least five significant differences between DTD and XML schema for
defining XML document structures with appropriate examples.
[May/June 16]
105
DTD, or Document Type Definition, and XML Schema, which is also
known as XSD, are two ways of describing the structure and content of an
XML document.
DTD is the older of the two, and as such, it has limitations that XML
Schema has tried to improve.
The first difference between DTD and XML Schema, is namespace
awareness; XML Schema is, while DTD is not.
Namespace awareness removes the ambiguity that can result in having
certain elements and attributes from multiple XML vocabularies, by giving
them namespaces that put the element or attribute into context.
Part of the reason why XML Schema is namespace aware while DTD is
not, is the fact that XML Schema is written in XML, and DTD is not.
Therefore, XML Schemas can be programmatically processed just like any
XML document.
XML Schema also eliminates the need to learn another language, as it is
written in XML, unlike DTD.
Another key advantage of XML Schema, is its ability to implement strong
typing.
An XML Schema can define the data type of certain elements, and even
constrain it to within specific lengths or values.
This ability ensures that the data stored in the XML document is accurate.
DTD lacks strong typing capabilities, and has no way of validating the
content to data types.
XML Schema has a wealth of derived and built-in data types to validate
content.
It also has uniform data types, but as all processors and validators need to
support these data types, it often causes older XML parsers to fail.
A characteristic of DTD that people often consider both as an advantage
and disadvantage, is the ability to define DTDs inline, which XML Schema
lacks.
This is good when working with small files, as it allows you to contain both
the content and the schema within the same document, but when it comes to
larger documents, we have to pull content every time while we retrieve the
schema. This can lead to serious overhead that can degrade performance.
1. XML Schema is namespace aware, while DTD is not.
2. XML Schemas are written in XML, while DTDs are not.
3. XML Schema is strongly typed, while DTD is not.
4. XML Schema has a wealth of derived and built-in data types that are not
available in DTD.
5. XML Schema does not allow inline definitions, while DTD does.
No. DTD XSD
1) DTD stands for Document Type XSD stands for XML Schema Definition.
Definition.
2) DTDs are derived XSDs are written in XML.
from SGML syntax.
3) DTD doesn't support datatypes. XSD supports datatypes for elements and
attributes.
4) DTD doesn't support namespace. XSD supports namespace.
106
5) DTD doesn't define order for child XSD defines order for child elements.
elements.
6) DTD is not extensible. XSD is extensible.
7) DTD is not simple to learn.. XSD is simple to learn because you don't need to
learn new language..
8) DTD provides less control on XSD provides more control on XML structure
XML structure.
3(i). Explain in detail about XML parsers and Validation [Nov / Dec 15]
XML PARSERS:
An XML parser is a software library or package that provides interfaces for client
applications to work with an XML document. The XML Parser is designed to read the
XML and create a way for programs to use XML.
XML parser validates the document and check that the document is well formatted.
Let's understand the working of XML parser by the figure given below:
107
It is an event based parser, it works like an event handler in Java.
Advantages
1) It is simple and memory efficient.
2) It is very fast and works for huge documents.
Disadvantages
1) It is event-based so its API is less intuitive.
2) Clients never know the full information because the data is broken into pieces.
XML VALIDATION:
A well formed XML document can be validated against DTD or Schema.
A well-formed XML document is an XML document with correct syntax. It is very
necessary to know about valid XML document before knowing XML validation.
Valid XML document
It must be well formed (satisfy all the basic syntax condition)
It should be behave according to predefined DTD or XML schema
Rules for well formed XML
o It must begin with the XML declaration.
o It must have one unique root element.
o All start tags of XML documents must match end tags.
o XML tags are case sensitive.
o All elements must be closed.
o All elements must be properly nested.
o All attributes values must be quoted.
o XML entities must be used for special characters.
3(ii) List the essential features of XML parsers. [May/June 16]
XML is widely used in the era of web development. It is also used to simplify data
storage and data sharing.
The main features or advantages of XML are given below.
1) XML separates data from HTML
If we need to display dynamic data in your HTML document, it will take a lot of
work to edit the HTML each time the data changes.
With XML, data can be stored in separate XML files. This way we can focus on
using HTML/CSS for display and layout, and be sure that changes in the
underlying data will not require any changes to the HTML.
With a few lines of JavaScript code, we can read an external XML file and update
the data content of your web page.
2) XML simplifies data sharing
In the real world, computer systems and databases contain data in incompatible
formats.
XML data is stored in plain text format. This provides a software- and hardware-
independent way of storing data.
This makes it much easier to create data that can be shared by different
applications.
3) XML simplifies data transport
One of the most time-consuming challenges for developers is to exchange data
between incompatible systems over the Internet.
Exchanging data as XML greatly reduces this complexity, since the data can be
read by different incompatible applications.
108
4) XML simplifies Platform change
Upgrading to new systems (hardware or software platforms), is always time
consuming.
Large amounts of data must be converted and incompatible data is often lost.
XML data is stored in text format. This makes it easier to expand or upgrade to
new operating systems, new applications, or new browsers, without losing data.
5) XML increases data availability
Different applications can access your data, not only in HTML pages, but also
from XML data sources.
With XML, your data can be available to all kinds of "reading machines"
(Handheld computers, voice machines, news feeds, etc), and make it more
available for blind people, or people with other disabilities.
6) XML can be used to create new internet languages
A lot of new Internet languages are created with XML.
Here are some examples:
o XHTML
o WSDL for describing available web services
o WAP and WML as markup languages for handheld devices
o RSS languages for news feeds
o RDF and OWL for describing resources and ontology
o SMIL for describing multimedia for the web
109
I've gone off the idea of progress.
It's overrated
</speech>
</scene>
This XML file doesn't contain any presentation information, which is contained in
the stylesheet.
Separating the document's content and the document's styling information allows
displaying the same document on different media (like screen, paper, cell phone),
and it also enables users to view the document according to their preferences and
abilities, just by modifying the style sheet.
The Stylesheet
Here are two templates from the stylesheet used to format the XML file. The full
stylesheet (which includes extra information on pagination and margins) is available.
...
<xsl:template match="FX">
<fo:block font-weight="bold">
<xsl:apply-templates/>
</fo:block>
</xsl:template>
<xsl:template match="speech[@speaker='Arthur']">
<fo:block background-color="blue">
<xsl:value-of select="@speaker"/>:
<xsl:apply-templates/>
</fo:block>
</xsl:template>
...
The stylesheet can be used to transform any instance of the DTD it was designed
for.
The first rule says that an FX element will be transformed into a block with a bold
font. <xsl:apply-templates/> is a recursive call to the template rules for the
contents of the current element.
The second template applies to all speech elements that have the speaker attribute
set to Arthur, and formats them as blue blocks within which the value speaker
attribute is added before the text.
XSL TRANSFORMATION
XSLT essentials and goals
XSLT is a transformation language for XML. That means, using XSLT, we could
generate any sort of other document from an XML document.
XSLT is a W3C XML language (the usual XML well-formedness criteria apply)
XSLT can translate XML into almost anything , e.g.:
wellformed HTML (closed tags)
any XML, e.g. yours or other XML languages like SVG, X3D
non XML, e.g. RTF (this is a bit more complicated)
110
An XSLT program is an XML document. It's top-level skeleton looks like this:
<?xml version="1.0"?>
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
....
</xsl:stylesheet>
Mandatory "elements"
An XML declaration on top of the file
A stylesheet root tag, including version and namespace attributes (as seen in the
example above):
version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
Association of XML and an XSLT file
XSLT was already implemented in IE 5.5., i.e. in the last millenium...
<?xml version="1.0" encoding="ISO-8859-1"?>
<?xml-stylesheet href="project.xsl" type="text/xsl" ?>
<yourxml>
....
</yourxml>
There exist various so-called XSLT processors. Most programming languages and all
well-know server-side scripting languages like PHP include an XSLT library. XML
editors usually include an XSLT processor.
Below is the complete code for a simple "Hello XSLT" example.
XML file (source)
hello.xml
<?xml version="1.0"?>
<?xml-stylesheet href="hello.xsl" type="text/xsl"?>
<page>
<title>Hello</title>
<content>Here is some content</content>
<comment>Written by DKS.</comment>
</page>
Wanted result document
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN"
"http://www.w3.org/TR/REC-html40/strict.dtd">
<html>
<head>
111
<title>Hello</title>
</head>
<body bgcolor="#ffffff">
<h1 align="center">Hello</h1>
<p align="center"> Here is some content</p>
<hr><i>Written by DKS</i>
</body>
</html>
The XSLT Stylesheet
hello.xslt
<?xml version="1.0"?>
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="page">
<html>
<head>
<title> <xsl:value-of select="title"/>
</title>
</head>
<body bgcolor="#ffffff">
<xsl:apply-templates/>
</body>
</html>
</xsl:template>
<xsl:template match="title">
<h1 align="center"> <xsl:apply-templates/> </h1>
</xsl:template>
<xsl:template match="content">
<p align="center"> <xsl:apply-templates/> </p>
</xsl:template>
<xsl:template match="comment">
<hr/> <i><xsl:apply-templates/> </i>
</xsl:template>
</xsl:stylesheet>
5(i). Explain in details about variables in PHP.
The main way to store information in the middle of a PHP program is by using a
variable.
Here are the most important things to know about variables in PHP.
All variables in PHP are denoted with a leading dollar sign ($).
The value of a variable is the value of its most recent assignment.
Variables are assigned with the = operator, with the variable on the left-hand side
and the expression to be evaluated on the right.
Variables can, but do not need, to be declared before assignment.
Variables in PHP do not have intrinsic types - a variable does not know in
advance whether it will be used to store a number or a string of characters.
Variables used before they are assigned have default values.
112
PHP does a good job of automatically converting types from one to another when
necessary.
PHP variables are Perl-like.
PHP has a total of eight data types which we use to construct our variables
Integers are whole numbers, without a decimal point, like 4195.
Doubles are floating-point numbers, like 3.14159 or 49.1.
Booleans have only two possible values either true or false.
NULL is a special type that only has one value: NULL.
Strings are sequences of characters, like 'PHP supports string operations.'
Arrays are named and indexed collections of other values.
Objects are instances of programmer-defined classes, which can package up
both other kinds of values and functions that are specific to the class.
Resources are special variables that hold references to resources external to
PHP (such as database connections).
The first five are simple types, and the next two (arrays and objects) are compound - the
compound types can package up other arbitrary values of arbitrary type, whereas the
simple types cannot.
Integers
They are whole numbers, without a decimal point, like 4195.
They are the simplest type .
They correspond to simple whole numbers, both positive and negative.
Integers can be assigned to variables, or they can be used in expressions
$int_var = 12345;
$another_int = -12345 + 12345;
Integer can be in decimal (base 10), octal (base 8), and hexadecimal (base 16)
format. Decimal format is the default, octal integers are specified with a leading
0, and hexadecimals have a leading 0x.
For most common platforms, the largest integer is (2**31 . 1) (or 2,147,483,647),
and the smallest (most negative) integer is . (2**31 . 1) (or .2,147,483,647).
Doubles
They like 3.14159 or 49.1. By default, doubles print with the minimum number of
decimal places needed. For example
<?php
$many = 2.2888800;
$many_2 = 2.2111200;
$few = $many + $many_2;
print("$many + $many_2 = $few <br>");
?>
It produces the following browser output
2.28888 + 2.21112 = 4.5
Boolean
They have only two possible values either true or false. PHP provides a couple of
constants especially for use as Booleans: TRUE and FALSE.
if (TRUE)
print("This will always print<br>");
else
print("This will never print<br>");
Interpreting other types as Booleans
Here are the rules for determine the "truth" of any value not already of the Boolean type
113
If the value is a number, it is false if exactly equal to zero and true otherwise.
If the value is a string, it is false if the string is empty (has zero characters) or is
the string "0", and is true otherwise.
Values of type NULL are always false.
If the value is an array, it is false if it contains no other values, and it is true
otherwise. For an object, containing a value means having a member variable that
has been assigned a value.
Valid resources are true (although some functions that return resources when they
are successful will return FALSE when unsuccessful).
Don't use double as Booleans.
Each of the following variables has the truth value embedded in its name when it is used
in a Boolean context.
$true_num = 3 + 0.14159;
$true_str = "Tried and true"
$true_array[49] = "An array element";
$false_array = array();
$false_null = NULL;
$false_num = 999 - 999;
$false_str = "";
NULL
NULL is a special type that only has one value: NULL. To give a variable the NULL
value, we can simply assign it like this
$my_var = NULL;
The special constant NULL is capitalized by convention, but actually it is case
insensitive.
$my_var = null;
A variable that has been assigned NULL has the following properties
It evaluates to FALSE in a Boolean context.
It returns FALSE when tested with IsSet() function.
Strings
They are sequences of characters, like "PHP supports string operations". Following are
valid examples of string
$string_1 = "This is a string in double quotes";
$string_2 = "This is a somewhat longer, singly quoted string";
$string_39 = "This string has thirty-nine characters";
$string_0 = ""; // a string with zero characters
Singly quoted strings are treated almost literally, whereas doubly quoted strings replace
variables with their values as well as specially interpreting certain character sequences.
<?php
$variable = "name";
$literally = 'My $variable will not print!';
print($literally);
print "<br>";
114
There are no artificial limits on string length - within the bounds of available memory,
you ought to be able to make arbitrarily long strings.
Strings that are delimited by double quotes (as in "this") are preprocessed in both the
following two ways by PHP
Certain character sequences beginning with backslash (\) are replaced with special
characters
Variable names (starting with $) are replaced with string representations of their
values.
The escape-sequence replacements are
\n is replaced by the newline character
\r is replaced by the carriage-return character
\t is replaced by the tab character
\$ is replaced by the dollar sign itself ($)
\" is replaced by a single double-quote (")
\\ is replaced by a single backslash (\)
5(ii). Explain in detail about built in functions in PHP.
Functions are reusable bits of code that you use throughout a project.
They help to better organize your application as well as eliminate the need to
copy/paste repetitive pieces of code.
In an ideal world an application should not have multiple functions doing the same
thing.
PHP has a lot of built in functions
STRING MANIPULATION FUNCTIONS
Some of the most useful PHP functions are string manipulation functions. As the name
suggests they manipulate strings.
FINDING THE LENGTH OF A STRING
The strlen() functions works by passing a string or variable and then returns the total
number of characters including spaces.
<?php
$name = "Matthew ";
echo strlen($name); // 8
?>
RETURN PART OF A STRING
The substr() function is used to return a substring or part of a string. This function has 3
parameters which we can pass along.
Syntax
substr($string, $start,$length);
$string a string of text or a variable containing a string of text. Input must be at least
one character.
$start think of the string as an array starting from [0]. If we wanted to start from the
first character you would enter 0. A negative value will go to the end of the string.
$length (Optional) is the number of characters returned after the start character. If this
value is less than or equal to the start value then it will return false.
<?php
$name = "Matthew ";
echo substr($name, 0, 5); // Matth
echo substr($name, 2); // tthew
echo substr($name, -6, 5); // tthew
?>
CONVERTING STRINGS TO UPPER OR LOWER CASE
Two useful string functions that are simple to use are strtoupper() and strtolower(), these
functions can convert your strings to all UPPERCASE or all lowercase.
115
They are very useful for case sensitive operations where you may require all characters to
be lowercase for example.
<?php
$name = "Matthew ";
echo strtoupper($name); // MATTHEW
echo strtolower($name); // matthew
?>
Searching for a needle in a haystack!
Sometimes we need to find a substring within a string and to do that we can use strpos.
Syntax
strpos ($haystack,$needle,$offset)
$haystack this is the string in which you are going to find the $needlestarting from [0].
$needle this is what you are going to search for in the $haystack.
$offset (Optional) search will start from this number of characters counted from the
beginning of the string.It cannot be negative.
<?php
$name = "Matthew ";
echo strpos($name, "M"); // 0
echo strpos($name, "hew"); // 4
echo strpos($name, "m"); // false
?>
This function is case sensitive and could not find a match.
We can almost make use of an if statement and some variables to make the strops
function more useful and meaningful.
<?php
$string = "I am learning how to use PHP string functions!";
$search = "JavaScript";
if(strpos($string, $search) === false) {
echo "Sorry we could not find '$search' in '$string'.";
}
?>
This would echo Sorry we could not find JavaScript in I am learning how to use PHP
string functions!.
ARITHMETIC MANIPULATION FUNCTIONS
As well as string manipulation function, PHP also has functions to manipulate numbers.
ROUNDING NUMBERS
One of the most commonly used math function is round(). This function rounds numbers
with decimal points up or down. We can round a number to an integer (whole number) or to a
floating point (decimal numbers).
Syntax
round($val, $precision, $mode)
$val is the value to be rounded.
$precision (optional) number of decimal places to round to.
$mode the type of rounding that occurs
<?php
$number = 3.55776232;
echo
round($number) . "<br/>". // 4
round($number, 1) . "<br/>". // 3.6
round($number, 3) . "<br/>"; // 3.558
?>
Other math functions for rounding are ceil() and floor() . To round a number to the
nearest whole number, these functions are better suited to that purpose.
ceil() rounds fractions up.
floor() rounds fractions down.
<?php
$number = 3.55776232;
116
echo
ceil($number) . "<br/>". // 4
floor($number) . "<br/>"; // 3
?>
Both functions require a value and unlike round(), do not have any additional parameters.
GENERATING RANDOM NUMBERS
Another very common math function is rand() which returns a random number between
two numbers.
Syntax
rand($min, $max)
$min (optional) sets the lowest value to be returned. Default is 0
$max (optional) sets the maximum value to be returned. Default returns get randmax().
We will need to specify a $max value in order to return a larger number.
<?php
echo rand(). "\n"; //10884
echo rand(). "\n"; // 621
echo rand(2, 10); //2
?>
ARRAY FUNCTIONS
Array or array() is itself a function that stores multiple values in to a single variable.
Aside from the array() function there are a number of other functions to manipulate
arrays, here we will look at some of the most common ones.
ADDING NEW ELEMENTS
Adding new elements to the end of an array can be achieved by calling the
array_push() function.
Syntax
array_push($array, $value1, $value2)
$array the array in which you are adding new elements to.
$value1 (required) is the first value to push onto the end of the $array.
$value2 (optional) is the second value to push onto the end of the $array.
You can push as many values as you need.
<?php
$games = array();
$array = array_push($games, "Farcry 4");
$array = array_push($games, "Fallout 4");
$array = array_push($games, "Metal Gear");
$array = array_push($games, "Witcher 3");
echo $array; // returns 4
var_dump($games);
?>
However it is better to list each element in a single call like this:
<?php
$games = array(); // target array
$array = array_push($games,
"Farcry 4",
"Fallout 4",
"Metal Gear",
"Witcher 3");
echo $array; // returns 4
var_dump($games);
?>
Both methods result in the same outcome. If you echo or print array_push() it will return
the number of items to be pushed in to the array.
If you var_dump() the target array you you will see something like this.
array(4) {
[0] => string(8) "Farcry 4"
[1] => string(9) "Fallout 4"
117
[2] => string(10) "Metal Gear"
[3] => string(9) "Witcher 3"
}
SORTING AN ARRAY
As well as adding items to an array we sometimes need to be able to sort them. PHP has a
handy function called funnily enough sort() to do just that.
Syntax
sort($array, $sort_flags)
$array the array in which you wish to sort.
$sort_flags (optional) modifies the sorting behavior.
By default the sorting behavior will reorganize an array alphabetically or numerically.
<?php
$games = array( "Farcry 4", "Metal Gear", "Fallout 4", "Witcher 3",
"Batman");
sort($games); // array to sort
echo join(", ", $games);
//output - Batman, Fallout 4, Farcry 4, Metal Gear, Witcher 3
?>
In order to echo or print out sorted arrays we can use a function called join()which is an
alias of another function called implode().
join(glue, array) or implode(glue, array) functions return a string from the elements of an
array and both have the same syntax.
glue (optional) also known as a separator is what to put between the array elements.
array (required) is the array to join to a string.
If you need to sort and reverse the order of any array then you can use a function
called rsort(). It works exactly the same way as sort() except the output is reversed.
<?php
$games = array( "Farcry 4", "Metal Gear", "Fallout 4", "Witcher 3",
"Batman");
rsort($games); // array to sort
echo join(", ", $games);
//output - Witcher 3, Metal Gear, Farcry 4, Fallout 4, Batman
?>
118
The expires field is an instruction to the browser to "forget" the cookie after the
given time and date.
If the browser is configured to store cookies, it will then keep this information
until the expiry date.
If the user points the browser at any page that matches the path and domain of the
cookie, it will resend the cookie to the server.
The browser's headers might look something like this
GET / HTTP/1.0
Connection: Keep-Alive
User-Agent: Mozilla/4.6 (X11; I; Linux 2.2.6-15apmac ppc)
Host: zink.demon.co.uk:1126
Accept: image/gif, */*
Accept-Encoding: gzip
Accept-Language: en
Accept-Charset: iso-8859-1,*,utf-8
Cookie: name=xyz
A PHP script will then have access to the cookie in the environmental variables
$_COOKIE or $HTTP_COOKIE_VARS[] which holds all cookie names and
values. Above cookie can be accessed using $HTTP_COOKIE_VARS["name"].
SETTING COOKIES WITH PHP
PHP provided setcookie() function to set a cookie. This function requires upto six
arguments and should be called before <html> tag. For each cookie this function
has to be called separately.
setcookie(name, value, expire, path, domain, security);
Here is the detail of all the arguments
Name This sets the name of the cookie and is stored in an environment variable called
HTTP_COOKIE_VARS. This variable is used while accessing cookies.
Value This sets the value of the named variable and is the content that you actually
want to store.
Expiry This specify a future time in seconds since 00:00:00 GMT on 1st Jan 1970.
After this time cookie will become inaccessible. If this parameter is not set then cookie
will automatically expire when the Web Browser is closed.
Path This specifies the directories for which the cookie is valid. A single forward slash
character permits the cookie to be valid for all directories.
Domain This can be used to specify the domain name in very large domains and must
contain at least two periods to be valid. All cookies are only valid for the host and domain
which created them.
Security This can be set to 1 to specify that the cookie should only be sent by secure
transmission using HTTPS otherwise set to 0 which mean cookie can be sent by regular
HTTP.
Following example will create two cookies name and age these cookies will be expired
after one hour.
<?php
setcookie("name", "John Watkin", time()+3600, "/","", 0);
setcookie("age", "36", time()+3600, "/", "", 0);
?>
<html>
<head>
<title>Setting Cookies with PHP</title>
</head>
<body>
<?php echo "Set Cookies"?>
</body>
</html>
119
ACCESSING COOKIES WITH PHP
PHP provides many ways to access cookies. Simplest way is to use either $_COOKIE or
$HTTP_COOKIE_VARS variables. Following example will access all the cookies set in
above example.
<html>
<head>
<title>Accessing Cookies with PHP</title>
</head>
<body>
<?php
echo $_COOKIE["name"]. "<br />";
/* is equivalent to */
echo $HTTP_COOKIE_VARS["name"]. "<br />";
/* is equivalent to */
echo $HTTP_COOKIE_VARS["name"] . "<br />";
?>
</body>
</html>
We can use isset() function to check if a cookie is set or not.
<html>
<head>
<title>Accessing Cookies with PHP</title>
</head>
<body>
<?php
if( isset($_COOKIE["name"]))
echo "Welcome " . $_COOKIE["name"] . "<br />";
else
echo "Sorry... Not recognized" . "<br />";
?>
</body>
</html>
DELETING COOKIE WITH PHP
Officially, to delete a cookie you should call setcookie() with the name argument only but
this does not always work well, however, and should not be relied on.
It is safest to set the cookie with a date that has already expired
<?php
setcookie( "name", "", time()- 60, "/","", 0);
setcookie( "age", "", time()- 60, "/","", 0);
?>
<html>
<head>
<title>Deleting Cookies with PHP</title>
</head>
<body>
<?php echo "Deleted Cookies" ?>
120
</body>
</html>
3 p? It matches any string containing zero or more p's. This is just an alternative way to
use p*.
121
8 ^p It matches any string with p at the beginning of it.
Examples
Following examples will clear our concepts about matching characters.
Sr.No Expression & Description
1 [^a-zA-Z]
It matches any string not containing any of the characters ranging from a through z
and A through Z.
2 p.p
It matches any string containing p, followed by any character, in turn followed by
another p.
3 ^.{2}$
It matches any string containing exactly two characters.
4 <b>(.*)</b>
It matches any string enclosed within <b> and </b>.
5 p(hp)*
It matches any string containing a p followed by zero or more instances of the
sequence php.
1 [[:alpha:]]
It matches any string containing alphabetic characters aA through zZ.
2 [[:digit:]]
It matches any string containing numerical digits 0 through 9.
3 [[:alnum:]]
It matches any string containing alphanumeric characters aA through zZ and 0
through 9.
4 [[:space:]]
It matches any string containing a space.
122
1 ereg()
The ereg() function searches a string specified by string for a string specified by
pattern, returning true if the pattern is found, and false otherwise.
2 ereg_replace()
The ereg_replace() function searches for string specified by pattern and replaces
pattern with replacement if found.
3 eregi()
The eregi() function searches throughout a string specified by pattern for a string
specified by string. The search is not case sensitive.
4 eregi_replace()
The eregi_replace() function operates exactly like ereg_replace(), except that the
search for pattern in string is not case sensitive.
5 split()
The split() function will divide a string into various elements, the boundaries of
each element based on the occurrence of pattern in string.
6 spliti()
The spliti() function operates exactly in the same manner as its sibling split(),
except that it is not case sensitive.
7 sql_regcase()
The sql_regcase() function can be thought of as a utility function, converting
each character in the input parameter string into a bracketed expression
containing two characters.
123
Modifiers
Several modifiers are available that can make your work with regexps much easier, like
case sensitivity, searching in multiple lines etc.
Modifier Description
i Makes the match case insensitive
m Specifies that if the string has newline or carriage
return characters, the ^ and $ operators will now
match against a newline boundary, instead of a
string boundary
o Evaluates the expression only once
s Allows use of . to match a newline character
x Allows you to use white space in the expression for clarity
g Globally finds all matches
cg Allows a search to continue even after a global match fails
PHP's Regexp PERL Compatible Functions
PHP offers following functions for searching strings using Perl-compatible regular
expressions
Sr.No Function & Description
1 preg_match()
The preg_match() function searches string for pattern, returning true if pattern
exists, and false otherwise.
2 preg_match_all()
The preg_match_all() function matches all occurrences of pattern in string.
3 preg_replace()
The preg_replace() function operates just like ereg_replace(), except that regular
expressions can be used in the pattern and replacement input parameters.
4 preg_split()
The preg_split() function operates exactly like split(), except that regular
expressions are accepted as input parameters for pattern.
5 preg_grep()
The preg_grep() function searches all elements of input_array, returning all
elements matching the regexp pattern.
6 preg_ quote()
Quote regular expression characters
124
UNIT V
INTRODUCTION TO AJAX and WEB SERVICES
Part A
1. What is Ajax? What technologies are being used in AJAX?
Ajax is a set of client side technologies that provides asynchronous
communication between user interfaces and web server. So the advantages of using
Ajax are asynchronous communication, minimal data transfer and server is not
overloaded with unnecessary load.
AJAX uses four technologies, which are as follows:
JavaScript,
XMLHttpRequest,
Document Object Model (DOM),
Extensible HTML (XHTML) and
Cascading Style
Sheets (CSS)
2. What is the syntax to create AJAX objects?
AJAX uses the following syntax to create an object:
Var myobject = new AjaxObject("page path");
The page path is the URL of the Web page containing the object that you want
to call. The URL must be of the same domain as the Web page.
3. What are the different ways to pass parameters to the server?
We can pass parameters to the server using either the GET or POST method.
The following code snippets show the example of both the
methods:
Get: XmlHttpObject.Open("GET","file1.txt", true);
Post: XmlHttpObject.Open("POST", "file2.txt", true);
4. Define Web service?
A Web service is a method of communication between two electronic devices
over the web. The W3C defines a "Web service" as "a software system designed
to support interoperable machine-to-machine interaction over a network". It has
an interface described in a machine-processable format specifically Web Services
Description Language (WSDL).
5. What is meant by WSDL?
WSDL stands for Web Services Description Language
WSDL is based on XML
WSDL is used to describe Web services
WSDL is used to locate Web services
WSDL is an XML-based language for locating and describing Web
services
6. What is UDDI?
UDDI means Universal Description, Discovery and Integration.
UDDI - platform-independent framework for describing services, discovering
businesses, and integrating business services by using the Internet.
- directory for storing information about web services
125
- directory of web service interfaces described by WSDL
- communicates via SOAP
7. What are the core elements of UDDI?
UDDI defines four core data elements within the data model:
o businessEntity (modeling business information)
o businessService (describing a service)
o tModel (describing specifications, classifications, or identifications)
o binding Template (mapping between a businessService and the set of
tModels that describe its technical fingerprint)
8. What is SOAP?
SOAP - Simple Object Access Protocol
- protocol specification for exchanging structured information in the
implementation of Web Services in computer networks.
- relies on Extensible Markup Language (XML) for its message format,
and usually relies on other Application Layer protocols, most notably
Hypertext Transfer Protocol (HTTP) and Simple Mail Transfer
Protocol (SMTP), for message negotiation and transmission.
9. What are the specifications of web service architecture?
The specifications are
Standards based
Modular
Federated
General purpose
10. What is the use of web services?
o Web services encompass a set of related standards that can enable two
computers
o The data is passed back and forth using standard protocols such as
HTTP, the same protocol used to transfer ordinary web pages.
o Web services operate using open, text-based standards that enable
components written in different languages and on different platforms to
communicate.
o They are ready to use pieces of software on the Internet. XML,
SOAP, Web Services Description Language (WSDL) and Universal
Description, Discovery and Integration (UDDI) are the standards on which
web services rely.
o UDDI is another XML based format that enables developers and
business to publish and locate Web services on a network.
Part - B
1. Compare and contrast the traditional web application architecture and AJAX
based web application architecture?
Introduction
AJAX is an acronym for Asynchronous JavaScript and XML. It is a group of
inter-related technologies like javascript, dom, xml, html, css etc.
AJAX allows you to send and receive data asynchronously without reloading
the web page. So it is fast.
AJAX allows you to send only important information to the server not the
entire page. So only valuable data from the client side is routed to the server
side. It makes your application interactive and faster.
Where it is used?
126
There are too many web applications running on the web that are using ajax
technology like gmail, facebook,twitter, google map, youtube etc.
Synchronous (Classic Web-Application Model)
A synchronous request blocks the client until operation completes i.e. browser
is not unresponsive. In such case, javascript engine of the browser is blocked.
As we can see in the above image, full page is refreshed at request time and user is
blocked until request completes. Let's understand it another way.
127
Traditional web application architecture Vs AJAX based web application
architecture
2. How AJAX will work? Explain in detail about XMLHttpRequest and call back?
An object of XMLHttpRequest is used for asynchronous communication between
client and server. It performs following operations:
1. Sends data from the client in the background.
2. Receives the data from the server.
3. Updates the webpage without reloading it.
Properties of XMLHttpRequest object
The common properties of XMLHttpRequest object are as follows:
Property Description
onReadyStateChange It is called whenever readystate attribute changes. It must not be
used with synchronous requests.
readyState represents the state of the request. It ranges from 0 to 4.
0 UNOPENED open() is not called.
1 OPENED open is called but send() is not called.
2 HEADERS_RECEIVED send() is called, and headers and status
are available.
3 LOADING Downloading data; responseText holds the data.
4 DONE The operation is completed fully.
reponseText returns response as text.
responseXML returns response as XML
Methods of XMLHttpRequest object
The important methods of XMLHttpRequest object are as follows:
128
Method Description
void open(method, URL) opens the request specifying get or post
method and url.
void open(method, URL, async) same as above but specifies asynchronous
or not.
void open(method, URL, async, username, same as above but specifies username and
password) password.
void send() sends get request.
void send(string) send post request.
setRequestHeader(header,value) it adds request headers.
How AJAX works?
AJAX communicates with the server using XMLHttpRequest object. Let's try to
understand the flow of ajax or how ajax works by the image displayed below.
1. User sends a request from the UI and a javascript call goes to XMLHttpRequest
object.
2. HTTP Request is sent to the server by XMLHttpRequest object.
3. Server interacts with the database using JSP, PHP, Servlet, ASP.net etc.
4. Data is retrieved.
5. Server sends XML data or JSON data to the XMLHttpRequest callback function.
6. HTML and CSS data is displayed on the browser.
Ajax Example
To create ajax example, you need to use any server-side language e.g. servlet, jsp,
php, asp.net etc. Here we are using JSP for generating the server-side code.
In this example, we are simply printing the table of the given number.
Steps to create ajax example with jsp
1. load the org.json.jar file
2. create input page to receive any text or number
3. create server side page to process the request
4. provide entry in web.xml file
1. Load the org.json.jar file
download the org.json.jar file and save it in inside the WEB-INF/lib directory.
2. Create input page to receive any text or number
In this example, we have created a form that gets input from the user.
When user clicks on the showTable button, sendInfo()function is called. We
have written all the ajax code inside this function.
129
We have called the getInfo() function whenever ready state changes.
It writes the returned data in the web page dynamically by the help
of innerHTML property.
table1.html
<html>
<head>
<script>
var request;
function sendInfo()
{
var v=document.vinform.t1.value;
var url="index.jsp?val="+v;
if(window.XMLHttpRequest){
request=new XMLHttpRequest();
}
else if(window.ActiveXObject){
request=new ActiveXObject("Microsoft.XMLHTTP");
}
try
{
request.onreadystatechange=getInfo;
request.open("GET",url,true);
request.send();
}
catch(e)
{
alert("Unable to connect to server");
}
}
function getInfo(){
if(request.readyState==4){
var val=request.responseText;
document.getElementById('amit').innerHTML=val;
}
}
</script>
</head> <body>
<marquee><h1>This is an example of ajax</h1></marquee>
<form name="vinform">
<input type="text" name="t1">
<input type="button" value="ShowTable" onClick="sendInfo()">
</form>
<span id="amit"> </span>
</body>
</html>
3. Create server side page to process the request
index.jsp
<%
int n=Integer.parseInt(request.getParameter("val"));
for(int i=1;i<=10;i++)
130
out.print(i*n+"<br>");
%>
4. web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
<session-config>
<session-timeout> 30 </session-timeout>
</session-config>
<welcome-file-list>
<welcome-file>table1.html</welcome-file>
</welcome-file-list>
</web-app>
Output
131
A web service is a collection of open protocols and standards used for
exchanging data between applications or systems. Software applications written
in various programming languages and running on various platforms can use web
services to exchange data over computer networks like the Internet in a manner
similar to inter-process communication on a single computer. This
interoperability (e.g., between Java and Python, or Windows and Linux
applications) is due to the use of open standards.
To summarize, a complete web service is, therefore, any service that:
Is available over the Internet or private (intranet) networks
Uses a standardized XML messaging system
Is not tied to any one operating system or programming language
Is self-describing via a common XML grammar
Is discoverable via a simple find mechanism
Components of Web Services
The basic web services platform is XML + HTTP. All the standard web services
work using the following components
SOAP (Simple Object Access Protocol)
UDDI (Universal Description, Discovery and Integration)
WSDL (Web Services Description Language)
Working of Web Service
A web service enables communication among various applications by using open
standards such as HTML, XML, WSDL, and SOAP. A web service takes the help of:
XML to tag the data
SOAP to transfer a message
WSDL to describe the availability of service.
Example
Consider a simple account-management and order processing system. The
accounting personnel use a client application built with Visual Basic or JSP to create
new accounts and enter new customer orders.
The processing logic for this system is written in Java and resides on a Solaris
machine, which also interacts with a database to store information.
The steps to perform this operation are as follows:
The client program bundles the account registration information into a SOAP
message.
This SOAP message is sent to the web service as the body of an HTTP POST
request.
The web service unpacks the SOAP request and converts it into a command that
the application can understand.
The application processes the information as required and responds with a new
unique account number for that customer.
Next, the web service packages the response into another SOAP message, which
it sends back to the client program in response to its HTTP request.
The client program unpacks the SOAP message to obtain the results of the
account registration process.
Web Services - Architecture
There are two ways to view the web service architecture:
The first is to examine the individual roles of each web service actor.
The second is to examine the emerging web service protocol stack.
132
Web Service Roles
There are three major roles within the web service architecture:
1. Service Provider
a. This is the provider of the web service. The service provider implements
the service and makes it available on the Internet.
2. Service Requestor
a. This is any consumer of the web service. The requestor utilizes an existing
web service by opening a network connection and sending an XML
request.
3. Service Registry
a. This is a logically centralized directory of services. The registry provides a
central place where developers can publish new services or find existing
ones. It therefore serves as a centralized clearing house for companies and
their services.
Web Service Protocol Stack
A second option for viewing the web service architecture is to examine the
emerging web service protocol stack. The stack is still evolving, but currently has four
main layers.
1. Service Transport
a. This layer is responsible for transporting messages between applications.
Currently, this layer includes Hyper Text Transport Protocol (HTTP),
Simple Mail Transfer Protocol (SMTP), File Transfer Protocol (FTP), and
newer protocols such as Blocks Extensible Exchange Protocol (BEEP).
2. XML Messaging
a. This layer is responsible for encoding messages in a common XML format
so that messages can be understood at either end. Currently, this layer
includes XML-RPC and SOAP.
3. Service Description
a. This layer is responsible for describing the public interface to a specific
web service. Currently, service description is handled via the Web Service
Description Language (WSDL).
4. Service Discovery
a. This layer is responsible for centralizing services into a common registry
and providing easy publish/find functionality. Currently, service discovery
is handled via Universal Description, Discovery, and Integration (UDDI).
Web Services - Components
XML-RPC
This is the simplest XML-based protocol for exchanging information between
computers.
XML-RPC is a simple protocol that uses XML messages to perform RPCs.
Requests are encoded in XML and sent via HTTP POST.
XML responses are embedded in the body of the HTTP response.
XML-RPC is platform-independent.
XML-RPC allows diverse applications to communicate.
A Java client can speak XML-RPC to a Perl server.
XML-RPC is the easiest way to get started with web services.
SOAP
SOAP is an XML-based protocol for exchanging information between computers.
133
SOAP is a communication protocol.
SOAP is for communication between applications.
SOAP is a format for sending messages.
SOAP is designed to communicate via Internet.
SOAP is platform independent.
SOAP is language independent.
WSDL
WSDL is an XML-based language for describing web services and how to
access them.
WSDL stands for Web Services Description Language.
WSDL was developed jointly by Microsoft and IBM.
WSDL is an XML based protocol for information exchange in decentralized and
distributed environments.
WSDL is the standard format for describing a web service.
WSDL definition describes 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 UDDI, an XML-based worldwide business registry.
WSDL is pronounced as 'wiz-dull' and spelled out as 'W-S-D-L'.
UDDI
UDDI is an XML-based standard for describing, publishing, and finding web
services.
UDDI stands for Universal Description, Discovery, and Integration.
UDDI is a specification for a distributed registry of web services.
UDDI is platform independent, open framework.
UDDI can communicate via SOAP, CORBA, and Java RMI Protocol.
UDDI uses WSDL to describe interfaces to web services.
UDDI is seen with SOAP and WSDL as one of the three foundation standards of
web services.
UDDI is an open industry initiative enabling businesses to discover each other
and define how they interact over the Internet.
4. Describe the structure of WSDL document, its elements and their purposes with
appropriate examples.
The Web Services Description Language (WSDL) is the most fundamental
technology standard associated with the design of services.
WSDL definitions are a central part of all aspects of service design.
Figure: The structure of a WSDL definition
134
The definitions element is the root or parent element of every WSDL
document.
It defines the name of the web service and specifies the namespaces that used
within WSDL documents are established.
Example
<definitions name="Employee"
targetNamespace="http://www.xmltc.com/tls/employee/wsdl/"
xmlns="http://schemas.xmlsoap.org/wsdl/"
xmlns:act="http://www.xmltc.com/tls/employee/schema/accounting/"
xmlns:hr="http://www.xmltc.com/tls/employee/schema/hr/"
xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/"
xmlns:tns="http://www.xmltc.com/tls/employee/wsdl/"
xmlns:xsd="http://www.w3.org/2001/XMLSchema">
...
</definitions>
Description
Xmlns - specifies default name space
Xmlns:tns-Means this namespace i.e namespace used for particular WSDL.
xmlns:xsd namespace declaration, all elements within the WSDL that belong to
the XML Schema Definition Language.
xmlns:act and xmlns:hr - also a namespace declarations.
xmlns:soap - establishes the soap: qualifier used by elements defined in the
bindings.
targetNameSpace - it lets the WSDL document make references to itself an an
XML schema namespace.
Figure: The WSDL types construct populated by XSD schema types used by
the message construct to represent the SOAP message body.
The SOAP message body contains XML content that can represent anything from
simple parameter data to complex business documents. This content can be formally
defined through types provided by the WSDL types area.
135
targetNamespace=
"http://www.xmltc.com/railco/transform/schema/">
<complexType name="ReturnCodeType">
<sequence>
<element name="Code" type="xsd:integer"/>
<element name="Message" type="xsd:string"/>
</sequence>
</complexType>
</schema>
</types>
The message and part elements
Message elements
Message element assigns the message a name and contains one or more part
child elements that each are assigned a type.
Message elements are associated to operation elements to establish the input
and output messages of the operation.
Part elements
Part elements use the type or element attributes to identify the data type of the
message part.
1. Type attribute
A simple or complex type and generally is used for RPC-style messages.
2. Element attribute
This can reference an XSD element.
The name attribute is used to uniquely identify part elements within a
message construct.
Example
Two message constructs likely representing the input and output messages for an
operation.
<message name="getEmployeeWeeklyHoursRequestMessage">
<part name="RequestParameter" element="act:EmployeeHoursRequestType"/>
</message>
<message name="getEmployeeWeeklyHoursResponseMessage">
<part name="ResponseParameter" element="act:EmployeeHoursResponseType/>
</message>
Example
A simple parameter message requiring just a single integer value.
<message name="getID">
<part type="xsd:integer"/>
</message>
The portType, interface, and operation elements
Service operations are defined within the portType area of the WSDL
definition.
portType constructs simply represent collections of operations
Individual operations are defined using the aptly named operation element.
Example
The portType construct hosting two operation constructs.
<portType name="EmployeeInterface">
<operation name="GetWeeklyHoursLimit">
...
136
</operation>
<operation name="UpdateHistory">
...
</operation>
</portType>
Example
An operation element with a single child input element.
<operation name="Submit">
<input message="tns:receiveSubmitMessage"/>
</operation>
The binding element
The binding element begins the concrete portion of the service definition, to
assign a communications protocol that can be used to access and interact with the
WSDL.
The binding construct contains one or more operation elements.
Example
The binding construct hosting concrete operation definitions.
<binding name="EmployeeBinding" type="tns:EmployeeInterface">
<soap:binding style="document"
transport="http://schemas.xmlsoap.org/soap/http"/>
<operation name="GetWeeklyHoursLimit">
<soap:operation soapAction="..."/>
...
</operation>
<operation name="UpdateHistory">
<soap:operation soapAction="..."/>
...
</operation>
</binding>
The style attribute of the soap:binding element defines whether the SOAP messages
used to support an operation are to be formatted as document or RPC-style messages.
The input and output elements (when used with binding)
Each operation element within a binding construct mirrors the input and
137
output message child elements defined in the abstract definition.
The input and output elements do not reference the message elements again.
It contains protocol details that establish how the messages are going to be
processed and interpreted by the chosen communication technology.
Example
Input and output elements providing message processing information.
<operation name="GetWeeklyHoursLimit">
<soap:operation soapAction="..."/>
<input>
<soap:body use="literal"/>
</input>
<output>
<soap:body use="literal"/>
</output>
</operation>
<operation name="UpdateHistory">
<soap:operation soapAction="..."/>
<input>
<soap:body use="literal"/>
</input>
<output>
<soap:body use="literal"/>
</output>
</operation>
This introduces the soap: body element from the SOAP language that defines the
data type system to be used by SOAP processors, via the use attribute. The use
attribute can be set to "encoding" or "literal".
The service, port, and endpoint elements
The service element simply provides a physical address at which the service
can be accessed.
It hosts the port element that contains this location information.
Example
The service and port elements establishing the physical service address.
<service name="EmployeeService">
<port binding="tns:EmployeeBinding" name="EmployeePort">
<soap:address
location="http://www.xmltc.com/tls/employee/"/>
</port>
</service>
Because we are binding to the SOAP protocol, the port element contains a child
soap:address element with the physical address information.
The import element
The import element can be used to import parts of the WSDL definition as
well as XSD schemas.
Example
The import element referencing a schema document.
<import namespace="http://www.xmltc.com/tls/schemas/"
location="http://www.xmltc.com/tls/schemas/employee.xs d"/>
The documentation element
138
This optional element simply allows u s to add descriptive, human-readable
annotations within a WSDL definition.
Example
The documentation element providing a description of the overall service interface.
<portType name="TransformInterface">
<documentation>
Retrieves an XML document and converts it into the
native accounting document format.
</documentation>
...
</portType>
5. Explain in detail about the structure of SOAP protocol with example?
139
Example
The Header construct hosting a header block.
<Header>
<x:CorrelationID xmlns:x="http://www.xmltc.com/tls/headersample/"
mustUnderstand="1">
0131858580-JDJ903KD
</x:CorrelationID>
</Header>
The Body element
This is the one required child element of the SOAP Envelope construct.
SOAP message Body constructs are defined within the WSDL message
constructs.
A SOAP message body defined within the WSDL message constructs. The
actual processing of the SOAP message via a wire protocol is governed by the
constructs within the concrete definition
Example
The contents of a sample Body construct.
<Body>
<soa:book xmlns:soa="http://www.serviceoriented.ws/">
<soa:ISBN>
0131858580
</soa:ISBN>
<soa:title>
Service-Oriented Architecture
Concepts, Technology, and Design
</soa:title>
</soa:book>
</Body>
The Fault element
The optional Fault construct provides a ready made error response that is
added inside the Body construct.
The fault code element contains one of a set of fault conditions predefined by
the SOAP specification.
Example
140
The Fault constructs residing within the Body construct.
<Body>
<Fault>
<faultcode>
MustUnderstand
</faultcode>
<faultstring>
header was not recognized
</faultstring>
<detail>
<x:appMessage
xmlns:x="http://www.xmltc.com/tls/faults">
The CorrelationID header was not
processed by a recipient that was
required to process it. Now a fault's been
raised and it looks like this recipient is
going to be a problem.
</x:appMessage>
</detail>
</Fault>
</Body>
141
Industrial/Practical Connectivity of the subject
1. Relate effectively to web development supervisors, coworkers, and clients.
2. Configure and maintain internet services, internet application servers, database
servers, and network services.
3. Construct, modify, implement, query, and maintain effective databases, and
interface with applications.
4. Develop internet services and web application security by applying appropriate
techniques and strategies.
5. Program and debug internet applications using a variety of client-side and
serverside development languages.
6. Develop, deploy, and maintain electronic commerce (e-commerce) applications.
7. Create and maintain functional and dynamic websites by applying graphic and
web design skills and principles.
8. Develop and maintain websites reflective of business objectives and clients` needs
through the application of advertising and marketing principles.
9. Coordinate or participate as a member of a project management team that
develops internet applications.
10. Develop strategies for ongoing personal and professional development that will
lead to enhanced work performance and career opportunities, and keep pace with
industry changes.
11. Identify and apply discipline-specific practices that contribute to the local and
global community through social responsibility, economic commitment and
environmental stewardship.
142
B.E/ B.Tech. DEGRE EXAMINATION, NOVEMBER/DECEMBER 2015
Fifth Semester
Computer Science and Engineerring
CS6501 Internet Programming
(Regulations 2013)
Time: Three hours Maximum:100 marks
Answer ALL questions
Part- A (10x2=10 marks)
1. Define an abstract class. Give example.
2. Expand DOM, AJAX, AWT, JDBC.
3. List the unique features of java.
4. Differentiate internet and intranet.
5. What are cookies? Give its uses.
6. Define event programming. Name any 2 of its techniques.
7. What is XML parse tree?
8. Name any four built in functions in PHP.
9. What is a web service? Give any four examples.
143
10. List any four merits for usage of AJAX in web services.
Part B-(5x16=80 marks)
11 (a) (i) Write a Java program to draw smiley using applet. (10)
(ii) Compare overloading and overriding. (6)
Or
(b) Discuss the following:
(i) Multithreading in java (8)
(ii) Exception handling in Java (8)
12.(a) Discuss on
(i) web servers (8)
(ii) XHTML (8)
Or
(b) Elaborate with example the usage of CSS in HTML (16)
13.(a) Using HTML and JSP, design a scientific calculator (16)
Or
(b) Explain
(i) DOM model (8)
(ii) Database connectivity (8)
14.(a) Write a PHP program to do string manipulations (16)
Or
(b) Explain in detail about
(i) XML schema (8)
(ii) XML parsers and validation (8)
15. (a) Discuss Ajax client server architecture in detail (16)
Or
(b) Write short notes on:
(i) SOAP (8)
(ii) WSDL (8)
144
6. Write the code segment to store current server time in session using java
servlet API.
7. Why is XSLT an important tool in development of work applications?
8. When should the super global arrays in PHP be used? Which super global
array in PHP would contain a HTML forms POST data?
9. Draw the structure of a SOAP message.
10. What is the role of callback function in performing a partial page update in an
AJAX application?
Part B (5x16=80 marks)
11 (a)Consider a scenario where one thread ( Producer) is producing integer
data starting from 0 and another thread (consumer) consuming it. In
addition, assume that the producer has to wait until the consumer is finished
consuming before it generates more data. Using java interprocess
communication mechanism implement the above producer and consumer.
OR
(b) Write a java program to find the sum of the digits of the given number.
Create a swing GUI to get an input number and show the sum of its digits. In
case the sum cannot be found due to incorrect input should print Not able to
find the sum. Check input.
12(a) Write a brief note on each one of the following RIA technologies
AJAX
Flex
Silverlight
JavaFx
OR
(b) Write the HTML 5 code for creating a feedback form as shown below.
Include comments in the code to highlight the markup elements and their purpose.
The HTML form should use POST for submitting the form to a program
ProcessContactForm.php
Internet Programming
Contact Form
Name *
Email Address *
Telephone
Enquiry*
Message*
General
Your message must be greater than
20 characters
* indicates a required field
Hello!
13(a) Use javascript and HTML to create a page with two panes. The first pane( on
the left) should have a text area where HTML code can be typed by the user. The
pane on the right side should display the preview of the HTML code typed by the
user, as it would be seen on the browser.
OR
(b) Assume that database has a table Employee with two columns. EmployeeID
and Name. Assume that the administrator user id and password to access the
database table are, scott and tiger. Write a JDBC program that can query and print
all the entries in the table Employee. Make the database connection using a type2
driver database.driver and connection string jdbc:db:oci (16)
14 (a) Create a Webserver based chat applications using PHP. The application
should provide the following functions (16)
Login
145
Send message(to one or more contacts)
Receive messages ( from one or more contacts)
Add/ delete/ modify contact list of the user
Discuss the applications user interface and use comments in PHP to explain
the code clearly.
OR
(b) (i) List the essential features of XML parsers. (8)
(ii) List at least five significant differences between DID and XML schema for
defining XML document structures with appropriate examples. (8)
15(a) Compare and contrast the traditional web application architecture and
AJAX based web application architecture. (16)
OR
(b) Describe the structure of a WSDL document, its elements and their purposes
with appropriate examples (16)
146