CS6501 SCAD MSM by WWW - Learnengineering.in
CS6501 SCAD MSM by WWW - Learnengineering.in
in
ENGINEERING COLLEGES
Department of CSE
ANNA UNIVERSITY
SYLLABUS COPY (REGULATION 2013)
TABLE OF CONTENTS
Sl.No Topic Page No
a Aim and Objective of the Subject 1
b Detailed Lesson Plan 2
UNIT I JAVA PROGRAMMING
c Part A 6
d Part B 8
1 Multithreading 8
2 Exception Handling 11
3 Data types and Array 16
4 Inheritance 19
5 Operators 22
6 String handling 30
7 Applet 31
UNIT II WEBSITES BASICS, HTML 5, CSS 3, WEB 2.0
e Part A 37
f Part B 39
8 Rich Internet Applications 39
9 HTML 48
10 Cascading Style Sheet 55
11 XHTML 58
12 Tables 66
UNIT III CLIENT SIDE AND SERVER SIDE PROGRAMMING
g Part A 71
h Part B 72
13 Document Object Model 77
14 Database connectivity 79
15 Javascript 80
16 Java Servlet 88
17 Cookies 90
UNIT IV PHP and XML
i Part A 98
j Part B 101
18 XML 102
19 XML Parser and Validation 105
20 XSL and XSLT 107
21 PHP 110
22 Cookies 116
23 Regular Expression 118
UNIT V INTRODUCTION TO AJAX and WEB SERVICES
k Part A 122
l Part B 124
24 AJAX 124
25 AJAX with XMLHttpRequest and call back 125
26 Webservices 128
27 WSDL 131
28 SOAP 136
m Industrial/Practical Connectivity of the subject 139
29 University Question Bank 140
30 University Question Programs 143
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
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.
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.
PART-B
1. Describe the following
(i) Multithreading in java
(ii) Exception handling in java [Nov/Dec 2015]
(Or)
(i) Explain how the multiple programs are running simultaneously.
(ii) Explain how exceptions are handled in JAVA.
(Or)
(i) Explain about the life cycle of threads.
(ii) Describe about the method of handling the errors in JAVA.
(i) Multithreading
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()
{
10
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.
Example
class ThreadDemo implements Runnable
{
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");
}
}
11
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");
}
}
Output: (Order can change)
ONE
ONE
TWO
TWO
TWO
THREE
THREE
12
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
Catch
The syntax is
try
{
......
throw exception;
}
catch(type arg)
{
.....
.....
}
The catch block must be present immediately after the try block.
13
14
}
catch(ExceptionType e1)
{
//Statements
}
catch(ExceptionType e2)
{
//Statements
}
class Exception
{
public static void main(String []args)
{
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");
}
}
15
}
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 args[])
{
int a=10,b=0,c;
try
{
c=a/b;
}
catch(ArithmeticException e)
{
System.out.println("Divide by 0");
}
finally
{
System.out.println("Exiting..");
}
}
}
User Defined Exception
We can throw our own exception using the keyword throw
throw new classname
Example
import java.lang.Exception
class MyOwnException extends Exception
{
MyOwnException(String s)
{
super(s);
16
}
}
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);
}
}
17
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)
{
18
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));
}
}
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);
}
19
}
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)
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.
20
21
Syntax
dataType[] arrayRefVar;
Example
double[] myList;
Creating Arrays
We can create an array by using the new operator with the following syntax:
arrayRefVar =new dataType[arraySize];
• It creates an array using new dataType[arraySize];
• It assigns the reference of the newly created array to the variable arrayRefVar.
Declaring an array variable, creating an array, and assigning the reference of the
array to the variable can be combined in one statement, as shown below:
22
{
double[] myList ={1.9,2.9,3.4,3.5};
// Print all the array elements
for(int i =0; i < myList.length; i++)
{
System.out.println(myList[i]+" ");
}
// 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)
23
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
B
DERIVED CLASS
Example
class A
{
public:
int a;
void seta(int i)
{
a=i;
}
void puta()
{
System.out.println(a);
}
}
class B extends A
{
public:
int b;
24
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
B
Intermediate Base Class
Example C
class A
{
public:
int a;
void seta(int i)
{
a=i;
}
25
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);
26
obj.setc(20);
obj.puta();
obj.putb();
obj.putc();
}
}
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:
The symbols of the arithmetic operators are
Operation Operator Comment Value of Sum before Value of sum after
Multiply * sum = sum * 2; 4 8
Divide / sum = sum / 2; 4 2
Addition + sum = sum + 2; 4 6
Subtraction - sum = sum -2; 4 2
Increment ++ ++sum; 4 5
Decrement -- --sum; 4 3
Modulus % sum = sum % 3; 4 1
Example
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);
}
}
27
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)
{
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)
28
{
int count;
for( count = 1; count <= 10; count = count + 1 )
System.out.println(count);
}
}
RELATIONALS (AND, NOT, OR, EOR)
Combining more than one condition
These allow the testing of more than one condition as part of selection statements. The
symbols are
LOGICAL AND &&
Logical and requires all conditions to evaluate as TRUE (non-zero).
LOGICAL OR ||
Logical or will be executed if any ONE of the conditions is TRUE (non-zero).
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.
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
29
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
This conditional expression operator takes THREE operators.
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
condition ? expression1 : expression2
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;
If x is less than zero then s = -1. If x is greater than zero then s = x * x
BIT OPERATIONS
Java has the advantage of direct bit manipulation and the operations available are,
30
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.
31
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.
32
Syntax
Package packagename;
{
/*Classes
Sub packages
Block of statements*/
}
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
33
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);
}
}
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();
}
}
34
Example
interface A
{
static final int val=10;
}
interface B extends A
{
void display();
}
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,...
{
...
...
35
}
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
36
{
v=i;
}
}
interface B
{
public void showv();
}
class C extends A implements B
{
public void showv()
{
System.out.println("V="+v);
}
}
37
String s1="Hello";
String s2="Sam";
System.out.println(s1.concat(s2));
(or)
System.out.println(s1+s2); will produce HelloSam
CharAt
Individual characters of a string can be accessed using charAt().
Syntax
s.charAt(positon);
Example String s="Hello";
s.charAt(3);
will produce l as output
Equals
Two strings can be compared using equals() method.
Syntax
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
38
39
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.
40
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.
41
42
43
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;
public class ExampleEventHandling extends Applet implements MouseListener {
StringBuffer strBuffer;
public void init() {
addMouseListener(this);
strBuffer = new StringBuffer();
addItem("initializing the apple ");
}
public void start() {
addItem("starting the applet ");
}
public void stop() {
addItem("stopping the applet ");
}
public void destroy() {
addItem("unloading the applet");
}
void addItem(String word) {
System.out.println(word);
strBuffer.append(word);
44
repaint();
}
public void paint(Graphics g) {
//Draw a Rectangle around the applet's display area.
g.drawRect(0, 0, getWidth() - 1, getHeight() - 1);
//display the string inside the rectangle.
g.drawString(strBuffer.toString(), 10, 20);
}
public void mouseEntered(MouseEvent event) {
}
public void mouseExited(MouseEvent event) {
}
public void mousePressed(MouseEvent event) {
}
public void mouseReleased(MouseEvent event) {
}
public void mouseClicked(MouseEvent event) {
addItem("mouse clicked! ");
}
}
Now, let us call this applet as follows:
<html>
<title>Event Handling</title>
<hr>
<applet code="ExampleEventHandling.class"
width="300" height="300">
</applet>
<hr>
</html>
Initially, the applet will display "initializing the applet. Starting the applet." Then once
you click inside the rectangle "mouse clicked" will be displayed as well.
45
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.
• 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.
46
47
48
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.
Code reuse was low, because the code was spread over a large amount of web
page scripts.
49
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.
50
Despite the better separation of GUI and application logic, the two domains still
often got intertwined in each other. Also, since the GUI logic was written in the
same language as the application logic, changing the programming language
meant rewriting the whole application again.
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.).
51
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
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.
52
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
Silverlight is a powerful development tool for creating engaging, interactive user
experiences for Web and mobile applications. Silverlight is a free plug-in, powered by
the .NET framework and compatible with multiple browsers, devices and operating
systems, bringing a new level of interactivity wherever the Web works.
JavaFx
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
53
Collaboration tools can route work through a process, distribute pieces and tasks to
involved parties, and help to coordinate activities.
54
the specifications. The accounting department specifies the terms for purchase, and the
legal department inserts language in the contract to protect both parties in the transaction.
Everyone uses a collaborative software platform to work together to get the job done,
regardless of where they're located.
Collaboration tools allow people to work on a common project wherever they are.
55
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.
Internet allows us to communicate with the people sitting at remote locations.
There are various apps available on the wed that uses Internet as a medium for
communication. One can find various social networking sites such as:
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.
Apart from communication and source of information, internet also serves a
medium for entertainment. Following are the various modes for entertainment
over internet.
o Online Television
o Online Games
o Songs
o Videos
o Social Networking Apps
Internet allows us to use many services like:
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
56
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.
Another disadvantage is the Spamming. Spamming corresponds to the unwanted
e-mails in bulk. These e-mails serve no purpose and lead to obstruction of entire
system.
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:
Intranet is system in which multiple PCs are networked to be connected to each
other. PCs in intranet are not available to the world outside of the intranet.
Usually each company or organization has their own Intranet network and
members/employees of that company can access the computers in their intranet.
Every computer in internet is identified by a unique IP address.
Each computer in Intranet is also identified by a IP Address, which is unique
among the computers in that Intranet.
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.
57
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
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.
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:
Document publication applications
Document publication applications allow publishing documents such as manuals,
software guide, employee profits etc without use of paper.
Electronic resources applications
It offers electronic resources such as software applications, templates and tools, to be
shared across the network.
Interactive Communication applications
58
Like on internet, we have e-mail and chat like applications for Intranet, hence offering
an interactive communication among employees.
Support for Internet Applications
Intranet offers an environment to deploy and test applications before placing them on
Internet.
Internet vs. Intranet
Apart from similarities there are some differences between the two. Following are the
differences between Internet and Intranet:
Intranet Internet
60
<!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.
61
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 −
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
62
<!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>
</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>
63
CSS Tutorial
JavaScript Tutorial
Once article can have multiple sections
This is aside part of the web page
Created by SCAD Group
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.
contenteditable true, false Specifies if the user can edit the element's content
or not.
64
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.
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
65
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 protected] 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.
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>
</head>
<body>
66
<output name="result"></output>
</form>
</body>
</html>
67
68
Internal styling is defined in the <head> section of an HTML page, within a <style>
element:
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;
69
}
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.
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 we cannot see it.
The CSS border property defines a visible border around an HTML element:
70
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;
}
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.
OR
Discuss on XHTML (Nov/Dec 2015)
71
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>
</html>
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.
72
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.
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>
XHTML Elements Must Be Properly Nested
In HTML, some elements can be improperly nested within each other, like this:
<b><i>This text is bold and italic</b></i>
In XHTML, all elements must be properly nested within each other, like this:
<b><i>This text is bold and italic</i></b>
XHTML Elements Must Always Be Closed
Example
<p>This is a paragraph</p>
<p>This is another paragraph</p>
Empty Elements Must Also Be Closed
Example
A break: <br />
A horizontal rule: <hr />
An image: <img src="happy.gif" alt="Happy face" />
XHTML Elements Must Be In Lower Case
Example
<body>
<p>This is a paragraph</p>
</body>
XHTML Attribute Names Must Be In Lower Case
<table width="100%">
Attribute Values Must Be Quoted
<table width="100%">
Attribute Minimization Is Forbidden
<input type="checkbox" name="vehicle" value="car" checked="checked" />
73
<br>
74
75
76
Example
<h2>HTML <small>Small</small> Formatting</h2>
HTML Marked Formatting
The HTML <mark> element defines marked or highlighted text:
Example
<h2>HTML <mark>Marked</mark> Formatting</h2>HTML Formatting
The HTML <del> element defines deleted (removed) text.
Example
<p>My favorite color is <del>blue</del> red.</p>
HTML Inserted Formatting
The HTML <ins> element defines inserted (added) text.
Example
<p>My favorite <ins>color</ins> is red.</p>
HTML Subscript Formatting
The HTML <sub> element defines subscripted text.
Example
<p>This is <sub>subscripted</sub> text.</p>
HTML Superscript Formatting
The HTML <sup> element defines superscripted text.
Example
<p>This is <sup>superscripted</sup> text.</p>
HTML Text Formatting Elements
Tag Description
77
78
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
If our 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">
79
80
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;">
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
81
Tag Description
In HTML we can create the table in the web page using tag name table. We can add the rows and
columns as per our requirements.
Example
<table 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>
Explanataion
Tables are defined with the <table> tag.
Tables are divided into table rows with the <tr> tag.
Table rows are divided into table data with the <td> tag.
A table row can also be divided into table headings with the <th> tag.
82
83
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>
</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>
84
<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>
<th>Savings</th>
</tr>
<tr>
<td>January</td>
<td>$100</td>
</tr>
<tr>
<td>February</td>
<td>$50</td>
</tr>
</table>
85
Tag Description
86
<col> Specifies column properties for each column within a <colgroup> element
87
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. Define event programming. Name any 2 of its techniques.(Nov/Dec 2015)
In computer programming, event-driven programming is a programming
paradigm in which the flow of the program is determined by events such as user
actions (mouse clicks, key presses), sensor outputs, or messages from other
programs/threads
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 vendor„s 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.
88
89
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.
Part-B (16 marks)
1. Using HTMl and JSP, design a scientific calculator [Nov/Dec 15]
Step-1: Creating the HTML file
Here, we are just creating a bunch of buttons and getting its values when they are
clicked.
<html>
<body>
<div id=”big_wrapper”>
<h1 id=”heading”>SIMPLE SCIENTIFIC CALCULATOR</h1>
<div id=”form_wrapper”>
<form id=”formone” name=”calc”>
<input id=”display” type=”text” name=”display” value=” ” disabled
contenteditable=”false” >
<br>
<input class=”button number” type=”button” value=”1” onClick=
”calc.display.value+=1”>
<input class=”button number” type=”button” value=”2” onClick=
”calc.display.value+=2”>
<input class=”button number” type=”button” value=”3” 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”>
90
91
92
function closepara(valval)
{
calc.display.value+=valval;
flag-=1;
}
function backspace(calc)
{
var size = calc.display.value.length;
calc.display.value=calc.display.value.substring(0,size-1);
}
function Resetfunction(calc)
{
calc.display.value=” “;
flag=0;
}
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;
93
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) {
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>
94
95
}
.three:hover{background-color:#F66;}
</style>
96
<TD>Aeolian</TD>
</TR>
<TR>
<TD>Over the River, Charlie</TD>
<TD>Dorian</TD>
</TR>
</ROWS>
</TABLE>
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.
97
98
99
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.
100
101
</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);
Property Description
constructor Returns the function that created the Date object's prototype
Method Description
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
102
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).
i is a modifier (modifies the search to be case-insensitive).
MODIFIERS
Modifiers are used to perform case-insensitive and global searches:
Modifier Description
103
BRACKETS
Brackets are used to find a range of characters:
Expression Description
METACHARACTERS
Metacharacters are characters with a special meaning:
Metacharacter Description
\d Find a digit
104
QUANTIFIERS
Quantifier Description
Property Description
105
Method Description
<html>
<head>
<script type="text/javascript">
<!--
function sayHello() {
alert("Hello World")
}
//-->
106
</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.
<html>
<head>
<script type="text/javascript">
<!--
function validation() {
all validation goes here
.........
return either true or false
}
//-->
</script>
</head>
<body>
107
.......
<input type="submit" value="Submit" />
</form>
</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>
108
Attribute Description
oncanplay Triggers when media can start play, but might has to stop for
buffering
109
8. Explain in detail about Java servlet architecture and its life cycle.
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.
110
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:
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.
111
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.
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.
1) Servlet class is loaded
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.
2) Servlet instance is created
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.
3) init method is invoked
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
112
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.
113
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
Method Description
public void setMaxAge(int expiry) Sets the maximum age of the cookie in seconds.
public String getName() Returns the name of the cookie. The name cannot
be changed after creation.
Creation of Cookie
Let's see the simple code to create cookie.
1. Cookie ck=new Cookie("user","sonoo jaiswal");//creating cookie object
114
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
115
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
2. web.xml
3. context.xml
4. tomcat-users.xml
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".
116
<!-- 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.
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.
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).
117
118
119
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'.
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:
Tag Description
<fmt:formatDate> Formats a date and/or time using the supplied styles and pattern
120
<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" %>
Following is the list of SQL JSTL Tags:
Tag Description
<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.
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/
121
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.
JSTL Functions
JSTL includes a number of standard functions, most of which are common string
manipulation functions. Following is the syntax to include JSTL Functions library in
your JSP:
<%@ taglib prefix="fn"
uri="http://java.sun.com/jsp/jstl/functions" %>
Following is the list of JSTL Functions:
Function Description
122
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 form’s POST data? [May/June 16]
123
addition();
echo $z;
?>
In the example above, since z is a variable present within the $GLOBALS array, it
is also accessible from outside the function
PHP $_POST is widely used to collect form data after submitting an HTML form
with method="post". $_POST is also widely used to pass variables.
$_SERVER['REQUEST_METHOD'] - Returns the request method used to access
the page (such as POST)
4. Name any four built-in functions in PHP. [Nov/Dec 15]
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.
124
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.
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:
125
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_database";
We should replace "our_username", "our_password" and "our_database" with the
MySQL username, password and database that will be used by our script.
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);
126
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
127
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
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().
128
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>
</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".
129
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]
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.
131
1) DTD stands for Document Type XSD stands for XML Schema Definition.
Definition.
3) DTD doesn't support datatypes. XSD supports datatypes for elements and
attributes.
5) DTD doesn't define order for child XSD defines order for child elements.
elements.
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:
132
133
134
135
136
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)
With XSLT we then can produce some "enriched" or otherwise transformed XML
or directly some other format that is used to render the contents.
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"
137
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.
<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.
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 −
139
<?php
$many = 2.2888800;
$many_2 = 2.2111200;
$few = $many + $many_2;
print("$many + $many_2 = $few <br>");
?>
140
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
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.
141
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>";
$literally = "My $variable will print!";
print($literally);
?>
142
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.
143
<?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)
144
145
146
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
?>
5(iii) Explain in detail about Cookies.
Cookies are text files stored on the client computer and they are kept of use
tracking purpose. PHP transparently supports HTTP cookies.
There are three steps involved in identifying returning users −
Server script sends a set of cookies to the browser. For example name, age, or
identification number etc.
Browser stores this information on local machine for future use.
147
When next time browser sends any request to web server then it sends those
cookies information to the server and server uses that information to identify the
user.
Cookies are usually set in an HTTP header (although JavaScript can also set a
cookie directly on a browser). A PHP script that sets a cookie might send headers
that look something like this
HTTP/1.1 200 OK
Date: Fri, 04 Feb 2000 21:03:38 GMT
Server: Apache/1.3.9 (UNIX) PHP/4.0b3
Set-Cookie: name=xyz; expires=Friday, 04-Feb-07 22:03:38 GMT;
path=/; domain=tutorialspoint.com
Connection: close
Content-Type: text/html
The Set-Cookie header contains a name value pair, a GMT date, a path and a
domain. The name and value will be URL encoded.
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.
148
149
</head>
<body>
<?php
echo $_COOKIE["name"]. "<br />";
/* is equivalent to */
echo $HTTP_COOKIE_VARS["name"]. "<br />";
echo $_COOKIE["age"] . "<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>
150
<body>
<?php echo "Deleted Cookies" ?>
</body>
</html>
The ranges shown above are general; we could also use the range [0-3] to match any
decimal digit ranging from 0 through 3, or the range [b-v] to match any lowercase
character ranging from b through v.
151
Quantifiers
The frequency or position of bracketed character sequences and single characters can be
denoted by a special character. Each special character having a specific connotation. The
+, *, ?, {int. range}, and $ flags all follow a character sequence.
3 p? It matches any string containing zero or more p's. This is just an alternative way
to use p*.
Examples
Following examples will clear our concepts about matching characters.
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.
152
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.
153
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.
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
154
6 preg_ quote()
Quote regular expression characters
155
UNIT V
INTRODUCTION TO AJAX and WEB SERVICES
Part –A (2marks)
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. What is a web service? Give any four examples (Nov/Dec 2015)
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). Four examples are
SOAP
WSDL
UDDI
AJAX
5. What is meant by WSDL?
WSDL stands for Web Services Description Language
156
157
Part - B
1. Compare and contrast the traditional web application architecture and AJAX
based web application architecture? (April/May 2016)
OR
Discuss Ajax client server architecture in detail (Nov/Dec 2015)
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?
There are too many web applications running on the web that are using ajax
technology like gmail, facebook,twitter, google map, youtube etc.
158
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.
159
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
160
Method Description
void open(method, URL, async, username, same as above but specifies username and
password) password.
5. Server sends XML data or JSON data to the XMLHttpRequest callback function.
6. HTML and CSS data is displayed on the browser.
161
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.
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();
162
}
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++)
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>
163
</session-config>
<welcome-file-list>
<welcome-file>table1.html</welcome-file>
</welcome-file-list>
</web-app>
Output
164
165
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.
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.
166
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.
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.
167
168
<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.
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.
Example: A types construct containing an XSD schema construct in which
a complexType is defined.
<types>
<schema
xmlns="http://www.w3.org/2001/XMLSchema"
targetNamespace=
"http://www.xmltc.com/railco/transform/schema/">
169
<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>
170
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
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="..."/>
172
<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
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>
173
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?
OR
Draw the structure of a SOAP message (May/June 2016)
SOAP stands for simple object Access protocol.
SOAP is an XML-based messaging protocol.
It defines a set of rules for structuring messages that can be used for simple
one-way messaging but is particularly useful for performing RPC-style (Remote
Procedure call) request-response dialogues.
Figure: The structure of a SOAP message document.
174
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>
175
<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
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>
176
177
179
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 [Page.No. 188]
Internet Programming
Contact Form
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. [Page.No. 197]
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 [Page.No. 185]
(16)
14 (a) Create a Webserver based chat applications using PHP. The application
should provide the following functions
181
Login
Send message(to one or more contacts)
Receive messages ( from one or more contacts)
Add/ delete/ modify contact list of the user
Discuss the application’s user interface and use comments in PHP to explain
the code clearly.
[Page.No. 199]
OR
(b) (i) List the essential features of XML parsers. [Page.No. 132]
(8)
(ii)List at least five significant differences between DID and XML schema for
defining XML document structures with appropriate examples.
[Page.No. 129] (8)
15(a) Compare and contrast the traditional web application architecture and AJAX
based web application architecture. [Page.No. 158] (16)
OR
(b) Describe the structure of a WSDL document, its elements and their purposes
with appropriate examples [Page.No. 164] (16)
182
University Programs
1. 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 implements the above producer and consumer.
(May/June 2016)
183
}
contents = value;
available = true;
notifyAll();
}
}
class Consumer extends Thread {
private CubbyHole cubbyhole;
private int number;
public Consumer(CubbyHole c, int number) {
cubbyhole = c;
this.number = number;
}
public void run() {
int value = 0;
for (int i = 0; i < 10; i++) {
value = cubbyhole.get();
System.out.println("Consumer #" + this.number+ " got: " + value);
}
}
}
class Producer extends Thread {
private CubbyHole cubbyhole;
private int number;
public Producer(CubbyHole c, int number) {
cubbyhole = c;
this.number = number;
}
public void run() {
for (int i = 0; i < 10; i++) {
cubbyhole.put(i);
System.out.println("Producer #" + this.number + " put: " + i);
try {
sleep((int)(Math.random() * 100));
} catch (InterruptedException e) { }
}
}
}
184
Result
Producer #1 put: 0
Consumer #1 got: 0
Producer #1 put: 1
Consumer #1 got: 1
Producer #1 put: 2
Consumer #1 got: 2
Producer #1 put: 3
Consumer #1 got: 3
Producer #1 put: 4
Consumer #1 got: 4
Producer #1 put: 5
Consumer #1 got: 5
Producer #1 put: 6
Consumer #1 got: 6
Producer #1 put: 7
Consumer #1 got: 7
Producer #1 put: 8
Consumer #1 got: 8
Producer #1 put: 9
Consumer #1 got: 9
2. 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)
(May/ June 16)
import java.sql.DriverManager;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.*;
import java.io.*;
import java.net.*;
public class jdbcex {
185
186
187
case 5:
System.exit(0);
break;
default: System.out.println("choice");
break;
}}
connection.close();
}
catch (Exception e) {
System.err.println("Got an exception! ");
System.err.println(e.getMessage());
}
}
}
3.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 (May/June 2016)
index.html
<div id="contact-form" class="clearfix">
<h1>Get In Touch!</h1>
<h2>Fill out our super swanky HTML5 contact form below to get in touch
with us! Please provide as much information as possible for us to help you
with your enquiry :)</h2>
<ul id="errors" class="">
<li id="info">There were some problems with your form submission:</li>
</ul>
188
<span id="loading"></span>
<input type="submit" value="Holla!" id="submit-button" />
<p id="req-field-desc"><span class="required">*</span> indicates a
required field</p>
</form>
</div>
#contact-form {
background-color:#F2F7F9;
width:465px;
padding:20px;
margin: 50px auto;
189
#contact-form h1 {
font-size:42px;
}
#contact-form h2 {
margin-bottom:15px;
font-style:italic;
font-weight:normal;
}
#contact-form input,
#contact-form select,
#contact-form textarea,
#contact-form label {
font-size:15px;
margin-bottom:2px;
}
#contact-form input,
#contact-form select,
#contact-form textarea {
width:450px;
border: 1px solid #CEE1E8;
margin-bottom:20px;
padding:4px;
}
#contact-form input:focus,
#contact-form select:focus,
#contact-form textarea:focus {
border: 1px solid #AFCDD8;
190
background-color: #EBF2F4;
}
#contact-form textarea {
height:150px;
resize: none;
}
#contact-form label {
display:block;
}
#contact-form .required {
font-weight:bold;
color:#F00;
}
#contact-form #submit-button {
width: 100px;
background-color:#333;
color:#FFF;
border:none;
display:block;
float:right;
margin-bottom:0px;
margin-right:6px;
background-color:#8FB5C1;
-moz-border-radius:8px;
}
#contact-form #submit-button:hover {
background-color: #A6CFDD;
}
#contact-form #submit-button:active {
position:relative;
top:1px;
}
191
#contact-form #loading {
width:32px;
height:32px;
background-image:url(../img/loading.gif);
display:block;
position:absolute;
right:130px;
bottom:16px;
display:none;
}
#errors {
border:solid 1px #E58E8E;
padding:10px;
margin:25px 0px;
display:block;
width:437px;
-webkit-border-radius:8px;
-moz-border-radius:8px;
border-radius:8px;
background:#FFE6E6 url(../img/cancel_48.png) no-repeat 405px center;
display:none;
}
#errors li {
padding:2px;
list-style:none;
}
#errors li:before {
content: ' - ';
}
#errors #info {
font-weight:bold;
}
192
#errors #info:before {
content: '';
}
#success {
border:solid 1px #83D186;
padding:25px 10px;
margin:25px 0px;
display:block;
width:437px;
-webkit-border-radius:8px;
-moz-border-radius:8px;
border-radius:8px;
background:#D3EDD3 url(../img/accepted_48.png) no-repeat 405px center;
font-weight:bold;
display:none;
}
#errors.visible, #success.visible {
display:block;
}
#req-field-desc {
font-style:italic;
}
/* Remove box shadow firefox, chrome and opera put around required fields. It
looks rubbish. */
input:required, textarea:required {
-moz-box-shadow:none;
-webkit-box-shadow:none;
-o-box-shadow:none;
box-shadow:none;
}
/* Normalize placeholder styles */
/* chrome, safari */
::-webkit-input-placeholder {
color:#CCC;
193
font-style:italic;
}
/* mozilla */
input:-moz-placeholder, textarea:-moz-placeholder {
color:#CCC;
font-style:italic;
}
/* ie (faux placeholder) */
input.placeholder-text, textarea.placeholder-text {
color:#CCC;
font-style:italic;
}
1 #errors li:before {
2 content: ' - ';
3 }
This will put a dash next to our error validation messages. It's basically replacing
the bullet point in the list, I just think this looks better.
1 #contact-form #submit-button:active {
2 position:relative;
3 top:1px;
4 }
Process.php
<?php
if( isset($_POST) ){
//form validation vars
$formok = true;
$errors = array();
//sumbission data
$ipaddress = $_SERVER['REMOTE_ADDR'];
$date = date('d/m/Y');
$time = date('H:i:s');
194
//form data
$name = $_POST['name'];
$email = $_POST['email'];
$telephone = $_POST['telephone'];
$enquiry = $_POST['enquiry'];
$message = $_POST['message'];
//form validation to go here....
}
//validate name is not empty
if(empty($name)){
$formok = false;
$errors[] = "You have not entered a name";
}
//validate email address is not empty
if(empty($email)){
$formok = false;
$errors[] = "You have not entered an email address";
//validate email address is valid
}elseif(!filter_var($email, FILTER_VALIDATE_EMAIL)){
$formok = false;
$errors[] = "You have not entered a valid email address";
}
//validate message is not empty
if(empty($message)){
$formok = false;
$errors[] = "You have not entered a message";
}
//validate message is greater than 20 charcters
elseif(strlen($message) < 20){
$formok = false;
$errors[] = "Your message must be greater than 20 characters";
}
3. 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”. (May/June 2016)
import javax.swing.JOptionPane;
public class Oppgave2{
195
}
}
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
public class Calculate extends JTextField {
public static void main(String[] args) {
JFrame f = new JFrame("Calculate");
f.getContentPane().setLayout(new BoxLayout(f.getContentPane(),
BoxLayout.Y_AXIS));
196
4. 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 (May/June 2016)
197
HTML file
<html>
<textarea id="core_input">
<script type="text/javascript"> var foo = "test"; </script>
</textarea>
<button id="process">process</button>
<div id="iframe-body"></div>
</html>
Javascript file
document.addEventListener("DOMContentLoaded", function() {
document.getElementById("process").addEventListener("click", function () {
var $iframe = document.getElementById("iframe-render"),
iframe, iframeDoc;
if ( !$iframe ) {
iframe = document.createElement("iframe");
iframe.id = "iframe-render";
document.getElementById("iframe-body").appendChild( iframe );
} else {
iframe = $iframe;
}
iframeDoc = iframe.contentWindow ?
iframe.contentWindow :
iframe.contentDocument.document ?
iframe.contentDocument.document :
iframe.contentDocument;
iframeDoc.document.open();
iframeDoc.document.write(
document.getElementById("core_input").value
);
iframeDoc.document.close();
}, false);
}, false);
CSS File
textarea {display:block;width:100%;height:100px;}
iframe {width:100%;height:300px;}
198
login_form.html
</form>
<div>You can use username "User1" or "User2" or "User3" and password
"qwerty" to login in system</div>
Here are new 3 template files to chat (2 to messages box and 1 to send message
form):
chat_begin.html
<div class="chat_main">
199
<h3>Chat</h3>
chat_end.html
</div>
chat_input.html
</form>
<div>You can type anything in chat</div>
Step 2. CSS
Here are used CSS styles.
styles.css
.login_form {
border: 1px solid #AAA;
padding:10px;
}
h3 {margin-top:3px;}
.chat_main {
padding:10px;
background:#f3f3f3;
.message {
border:1px solid #AAA;
margin:4px;
padding:5px;
-moz-border-radius:7px;
200
-webkit-border-radius:7px;
background:#ffffff;
}
.textf {
.submit {
-moz-border-radius:7px;
-webkit-border-radius:7px;
background:#F3F3F3;
font-weight:bold;
height:35px;
margin-left:10px;
padding:5px;
}
.message span {
font-size:10px;
color:#888;
margin-left:10px;
}
.submit_form {
margin:10px 0px;
}
Step 3. SQL
We will need to execute next SQL in our database.
201
STEP 4
As we remember – we had ready easy authentication system. I moved it to external
library file (inc/login.inc.php). This will useful for us – now code more structured and it
comfortable to use in different places of code.
After I created new library to work with chat (inc/chat.inc.php). This class have next
functions:
acceptMessages – function accept sent messages and store it in DB table
getMessages – return list of last 15 messages
\After I created 2 last files: messages.php and main.php. First file used to draw list of
messages. It have autoupdate each 5 second (I thing this is enough to our chat). Second
draw login form and input field of chat. Where we due logged able to post text in chat.
Ok, here are all used PHP files:
main.php
<?php
require_once('inc/login.inc.php');
require_once('inc/chat.inc.php');
$oSimpleLoginSystem = new
SimpleLoginSystem();
if ($oSimpleLoginSystem->check_login($_COOKIE['member_name'],
202
$_COOKIE['member_pass'])) {
$sChatResult = $oSimpleChat->acceptMessages();
}
}
echo $sChatResult;
?>
messages.php
require_once('inc/chat.inc.php');
?>
inc/chat.inc.php
<?php
// DB variables
var $sDbName;
var $sDbUser;
var $sDbPass;
// constructor
function SimpleChat() {
//mysql_connect("localhost","username","password");
$this->sDbName = 'database_name';
$this->sDbUser = 'username';
$this->sDbPass = 'password';
if ($_COOKIE['member_name']) {
203
$sUsername = $_COOKIE['member_name'];
mysql_select_db($this->sDbName);
$sMessage = mysql_real_escape_string($_POST['s_message']);
if ($sMessage != '') {
mysql_close($vLink);
}
}
ob_start();
require_once('chat_input.html');
$sShoutboxForm = ob_get_clean();
return $sShoutboxForm;
function getMessages() {
$vLink = mysql_connect("localhost", $this->sDbUser, $this->sDbPass);
mysql_select_db($this->sDbName);
$sMessages = '';
if ($vRes) {
while($aMessages = mysql_fetch_array($vRes)) {
204
}
} else {
mysql_close($vLink);
ob_start();
require_once('chat_begin.html');
echo $sMessages;
require_once('chat_end.html');
return ob_get_clean();
}
}
?>
inc/login.inc.php
<?
// class SimpleLoginSystem
class SimpleLoginSystem
{
// variables
// constructor
function SimpleLoginSystem() {
$this->aExistedMembers = array(
'User1' => 'd8578edf8458ce06fbc5bb76a58c5ca4',
);
}
function getLoginBox() {
205
ob_start();
require_once('login_form.html');
$sLoginForm = ob_get_clean();
if ((int)$_REQUEST['logout'] == 1) {
if (isset($_COOKIE['member_name']) &&
isset($_COOKIE['member_pass']))
$this->simple_logout();
}
if ($this->check_login($_REQUEST['username'],
MD5($_REQUEST['password']))) {
$this->simple_login($_REQUEST['username'],
$_REQUEST['password']);
} else {
if ($_COOKIE['member_name'] && $_COOKIE['member_pass']) {
if ($this->check_login($_COOKIE['member_name'],
$_COOKIE['member_pass'])) {
return 'Hello ' . $_COOKIE['member_name'] . '! ' . $sLogoutForm;
}
}
return $sLoginForm;
}
$sMd5Password = MD5($sPass);
206
function simple_logout() {
setcookie('member_name', '', time() - 96 * 3600, '/');
unset($_COOKIE['member_name']);
unset($_COOKIE['member_pass']);
}
}
?>
6. Write appropriate inline CSS to show a section of the HTML document
with the font size of 20. (May/June 2016)
<html>
<h1 style="color:blue;margin-left:30px;" font-size:20px>This is a heading.</h1>
</html>
CSS file
h1 {
font-size: 40px;
}
h2 {
font-size: 30px;
}
p{
font-size: 14px;
}
7. Write appropriate javascript code to remove an element (current
element) from a DOM. [May / June 2016]
<html>
207
<div id="div1">
<p id="p1">This is a paragraph.</p>
<p id="p2">This is another paragraph.</p>
</div>
<script>
var para = document.createElement("p");
var node = document.createTextNode("This is new.");
para.appendChild(node);
var element = document.getElementById("div1");
var child = document.getElementById("p1");
element.insertBefore(para,child);
</script>
</html>
8. Write the code segment to store current server time in session using
java servlet API. [May / June 2016]
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.util.Date;
rsp.setContentType("text/html");
out.println("<html>");
out.println("<body>");
out.println("</body></html>");
208
209