Ip Questions and Answers
Ip Questions and Answers
com
www.rejinpaul.com
1 Define Java.
Java is a programming language expressly designed for use in the distributed environment of
the Internet. It was designed to have the "look and feel" of the C++ language, but it is simpler to
use than C++ and enforces an object-oriented programming model.
2. What is a Class?
Class is a template for a set of objects that share a common structure and a common behaviour.
3. What is an Object?
Object is an instance of a class. It has state, behaviour and identity. It is also called as an
instance of a class.
4. What is an Instance?
An instance has state, behaviour and identity. The structure and behaviour of similar classes are
defined in their common class. An instance is also called as an object.
5. What are different types of access modifiers (Access specifiers)?
Access specifiers are keywords that determine the type of access to the member of a class.
These keywords are for allowing privilegesto parts of a program such as functions and
variables. These are: public: Anything declared as public can be accessed from anywhere.
private: Anything declared as private can‘t be seen outside of its class.
protected: Anything declared as protected can be accessed by classes in the same package and
subclasses in the there packages.
default modifier : Can be accessed only to classes in the same package.
6. What is method overloading and method overriding?
Method overloading: When a method in a class having the same method name with different
arguments is said to be method overloading.
Method overriding: When a method in a class having the same method name with same
arguments is said to be method overriding.
7. List the access specifier used in JAVA?
Java provides a number of access modifiers to set access levels for classes, variables, methods
and constructors. The four access levels are:
A package is a collection of classes and interfaces that provides a high-level layer of access
protection and name space management.
a) All the methods declared inside an interface are abstract whereas abstract class must have at
least one abstract method and others may be concrete or abstract.
b) In abstract class, key word abstract must be used for the methods whereas interface we need
not use that keyword for the methods.
c) Abstract class must have subclasses whereas interface can‘t have subclasses.
Package represents a collection of classes, methods and interface. The name of the package
must be written as the first statement in the java source program. Syntax: package
name_of_package
Unchecked exceptions:All Exceptions that extend the RuntimeException class are unchecked
exceptions. Class Error and its subclasses also are unchecked.
} }
20. Write the properties of Threads.(Nov/Dec 2014).
• Thread Priority
• Deamon Thread
• Thread group
21. What is multi-threaded programming?(Nov/Dec 2014)
Multithreading is the ability of a program or an operating system process to manage its use by
more than one user at a time and to even manage multiple requests by the same user without
having to have multiple copies of the programming running in the computer.
A thread goes through various stages in its life cycle. For example, a thread is born, started,
runs, and then dies. Following diagram shows complete life cycle of a thread
23. What is daemon thread and which method is used to create the daemon thread?
A daemon thread is a thread, that does not prevent the JVM from exiting when the program
finishes but the thread is still running. An example for a daemon thread is the garbage
collection. You can use the setDaemon() method to change the Thread daemon properties
24. What is the purpose of toString() method in java ?
The toString() method returns the string representation of any object. If you print any object,
java compiler internally invokes the toString() method on the object. So overriding the
toString() method, returns the desired output, it can be the state of an object etc. depends on
your implementation.
Eg:
class Testimmutablestring{
String s="Sachin";
Java assertion feature allows developer to put "assert" statements in Java source code to help
unit testing and debugging.
An applet is a small Internet-based program written in Java, a programming language for the
Web, which can be downloaded by any computer. The applet is also able to run in HTML. The
applet is usually embedded in an HTML page on a Web site and can be executed from within a
browser.
Java defines two interesting type modifiers: transient and volatile. These modifiers are usedto
handle somewhat specialized situations. When an instance variable is declared as transient, then
its value need not persist when an object is stored. For example:
class T {
Here, if an object of type T is written to a persistent storage area, the contents of a would not be
saved, but the contents of b would.
objrefinstanceof type
Here, objref is a reference to an instance of a class, and type is a class type. If objref is of the
specified type or can be cast into the specified type, then the instanceof operator evaluates to
true. Otherwise, its result is false. Thus, instanceof is the means by which your program
canobtain run-time type information about an object
When executing code, you can disable assertions by using the -da option. You can
enable or disable a specific package by specifying its name after the -ea or -da option. For
example, to enable assertions in a package called MyPack, use
-ea:MyPack
-da:MyPack
The String class supports several constructors. To create an empty String, you call the default
will create an instance of String with no characters in it. Frequently, you will want to create
strings that have initial values. The String class provides a variety of constructors to handle this.
To create a String initialized by an array of characters, use the constructor shown here:
String(char chars[ ])
Here is an example:
The String class includes several methods that compare strings or substrings within strings.
equals( ) and equalsIgnoreCase( To compare two strings for equality, use equals( ). To perform
) comparison that ignores case differences, call equalsIgnoreCas
startsWith( ) and endsWith( ) The startsWith( ) method determines whether a given String begins with a
specified string.
equals( ) Versus == The equals( ) method compares the characters insidea String object. The
== operator compares two object references to see whether they referto the
same instance.
• substring( )
• concat( )
• replace( )
• trim( )
PART – B
Abstraction
Hiding internal details and showing functionality is known as abstraction. For
example: phone call, we don't know the internal processing. In java, we use abstract
class and interface to achieve abstraction.
Encapsulation
Binding (or wrapping) code and data together into a single unit is known as
encapsulation. For example: capsule, it is wrapped with different medicines.
A java class is the example of encapsulation. Java bean is the fully encapsulated class
because all the data members are private here.
(ii).What is meant by overriding method? Give example.(5)
If subclass (child class) has the same method as declared in the parent class, it is known
as method overriding in java.
In other words, If subclass provides the specific implementation of the method that has
been provided by one of its parent class, it is known as method overriding.
Usage of Java Method Overriding
Method overriding is used to provide specific implementation of a method that
is already provided by its super class.
Method overriding is used for runtime polymorphism
Rules for Java Method Overriding
1. method must have same name as in the parent class
2. method must have same parameter as in the parent class.
3. must be IS-A relationship (inheritance).
Consider a scenario, Bank is a class that provides functionality to get rate of interest.
But, rate of interest varies according to banks. For example, SBI, ICICI and AXIS
banks could provide 8%, 7% and 9% rate of interest.
class Bank{
int getRateOfInterest(){return 0;}
}
class Test2{
public static void main(String args[]){
SBI s=new SBI();
ICICI i=new ICICI();
AXIS a=new AXIS();
System.out.println("SBI Rate of Interest: "+s.getRateOfInterest());
System.out.println("ICICI Rate of Interest: "+i.getRateOfInterest());
System.out.println("AXIS Rate of Interest: "+a.getRateOfInterest());
}
}
Output:
SBI Rate of Interest: 8
ICICI Rate of Interest: 7
AXIS Rate of Interest: 9
import java.util.*;
public class RevNumString
{
public static void main(String[] args)
{
Scanner scanner = new Scanner(System.in);
System.out.println("Please enter a number: ");
int num = scanner.nextInt();
System.out.println("Please enter a string: ");
String str = scanner.next();
RevNumString rns = new RevNumString();
int revNum = rns.reverse(num);
String revStr = rns.reverse(str);
System.out.printf("\n The reverse of number %d is %d ", num, revNum);
System.out.printf("\n The reverse of string '%s' is '%s' ", str, revStr);
}
// Method to return the reverse of a number
public int reverse(int num) {
int revNum = 0;
while (num > 0) {
int rem = num % 10;
revNum = (revNum * 10) + rem;
num = num / 10;
}
return revNum;
}
Packages are used in Java in order to prevent naming conflicts, to control access, to
make searching/locating and usage of classes, interfaces, enumerations and annotations
easier, etc.
Programmers can define their own packages to bundle group of classes/interfaces, etc. It
is a good practice to group related classes implemented by you so that a programmer
can easily determine that the classes, interfaces, enumerations, annotations are related.
Since the package creates a new namespace there won't be any name conflicts with
names in other packages. Using packages, it is easier to provide access control and it is
also easier to locate the related classes.
Creating a package:
When creating a package, you should choose a name for the package and put a package
statement with that name at the top of every source file that contains the classes,
interfaces, enumerations, and annotation types that you want to include in the package.
The package statement should be the first line in the source file. There can be only one
package statement in each source file, and it applies to all types in the file.
If a package statement is not used then the class, interfaces, enumerations, and
annotation types will be put into an unnamed package.
Example:
Let us look at an example that creates a package called animals. It is common practice
to use lowercased names of packages to avoid any conflicts with the names of classes,
interfaces.
Put an interface in the package animals:
/* File name : Animal.java */
package animals;
interface Animal {
public void eat();
public void travel();
}
Now, put an implementation in the same package animals:
package animals;
package payroll;
public class Boss
{
public void payEmployee(Employee e)
{
e.mailCheck();
}
}
What happens if Boss is not in the payroll package? The Boss class must then use one
of the following techniques for referring to a class in a different package.
The fully qualified name of the class can be used. For example:
payroll.Employee
The package can be imported using the import keyword and the wild card (*).
For example:
import payroll.*;
The class itself can be imported using the import keyword. For example:
import payroll.Employee;
Note: A class file can contain any number of import statements. The import statements
must appear after the package statement and before the class declaration.
Now, put the source file in a directory whose name reflects the name of the package to
which the class belongs:
....\vehicle\Car.java
Now, the qualified class name and pathname would be as below:
Class name -> vehicle.Car
Path name -> vehicle\Car.java (in windows)
In general, a company uses its reversed Internet domain name for its package names.
Example: A company's Internet domain name is apple.com, then all its package names
would start with com.apple. Each component of the package name corresponds to a
subdirectory.
Example: The company had a com.apple.computers package that contained a Dell.java
source file, it would be contained in a series of subdirectories like this:
....\com\apple\computers\Dell.java
At the time of compilation, the compiler creates a different output file for each class,
interface and enumeration defined in it. The base name of the output file is the name of
the type, and its extension is .class
For example:
// File Name: Dell.java
package com.apple.computers;
public class Dell{
}
class Ups{
}
Now, compile this file as follows using -d option:
$javac -d . Dell.java
(ii).Write a JAVA program to find the smallest number in the given list. (8)
import java.util.Scanner;
class group{
public static void main(String arng[]){
int value[]= new int[5];
int temp,i;
Scanner data = new Scanner(System.in);
System.out.println("Enter 5 element of array" );
// Enhanced for loop
for(i=0; i < 5; i++ )
value[i] = data.nextInt();
// finding smallest number
temp = value[0];
for(i=0; i < 5; i++ )
{
if(temp < value[i])
continue;
else
temp = value[i];
}
System.out.println("Smallest number in array is "+temp);
}
}
Output:-
Enter 5 element of array
56
84
95
12
32
Smallest number in array is 12
Output:-
Enter 5 element of array
48
124
20
54
14
Smallest number in array is 14
An interface is not a class. Writing an interface is similar to writing a class, but they are
two different concepts. A class describes the attributes and behaviors of an object. An
interface contains behaviors that a class implements.
Unless the class that implements the interface is abstract, all the methods of the
interface need to be defined in the class.
An interface is written in a file with a .java extension, with the name of the
interface matching the name of the file.
An interface cannot contain instance fields. The only fields that can appear in an
interface must be declared both static and final.
Declaring Interfaces:
An interface is implicitly abstract. You do not need to use the abstract keyword
when declaring an interface.
Example:
Implementing Interfaces:
When a class implements an interface, you can think of the class as signing a contract,
agreeing to perform the specific behaviors of the interface. If a class does not perform
all the behaviors of the interface, the class must declare itself as abstract.
System.out.println("Mammal eats");
}
Mammal eats
Mammal travels
When overriding methods defined in interfaces there are several rules to be followed:
The signature of the interface method and the same return type or subtype should be
maintained when overriding the methods.
An implementation class itself can be abstract and if so interface methods need not be
implemented.
A class can extend only one class, but implement many interfaces.
An interface can extend another interface, similarly to the way that a class can
extend another class.
Extending Interfaces:
An interface can extend another interface, similarly to the way that a class can extend
another class. The extends keyword is used to extend an interface, and the child
interface inherits the methods of the parent interface.
//Filename: Sports.java
public interface Sports
{
public void setHomeTeam(String name);
public void setVisitingTeam(String name);
}
//Filename: Football.java
public interface Football extends Sports
{
public void homeTeamScored(int points);
public void visitingTeamScored(int points);
public void endOfQuarter(int quarter);
}
//Filename: Hockey.java
public interface Hockey extends Sports
{
public void homeGoalScored();
public void visitingGoalScored();
public void endOfPeriod(int period);
public void overtimePeriod(int ot);
}
The Hockey interface has four methods, but it inherits two from Sports; thus, a class
that implements Hockey needs to implement all six methods. Similarly, a class that
implements Football needs to define the three methods from Football and the two
methods from Sports.
Extending Multiple Interfaces:
A Java class can only extend one parent class. Multiple inheritance is not allowed.
Interfaces are not classes, however, and an interface can extend more than one parent
interface.
The extends keyword is used once, and the parent interfaces are declared in a comma-
separated list.
For example, if the Hockey interface extended both Sports and Event, it would be
declared as:
3. class
The final keyword can be applied with the variables, a final variable that have no value
it is called blank final variable or uninitialized final variable. It can be initialized in the
constructor only. The blank final variable can be static also which will be initialized in
the static block only. We will have detailed learning of these
Example of final variable
class Bike9{
final int speedlimit=90;//final variable
void run(){
speedlimit=400;
}
public static void main(String args[]){
Bike9 obj=new Bike9();
obj.run();
}
}//end of class
Example of final method
class Bike{
final void run(){System.out.println("running");}
}
Java inner class or nested class is a class i.e. declared inside the class or interface.
We use inner classes to logically group classes and interfaces in one place so that it can
be more readable and maintainable.
Additionally, it can access all the members of outer class including private data
There are basically three advantages of inner classes in java. They are as follows:
1) Nested classes represent a special type of relationship that is it can access all the
members (data members and methods) of outer class including private.
2) Nested classes are used to develop more readable and maintainable code because
it logically group classes and interfaces in one place only.
Inner class is a part of nested class. Non-static nested classes are known as inner
classes.
There are two types of nested classes non-static and static nested classes.The non-static
nested classes are also known as inner classes.
Type Description
Member Inner
A class created within class and outside method.
Class
Anonymous Inner A class created for implementing interface or extending class. Its
Class name is decided by the java compiler.
Local Inner Class A class created within method.
Static Nested Class A static class created within class.
Nested Interface An interface created within class or interface.
(ii).Explain in details the concepts of applets.
Applet is a special type of program that is embedded in the webpage to generate the
dynamic content. It runs inside the browser and works at client side.
Advantage of Applet
Drawback of Applet
Hierarchy of Applet
As displayed in the above diagram, Applet class extends Panel. Panel class extends Container
which is the subclass of Component.
1. Applet is initialized.
2. Applet is started.
3. Applet is painted.
4. Applet is stopped.
5. Applet is destroyed.
java.applet.Applet class
For creating any applet java.applet.Applet class must be inherited. It provides 4 life
cycle methods of applet.
1. public void init(): is used to initialized the Applet. It is invoked only once.
2. public void start(): is invoked after the init() method or browser is maximized.
It is used to start the Applet.
3. public void stop(): is used to stop the Applet. It is invoked when Applet is stop
or browser is minimized.
4. public void destroy(): is used to destroy the Applet. It is invoked only once.
java.awt.Component class
1. public void paint(Graphics g): is used to paint the Applet. It provides Graphics
class object that can be used for drawing oval, rectangle, arc etc.
1. By html file.
2. By appletViewer tool (for testing purpose).
To execute the applet by html file, create an applet and compile it. After that create an
html file and place the applet code in html file. Now click the html file.
//First.java
import java.applet.Applet;
import java.awt.Graphics;
public class First extends Applet{
public void paint(Graphics g){
g.drawString("welcome",150,150);
}
}
myapplet.html
<html>
<body>
<applet code="First.class" width="300" height="300">
</applet>
</body>
</html>
To execute the applet by appletviewer tool, create an applet that contains applet tag in
comment and compile it. After that run it by: appletviewer First.java. Now Html file is
not required but it is for testing purpose only.
//First.java
import java.applet.Applet;
import java.awt.Graphics;
public class First extends Applet{
}
/*
<applet code="First.class" width="300" height="300">
</applet>
*/
c:\>javac First.java
c:\>appletviewer First.java
5. What is Exception handling in java? Why it is used? Write a java code to simulate
the way a stack mechanisms works with exception handling, throwing and dealing
with exceptions such as stack is full( if you want to add more elements into the
stack)or Stack is empty(you want to pop elements from the stack).
Some of these exceptions are caused by user error, others by programmer error, and
others by physical resources that have failed in some manner.
To understand how exception handling works in Java, you need to understand the three
categories of exceptions:
class SimpleStackDemo {
public static void main(String arg[])
{
FixedLengthStack stack=new FixedLengthStack(5);
char ch;
int i;
try{
// overrun the stack
for(i=0;i<6;i++)
System.out.println(“Attempting to push:”+(char) („A‟+i));
stack.push((char) („A‟+i));
System.out.println(“=ok”);
}
catch(StackFullException exc) {
System.out.println(exc);
}
System.out.println();
try{
//over-empty the stack
for(i=0;i<6;i++) {
6. Discuss the concept of synchronization in thread and develop a JAVA code for
reader/writer problem.
When we start two or more threads within a program, there may be a situation when
multiple threads try to access the same resource and finally they can produce unforeseen
result due to concurrency issue. For example if multiple threads try to write within a
same file then they may corrupt the data because one of the threads can overrite data or
while one thread is opening the same file at the same time another thread might be
closing the same file.
So there is a need to synchronize the action of multiple threads and make sure that only
one thread can access the resource at a given point in time. This is implemented using a
concept called monitors. Each object in Java is associated with a monitor, which a
thread can lock or unlock. Only one thread at a time may hold a lock on a monitor.
Java programming language provides a very handy way of creating threads and
synchronizing their task by using synchronized blocks. You keep shared resources
within this block. Following is the general form of the synchronized statement:
synchronized(objectidentifier) {
// Access shared variables and other shared resources
}
Here, the objectidentifier is a reference to an object whose lock associates with the
monitor that the synchronized statement represents. Now we are going to see two
examples where we will print a counter using two different threads. When threads are
not synchronized, they print counter value which is not in sequence, but when we print
counter by putting inside synchronized() block, then it prints counter very much in
sequence for both the threads.
Here is the same example which prints counter value in sequence and every time we run
it, it produces same result.
class PrintDemo {
public void printCount(){
try {
for(int i = 5; i > 0; i--) {
System.out.println("Counter --- " + i );
}
} catch (Exception e) {
System.out.println("Thread interrupted.");
}
}
T1.start();
T2.start();
This produces same result every time you run this program:
Starting Thread - 1
Starting Thread - 2
Counter --- 5
Counter --- 4
Counter --- 3
Counter --- 2
Counter --- 1
Thread Thread - 1 exiting.
Counter --- 5
Counter --- 4
Counter --- 3
Counter --- 2
Counter --- 1
Thread Thread - 2 exiting.
/**
* Reader.java
*
* A reader to the database.
*
*/
database.releaseReadLock(readerNum);
}
}
;
}
//**************************************************************
/**
* Writer.java
*
* A writer to the database.
*
*/
class Writer implements Runnable
{
private RWLock database;
private int writerNum;
database.releaseWriteLock(writerNum);
}
}
}
Stream
A stream is a sequence of data.In Java a stream is composed of bytes. It's called a
stream because it's like a stream of water that continues to flow.
In java, 3 streams are created for us automatically. All these streams are attached with
console.
1. System.out.println("simple message");
2. System.err.println("error message");
OutputStream
InputStream
Java application uses an input stream to read data from a source, it may be a file,an
array,peripheral device or socket.
Let's understand working of Java OutputStream and InputStream by the figure given
below.
OutputStream class
Method Description
IOException: stream.
4) public void close()throws IOException: is used to close the current output stream.
InputStream class
Method Description
1) public abstract int read()throws reads the next byte of data from the input stream.It
IOException: returns -1 at the end of file.
2) public int available()throws returns an estimate of the number of bytes that can be
IOException: read from the current input stream.
Java String provides a lot of concepts that can be performed on a string such as
compare, concat, equals, split, length, replace, compareTo, intern, substring etc.
1. char[] ch={'j','a','v','a','t','p','o','i','n','t'};
2. String s=new String(ch);
is same as:
1. String s="javatpoint";
The java String is immutable i.e. it cannot be changed but a new instance is created. For
mutable class, you can use StringBuffer and StringBuilder class.
1. By string literal
2. By new keyword
1) String Literal
1. String s="welcome";
Each time you create a string literal, the JVM checks the string constant pool first. If the
string already exists in the pool, a reference to the pooled instance is returned. If string
doesn't exist in the pool, a new string instance is created and placed in the pool. For
example:
1. String s1="Welcome";
2. String s2="Welcome";//will not create new instance
2) By new keyword
char ch[]={'s','t','r','i','n','g','s'};
String s2=new String(ch);//converting char array to string
System.out.println(s1);
System.out.println(s2);
System.out.println(s3);
}}
Output:
java
strings
example
In this example, we have created the constructor of Student class that have two
parameters. We can have any number of parameters in the constructor.
class Student4{
int id;
String name;
Student4(int i,String n){
id = i;
name = n;
}
void display(){System.out.println(id+" "+name);}
public static void main(String args[]){
Student4 s1 = new Student4(111,"Karan");
Student4 s2 = new Student4(222,"Aryan");
s1.display();
s2.display();
}
}
Output:
111 Karan
222 Aryan
Constructor Overloading in Java
Constructor overloading is a technique in Java in which a class can have any number of
constructors that differ in parameter lists.The compiler differentiates these constructors
by taking into account the number of parameters in the list and their type.
class Student5{
int id;
String name;
int age;
Student5(int i,String n){
id = i;
name = n;
}
Student5(int i,String n,int a){
id = i;
name = n;
age=a;
}
void display(){System.out.println(id+" "+name+" "+age);}
There is no copy constructor in java. But, we can copy the values of one object to
another like copy constructor in C++.
There are many ways to copy the values of one object into another in java. They are:
By constructor
By assigning the values of one object into another
By clone() method of Object class
In this example, we are going to copy the values of one object into another using
java constructor.
class Student6{
int id;
String name;
Student6(int i,String n){
id = i;
name = n;
}
Student6(Student6 s){
id = s.id;
name =s.name;
}
void display(){System.out.println(id+" "+name);}
Test it Now
Output:
111 Karan
111 Karan
9. Define inheritances. Explain in details types of inheritances supported by JAVA
with example program.
Inheritance in java is a mechanism in which one object acquires all the properties and
behaviors of parent object.
The idea behind inheritance in java is that you can create new classes that are built upon
existing classes. When you inherit from an existing class, you can reuse methods and
fields of parent class, and you can add new methods and fields also.
The extends keyword indicates that you are making a new class that derives from an
existing class.
In the terminology of Java, a class that is inherited is called a super class. The new class
is called a subclass.
As displayed in the above figure, Programmer is the subclass and Employee is the
superclass. Relationship between two classes is Programmer IS-A Employee.It means
that Programmer is a type of Employee.
class Employee{
float salary=40000;
}
When a class extends multiple classes i.e. known as multiple inheritance. For Example:
supported in java.
Consider a scenario where A, B and C are three classes. The C class inherits A and B
classes. If A and B classes have same method and you call it from child class object,
there will be ambiguity to call method of A or B class.
Since compile time errors are better than runtime errors, java renders compile time
error if you inherit 2 classes. So whether you have same method or different, there
will be compile time error now.
class A{
void msg(){System.out.println("Hello");}
}
class B{
void msg(){System.out.println("Welcome");}
}
class C extends A,B{//suppose if it were
The java.io package contains nearly every class you might ever need to perform input
and output (I/O) in Java. All these streams represent an input source and an output
destination. The stream in the java.io package supports many data such as primitives,
Object, localized characters, etc.
A stream can be defined as a sequence of data. The InputStream is used to read data
from a source and the OutputStream is used for writing data to a destination.
Java provides strong but flexible support for I/O related to Files and networks but this
tutorial covers very basic functionality related to streams and I/O. We would see most
commonly used example one by one:
Byte Streams
Java byte streams are used to perform input and output of 8-bit bytes. Though there are
many classes related to byte streams but the most frequently used classes are ,
FileInputStream and FileOutputStream. Following is an example which makes use
of these two classes to copy an input file into an output file:
import java.io.*;
{
FileInputStream in = null;
FileOutputStream out = null;
try {
in = new FileInputStream("input.txt");
out = new FileOutputStream("output.txt");
int c;
while ((c = in.read()) != -1) {
out.write(c);
}
}finally {
if (in != null) {
in.close();
}
if (out != null) {
out.close();
}
}
}
}
As a next step, compile above program and execute it, which will result in creating
output.txt file with the same content as we have in input.txt. So let's put above code in
CopyFile.java file and do the following:
$javac CopyFile.java
$java CopyFile
Character Streams
Java Byte streams are used to perform input and output of 8-bit bytes, where as Java
Character streams are used to perform input and output for 16-bit unicode. Though
there are many classes related to character streams but the most frequently used classes
are , FileReader and FileWriter.. Though internally FileReader uses FileInputStream
and FileWriter uses FileOutputStream but here major difference is that FileReader reads
two bytes at a time and FileWriter writes two bytes at a time.
We can re-write above example which makes use of these two classes to copy an input
file (having unicode characters) into an output file:
import java.io.*;
{
FileReader in = null;
FileWriter out = null;
try {
in = new FileReader("input.txt");
out = new FileWriter("output.txt");
int c;
while ((c = in.read()) != -1) {
out.write(c);
}
}finally {
if (in != null) {
in.close();
}
if (out != null) {
out.close();
}
}
}
}
As a next step, compile above program and execute it, which will result in creating
output.txt file with the same content as we have in input.txt. So let's put above code in
CopyFile.java file and do the following:
$javac CopyFile.java
$java CopyFile
Standard Streams
All the programming languages provide support for standard I/O where user's program
can take input from a keyboard and then produce output on the computer screen. If you
are aware if C or C++ programming languages, then you must be aware of three
standard devices STDIN, STDOUT and STDERR. Similar way Java provides following
three standard streams
Standard Input: This is used to feed the data to user's program and usually a
keyboard is used as standard input stream and represented as System.in.
Standard Output: This is used to output the data produced by the user's
program and usually a computer screen is used to standard output stream and
represented as System.out.
Standard Error: This is used to output the error data produced by the user's
program and usually a computer screen is used to standard error stream and
represented as System.err.
import java.io.*;
try {
cin = new InputStreamReader(System.in);
System.out.println("Enter characters, 'q' to quit.");
char c;
do {
c = (char) cin.read();
System.out.print(c);
} while(c != 'q');
}finally {
if (cin != null) {
cin.close();
}
}
}
}
Let's keep above code in ReadConsole.java file and try to compile and execute it as
below. This program continues reading and outputting same character until we press 'q':
$javac ReadConsole.java
$java ReadConsole
Enter characters, 'q' to quit.
1
1
e
e
q
q
Unit-II
1. What is web 2.0?
A Web 2.0 site may allow users to interact and collaborate with each other in a social media
dialogue as creators of user-generated content in a virtual community, in contrast to Web sites
where people are limited to the passive viewing of content. Examples of Web 2.0 include social
networking sites, blogs, wikis, folksonomies, video sharing sites, hosted services, Web
2. Define RIA.
A rich Internet application (RIA) is a Web application designed to deliver the same features and
functions normally associated with deskop applications. RIAs generally split the processing
across the Internet/network divide by locating the user interface and related activity and
capability on the client side, and the data manipulation and operation on the application server
side.
3. Define collaboration.
AnswerGaeden,Thinkature,DotVoting,ePals,Gaggle,Glass,Tricider.
Team Creation
Idea Generation
Decision-Making
Work or Production
Evaluation or Recap
6. Define Web services.
A Web service is a method of communication between two electronic devices over a network. It
is a software function provided at a network address over the Web with the service always on as
in the concept of utility computing.
A social network is a social structure made up of a set of social actors (such as individuals or
organizations) and a set of the dyadic ties between these actors. The social network perspective
provides a set of methods for analyzing the structure of whole social entities as well as a variety
of theories explaining the patterns observed in these structures.
9. Define Website.
A website is hosted on at least one web server, accessible via a network such as the Internet or a
private local area network through an Internet address known as a uniform resource locator
(URL). All publicly accessible websites collectively constitute the World Wide Web
Website:
A website is a set of linked documents associated with a particular person, organization or topic
that is held on a computer system and can be accessed as part of the world wide web. (Not to be
confused with: Web page, a document on the world wide web written in HTML and displayed
in a web browser.)
Web server:
The web server on the other side is a computer program, which delivers content, such as
websites or web pages, for example, over the world wide web from a web server to your
computer.
The Internet is a global system of interconnected computer networks that use the standard
Internet protocol suite (TCP/IP) to link several billion devices worldwide. It is a network of
networks that consists of millions of private, public, academic, business, and government
networks of local to global scope, linked by a broad array of electronic, wireless, and optical
networking technologies.
An intranet is a computer network that uses Internet Protocol technology to share information,
operational systems, or computing services within an organization. This term is used in contrast
to extranet, a network between organizations, and instead refers to a network within an
organization. Sometimes, the term refers only to the organization's internal website, but may be
a more extensive part of the organization's information technology infrastructure, and may be
composed of multiple local area networks. The objective is to organize each individual's
desktop with minimal cost, time and effort to be more productive, cost efficient, timely, and
competitive.
Internet is general to PCs all over the world whereas Intranet is specific to few PCs.
Internet has wider access and provides a better access to websites to large population whereas
Intranet is restricted.
Internet is not as safe as Intranet as Intranet can be safely privatized as per the need.
14. Define HTML.
HTML is a simple web page description language, which enables document creation for the
web.HTML is the set of mark-up symbols or codes placed in a file intended for display on the
web browser page. These mark-up symbol and codes identify structural elements such as
paragraphs, heading, and lists. HTML can be used to place media (such as graphics, video, and
audio) on the Web page and describe fill-in-forms. A method is an implementation of an objects
behavior.
It is a communication channel between web browser and web server. It begins on the
client side with the browser sending a request to the web server for a document.
1. From
2. Reference
3. If_modified_since
4. Pragma
5. User Agent
Cascading refers to a certain set of rules that browsers use, in cascading order, to determine
how to use the style information. Such a set of rules is useful in the event of conflicting style
information because the rules would give the browser a way to determine which style is given
precedence.
17. State the use of web server logs and list the contents of a message log. (APR/MAY 2011)
A server log is a log file (or several files) automatically created and maintained by a server of
activity performed by it. A typical example is a web server log which maintains a history of
page requests. The W3C maintains a standard format (the Common Log Format) for web server
log files, but other proprietary formats exist.
The message log is used by a number of processes to provide debugging and troubleshooting
information. You can view the message log from the process monitor after clicking on the
details hyperlink for a process and the by clicking on the message log hyperlink in the actions
area.
18. How will you create a password field in a HTML form? (NOV/DEC 2011)
• Google Chrome
• Netscape Navigator
• Microsoft Internet Explorer
• Mozilla
20. State the uses of internet protocol. (APR/MAY 2012)
Tags signal the browser to inform about the formatting details.ie how the content shouls be
displayed in the browser screen. Tags are enclosed between ―<‖ and‖>‖
Standalone tag only start tag is present and no end tag. Example <BR> and container tag have
start and end tag will be present .Example <html>…. </html>
Attributes should be placed inside start tag, appears as Name-value pairs separted by blank
spaces, Attributes should have only one value,values should be enclosed within either single(‗)
or double (―) quotes.
The pre tag can be used to preserve the white spaces and lines in the text.
The cellpadding allows to have some space between the contents of each cell and its borders.
The distance between each cell is called cell spacing.
Form is a typical layout on the web page by which user can interact with the web page. The
components that can be placed on the form are text box, check box, radio buttons, and push
buttons and so on. Thus form is typically used to create an interactive Graphical User Interface.
The HTML frames allows the web designer to present the web document in multiple views.
Using multiple views one can keep the formation visible and at the same time other views can
be scrolled or replaced.
There are some symbols that cannot be used directly in HTML document. For example <(less
than) because this symbol is also used along with the tag. Hence this is called a special symbol
and can be denoted with the help of entity reference.
29. State how an unrecognized element or attribute treated by the HTML document?
If any unrecocognized element or attribute is written then the HTML document simply displays
the contents. For example <title>testing</title> will display the string ―testing‖ on the web
page. It will not display it as a title of the web page.
The hyperlink tag is used to link logically with other page. Using this tag a web link can be
specified. The <a> tag is used to specify the hyperlink in HTML.
To logically link one page with another, use of link to enhance readability of the web document,
the navigation from one page to another is possible.
The effects which we want in the window are mentioned with the help of tags in the body. It is
the place where the actual data is written in html. All the changes can be viewed by changing
the tags content in the body whereas the head part is the introduction part and the body is the
actual content part.<BODY>data content</BODY>
The style sheets are the collection of styles that can be either embedded within the HTML
documents or can be externally applied. The Cascading style sheet is a markup language used to
apply the styles to HTML elements.
The rule set in CSS consists of selector string which is basically an HTML element. These
selectors can be defined with the help of properties and values.
Using the universal selector the values can be defined for all the elements in the document. It is
denoted by *.
The generic class applied to any tag in the HTML document. And thus the values defined within
that generic selector can be applied to the corresponding tag. The class selector must be
preceded by the dot operator.
When we use external style sheet then the style is defined in one file and actual contents of the
web are defined in another file. Hence if we want to change the style of presentation of web
page then we can simply modify the file in which the style is defined.
39. What is the difference the external style sheet and embedded style sheet?
The external style sheet is a kind of style sheet in which the styles are defined in a separate.css
file and this file is mentioned at the beginning of the HTML document. When we need to apply
the particular style to more than one web documents then the external style sheet is used. The
embedded style sheet is a method in which the style is specified within the HTML document
itself. It is not defined in separate file. Due to embedded style sheet unique style can be applied
to all the elements.
The inline elements are those elements that do not form new blocks of content. The content is
distributed in lines.
Inline, external, imported and embedded are the different types of style sheets.
42. Explain inline, embedded and external style sheets.
Inline
If only a small piece of code has to be styled then inline style sheets can be used.
Embedded
Embedded style sheets are put between the <head></head> tags.
External
If you want to apply a style to all the pages within your website by changing just one
style sheet, then external style sheets can be used.
43. Give example for inline style sheet. (APR/MAY 2013)
<h2>InLINE CSS</h2>
<p style=‖color:sienna;margin-left:20px‖>
The style ATTRIBUTE we are able to modify the appearance of HTML elements </p>
44. How will you embed the external style sheet? (May 2014)
In external style sheet is ideal when the style is applied to many pages. With an external style
sheet, you can change the look of an entire Web site by changing just one file.Each page must
include a link to the style sheet with the <link> tag. The <link> tag goes inside the head section:
<head>
<link rel="stylesheet" type="text/css" href="mystyle.css">
</head>
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. An example of a style sheet file is
shown below:
"myStyle.css":
body {
background-color: lightblue;}
h1 {
color: navy;
margin-left: 20px;}
45. How will you include CSS in a web site? (MAY/JUNE 2014)
Inline
Inline styles are when you just insert the type of style you want inside another tag, using the
style attribute. This is usually the least useful way to use CSS.
Embedded
Styles can also be placed in the document using the <style> tag. The <style> tag is usually
placed in the head section of the document, where it will apply to the whole document.
<style><!--
p { color:#009900;
h1 { color:#660000; font-size:12pt; }
</style>
External styles
Styles can also be set in an external style sheet which is linked to the page with a <link> tag.
For example the style sheet for this site is included like this:
46. What is the purpose of CSS Box Model and mention its parts also.
The CSS box model is essentially a box that wraps around HTML elements, and it consists of:
margins, borders, padding, and the actual content.
The different parts are:
• Margin
• Border
• Padding
• Content
Part-B
1. Explain WWW and HTTP Protocol.
WWW
The term WWW refers to the World Wide Web or simply the Web. The World Wide
Web consists of all the public Web sites connected to the Internet worldwide, including
the client devices (such as computers and cell phones) that access Web content. The
WWW is just one of many applications of the Internet and computer networks. The
World Web is based on these technologies:
1. HTML - Hypertext Markup Language
2. HTTP - Hypertext Transfer Protocol
3. Web servers and Web browsers
HTTP
HTTP (Hypertext Transfer Protocol) is the set of rules for transferring files (text,
graphic images, sound, video, and other multimedia files) on the World Wide Web.
HTTP is an application protocol that runs on top of the TCP/IP suite of protocols.
HTTP concepts include (as the Hypertext part of the name implies) the idea that files
can contain references to other files whose selection will elicit additional transfer
requests. Any Web server machine contains, in addition to the Web page files it can
serve, an HTTP daemon, a program that is designed to wait for HTTP requests and
handle them when they arrive. Your Web browser is an HTTP client, sending requests
to server machines. When the browser user enters file requests by either "opening" a
Web file (typing in a Uniform Resource Locator or URL) or clicking on a hypertext
link, the browser builds an HTTP request and sends it to the Internet Protocol address
(IP address) indicated by the URL. The HTTP daemon in the destination server
machine receives the request and sends back the requested file or files associated with
the request. (A Web page often consists of more than one file.)
– In HTTP, typically used to specify content type of the body of the response
– MIME content type syntax:
– top-level type / subtype
– Examples: text/html, image/jpeg
– Example header field with quality values:
accept:
text/xml,text/html;q=0.9,
text/plain;q=0.8, image/jpeg,
image/gif;q=0.2,*/*;q=0.1
– Quality value applies to all preceding items
– Higher the value, higher the preference
– Note use of wildcards to specify quality 0.1 for any MIME type not specified earlier
3. Common header fields:
– Host: host name from URL (required)
– User-Agent: type of browser sending request
– Accept: MIME types of acceptable documents
– Connection: value close tells server to close connection after single request/response
– Content-Type: MIME type of (POST) body, normally application/x-www-form-
urlencoded
– Content-Length: bytes in body
Referer: URL of document containing link that supplied URI for this HTTP request
• Client Caching
– A cache is a local copy of information obtained from some other source
– Most web browsers use cache to store requested resources so that
subsequent requests to the same resource will not necessarily require an
HTTP request/response
• Ex: icon appearing multiple times in a Web page
• Cache advantages
– (Much) faster than HTTP request/response
– Less network traffic
– Less load on server
• Cache disadvantage
– Cached copy of resource may be invalid (inconsistent with remote version)
• Validating cached resource:
– Send HTTP HEAD request and check Last-Modified or ETag header in
response
– Compare current date/time with Expires header sent in response containing
resource
– If no Expires header was sent, use heuristic algorithm to estimate value for
Expires
– Ex: Expires = 0.01 * (Date – Last-Modified) + Date
• Character sets
– Every document is represented by a string of integer values (code points)
– The mapping from code points to characters is defined by a character set
– Some header fields have character set values:
– Accept-Charset: request header listing character sets that the client can
recognize
• Ex: accept-charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7
– Content-Type: can include character set used to represent the body of the
HTTP message
• Ex: Content-Type: text/html; charset=UTF-8
– Technically, many ―character sets‖ are actually character encodings
– An encoding represents code points using variable-length byte strings
– Most common examples are Unicode-based encodings UTF-8 and UTF-16
IANA maintains complete list of Internet-recognized character sets/encodings
4. Explain HTML elements in detail also State the types of lists supported by HTML
and explain them in detail. (APR/MAY 2011)
HTML element
An HTML element is an individual component of an HTML document or web page,
once this has been parsed into the Document Object Model. HTML is composed of a tree
of HTML elements and other nodes, such as text nodes. Each element can have HTML
attributes specified. Elements can also have content, including other elements and text.
HTML elements represent semantics, or meaning. For example, the title element
represents the title of the document.
Heading Tags
Any document starts with a heading. You can use different sizes for your headings.
HTML also has six levels of headings, which use the elements <h1>, <h2>, <h3>, <h4>,
<h5>, and <h6>. While displaying any heading, browser adds one line before and one
line after that heading.
Example
<h1>This is heading 1</h1>
<h2>This is heading 2</h2>
<h3>This is heading 3</h3>
<h4>This is heading 4</h4>
<h5>This is heading 5</h5>
• Log information about the request and response such as IP address and the status
code in a plain-text file.
• If the TCP connection is kept alive , the server subtask continues to monitor the
connection, the client send another request or initiates a connection close.
Few Definitions
• All modern servers concurrently process multiple requests
• Multiple copies of the server running simultaneously(Concurrency)
• Subtask Single copy of server software handling a single client connection
• Virtual Host HTTP request include a host header field
• Multiple host names mapped by a DNS to a single IP address
• Web server determine which virtual host is being requested by examining the
host header field.
Server Configuration and Tuning
• Modern servers have large number of Configuration parameters
• Server Configuration broken into two areas:
– External Communication
– Internal Processing
• In Tomcat two separate Java Packages:
– Coyote
– Catalina
• Coyote Provides HTTP 1.1 communication
– Catalina Actual Servlet Container
Coyote parameters affecting External Communication
IP addresses and TCP ports
Number of subtasks created when server initialized
Max number of threads allowed to exist simultaneously
Max no of TCP connection request that will be queued if server is running its
max no of threads. If queue full the received connection request is refused.
―Keep-alive‖ time for inactive TCP connections
• Settings of the parameter affect the performance of the server.
• Tuning the Server
– Changing the values of these and similar parameters in order to optimize
performance
• Tuning is done by trial and error
• Load generation or stress test tools used to simulate request to a web server
helpful for experimenting with tuning parameters
Service has Five Components
• Connector, Host, Logger, Realm, and Valve
• Connector is a coyote component handles HTTP communication
• Clicking on the connector will produce the window containing the dropdown
menus of possible action that can be performed for this component
Defining Virtual Hosts
Configuring Host Elements
• The Host element represents a virtual host, which is an association of a network
name for a server (such as www.mycompany.com) with the particular server on
which Tomcat is running.
Host Attributes
• The attributes shown in following table may be viewed, set, or modified for a
Host.
• Web server logs record information about server activity
• Access log is a file that records information about every HTTP request
processed by the server
• Message logs variety of debugging and other information generated by web
server
• Access logging is performed by adding a valve component
Logging
• Web server logs record information about server activity
• Access log is a file that records information about every HTTP request
processed by the server
• Message logs variety of debugging and other information generated by web
server
• Access logging is performed by adding a valve component
Access Control
• Provide automatic password protection for resources
• Access control:
– Password protection (e.g., admin pages)
• Users and roles defined in
conf/tomcat-users.xml
<!DOCTYPE html
PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
Example
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html
PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"DTD/xhtml1-transitional.dtd">
7. Explain the significance of XHTML with the help of a real time application. Write
necessary code snippets (MAY/JUNE 2014)
Extensible Hypertext Markup Language (XHTML) is a family of XML markup
languages that mirror or extend versions of the widely used Hypertext Markup
Language (HTML), the language in which Web pages are formulated.
Significance
Sustainability.
Web applications tend towards XML. Using XHTML now instead of HTML
makes any future conversion of the website easier.
Extensibility.
Owing to the extensibility of XML, XHTML documents can be supplemented
with other forms of markup, MathML (Math Markup Language) SVG (Scalable
Vector Graphics) or your own markup variants, thanks to the use of
namespaces.
Compatibility.
Because XHTML documents are written in compliance with the rules of XML,
XML-processing programmes can effortlessly convert an XHTML file to
another format (e.g. PDF, RSS or RTF).
Efficiency of processing applications.
Once browsers support XHTML documents and the strict rules of XML, they
will become quicker thanks to shorter error processing routines. At present, a
great deal of the processing power of a browser is still spent on liberal error
processing of documents containing malformed HTML markup.
Features
XHTML requires strict adherence to coding rules.
Cascading order
What style will be used when there is more than one style specified for an HTML
element?
all the styles will "cascade" into a new "virtual" style sheet by the following rules, where
number four has the highest priority:
1. Browser default
2. External style sheet
3. Internal style sheet (in the head section)
4. Inline style (inside an HTML element)
So, an inline style (inside an HTML element) has the highest priority, which means that it
will override a style defined inside the <head> tag, or in an external style sheet, or in a
browser (a default value).
Note: If the link to the external style sheet is placed after the internal style sheet in HTML
<head>, the external style sheet will override the internal style sheet!
Style Inheritance
• Cascading based on structure of style sheets
• Inheritance based on tree structure of document
• What if no style declaration applies to a property of an element?
• Generally, the property value is inherited from the nearest ancestor element that has a
value for the property
• If no ancestor has a value (or the property does not inherit) then CSS defines an initial
value that is used
• Property values:
• Specified: value contained in declaration
• Absolute: value can be determined without reference to context (e.g.,
2cm)
• Relative: value depends on context (e.g., larger)
• Computed: browser performs calculation depends on particular relative value
• absolute representation of relative value (e.g., larger might be 1.2 x parent font
size)
LINE BOXES:
Text is rendered using line boxes
10. Explain about the various style sheets with examples. (Internal,External,Inline)
(APR/MAY 2013)
1. To create an inline style
a. Add the style attribute to the HTML tag.
b. The style declaration must be enclosed within double quotation marks.
2. To create an embedded style
</html>
Web server and web browser are the terms which are commonly used for website.
The basic purpose of both is to develop a platform for internet web directory. So that
any users can anytime access any kind of website. Major difference between them is
on their function and how they perform their functions. Check for the detail of both
topics before understanding the differences between them.
Web Server:
Web server is a computer system, which provides the web pages via HTTP
(Hypertext Transfer Protocol). IP address and a domain name is essential for every
web server. Whenever, you insert a URL or web address into your web browser, this
sends request to the web address where domain name of your URL is already saved.
Then this server collects the all information of your web page and sends to browser,
which you see in form of web page on your browser. Making a web server is not a
difficult job. You can convert your computer into a web server with the help of any
server software and connecting the computer to the internet. Lot of web server
software are available in the market in shape of NCSA, Apache, Microsoft and
Netscape. Storing, processing and delivering web pages to clients is its main
function. All the communication between client (web browser) and server takes place
via HTTP.
Web Browser:
Web browser is a client, program, software or tool through which we sent HTTP
request to web server. The main purpose of web browser is to locate the content on
the World Wide Web and display in the shape of web page, image, audio or video
form. You can call it a client server because it contacts the web server for desired
information. If the requested data is available in the web server data then it will send
back the requested information again via web browser. Microsoft Internet Explorer,
Mozilla Firefox, Safari, Opera and Google Chrome are examples of web browser and
they are more advanced than earlier web browser because they are capable to
understand the HTML, JavaScript, AJAX, etc. Now a days, web browser for mobiles
are also available, which are called microbrowser.
Difference:
Following are the differences between web server and web browser.
Web server is essential to store all information and data of websites. While web
browser are used to access and locate these information and data.
Web browser is used to search something on the internet via websites. While
web server is used to make the links between websites and web browser.
Web browser is a software or application which is used for collection and
presentation of data in shape of websites while web server is a program server
on computer or in cloud on internet that gives the data.
Internet
Intranet
Internet is general to PCs all over the world whereas Intranet is specific to few
PCs.
Internet has wider access and provides a better access to websites to large
population whereas Intranet is restricted.
Internet is not as safe as Intranet as Intranet can be safely privatized as per the
need.
With the exception of some Flex applications created using Flex Data Services,
almost all Flex applications are composed of precompiled .swf files that are loaded in
Flash Player on the client.
Because Flex applications are stateful and self-contained, they don‘t require new page
requests and wholesale screen refreshes to make data requests and handle responses.
The Flex framework provides components for working with data communication
using standard HTTP requests as well as SOAP requests.
Working with Request/Response Data Communication
You can work with request/response data communication in three basic ways: via
simple HTTP services, web services, and Flash Remoting.
Simple HTTP Services
The most basic type of HTTP request/response communication uses what we call
simple HTTP services. These services include things such as text and XML
resources, either in static documents or dynamically generated by something such as a
ColdFusion page, a servlet, or an ASP.NET page.
HTTPService
HTTPService is a component that allows you to make requests to simple HTTP
services such as text files, XML files, or scripts and pages that return dynamic data.
You must always define a value for the url property of an HTTPService object.
The following example uses MXML to create an HTTPService object that loads text
from a file called data.txt saved in the same directory as the compiled .swf file:
<mx:HTTPService id="textService" url="data.txt" />
Sending requests
Creating an HTTPService object does not automatically make the request to load the
data. In order to make the request, you must call the send( ) method. If you want to
load the data when the use clicks a button, you can call the send( ) method in
response to a click event:
textService.send( );
Handling results
The send( ) method makes the request, but a response is not likely to be returned
instantaneously. Instead, the application must wait for a result event. The following
example displays an alert when the data loads:
<mx:HTTPService id="textService" url="data.txt" result="mx.controls.Alert.show('Data loaded')" />
Sending parameters
When you want to pass parameters to the service, you can use the request property of
the HTTPService instance. The request property requires an Object value. By
default, the name/value pairs of the object are converted to URL-encoded format and
are sent to the service using HTTP GET.
The default value is object, which yields the default behavior you‘ve already seen.
You can optionally specify any of the following values:
text
The data is not parsed at all, but is treated as raw text.
flashvars
The data is assumed to be in URL-encoded format, and it will be parsed
into an object with properties corresponding to the name/value pairs.
array
The data is assumed to be in XML format, and it is parsed into objects much
the same as with the object settings. However, in this case, the result is always
an array. If the returned data does not automatically parse into an array, the
1. What is JavaScript?
JavaScript supports five primitive data types: number, string, Boolean, undefined, and null.
These types are referred to as primitive typesbecause 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. Undefinedand null are types that arise under
special circumstances.
\n Linefeed (newline),\v Tab (vertical),\f Form feed,\r Carriage return,\" Double quote
Using global variables in JavaScript is evil and a bad practice. That being said,
namespacing is used to bundle up all your functionality using a unique name. In JavaScript, a
namespace is really just an object that you‘ve attached all further methods, properties and
objects. It promotes modularity and code reuse in the application.
If you are a programmer, you know the use of loops. It is used to run a piece of code multiple
times according to some particular condition. Javascript being a popular scripting language
supports the following loops for, while, do-while loop
<!DOCTYPE html>
<html>
<head>
<script>
function validateForm() {
var x = document.forms["myForm"]["email"].value;
varatpos = x.indexOf("@");
vardotpos = x.lastIndexOf(".");
if (atpos<1 || dotpos<atpos+2 || dotpos+2>=x.length) {
alert("Not a valid e-mail address");
return false;}}
</script>
</head>
<body>
<form name="myForm" action="demo_form.asp" onsubmit="return validateForm();"
method="post">
Email: <input type="text" name="email">
<input type="submit" value="Submit">
</form>
</body>
</html>
18. Write short notes on JDBC.
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.
Performance is significantly better, servlet execute within the address space of a web server.
Servlets are platform independent
The java security manager on the server enforces a set of restrictions to protect the resources on
a server machine.
The full functionality of java class libraries is available to a servlet.
21. Write down the methods of servlet interface
<!DOCTYPE html>
<html>
<head>
<script>
function validateForm() {
var x = document.forms["myForm"]["email"].value;
varatpos = x.indexOf("@");
vardotpos = x.lastIndexOf(".");
if (atpos<1 || dotpos<atpos+2 || dotpos+2>=x.length) {
alert("Not a valid e-mail address");
return false;}}
</script>
</head>
<body>
<form name="myForm" action="demo_form.asp" onsubmit="return validateForm();"
method="post">
Email: <input type="text" name="email">
<input type="submit" value="Submit">
</form>
</body>
</html>
18. Write short notes on JDBC.
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.
Performance is significantly better, servlet execute within the address space of a web server.
Servlets are platform independent
The java security manager on the server enforces a set of restrictions to protect the resources on
a server machine.
The full functionality of java class libraries is available to a servlet.
21. Write down the methods of servlet interface
occurs.
Performance is significantly better, servlet execute within the address space of a web
server.
Servlets are platform independent
The java security manager on the server enforces a set of restrictions to protect the
resources on a server machine.
The full functionality of java class libraries is available to a servlet.
23. Define Servlet Life Cycle?
init( ) method - invoked when the servlet is first loaded into memory
service( ) - called for each HTTP request (for processing)
destroy( ) - unloads the servlet from its memory.
24. What is JSP?
JavaServer Pages (JSP) is a technology for developing web pages that support dynamic content
which helps developers insert java code in HTML pages by making use of special JSP tags,
most of which start with <% and end with %>.
Performance is significantly better because JSP allows embedding Dynamic Elements in HTML
Pages itself.
JSP are always compiled before it's processed by the server unlike CGI/Perl which requires the
server to load an interpreter and the target script each time the page is requested.
26. Explain lifecycle of a JSP.
Compilation
Initialization
Execution
Cleanup
27. What are the types of directive tags?
JSP actions use constructs in XML syntax to control the behavior of the servlet engine. You can
dynamically insert a file, reuse JavaBeans components, forward the user to another page, or
generate HTML for the Java plugin.
Part - B
3. Discuss Javascript objects in detail with suitable examples. (NOV/DEC 2012, MAY/JUNE
2014)
4. Discuss about Javascript debugging. Explain how local and global functions can be written
using java script (MAY/JUNE 2012)
5. Explain the way in which java script handles arrays with example. (MAY/JUNE 2012)
8. Write a Java script program to create Popup box, alert and confirm box.
9. Write a Java script program to print the numbers from 0 to 50. b. Write a Java Script program
to create table.
10. Write a Java script program to create user registration form.
11.i) (i)Explain JavaScript & document object model (DOM ) with example.(8)
(ii)Explain in details the JDBC CONNECTIVITY with example program.(8)
12. Explain the JDBC database access in detail. Write a java servlet to conduct online examination.
(APR/MAY 2013)
13. What is a servlet? Explain briefly the Servlet life cycle and Servlet HTTP package?
14. List out the classes and interfaces available in javax.servlet.http package?
16. Write a servlet program which displays the different image each time the user visits the page
and the images are links
17. Explain in detail about Servlet Database Connectivity with an example of Student database.
a. Write a servlet for creating Student Entry form. b. Write a servlet for creating Department
details.
18. Explain in detail about JSP with an example of currents date and simple message.
19. Discuss in detail about Action elements in JSP with an example of display current time and
color.
20. Explain about JSP object in detail.
Unit – IV
Part - A
1. What is PHP?
PHP - Hypertext Preprocessor -one of the most popular server-side scripting languages for
creating dynamic Web pages.
an open-source technology
platform independent
2. List the data types used in PHP.
In PHP, data-type conversion can be performed by passing the data type as an argument to
function settype. Function settype takes two arguments: The variable whose data type is to be
changed and the variable ‘s new data type.
PHP processes text data easily and efficiently, enabling straightforward searching, substitution,
extraction and concatenation of strings.
Text manipulation in PHP is usually done with regular expressions — a series of characters that
serve as pattern-matching templates (or search criteria) in strings, text files and databases.
This feature allows complex searching and string processing to be performed using relatively
simple expressions
5. List the important characteristics of PHP.
</script>
• Method (2) is useful in environments supporting mixed scripting languages in the same
HTML file
Here is PHP script which is embedded in HTML using level one header with the PHP
output text. The name of this file is called hello.php.
<html>
<head>
<title>Hello world</title>
</head>
<body>
</body>
<html>
E.g.:
$myInteger = 3;
$myFloat = 3.145;
Defined as false
Defined as true
$myArray[1]= "Bananas";
$myArray["Monday"]= "Apples";
$myArray["Tuesday"]= "Bananas";
The symbol => delimits the hash name from the hash value.
Once PHP variables have been defined they are known for the rest of the Web page:
if,
if/else
switch
while
for
16. $a=3;
Function what()
++$a;
echo "a=$a\n";
what();
echo "a=$a\n";
13
Preg_match,
Preg_matchall,
Preg_replace,
Preg_split
18. Write a PHP script to set the background colour to blue on Tuesday in a given date.
<?php
?>
<html>
<head>
<title>Welcome</title>
</head>
<h1>Welcome</h1>
</body>
</html>
A cookie is a text string stored on the client machine by your script (to track users and manage
transactions). Cookies are automatically returned (by the client), and can be accessed using a
variable of the same name
• The following script reads and displays a cookie, and sets it with a new value (string) that was
passed to the script as a parameter.
<html>
<head><title>Welcome</title></head>
<body>
</body>
</html>
Extensible markup language. It offer a standard, flexible and inherently extensible data format,
XML significantly reduces the burden of deploying the many technologies needed to ensure the
success of Web services.
XML Namespaces provide a method to avoid element name conflicts. When using prefixes in
XML, a so-called namespace for the prefix must be defined. The namespace is defined by the
xmlns attribute in the start tag of an element. The namespace declaration has the following
syntax. xmlns:prefix="URI".
<root><h:tablexmlns:h="http://www.w3.org/TR/html4/">
<h:tr>
<h:td>Apples</h:td>
<h:td>Bananas</h:td>
</h:tr></h:table>
<f:tablexmlns:f="http://www.w3schools.com/furniture">
<f:width>80</f:width>
<f:length>120</f:length></f:table></root>
XML Namespaces provide a method to avoid element name conflicts. In XML, element names
are defined by the developer. This often results in a conflict when trying to mix XML
documents from different XML applications.
DOM SAX
DOM is an interface-oriented SAX parser works incrementally and generates
Application Programming Interface. events that are passed to the application.
It allows for navigation of the entire DOM parser reads the whole XML document and
document. returns a DOM tree representation of xml
document.
DOM allows you to read and write. SAX is essentially an API for reading XML
27. What are complex types?
complex types are an important aspects of xml schema that allow application developers to
define application-specific data types that can be checked by programs that check XML
document for validity. XML schema divides complex types into two categories: those with
simple content& those with complex content.
XSLT - it is an XML- based languages used to transform XML documents into others format
such as HTML for web display.
XLINK - highlighting that element or taking the user directly to that point in the document.
XPATH - xpath gets its name from its use of a payh notation to navigate through the
hierarchical tree structure of an XML document
XQUERY - it is W3C initiative to define a standard set of constructs for querying & searching
XML document.
29. What is XSLT?
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.
DTD is stands for Document Type Definition which is used to structure the XML
document. The type of DTD are as follows i) Internal Declaration ii) External Declaration.
An XML schema is itself an XML document. It provides more detail about the kind of data
that can appear as part of an XML document.
The schemas are more specific and provide the support for data types.
The schema is aware of namespace
The XML Schema is written in XML itself and has a large number of built-in and derived types.
The xml schema is the W3C recommendation. Hence it is supported by various XML validator
and XML Processors.
35. What are the disadvantages of schema?
Mozilla Firefox
As of version 1.0.2, Firefox has support for XML and XSLT (and CSS).
Mozilla: Mozilla includes Expat for XML parsing and has support to display XML + CSS.
Mozilla also has some support for Namespaces. Mozilla is available with an XSLT
implementation.
Netscape: As of version 8, Netscape uses the Mozilla engine, and therefore it has the same
XML / XSLT support as Mozilla.
Opera: As of version 9, Opera has support for XML and XSLT (and CSS). Version 8 supports
only XML + CSS.
Internet Explorer: As of version 6, Internet Explorer supports XML, Namespaces, CSS,
XSLT, and XPath. Version 5 is NOT compatible with the official W3C XSL Recommendation.
XML presentation technologies provide a modular way to deliver and display content to a
variety of devices. There are different presentation technologies used in XML to display the
content. Eg: CSS
Presentation technologies provide a modular way to deliver and display content to a variety of
devices.
SAX is an example of a grass- roots development effort to provide a simple; Java based API for
processing XML.
Part – B
1. List and explain the XML syntax rules in detail. Explain how a XML document can be
displayed on a browser. ( APR/MAY 2011 )
3. Given an XSLT document and a source XML document explain the XSLT transformation process
that produces a single result XML document. (NOV/DEC 2012)
5. Explain the following: XML namespace ii) XML style sheet. iii) XML attributes iv) XML
Schema
8. Write a program using PHP that creates the web application for result publication
13. Describe the data base connections in PHP with suitable example.
14. Explain the steps in the PHP code for querying a database with suitable examples.
Unit-V
Part – A
1. What is 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.
2. What technologies are being used in AJAX?
6. How can you find out that an AJAX request has been completed?
You can find out that an AJAX request has been completed by using
the readyState property. If the value of this property equals to four, it means that the
request has been completed and the data is available.
7. 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);
The extender controls uses a block of JavaScript code to add new and enhanced capabilities to
ASP.NET. The developers can use a set of sample extender controls through a separate
download - AJAX Control Toolkit (ACT).
• Better interactivity
• Easier navigation
• Compact
• Backed by reputed brands
10. Define Web service? (Nov 2011)
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).
11. What are the different applications that could use web services??
Data providers, for example, those that provide data such as a stock quote
Business-to-business process integrations, such as those that send a purchase order from
one company to another
Integration with multiple partners, and even with competitors
Enterprise application integration, for example, integration of a company's e-mail
database with its human resources (HR) database
12. What are the features of web service?
Web services are having the features such as heterogeneous, interoperable, loosely coupled, and
implementation-independent programs and modular design
13. What are the rules to be followed in designing the web service?
Web Services Description Language (WSDL) is a document written in XML. The document
describes a Web service. It specifies the location of the service and the operations (or methods)
the service exposes.
Web services encompass a set of related standards that can enable two computers
The data is passed back and forth using standard protocols such as HTTP, the same protocol
used to transfer ordinary web pages.
Web services operate using open, text-based standards that enable components written in
different languages and on different platforms to communicate.
They are ready to use pieces of software on the Internet. XML, SOAP, Web Services
Description Language (WSDL) and Universal Description, Discovery and Integration (UDDI)
are the standards on which web services rely.
UDDI is another XML based format that enables developers and business to publish and locate
Web services on a network.
18. State the uses of WSDL. (APR/MAY 2012)
One-way
Request–response
Solicit–response
Notification
20. State the significance of a WSDL document. (NOV/DEC 2012)
ELEMENT DESCRIPTION
Types It Specifies the data types of the symbols used by the web services.
Messages It specifies the messages used by the web services.
Porttype It specifies the name of the operations
Binding It specifies the name of the protocol of the web services, typically it is SO
UDDI defines four core data elements within the data model:
businessEntity (modeling business information)
businessService (describing a service)
tModel (describing specifications, classifications, or identifications)
binding Template (mapping between a businessService and the set of tModels that
describe its technical fingerprint)
24. List some examples of web services. (APR/MAY 2012)
XML
SOAP
WSDL
26. What is SOAP?
<Envelope> is the root element in every SOAP message, and contains two child elements, an
optional <Header> element, and a mandatory <Body> element.
<Header> is an optional sub element of the SOAP envelope, and is used to pass application-
related information that is to be processed by SOAP nodes along the message path; see The
SOAP header.
<Body> is a mandatory sub element of the SOAP envelope, which contains information
intended for the ultimate recipient of the message; see The SOAP body.
<Fault> is a sub element of the SOAP body, which is used for reporting errors; see The SOAP
fault.
XML elements in <Header> and <Body> are defined by the applications that make use of them,
although the SOAP specification imposes some constraints on their structure.
Simple Object Access Protocol (SOAP) is a protocol based on XML. It is used by the web
services for exchange of information. The Client- Server communication is based on RPC. The
HTTP does not design to handle the distributed objects that are required by the RPC. Hence
another application protocol is build over HTTP which popularly known as SOAP. SOAP
allows talking different applications that are running in two different operating systems.
It refers to a place in which service providers can impart information about their offered
Web services standards features such as transactions are currently nonexistent or still in their
infancy compared to more mature distributed computing open standards such as CORBA. Web
services may suffer from poor performance compared to other distributed computing
approaches such as RMI, CORBA, or DCOM.
Java Web Service Developer Pack (JWSDP) is a tool. Using the JWSDP tool the simple
implementation files written in java can be converted to Web Service.
1. Explain about the object that helps AJAX reload parts of a web page without reloading the
whole page. (NOV/DEC 2011, MAY/JUNE 2014)
6. With a simple example illustrate the steps to create a java web service. (NOV/DEC 2012)
8. Explain the creation of a java web service Client in detail with examples. (MAY/JUNE 2012)
12. Describe the major elements of SOAP. (NOV/DEC 2011, MAY/JUNE 2014) (APR/MAY
2013)
Anonymous class: Anonymous class is a class defined inside a method without a name and is instantiated and
declared in the same place and cannot have explicit constructors.
13. Define interface and write the syntax of the Interface.
Interface is an outside view of a class or object which emphaizes its abstraction while hiding its structure and
secrets of its behaviour.
Syntax:
[visibility] interface InterfaceName [extends other interfaces] {
constant declarations
abstract method declarations
}
14. What is the difference between abstract class and interface?
a) All the methods declared inside an interface are abstract whereas abstract class must have at least one abstract
method and others may be concrete or abstract.
b) In abstract class, key word abstract must be used for the methods whereas interface we need not use that
keyword for the methods.
c) Abstract class must have subclasses whereas interface can’t have subclasses.
15. What is an exception?
An exception is an event, which occurs during the execution of a program, that disrupts the normal flow of the
program's instructions.
16. What is meant by JAVA package?(Nov/Dec 2014)
Package represents a collection of classes, methods and interface. The name of the package must be written as the
first statement in the java source program. The syntax of specifying the package in the java program is: package
name_of_package
17. What are the types of Exceptions in Java?
There are two types of exceptions in Java, unchecked exceptions and checked exceptions.
Checked exceptions: A checked exception is some subclass of Exception (or Exception itself), excluding class
RuntimeException and its subclasses. Each method must either handle all checked exceptions by supplying a catch
clause or list each unhandled checked exception as a thrown exception.
Unchecked exceptions: All Exceptions that extend the RuntimeException class are unchecked exceptions. Class
Error and its subclasses also are unchecked.
18. What are the different ways to handle exceptions?
There are two ways to handle exceptions:
• Wrapping the desired code in a try block followed by a catch block to catch the exceptions.
• List the desired exceptions in the throws clause of the method and let the caller of the method handle those
exceptions.
19. How to create custom exceptions? By Extending
the Exception class or one of its subclasses.
class MyException extends Exception {
public MyException() { super(); }
public MyException(String s) { super(s);
} }
20. Write the properties of Threads.(Nov/Dec 2014).
• Thread Priority
• Deamon Thread
• Thread group
21. What is multi-threaded programming?(Nov/Dec 2014)
Multithreading is the ability of a program or an operating system process to manage its use by more than one user
at a time and to even manage multiple requests by the same user without having to have multiple copies of the
23. What is daemon thread and which method is used to create the daemon thread?
A daemon thread is a thread, that does not prevent the JVM from exiting when the program finishes but the thread
is still running. An example for a daemon thread is the garbage collection. You can use the setDaemon() method to
change the Thread daemon properties
24. What is the purpose of toString() method in java ?
The toString() method returns the string representation of any object. If you print any object, java compiler
internally invokes the toString() method on the object. So overriding the toString() method, returns the desired
output, it can be the state of an object etc. depends on your implementation.
25. What is immutable string in java?
In java, string objects are immutable. Immutable simply means unmodifiable or unchangeable. Once string
object is created its data or state can't be changed but a new string object is created.
Eg:
class Testimmutablestring{
public static void main(String args[]){
String s="Sachin";
s.concat(" Tendulkar");//concat() method appends the string at the end
System.out.println(s);//will print Sachin because strings are immutable objects
}
26. Define assert .
Java assertion feature allows developer to put "assert" statements in Java source code to help unit testing and
debugging.
An "assert" statement has the following format:
assert boolean_expression : string_expression;
When this statement is executed:
If boolean_expression evaluates to true, the statement will pass normally.
If boolean_expression evaluates to false, the statement will fail with an "AssertionError" exception.
27. Define Applet.
An applet is a small Internet-based program written in Java, a programming language for the Web, which can be
downloaded by any computer. The applet is also able to run in HTML. The applet is usually embedded in an
HTML page on a Web site and can be executed from within a browser.
28. Define transient and volatile Modifiers.
Java defines two interesting type modifiers: transient and volatile. These modifiers are usedto handle somewhat
specialized situations. When an instance variable is declared as transient, then its value need not persist when an
object is stored. For example:
class T {
transient int a; // will not persist
int b; // will persist
}
Here, if an object of type T is written to a persistent storage area, the contents of a would not be saved, but the
contents of b would.
29. What is use of the run-time operator instanceof.
The instanceof operator has this general form:
objref instanceof type
Here, objref is a reference to an instance of a class, and type is a class type. If objref is of the specified type or can
be cast into the specified type, then the instanceof operator evaluates to true. Otherwise, its result is false. Thus,
instanceof is the means by which your program canobtain run-time type information about an object
30. How to Enabling and Disabling Assertion Options?
When executing code, you can disable assertions by using the -da option. You can enable or disable a
specific package by specifying its name after the -ea or -da option. For example, to enable assertions in a package
called MyPack, use
-ea:MyPack
To disable assertions in MyPack, use
-da:MyPack
31. Define String Constructors.
The String class supports several constructors. To create an empty String, you call the default
constructor. For example,
String s = new String();
will create an instance of String with no characters in it. Frequently, you will want to create strings that have initial
values. The String class provides a variety of constructors to handle this. To create a String initialized by an array
of characters, use the constructor shown here:
String(char chars[ ])
Here is an example:
char chars[] = { 'a', 'b', 'c' };
String s = new String(chars);
This constructor initializes s with the string “abc”.
32. What are the String Comparison?
The String class includes several methods that compare strings or substrings within strings.
equals( ) and equalsIgnoreCase( To compare two strings for equality, use equals( ). To perform a
) comparison that ignores case differences, call equalsIgnoreCase( ).
regionMatches( ) The regionMatches( ) method compares a specific region inside a string
with another specific region in another string.
startsWith( ) and endsWith( ) The startsWith( ) method determines whether a given String begins with a
specified string.
Conversely, endsWith( ) determines whether the String in question ends
with a specified string.
equals( ) Versus = = The equals( ) method compares the characters inside a String object. The =
= operator compares two object references to see whether they refer to the
same instance.
compareTo( ) to simply know whether two strings are identical
class Bank{
int getRateOfInterest(){return 0;}
}
class Test2{
public static void main(String args[]){
SBI s=new SBI();
ICICI i=new ICICI();
AXIS a=new AXIS();
System.out.println("SBI Rate of Interest: "+s.getRateOfInterest());
System.out.println("ICICI Rate of Interest: "+i.getRateOfInterest());
System.out.println("AXIS Rate of Interest: "+a.getRateOfInterest());
}
}
Output:
SBI Rate of Interest: 8
ICICI Rate of Interest: 7
AXIS Rate of Interest: 9
-------------------------------------------------------------------------------------------------------------------------------
(iii) Write a JAVA program to reverse the given number.(6)
import java.util.*;
public class RevNumString
{
public static void main(String[] args)
{
Scanner scanner = new Scanner(System.in);
System.out.println("Please enter a number: ");
int num = scanner.nextInt();
System.out.println("Please enter a string: ");
String str = scanner.next();
RevNumString rns = new RevNumString();
int revNum = rns.reverse(num);
String revStr = rns.reverse(str);
System.out.printf("\n The reverse of number %d is %d ", num, revNum);
System.out.printf("\n The reverse of string '%s' is '%s' ", str, revStr);
}
// Method to return the reverse of a number
public int reverse(int num) {
int revNum = 0;
while (num > 0) {
int rem = num % 10;
revNum = (revNum * 10) + rem;
num = num / 10;
}
return revNum;
}
// Method to return the reverse of a string
public String reverse(String str) {
StringBuilder revStr = new StringBuilder();
for (int i = str.length()-1; i >= 0; i--) {
revStr.append(str.charAt(i));
}
return revStr.toString();
}
}
Program Output:
Please enter a number:
1234
Programmers can define their own packages to bundle group of classes/interfaces, etc. It is a good
practice to group related classes implemented by you so that a programmer can easily determine that the
classes, interfaces, enumerations, annotations are related.
Since the package creates a new namespace there won't be any name conflicts with names in other
packages. Using packages, it is easier to provide access control and it is also easier to locate the related
classes.
Creating a package:
When creating a package, you should choose a name for the package and put a package statement with
that name at the top of every source file that contains the classes, interfaces, enumerations, and
annotation types that you want to include in the package.
The package statement should be the first line in the source file. There can be only one package
statement in each source file, and it applies to all types in the file.
If a package statement is not used then the class, interfaces, enumerations, and annotation types will be
put into an unnamed package.
Example:
Let us look at an example that creates a package called animals. It is common practice to use
lowercased names of packages to avoid any conflicts with the names of classes, interfaces.
Put an interface in the package animals:
/* File name : Animal.java */
package animals;
interface Animal {
public void eat();
public void travel();
}
Now, put an implementation in the same package animals:
package animals;
package payroll;
public class Boss
{
public void payEmployee(Employee e)
{
e.mailCheck();
}
}
What happens if Boss is not in the payroll package? The Boss class must then use one of the following
techniques for referring to a class in a different package.
The fully qualified name of the class can be used. For example:
payroll.Employee
The package can be imported using the import keyword and the wild card (*). For example:
import payroll.*;
The class itself can be imported using the import keyword. For example:
import payroll.Employee;
Note: A class file can contain any number of import statements. The import statements must appear
after the package statement and before the class declaration.
Now, put the source file in a directory whose name reflects the name of the package to which the class
belongs:
....\vehicle\Car.java
Now, the qualified class name and pathname would be as below:
Class name -> vehicle.Car
Path name -> vehicle\Car.java (in windows)
In general, a company uses its reversed Internet domain name for its package names. Example: A
company's Internet domain name is apple.com, then all its package names would start with com.apple.
Each component of the package name corresponds to a subdirectory.
Example: The company had a com.apple.computers package that contained a Dell.java source file, it
would be contained in a series of subdirectories like this:
....\com\apple\computers\Dell.java
At the time of compilation, the compiler creates a different output file for each class, interface and
enumeration defined in it. The base name of the output file is the name of the type, and its extension is
.class
For example:
// File Name: Dell.java
package com.apple.computers;
}
Now, compile this file as follows using -d option:
$javac -d . Dell.java
----------------------------------------------------------------------------------------------------------------------------
(ii) Write a JAVA program to find the smallest number in the given list. (8)
import java.util.Scanner;
class group{
public static void main(String arng[]){
int value[]= new int[5];
int temp,i;
Scanner data = new Scanner(System.in);
System.out.println("Enter 5 element of array" );
// Enhanced for loop
for(i=0; i < 5; i++ )
value[i] = data.nextInt();
// finding smallest number
temp = value[0];
for(i=0; i < 5; i++ )
{
if(temp < value[i])
continue;
else
temp = value[i];
}
System.out.println("Smallest number in array is "+temp);
}
}
Output:-
Enter 5 element of array
56
84
95
12
32
Smallest number in array is 12
Output:-
Enter 5 element of array
48
124
20
54
14
An interface is not a class. Writing an interface is similar to writing a class, but they are two different
concepts. A class describes the attributes and behaviors of an object. An interface contains behaviors
that a class implements.
Unless the class that implements the interface is abstract, all the methods of the interface need to be
defined in the class.
Declaring Interfaces:
The interface keyword is used to declare an interface. Here is a simple example to declare an
interface:
Example:
Example:
Implementing Interfaces:
When a class implements an interface, you can think of the class as signing a contract, agreeing to
perform the specific behaviors of the interface. If a class does not perform all the behaviors of the
interface, the class must declare itself as abstract.
A class uses the implements keyword to implement an interface. The implements keyword appears in
the class declaration following the extends portion of the declaration.
m.eat();
m.travel();
}
}
Mammal eats
Mammal travels
When overriding methods defined in interfaces there are several rules to be followed:
Checked exceptions should not be declared on implementation methods other than the ones declared
by the interface method or subclasses of those declared by the interface method.
The signature of the interface method and the same return type or subtype should be maintained
when overriding the methods.
An implementation class itself can be abstract and if so interface methods need not be implemented.
(xv) A class can extend only one class, but implement many interfaces.
(xvi) An interface can extend another interface, similarly to the way that a class can extend
another class.
Extending Interfaces:
An interface can extend another interface, similarly to the way that a class can extend another class.
The extends keyword is used to extend an interface, and the child interface inherits the methods of the
parent interface.
//Filename: Sports.java
public interface Sports
{
public void setHomeTeam(String name);
public void setVisitingTeam(String name);
}
//Filename: Football.java
public interface Football extends Sports
{
public void homeTeamScored(int points);
public void visitingTeamScored(int points);
public void endOfQuarter(int quarter);
}
//Filename: Hockey.java
public interface Hockey extends Sports
{
public void homeGoalScored();
public void visitingGoalScored();
public void endOfPeriod(int period);
public void overtimePeriod(int ot);
}
The Hockey interface has four methods, but it inherits two from Sports; thus, a class that implements
Hockey needs to implement all six methods. Similarly, a class that implements Football needs to
define the three methods from Football and the two methods from Sports.
Extending Multiple Interfaces:
A Java class can only extend one parent class. Multiple inheritance is not allowed. Interfaces are not
classes, however, and an interface can extend more than one parent interface.
The extends keyword is used once, and the parent interfaces are declared in a comma-separated list.
For example, if the Hockey interface extended both Sports and Event, it would be declared as:
Type Description
Member Inner
A class created within class and outside method.
Class
Anonymous Inner A class created for implementing interface or extending class. Its
Class name is decided by the java compiler.
Local Inner Class A class created within method.
Static Nested Class A static class created within class.
Nested Interface An interface created within class or interface.
-------------------------------------------------------------------------------------------------------------------------------------
(ii) Explain in details the concepts of applets.
Applet is a special type of program that is embedded in the webpage to generate the dynamic content. It
runs inside the browser and works at client side.
Advantage of Applet
There are many advantages of applet. They are as follows:
It works at client side so less response time.
Secured
It can be executed by browsers running under many plateforms, including Linux, Windows, Mac
Os etc.
Drawback of Applet
Plugin is required at client browser to execute applet.
Hierarchy of Applet
As displayed in the above diagram, Applet class extends Panel. Panel class extends Container which is the subclass
of Component.
Lifecycle of Java Applet
1. Applet is initialized.
2. Applet is started.
3. Applet is painted.
4. Applet is stopped.
5. Applet is destroyed.
6.
Lifecycle methods for Applet:
The java.applet.Applet class 4 life cycle methods and java.awt.Component class provides 1 life cycle
methods for an applet.
java.applet.Applet class
For creating any applet java.applet.Applet class must be inherited. It provides 4 life cycle methods of
applet.
1. public void init(): is used to initialized the Applet. It is invoked only once.
2. public void start(): is invoked after the init() method or browser is maximized. It is used to start
the Applet.
3. public void stop(): is used to stop the Applet. It is invoked when Applet is stop or browser is
minimized.
4. public void destroy(): is used to destroy the Applet. It is invoked only once.
java.awt.Component class
The Component class provides 1 life cycle method of applet.
1. public void paint(Graphics g): is used to paint the Applet. It provides Graphics class object that
can be used for drawing oval, rectangle, arc etc.
}
/*
<applet code="First.class" width="300" height="300">
</applet>
*/
To execute the applet by appletviewer tool, write in command prompt:
c:\>javac First.java
c:\>appletviewer First.java
5. What is Exception handling in java? Why it is used? Write a java code to simulate the way a stack
mechanisms works with exception handling, throwing and dealing with exceptions such as stack is full( if
you want to add more elements into the stack)or Stack is empty(you want to pop elements from the stack).
An exception is a problem that arises during the execution of a program. An exception can occur for
many different reasons, including the following:
Some of these exceptions are caused by user error, others by programmer error, and others by physical
resources that have failed in some manner.
To understand how exception handling works in Java, you need to understand the three categories of
exceptions:
class SimpleStackDemo {
public static void main(String arg[])
{
FixedLengthStack stack=new FixedLengthStack(5);
char ch;
int i;
try{
// overrun the stack
for(i=0;i<6;i++)
System.out.println(“Attempting to push:”+(char) (‘A’+i));
stack.push((char) (‘A’+i));
System.out.println(“=ok”);
}
catch(StackFullException exc) {
System.out.println(exc);
}
System.out.println();
try{
//over-empty the stack
for(i=0;i<6;i++) {
When we start two or more threads within a program, there may be a situation when multiple threads try
to access the same resource and finally they can produce unforeseen result due to concurrency issue. For
example if multiple threads try to write within a same file then they may corrupt the data because one of
the threads can overrite data or while one thread is opening the same file at the same time another thread
might be closing the same file.
So there is a need to synchronize the action of multiple threads and make sure that only one thread can
access the resource at a given point in time. This is implemented using a concept called monitors. Each
object in Java is associated with a monitor, which a thread can lock or unlock. Only one thread at a time
may hold a lock on a monitor.
Java programming language provides a very handy way of creating threads and synchronizing their task
by using synchronized blocks. You keep shared resources within this block. Following is the general
form of the synchronized statement:
synchronized(objectidentifier) {
// Access shared variables and other shared resources
}
Here, the objectidentifier is a reference to an object whose lock associates with the monitor that the
synchronized statement represents. Now we are going to see two examples where we will print a counter
using two different threads. When threads are not synchronized, they print counter value which is not in
sequence, but when we print counter by putting inside synchronized() block, then it prints counter very
much in sequence for both the threads.
Here is the same example which prints counter value in sequence and every time we run it, it produces
same result.
class PrintDemo {
public void printCount(){
try {
for(int i = 5; i > 0; i--) {
System.out.println("Counter --- " + i );
}
} catch (Exception e) {
System.out.println("Thread interrupted.");
}
}
T1.start();
T2.start();
This produces same result every time you run this program:
Starting Thread - 1
Starting Thread - 2
Counter --- 5
Counter --- 4
Counter --- 3
Counter --- 2
Counter --- 1
Thread Thread - 1 exiting.
Counter --- 5
Counter --- 4
Counter --- 3
Counter --- 2
Counter --- 1
Thread Thread - 2 exiting.
/**
* Reader.java
*
* A reader to the database.
*
*/
database.releaseReadLock(readerNum);
}
}
;
}
//**************************************************************
/**
* Writer.java
*
* A writer to the database.
*
*/
class Writer implements Runnable
{
private RWLock database;
private int writerNum;
database.releaseWriteLock(writerNum);
}
}
}
7. (i) Describe the concept of I/O with example.(8)
Java I/O (Input and Output) is used to process the input and produce the output based on the input.
Java uses the concept of stream to make I/O operation fast. The java.io package contains all the classes
required for input and output operations.
We can perform file handling in java by java IO API.
Stream
A stream is a sequence of data.In Java a stream is composed of bytes. It's called a stream because it's like
a stream of water that continues to flow.
In java, 3 streams are created for us automatically. All these streams are attached with console.
1) System.out: standard output stream
2) System.in: standard input stream
3) System.err: standard error stream
Let's see the code to print output and error message to the console.
1. System.out.println("simple message");
2. System.err.println("error message");
Let's see the code to get input from console.
1. int i=System.in.read();//returns ASCII code of 1st character
2. System.out.println((char)i);//will print the character
3.
OutputStream
Java application uses an output stream to write data to a destination, it may be a file,an array,peripheral
device or socket.
InputStream
Java application uses an input stream to read data from a source, it may be a file,an array,peripheral
device or socket.
Let's understand working of Java OutputStream and InputStream by the figure given below.
OutputStream class
OutputStream class is an abstract class.It is the superclass of all classes representing an output stream of
bytes. An output stream accepts output bytes and sends them to some sink.
InputStream class
InputStream class is an abstract class.It is the superclass of all classes representing an input stream of
bytes.
Commonly used methods of InputStream class
Method Description
1) public abstract int read()throws reads the next byte of data from the input stream.It
IOException: returns -1 at the end of file.
2) public int available()throws returns an estimate of the number of bytes that can be
IOException: read from the current input stream.
3) public void close()throws
is used to close the current input stream.
IOException:
-------------------------------------------------------------------------------------------------------------------------------
(ii) Explain the detail about string handling.(8).
Java String provides a lot of concepts that can be performed on a string such as compare, concat, equals,
split, length, replace, compareTo, intern, substring etc.
1. char[] ch={'j','a','v','a','t','p','o','i','n','t'};
2. String s=new String(ch);
is same as:
1. String s="javatpoint";
The java String is immutable i.e. it cannot be changed but a new instance is created. For mutable class,
you can use StringBuffer and StringBuilder class.
Generally, string is a sequence of characters. But in java, string is an object that represents a sequence of
characters. String class is used to create string object.
There are two ways to create String object:
1. By string literal
2. By new keyword
1) String Literal
1. String s="welcome";
Each time you create a string literal, the JVM checks the string constant pool first. If the string already
exists in the pool, a reference to the pooled instance is returned. If string doesn't exist in the pool, a new
string instance is created and placed in the pool. For example:
1. String s1="Welcome";
2. String s2="Welcome";//will not create new instance
2) By new keyword
char ch[]={'s','t','r','i','n','g','s'};
String s2=new String(ch);//converting char array to string
System.out.println(s1);
System.out.println(s2);
System.out.println(s3);
}}
Output:
java
strings
example
8. What is meant by constructors? Describe the type of constructors supported by java with example.
Constructor in java is a special type of method that is used to initialize the object.
Java constructor is invoked at the time of object creation. It constructs the values i.e. provides data for the
object that is why it is known as constructor.
}
Student5(int i,String n,int a){
id = i;
name = n;
age=a;
}
void display(){System.out.println(id+" "+name+" "+age);}
There is no copy constructor in java. But, we can copy the values of one object to another like copy
constructor in C++.
There are many ways to copy the values of one object into another in java. They are:
By constructor
By assigning the values of one object into another
By clone() method of Object class
In this example, we are going to copy the values of one object into another using java constructor.
class Student6{
int id;
String name;
Student6(int i,String n){
id = i;
name = n;
}
Student6(Student6 s){
id = s.id;
name =s.name;
}
void display(){System.out.println(id+" "+name);}
Test it Now
Output:
111 Karan
111 Karan
9. Define inheritances. Explain in details types of inheritances supported by JAVA with example program.
Inheritance in java is a mechanism in which one object acquires all the properties and behaviors of
parent object.
The idea behind inheritance in java is that you can create new classes that are built upon existing classes.
When you inherit from an existing class, you can reuse methods and fields of parent class, and you can
add new methods and fields also.
The extends keyword indicates that you are making a new class that derives from an existing class.
In the terminology of Java, a class that is inherited is called a super class. The new class is called a
subclass.
As displayed in the above figure, Programmer is the subclass and Employee is the superclass.
Relationship between two classes is Programmer IS-A Employee.It means that Programmer is a type of
Employee.
class Employee{
float salary=40000;
}
class Programmer extends Employee{
int bonus=10000;
public static void main(String args[]){
Programmer p=new Programmer();
System.out.println("Programmer salary is:"+p.salary);
System.out.println("Bonus of Programmer is:"+p.bonus);
}
}
Programmer salary is:40000.0
Bonus of programmer is:10000
In java programming, multiple and hybrid inheritance is supported through interface only. We will learn
about interfaces later.
When a class extends multiple classes i.e. known as multiple inheritance. For Example:
To reduce the complexity and simplify the language, multiple inheritance is not supported in java.
Consider a scenario where A, B and C are three classes. The C class inherits A and B classes. If A and B
classes have same method and you call it from child class object, there will be ambiguity to call method
of A or B class.
Since compile time errors are better than runtime errors, java renders compile time error if you inherit 2
classes. So whether you have same method or different, there will be compile time error now.
class A{
void msg(){System.out.println("Hello");}
}
class B{
void msg(){System.out.println("Welcome");}
}
The java.io package contains nearly every class you might ever need to perform input and output (I/O) in
Java. All these streams represent an input source and an output destination. The stream in the java.io
package supports many data such as primitives, Object, localized characters, etc.
A stream can be defined as a sequence of data. The InputStream is used to read data from a source and
the OutputStream is used for writing data to a destination.
Java provides strong but flexible support for I/O related to Files and networks but this tutorial covers very
basic functionality related to streams and I/O. We would see most commonly used example one by one:
Byte Streams
Java byte streams are used to perform input and output of 8-bit bytes. Though there are many classes
related to byte streams but the most frequently used classes are , FileInputStream and
FileOutputStream. Following is an example which makes use of these two classes to copy an input file
into an output file:
import java.io.*;
try {
in = new FileInputStream("input.txt");
out = new FileOutputStream("output.txt");
int c;
while ((c = in.read()) != -1) {
out.write(c);
}
}finally {
if (in != null) {
in.close();
}
if (out != null) {
out.close();
}
}
}
}
As a next step, compile above program and execute it, which will result in creating output.txt file with the
same content as we have in input.txt. So let's put above code in CopyFile.java file and do the following:
$javac CopyFile.java
$java CopyFile
Character Streams
Java Byte streams are used to perform input and output of 8-bit bytes, where as Java Character streams
are used to perform input and output for 16-bit unicode. Though there are many classes related to
character streams but the most frequently used classes are , FileReader and FileWriter.. Though
internally FileReader uses FileInputStream and FileWriter uses FileOutputStream but here major
difference is that FileReader reads two bytes at a time and FileWriter writes two bytes at a time.
We can re-write above example which makes use of these two classes to copy an input file (having
unicode characters) into an output file:
import java.io.*;
try {
in = new FileReader("input.txt");
out = new FileWriter("output.txt");
int c;
while ((c = in.read()) != -1) {
out.write(c);
}
}finally {
if (in != null) {
in.close();
}
if (out != null) {
out.close();
}
}
}
}
As a next step, compile above program and execute it, which will result in creating output.txt file with the
same content as we have in input.txt. So let's put above code in CopyFile.java file and do the following:
$javac CopyFile.java
$java CopyFile
Standard Streams
All the programming languages provide support for standard I/O where user's program can take input
from a keyboard and then produce output on the computer screen. If you are aware if C or C++
programming languages, then you must be aware of three standard devices STDIN, STDOUT and
STDERR. Similar way Java provides following three standard streams
Standard Input: This is used to feed the data to user's program and usually a keyboard is used as
standard input stream and represented as System.in.
Standard Output: This is used to output the data produced by the user's program and usually a
computer screen is used to standard output stream and represented as System.out.
Standard Error: This is used to output the error data produced by the user's program and usually
a computer screen is used to standard error stream and represented as System.err.
Following is a simple program which creates InputStreamReader to read standard input stream until the
user types a "q":
import java.io.*;
try {
cin = new InputStreamReader(System.in);
Let's keep above code in ReadConsole.java file and try to compile and execute it as below. This program
continues reading and outputting same character until we press 'q':
$javac ReadConsole.java
$java ReadConsole
Enter characters, 'q' to quit.
1
1
e
e
q
q
Unit-II
Part-A
1. What is web 2.0?
A Web 2.0 site may allow users to interact and collaborate with each other in a social media dialogue as creators of
user-generated content in a virtual community, in contrast to Web sites where people are limited to the passive
viewing of content. Examples of Web 2.0 include social networking sites, blogs, wikis, folksonomies, video
sharing sites, hosted services, Web applications, and mashups.
2. Define RIA.
A rich Internet application (RIA) is a Web application designed to deliver the same features and functions normally
associated with deskop applications. RIAs generally split the processing across the Internet/network divide by
locating the user interface and related activity and capability on the client side, and the data manipulation and
operation on the application server side.
3. Define collaboration.
Collaboration is a process defined by the recursive interaction of knowledge and mutual learning between two or
more people who are working together, in an intellectual endeavour, toward a common goal which is typically
creative in nature.
4. List the Collaborations tools.
AnswerGaeden,Thinkature,DotVoting,ePals,Gaggle,Glass,Tricider.
5. What are the collaborative processes.
Team Creation
Idea Generation
Decision-Making
Work or Production
Evaluation or Recap
6. Define Web services.
A Web service is a method of communication between two electronic devices over a network. It is a software
function provided at a network address over the Web with the service always on as in the concept of utility
computing.
7. Write short notes on Software as service(Soas).
SOAs : Software as a service (SaaS), sometimes referred to as "software on demand," is software that is deployed
over the internet and/or is deployed to run behind a firewall on a local area network or personal computer. With
SaaS, a provider licenses an application to customers either as a service on demand, through a subscription, in a
"pay-as-you-go" model, or (increasingly) at no charge.
8. Write short notes on Social networking.
A social network is a social structure made up of a set of social actors (such as individuals or organizations) and a
set of the dyadic ties between these actors. The social network perspective provides a set of methods for analyzing
the structure of whole social entities as well as a variety of theories explaining the patterns observed in these
structures.
9. Define Website.
A website is hosted on at least one web server, accessible via a network such as the Internet or a private local area
network through an Internet address known as a uniform resource locator (URL). All publicly accessible websites
collectively constitute the World Wide Web
10. Differences between web sites and web server.
Website:
A website is a set of linked documents associated with a particular person, organization or topic that is held on a
computer system and can be accessed as part of the world wide web. (Not to be confused with: Web page, a
document on the world wide web written in HTML and displayed in a web browser.)
Web server:
The web server on the other side is a computer program, which delivers content, such as websites or web pages, for
example, over the world wide web from a web server to your computer.
11. Define internet.
The Internet is a global system of interconnected computer networks that use the standard Internet protocol suite
(TCP/IP) to link several billion devices worldwide. It is a network of networks that consists of millions of private,
public, academic, business, and government networks of local to global scope, linked by a broad array of
electronic, wireless, and optical networking technologies.
12. Define intranet.
An intranet is a computer network that uses Internet Protocol technology to share information, operational systems,
or computing services within an organization. This term is used in contrast to extranet, a network between
organizations, and instead refers to a network within an organization. Sometimes, the term refers only to the
organization's internal website, but may be a more extensive part of the organization's information technology
infrastructure, and may be composed of multiple local area networks. The objective is to organize each individual's
desktop with minimal cost, time and effort to be more productive, cost efficient, timely, and competitive.
13. Differentiate between internet and intranet.
Internet is general to PCs all over the world whereas Intranet is specific to few PCs.
Internet has wider access and provides a better access to websites to large population whereas Intranet is
restricted.
Internet is not as safe as Intranet as Intranet can be safely privatized as per the need.
14. Define HTML.
HTML is a simple web page description language, which enables document creation for the web. HTML is the set
of mark-up symbols or codes placed in a file intended for display on the web browser page. These mark-up symbol
and codes identify structural elements such as paragraphs, heading, and lists. HTML can be used to place media
(such as graphics, video, and audio) on the Web page and describe fill-in-forms. A method is an implementation of
an objects behavior.
15. Explain about HTTP Connection.
It is a communication channel between web browser and web server. It begins on the
client side with the browser sending a request to the web server for a document.
Request Header Fields are
1. From
2. Reference
3. If_modified_since
4. Pragma
5. User Agent
16. Define cascading.
Cascading refers to a certain set of rules that browsers use, in cascading order, to determine how to use the style
information. Such a set of rules is useful in the event of conflicting style information because the rules would give
the browser a way to determine which style is given precedence.
17. State the use of web server logs and list the contents of a message log. (APR/MAY 2011)
A server log is a log file (or several files) automatically created and maintained by a server of activity performed
by it. A typical example is a web server log which maintains a history of page requests. The W3C maintains a
standard format (the Common Log Format) for web server log files, but other proprietary formats exist.
The message log is used by a number of processes to provide debugging and troubleshooting information. You can
view the message log from the process monitor after clicking on the details hyperlink for a process and the by
clicking on the message log hyperlink in the actions area.
18. How will you create a password field in a HTML form? (NOV/DEC 2011)
<input type=”password” name=”pwd” size=”15”>
19. List any four common browsers. (NOV/DEC 2011)
• Google Chrome
• Netscape Navigator
• Microsoft Internet Explorer
• Mozilla
20. State the uses of internet protocol. (APR/MAY 2012)
• IP function: transfer data from source device to destination device
• IP source software creates a packet representing the data
• Header: source and destination IP addresses, length of data, etc.
• Data: Data itself
21. Define Tags. What are the two different types of tags?
Tags signal the browser to inform about the formatting details.ie how the content shouls be displayed in the
browser screen. Tags are enclosed between “<” and”>”
Standalone tag only start tag is present and no end tag. Example <BR> and container tag have start and end tag will
be present .Example <html>…. </html>
22. What are the rules to define a tag?
Attributes should be placed inside start tag, appears as Name-value pairs separted by blank spaces, Attributes
should have only one value,values should be enclosed within either single(‘) or double (“) quotes.
specified within the HTML document itself. It is not defined in separate file. Due to embedded style sheet unique
style can be applied to all the elements.
40. What do you mean by the term inline element?
The inline elements are those elements that do not form new blocks of content. The content is distributed in lines.
41. What are the various style sheets?
Inline, external, imported and embedded are the different types of style sheets.
42. Explain inline, embedded and external style sheets.
Inline
If only a small piece of code has to be styled then inline style sheets can be used.
Embedded
Embedded style sheets are put between the <head> </head> tags.
External
If you want to apply a style to all the pages within your website by changing just one
style sheet, then external style sheets can be used.
43. Give example for inline style sheet. (APR/MAY 2013)
<h2>InLINE CSS</h2>
<p style=”color:sienna;margin-left:20px”>
The style ATTRIBUTE we are able to modify the appearance of HTML elements </p>
44. How will you embed the external style sheet? (May 2014)
In external style sheet is ideal when the style is applied to many pages. With an external style sheet, you can
change the look of an entire Web site by changing just one file.Each page must include a link to the style sheet
with the <link> tag. The <link> tag goes inside the head section:
<head>
<link rel="stylesheet" type="text/css" href="mystyle.css">
</head>
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. An example of a style sheet file is shown below:
"myStyle.css":
body {
background-color: lightblue;}
h1 {
color: navy;
margin-left: 20px;}
45. How will you include CSS in a web site? (MAY/JUNE 2014)
Inline
Inline styles are when you just insert the type of style you want inside another tag, using the style attribute. This is
usually the least useful way to use CSS.
<p style="width:100%; color:#660099; text-align:right; background-color:#ffcc00;" >
Embedded
Styles can also be placed in the document using the <style> tag. The <style> tag is usually placed in the head
section of the document, where it will apply to the whole document.
<style> <!--
p { color:#009900;
font-family:"comic sans ms",sans-serif; }
h1 { color:#660000; font-size:12pt; }
</style>
External styles
Styles can also be set in an external style sheet which is linked to the page with a <link> tag. For example the style
sheet for this site is included like this:
<link rel="stylesheet" type="text/css" href="class.css" />
46. What is the purpose of CSS Box Model and mention its parts also.
The CSS box model is essentially a box that wraps around HTML elements, and it consists of: margins, borders,
padding, and the actual content.
The different parts are:
• Margin
• Border
• Padding
• Content
Part-B
1. Explain WWW and HTTP Protocol.
WWW
The term WWW refers to the World Wide Web or simply the Web. The World Wide Web consists of all the
public Web sites connected to the Internet worldwide, including the client devices (such as computers and cell
phones) that access Web content. The WWW is just one of many applications of the Internet and computer
networks. The World Web is based on these technologies:
1. HTML - Hypertext Markup Language
2. HTTP - Hypertext Transfer Protocol
3. Web servers and Web browsers
HTTP
HTTP (Hypertext Transfer Protocol) is the set of rules for transferring files (text, graphic images, sound, video,
and other multimedia files) on the World Wide Web. HTTP is an application protocol that runs on top of the
TCP/IP suite of protocols. HTTP concepts include (as the Hypertext part of the name implies) the idea that files
can contain references to other files whose selection will elicit additional transfer requests. Any Web server
machine contains, in addition to the Web page files it can serve, an HTTP daemon, a program that is designed to
wait for HTTP requests and handle them when they arrive. Your Web browser is an HTTP client, sending requests
to server machines. When the browser user enters file requests by either "opening" a Web file (typing in a Uniform
Resource Locator or URL) or clicking on a hypertext link, the browser builds an HTTP request and sends it to the
Internet Protocol address (IP address) indicated by the URL. The HTTP daemon in the destination server machine
receives the request and sends back the requested file or files associated with the request. (A Web page often
consists of more than one file.)
GET
• Used if link is clicked or address typed in browser
• No body in request with GET method
POST
• Used when submit button is clicked on a form
• Form information contained in body of request
HEAD
• Requests that only header fields (no body) be returned in the response
• PUT
• DELETE
• TRACE
• OPTIONS
2. Header field structure:
– field name : field value
Syntax
– Field name is not case sensitive
– Field value may continue on multiple lines by starting continuation lines with white space
– Field values may contain MIME types, quality values, and wildcard characters (*’s)
3. MIME
– Convention for specifying content type of a message
– In HTTP, typically used to specify content type of the body of the response
– MIME content type syntax:
– top-level type / subtype
– Examples: text/html, image/jpeg
– Example header field with quality values:
accept:
text/xml,text/html;q=0.9,
text/plain;q=0.8, image/jpeg,
image/gif;q=0.2,*/*;q=0.1
– Quality value applies to all preceding items
– Higher the value, higher the preference
– Note use of wildcards to specify quality 0.1 for any MIME type not specified earlier
4. Common header fields:
– Host: host name from URL (required)
– User-Agent: type of browser sending request
– Accept: MIME types of acceptable documents
– Connection: value close tells server to close connection after single request/response
– Content-Type: MIME type of (POST) body, normally application/x-www-form-urlencoded
– Content-Length: bytes in body
Referer: URL of document containing link that supplied URI for this HTTP request
3. Discuss the structure of the HTTP response message.[8] (NOV/DEC 2012)
• Structure of the response
status line
header field(s)
blank line
optional body
• Status line
– Example: HTTP/1.1 200 OK
– Three space-separated parts:
HTTP version
status code
reason phrase (intended for human
use)
• Status code
– Three-digit number
– First digit is class of the status code:
1 Informational
2 Success
3 Redirection (alternate URL is
supplied)
4 Client Error
5 Server Error
– Other two digits provide additional information
• Header Fields
– Connection, Content-Type, Content-Length
– Date: date and time at which response was generated (required)
– Location: alternate URI if status is redirection
– Last-Modified: date and time the requested resource was last modified on the server
– Expires: date and time after which the client’s copy of the resource will be out-of-date
– ETag: a unique identifier for this version of the requested resource (changes if resource changes)
• Client Caching
– A cache is a local copy of information obtained from some other source
– Most web browsers use cache to store requested resources so that subsequent requests to the same
resource will not necessarily require an HTTP request/response
• Ex: icon appearing multiple times in a Web page
• Cache advantages
– (Much) faster than HTTP request/response
– Less network traffic
– Less load on server
• Cache disadvantage
– Cached copy of resource may be invalid (inconsistent with remote version)
• Validating cached resource:
– Send HTTP HEAD request and check Last-Modified or ETag header in response
– Compare current date/time with Expires header sent in response containing resource
– If no Expires header was sent, use heuristic algorithm to estimate value for Expires
– Ex: Expires = 0.01 * (Date – Last-Modified) + Date
• Character sets
– Every document is represented by a string of integer values (code points)
– The mapping from code points to characters is defined by a character set
– Some header fields have character set values:
– Accept-Charset: request header listing character sets that the client can recognize
• Ex: accept-charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7
– Content-Type: can include character set used to represent the body of the HTTP message
• Ex: Content-Type: text/html; charset=UTF-8
– Technically, many “character sets” are actually character encodings
– An encoding represents code points using variable-length byte strings
– Most common examples are Unicode-based encodings UTF-8 and UTF-16
IANA maintains complete list of Internet-recognized character sets/encodings
4. Explain HTML elements in detail also State the types of lists supported by HTML and explain
them in detail. (APR/MAY 2011)
HTML element
An HTML element is an individual component of an HTML document or web page, once this has been parsed
into the Document Object Model. HTML is composed of a tree of HTML elements and other nodes, such as
text nodes. Each element can have HTML attributes specified. Elements can also have content, including other
elements and text. HTML elements represent semantics, or meaning. For example, the title element represents
the title of the document.
Heading Tags
Any document starts with a heading. You can use different sizes for your headings. HTML also has six levels
of headings, which use the elements <h1>, <h2>, <h3>, <h4>, <h5>, and <h6>. While displaying any
heading, browser adds one line before and one line after that heading.
Example
<h1>This is heading 1</h1>
<h2>This is heading 2</h2>
<h3>This is heading 3</h3>
<h4>This is heading 4</h4>
<h5>This is heading 5</h5>
<h6>This is heading 6</h6>
Paragraph Tag
The <p> tag offers a way to structure your text into different paragraphs. Each paragraph of text should go in
between an opening <p> and a closing </p> tag as shown below in the example:
Example
<p>Here is a first paragraph of text.</p>
Centering Content
You can use <center> tag to put any content in the center of the page or any table cell.
Example
<center>
<p>This text is in the center.</p>
</center>
Horizontal Lines
Horizontal lines are used to visually break up sections of a document. The <hr> tag creates a line from the current
position in the document to the right margin and breaks the line accordingly.
Example
<hr />
Nonbreaking Spaces
you should use a nonbreaking space entity instead of a normal space. For example, when coding the "12
Angry Men" in a paragraph, you should use something similar to the following code:
Example
<p>An example of this technique appears in the movie "12 Angry Men."</p>
HTML Lists
HTML offers authors several mechanisms for specifying lists of information. All lists must contain one or more
list elements.
Unordered HTML List
The first item
The second item
The third item
The fourth item
Ordered HTML List
Example
<ul>
<li>Coffee</li>
<li>Tea</li>
<li>Milk</li>
</ul>
Ordered information.
1. The first item
2. The second item
3. The third item
4. The fourth item
5. HTML Description List
Example
<ol>
<li>Coffee</li>
<li>Milk</li>
</ol>
Definitions.
The first item
Description of item
The second item
Description of item
Example
<dl>
<dt>Coffee</dt>
<dd>- black hot drink</dd>
<dt>Milk</dt>
<dd>- white cold drink</dd>
</dl>
5. Discuss the various features available in HTML to format the text with example.
Basic functionality
– Server calls on TCP software and waits for connection req to one or more ports
– When a connection request is received , the server dedicates a subtask(Single copy of server
software handling a single client connection)
– Subtask establish connection and receives request
– Subtask examines the host header field to determine the host and invokes software for this host
– Virtual host software Map Request-URI to specific resource on the server.
– It maps Request-URI to specific resource associated with the virtual host
• File: Return file in HTTP response (MIME Type)
The HTML table model allows authors to arrange data -- text, preformatted text, images, links,
forms, form fields, other tables, etc. -- into rows and columns of cells.
Each table may have an associated caption that provides a short description of the table's purpose.
A longer description may also be for the benefit of people using speech or Braille-based user
agents.
Table rows may be grouped into a head, foot, and body sections, Row groups convey additional
structural information and may be rendered by user agents in ways that emphasize this structure.
User agents may exploit the head/body/foot division to support scrolling of body sections
independently of the head and foot sections.
When long tables are printed, the head and foot information may be repeated on each page that
contains table data.
Authors may also group columns to provide additional structural information that may be
exploited by user agents.
Furthermore, authors may declare column properties at the start of a table definition in a way that
enables user agents to render the table incrementally rather than having to wait for all the table
data to arrive before rendering.
Table cells may either contain "header" information or "data. Cells may span multiple rows and
columns.
Here's a simple table that illustrates some of the features of the HTML table model. The following table
definition:
<TABLE border="1"
summary="This table gives some statistics about fruit
flies: average height and weight, and percentage
--------------------------------------------------------------------------------------------------------------------------------------
ii) What is the significance of using forms on the web page? Enlist various components used on form.
A webform, or HTML form on a web page allows a user to enter data that is sent to a server for processing. Forms
can resemble paper or database forms because web users fill out the forms using checkboxes, radio buttons, or text
fields. For example, forms can be used to enter shipping or credit card data to order a product, or can be used to
retrieve search results from a search engine.
Forms are enclosed in the HTML form tag. This tag specifies the communication endpoint the data entered into the
form should be submitted to, and the method of submitting the data, GET or POST.
Elements
Forms can be made up of standard graphical user interface elements:
text input — a simple text box that allows input of a single line of text (an alternative, password, is used for
security purposes, in which the character typed in are invisible or replaced by symbols such as *)
radio — a radio button
file — a file select control for uploading a file
reset — a reset button that, when activated, tells the browser to restore the values to their initial values.
submit — a button that tells the browser to take action on the form (typically to send it to a server)
textarea — much like the text input field except a textarea allows for multiple rows of data to be shown and
entered
select — a drop-down list that displays a list of items a user can select from
Example
Following is the example to create three horizontal frames:
<!DOCTYPE html>
<html>
<head>
<title>HTML Frames</title>
</head>
<frameset rows="10%,80%,10%">
<frame name="top" src="/html/top_frame.htm" />
<frame name="main" src="/html/main_frame.htm" />
<frame name="bottom" src="/html/bottom_frame.htm" />
<noframes>
<body>
Your browser does not support frames.
</body>
</noframes>
</frameset>
</html>
Attribute Description
src This attribute is used to give the file name that should be loaded in the
frame. Its value can be any URL. For example,
src="/html/top_frame.htm" will load an HTML file available in html
directory.
frameborder This attribute specifies whether or not the borders of that frame are
shown; it overrides the value given in the frameborder attribute on the
<frameset> tag if one is given, and this can take values either 1 (yes)
or 0 (no).
marginwidth This attribute allows you to specify the width of the space between
the left and right of the frame's borders and the frame's content. The
value is given in pixels. For example marginwidth="10".
marginheight This attribute allows you to specify the height of the space between
the top and bottom of the frame's borders and its contents. The value
is given in pixels. For example marginheight="10".
noresize By default you can resize any frame by clicking and dragging on the
borders of a frame. The noresize attribute prevents a user from being
able to resize the frame. For example noresize="noresize".
scrolling This attribute controls the appearance of the scrollbars that appear on
the frame. This takes values either "yes", "no" or "auto". For example
scrolling="no" means it should not have scroll bars.
longdesc This attribute allows you to provide a link to another page containing
a long description of the contents of the frame. For example
longdesc="framedescription.htm"
List :
HTML offers web authors three ways for specifying lists of information. All lists must contain one or more list
elements. Lists may contain:
<ul> - An unordered list. This will list items using plain bullets.
<ol> - An ordered list. This will use different schemes of numbers to list your items.
<dl> - A definition list. This arranges your items in the same way as they are arranged in a dictionary.
HTML Unordered Lists
An unordered list is a collection of related items that have no special order or sequence. This list is created by using
HTML <ul> tag. Each item in the list is marked with a bullet.
Example
<!DOCTYPE html>
<html>
<head>
<title>HTML Unordered List</title>
</head>
<body>
<ul>
<li>Beetroot</li>
<li>Ginger</li>
<li>Potato</li>
<li>Radish</li>
</ul>
</body>
</html>
This will produce following result:
Beetroot
Ginger
Potato
Radish
The type Attribute
You can use type attribute for <ul> tag to specify the type of bullet you like. By default it is a disc. Following are the
possible options:
<ul type="square">
<ul type="disc">
<ul type="circle">
Example
Following is an example where we used <ul type="square">
<!DOCTYPE html>
<html>
<head>
<title>HTML Unordered List</title>
</head>
<body>
<ul type="square">
<li>Beetroot</li>
<li>Ginger</li>
<li>Potato</li>
<li>Radish</li>
</ul>
</body>
</html>
This will produce following result:
Beetroot
Ginger
Potato
Radish
The start Attribute
You can use start attribute for <ol> tag to specify the starting point of numbering you need. Following are the
possible options:
Example
Following is an example where we used <ol type="i" start="4" >
<!DOCTYPE html>
<html>
<head>
<title>HTML Ordered List</title>
</head>
<body>
<ol type="i" start="4">
<li>Beetroot</li>
<li>Ginger</li>
<li>Potato</li>
<li>Radish</li>
</ol>
</body>
</html>
This will produce following result:
iv. Beetroot
v. Ginger
vi. Potato
vii. Radish
8. Explain the capabilities of Web Server (APR/MAY 2013)
Basic functionality
• Server calls on TCP software and waits for connection req to one or more ports
• When a connection request is received , the server dedicates a subtask(Single copy of server
software handling a single client connection)
• Subtask establish connection and receives request
• Subtask examines the host header field to determine the host and invokes software for this host
• Virtual host software Map Request-URI to specific resource on the server.
• It maps Request-URI to specific resource associated with the virtual host
– File: Return file in HTTP response (MIME Type)
– Program: Run program and return output in HTTP response
• Log information about the request and response such as IP address and the status code in a plain-
text file.
• If the TCP connection is kept alive , the server subtask continues to monitor the connection, the
client send another request or initiates a connection close.
Few Definitions
• All modern servers concurrently process multiple requests
• Multiple copies of the server running simultaneously(Concurrency)
• Subtask Single copy of server software handling a single client connection
• Virtual Host HTTP request include a host header field
• Multiple host names mapped by a DNS to a single IP address
• Web server determine which virtual host is being requested by examining the host header field.
Server Configuration and Tuning
• Modern servers have large number of Configuration parameters
• Server Configuration broken into two areas:
– External Communication
– Internal Processing
• In Tomcat two separate Java Packages:
– Coyote
– Catalina
• Coyote Provides HTTP 1.1 communication
– Catalina Actual Servlet Container
Coyote parameters affecting External Communication
IP addresses and TCP ports
Number of subtasks created when server initialized
Max number of threads allowed to exist simultaneously
Max no of TCP connection request that will be queued if server is running its max no of threads.
If queue full the received connection request is refused.
“Keep-alive” time for inactive TCP connections
• Settings of the parameter affect the performance of the server.
• Tuning the Server
– Changing the values of these and similar parameters in order to optimize performance
• Tuning is done by trial and error
• Load generation or stress test tools used to simulate request to a web server helpful for
experimenting with tuning parameters
Service has Five Components
• Connector, Host, Logger, Realm, and Valve
• Connector is a coyote component handles HTTP communication
• Clicking on the connector will produce the window containing the dropdown menus of possible
action that can be performed for this component
Defining Virtual Hosts
Configuring Host Elements
• The Host element represents a virtual host, which is an association of a network name for a server
(such as www.mycompany.com) with the particular server on which Tomcat is running.
Host Attributes
• The attributes shown in following table may be viewed, set, or modified for a Host.
• Web server logs record information about server activity
• Access log is a file that records information about every HTTP request processed by the server
• Message logs variety of debugging and other information generated by web server
• Access logging is performed by adding a valve component
Logging
• Web server logs record information about server activity
• Access log is a file that records information about every HTTP request processed by the server
• Message logs variety of debugging and other information generated by web server
• Access logging is performed by adding a valve component
Access Control
• Provide automatic password protection for resources
• Access control:
– Password protection (e.g., admin pages)
• Users and roles defined in
conf/tomcat-users.xml
– Deny access to machines
• Useful for denying access to certain users by denying access from the machines
they use
List of denied machines maintained in RemoteHostValve (deny by host name) or RemoteAddressValve
(deny by IP address)
9. Explain about the XHTML DTD with an Example.
DTD's
XHTML documents have three parts: the DOCTYPE (which contains the DTD declaration), the head and the body.
To create web pages that properly conform to the XHTML 1.0 standard, each page must include a DTD
declaration; either strict, transitional, or frameset.
1. Strict
You should use the strict DTD when your XHTML pages will be marked up cleanly, free of presentational
clutter. You use the strict DTD together with cascading style sheets, because it doesn’t allow attributes like
"bgcolor" to be set for the <body> tag, etc.
The strict DTD looks like this:
<!DOCTYPE html
PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
Example
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html
PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<title> Strict DTD XHTML Example </title>
</head><body><p>
Please Choose a Day:
<br /><br />
<select name="day">
<option selected="selected">Monday</option>
<option>Tuesday</option>
<option>Wednesday</option>
</select>
</p></body>
</html>
2. Transitional
The transitional DTD should be used when you need to take advantage of the presentational features that are
available through HTML. You should also use the transitional DTD when you want to support older browsers that
don’t have built-in support for cascading style sheets.
The transitional DTD looks like this:
<!DOCTYPE html
PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
Example
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html
PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<title> Transitional DTD XHTML Example </title>
</head>
Extensibility.
Owing to the extensibility of XML, XHTML documents can be supplemented with other forms of markup,
MathML (Math Markup Language) SVG (Scalable Vector Graphics) or your own markup variants, thanks to the
use of namespaces.
Compatibility.
Because XHTML documents are written in compliance with the rules of XML, XML-processing programmes
can effortlessly convert an XHTML file to another format (e.g. PDF, RSS or RTF).
Efficiency of processing applications.
Once browsers support XHTML documents and the strict rules of XML, they will become quicker thanks to
shorter error processing routines. At present, a great deal of the processing power of a browser is still spent on
liberal error processing of documents containing malformed HTML markup.
Features
XHTML requires strict adherence to coding rules.
XHTML encourages a more structured and conceptual way of thinking about content and, combined with
the style sheet, a more creative way of displaying it.
XHTML makes it easier for people to dream up and add new elements.
Code snippets
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<title>Page Title</title>
<link rel="stylesheet" href="style.css" type="text/css" media="screen" charset="utf-8"/>
</head>
<body>
</body>
</html>
11. Explain about Style Rule Cascading and Inheritance
Rule cascading:
*{ font-weight : bold } applies to every element of HTML
#p1, #p3 { background-color : aqua }
#p3{ font-weight : bold }
What if more than one style declaration applies to a property of an element?
• Multiple declaration
• Browser applies rule cascading
• A multistage sorting process that selects a single declaration that supply the property value
• The CSS rule cascade determines which style rule’s declaration applies
• Once declaration identified, associate origin and weight with every declaration
• PERSON WHO WROTE THE DOCUMENT
• PERSON WHO IS VIEWING THE DOCUMENT
• PERSON WHO WROTE THE BROWSER SOFTWARE
Origin of a declaration is one of the following:
• Author-> declaration is part of an external or embed style sheet or part of the value specified by
style attribute
• User agent –>A browser define default style property values for HTML elements
• User-> Modern browsers allow users to provide a style sheet
Cascading order
What style will be used when there is more than one style specified for an HTML element?
all the styles will "cascade" into a new "virtual" style sheet by the following rules, where number four has the
highest priority:
1. Browser default
2. External style sheet
3. Internal style sheet (in the head section)
4. Inline style (inside an HTML element)
So, an inline style (inside an HTML element) has the highest priority, which means that it will override a style
defined inside the <head> tag, or in an external style sheet, or in a browser (a default value).
Note: If the link to the external style sheet is placed after the internal style sheet in HTML <head>, the
external style sheet will override the internal style sheet!
Style Inheritance
• font-family property can accept a list offamilies, including generic font families
LINE BOXES:
Text is rendered using line boxes
13. Explain about the various style sheets with examples. (Internal,External,Inline) (APR/MAY 2013)
1. To create an inline style
a. Add the style attribute to the HTML tag.
b. The style declaration must be enclosed within double quotation marks.
2. To create an embedded style
a. Insert a <style> tag within the head section of HTML file.
b. Within the <style> tag, enclose the style declarations need to the entire Web page.
c. The style sheet language identifies the type of style used in the document.
d. The default and the most common language is “text/css” for use with CSS.
3. To create an External styles
a. Create a text file containing style declarations
b. Create a link to that file in each page of the Web site using a <link> tag.
c. Specify the link attributes, such as href, rel, and type.
d. Link a style sheet, the value of the href attribute should be the “URL” of the linked document,
the value of the rel attribute should be “stylesheet” and the value of the type attribute should be
“text/css”.
EXTERNAL.CSS:
body{ background-color: gray;}
p { color: blue; }
h3{ color: white; }
EXTERNAL.HTML:
<html>
<head>
<link rel="stylesheet" type="text/css" href="EXTERNAL.css" /><!—Link tag for External CSS-->
</head>
<body>
<h3> A White Header </h3>
<p> This paragraph has a blue font.
The background color of this page is gray because
we changed it with CSS! </p>
</body>
</html>
INTERNAL.HTML:
<html>
<head>
<style> <!—Style tag for Internal CSS-->
body { background-color: blue; }
p { color: white; }
</style>
</head>
<body>
<h2>Internal CSS</h2>
<p>This page uses internal CSS. Using the style tag we are able to modify
the appearance of HTML elements.</p>
</body>
</html>
INLINE.HTML:
<html>
<head>
</head>
<body>
<h2>InLINE CSS</h2>
<p style="color:sienna;margin-left:20px"><!—Style Attribute(INLINE)-->
This page uses INLINE CSS. Using the style ATTRIBUTE we are able to modify
the appearance of HTML elements.
</p>
</body>
</html>
14 Difference between web browser and web server
Web server and web browser are the terms which are commonly used for website. The basic purpose of
both is to develop a platform for internet web directory. So that any users can anytime access any kind of
website. Major difference between them is on their function and how they perform their functions. Check
for the detail of both topics before understanding the differences between them.
Web Server:
Web server is a computer system, which provides the web pages via HTTP (Hypertext Transfer
Protocol). IP address and a domain name is essential for every web server. Whenever, you insert a URL
or web address into your web browser, this sends request to the web address where domain name of your
URL is already saved. Then this server collects the all information of your web page and sends to
browser, which you see in form of web page on your browser. Making a web server is not a difficult job.
You can convert your computer into a web server with the help of any server software and connecting the
computer to the internet. Lot of web server software are available in the market in shape of NCSA,
Apache, Microsoft and Netscape. Storing, processing and delivering web pages to clients is its main
function. All the communication between client (web browser) and server takes place via HTTP.
Web Browser:
Web browser is a client, program, software or tool through which we sent HTTP request to web server.
The main purpose of web browser is to locate the content on the World Wide Web and display in the
shape of web page, image, audio or video form. You can call it a client server because it contacts the web
server for desired information. If the requested data is available in the web server data then it will send
back the requested information again via web browser. Microsoft Internet Explorer, Mozilla Firefox,
Safari, Opera and Google Chrome are examples of web browser and they are more advanced than earlier
web browser because they are capable to understand the HTML, JavaScript, AJAX, etc. Now a days, web
browser for mobiles are also available, which are called microbrowser.
Difference:
Following are the differences between web server and web browser.
Web server is essential to store all information and data of websites. While web browser are used
Internet
Intranet
PCs in intranet are not available to the world outside 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.
Each computer in Intranet is also identified by an IP Address which is unique among the
computers in that Intranet.
Internet is general to PCs all over the world whereas Intranet is specific to few PCs.
Internet has wider access and provides a better access to websites to large population whereas
Intranet is restricted.
Internet is not as safe as Intranet as Intranet can be safely privatized as per the need.
Real-time communication
This category consists of persistent socket connections. Flash Player supports two types of socket
connections: those that require a specific format for packets (XMLSocket) and those that allow raw
socket connections (Socket)
When you build Flex applications that utilize data communication, it’s important to understand the
strategies available for managing those communications and how to select the right strategy for an
application. All Flex applications run in Flash Player. With the exception of some Flex applications
created using Flex Data Services, almost all Flex applications are composed of precompiled .swf files that
are loaded in Flash Player on the client.
Because Flex applications are stateful and self-contained, they don’t require new page requests and
wholesale screen refreshes to make data requests and handle responses.
The Flex framework provides components for working with data communication using standard HTTP
requests as well as SOAP requests.
HTTPService
HTTPService is a component that allows you to make requests to simple HTTP services such as text
files, XML files, or scripts and pages that return dynamic data. You must always define a value for the url
property of an HTTPService object.
The following example uses MXML to create an HTTPService object that loads text from a file called
data.txt saved in the same directory as the compiled .swf file:
<mx:HTTPService id="textService" url="data.txt" />
Sending requests
Creating an HTTPService object does not automatically make the request to load the data. In order to
make the request, you must call the send( ) method. If you want to load the data when the use clicks a
button, you can call the send( ) method in response to a click event:
textService.send( );
Handling results
The send( ) method makes the request, but a response is not likely to be returned instantaneously.
Instead, the application must wait for a result event. The following example displays an alert when the
data loads:
<mx:HTTPService id="textService" url="data.txt" result="mx.controls.Alert.show('Data loaded')" />
Sending parameters
When you want to pass parameters to the service, you can use the request property of the HTTPService
instance. The request property requires an Object value. By default, the name/value pairs of the object are
converted to URL-encoded format and are sent to the service using HTTP GET.
The default value is object, which yields the default behavior you’ve already seen. You can optionally
specify any of the following values:
components: using MXML and using ActionScript. Using WebService Components with MXML
You can create a WebService component instance using MXML. When you do, you should specify an
id and a value for the wsdl property.\
Eg: <mx:WebService id="statesService" wsdl="http://www.rightactionscript.com/states/
webservice/StatesService.php?wsdl" />
Web services define one or more methods or operations. You must define the WebService instance so that
it knows about the operations using nested operation tags. The operation tag requires that you specify the
name at a minimum.
Handling results
When a web service operation returns a result, you can handle it in one of two ways: explicitly handle
the result event or use data binding. Then, once a result is returned, you can retrieve the result value from
the lastResult property of the operation.
\n Linefeed (newline),\v Tab (vertical),\f Form feed,\r Carriage return,\" Double quote
\' Single quote,\\ Backslash.
4. What is JavaScript name spacing? How and where is it used?
Using global variables in JavaScript is evil and a bad practice. That being said, namespacing is used to
bundle up all your functionality using a unique name. In JavaScript, a namespace is really just an object that
you’ve attached all further methods, properties and objects. It promotes modularity and code reuse in the
application.
5. How many looping structures can you find in javascript?
If you are a programmer, you know the use of loops. It is used to run a piece of code multiple times according to
some particular condition. Javascript being a popular scripting language supports the following loops for, while,
do-while loop
6. Mention the various Java Script Object Models.
Math Object, String Object, Date Object, Boolean and Number Object, Document Object
Window Object.
7. How Scripting Language Is Differs from HTML?
HTML is used for simple web page design, HTML with FORM is used for both form design and Reading input
values from user, Scripting Language is used for Validating the given input values weather it is correct or not, if
the input value is incorrect, the user can pass an error message to the user, Using form concept various controls like
Text box, Radio Button, Command Button, Text Area control and List box can be created.
8. What are the different types of objects in JavaScript?
Type Example Implementation Provided By Governing Standard
User- Programmer defined Programmer None
defined Customer or Circle
Built-in Array, Math The browser via engine its ECMA-262
JavaScript
Browser Window, Navigator The browser None (though some portions
adhere to an adhoc standard)
Document Image, The browser via W3C DOM
HTMLInputElement its DOM engine
9. Justify “JavaScript” is an event-driven programming”
Javascript supports event driven programming. when user clicks the mouse or hit the keys on the keyboard or if
user submits the form then these events and response to them can be handled using javascript. Hence javascript is
mainly used in web programming for validating the data provided by the user.
10. What is the use of pop up boxes in java script?
There are three types of popup boxes used in javascript. Using these popup boxes the user can interact with the
web application.
11. What is DOM?
Document Object Model (DOM) is a set of platform independent and language neutral application interface (API)
which describes how to access and manipulate the information stored in XML, XHTML and javascript documents.
12. Enlist any four mouse events.
The MouseEvent are-mousedown, mouseup, mouseover, mousemove, mouseout.
13. List ad various level of document object modeling.
Various levels of DOM are DOM0, Dom1, Dom2, and Dom3
14. What are they validation properties and methods?
Validation properties and methods are checkvalidity (), validaionMessage, customerror, patternMismatch,
rangeOverflow, rangeUnderflow, tooLong.
15. Define event bubbling.
Suppose, there is an element present inside another element. Then during the event handling, if the event which is
present in the inner element is handled and then the event of the outer element is handled. This process of event
handling is called event bubbling
initialization parameters.
String get ServletInfo() – returns a string describing the servlet.
void init(ServletConfig sc) throws ServletException –called when the servlet is
initialized .Initialization parameters for servlet can be obtained from sc. An unavailable exception should be
thrown if the servlet is not initialized.
Void Service(ServletRequest req,ServletResponse res) throws ServletException, IOException- Called to process a
request from a client. The request from the client can be read from req. response to the client can be written to res.
An exception is generated if a servlet or IO problem occurs.
22. What is the difference between CGI and servlets?
Performance is significantly better, servlet execute within the address space of a web server.
Servlets are platform independent
The java security manager on the server enforces a set of restrictions to protect the resources on a server
machine.
The full functionality of java class libraries is available to a servlet.
23. Define Servlet Life Cycle?
init( ) method - invoked when the servlet is first loaded into memory
service( ) - called for each HTTP request (for processing)
destroy( ) - unloads the servlet from its memory.
24. What is JSP?
JavaServer Pages (JSP) is a technology for developing web pages that support dynamic content which helps
developers insert java code in HTML pages by making use of special JSP tags, most of which start with <% and
end with %>.
25. What are advantages of using JSP?
Performance is significantly better because JSP allows embedding Dynamic Elements in HTML Pages
itself.
JSP are always compiled before it's processed by the server unlike CGI/Perl which requires the server to
load an interpreter and the target script each time the page is requested.
26. Explain lifecycle of a JSP.
Compilation
Initialization
Execution
Cleanup
27. What are the types of directive tags?
The types directive tags are as follows:
<%@ page ... %> : Defines page-dependent attributes, such as scripting language, error page, and
buffering requirements.
<%@ include ... %> : Includes a file during the translation phase.
<%@ taglib ... %> : Declares a tag library, containing custom actions, used in the page.
28. What are JSP actions?
JSP actions use constructs in XML syntax to control the behavior of the servlet engine. You can dynamically insert
a file, reuse JavaBeans components, forward the user to another page, or generate HTML for the Java plugin.
Part - B
1. How to write function using Java Script? Give Example.
A JavaScript function is a block of code designed to perform a particular task.A JavaScript function is executed
when "something" invokes it (calls it).
A JavaScript function is defined with the function keyword, followed by a name, followed by parentheses ().
Function names can contain letters, digits, underscores, and dollar signs (same rules as variables).
The parentheses may include parameter names separated by commas: (parameter1, parameter2, ...)
}
});
var john = new Pirate('Long John');
john.say('ahoy matey');
// -> "Long John: ahoy matey, yarr!"
Observe the direct interaction with class prototypes and the clumsy inheritance technique using Object.extend.
Also, with Pirate redefining the say() method ofPerson, there is no way of calling the overridden method like you
can do in programming languages that support class-based inheritance.
Example:
<script language="javascript" type="text/javascript">
<!--
function superClass() {
this.supertest = superTest; //attach method superTest
}
function subClass() {
this.inheritFrom = superClass;
this.inheritFrom();
this.subtest = subTest; //attach method subTest
}
function superTest() {
return "superTest";
}
function subTest() {
return "subTest";
}
//-->
</script>
3. Discuss Javascript objects in detail with suitable examples. (NOV/DEC 2012, MAY/JUNE 2014)
• An object is a set of properties
• A property consists of a unique (within an object) name with an associated value
• The type of a property depends on the type of its value and can vary dynamically
• Object properties do not have data types
Ex: Single property prop of an object o
• Object constructors defined to create objects and automatically define properties for the objects created
• Instead, properties and methods can be created and deleted dynamically
• Second line adds a property named testing to the o1 object and assigns a string value to this property
• A constructor is a function
• When called via new expression, a new empty Object is created and passed to the constructor
along with the argument values
• Constructor performs initialization on the object
• Can add properties and methods to object
• Can add object to an inheritance hierarchy from which it can inherit additional properties
and methods
• The Object() built-in constructor
• Does not add any properties or methods directly to the object
• default toString() and valueOf() methods (used for conversions to String and Number, resp.)
Array notation
• To print the values of those properties
• The JavaScript object dot notation is actually shorthand for a more general associative array notation in
which Strings are array indices:
• Expressions can supply property names:
• Two different notations for accessing properties
• Dot notation
• Array reference syntax à index is viewed as string value hash
• Object can be viewed as a sort of array in which the elements are indexed by strings called associative
array
Object reference
StringBuffer s1 = new StringBuffer(“Hello”);
StringBuffer s2 = s1;
• Single StringBuffer is created and both s1 and s2 will be references to it
• Copies the reference from s1 to s2
• If code followed by s2. append(“World!”);
System.out.println(s1);
Methods
• JavaScript functions are stored as values of type Object
• A function declaration creates a function value and stores it in a variable (property of window) having the
same name as the function
A method is an object property for which the value is a function
4. Discuss about Javascript debugging. Explain how local and global functions can be written using java
script (MAY/JUNE 2012)
A debugger is an application that places all aspects of script execution under the control of the programmer.
Debuggers provide fine-grained control over the state of the script through an interface that allows you to examine
and set values as well as control the flow of execution. Once a script has been loaded into a debugger, it can be run
one line at a time or instructed to halt at certain breakpoints. Once execution is halted, the programmer can
examine the state of the script and its variables in order to determine if something is amiss. You can also watch
variables for changes in their values. The latest version of the Mozilla JavaScript Debugger for both Mozilla and
Netscape browsers
Local and global functions
When a function is defined certain variables used for storing values are incorporated inside the function. These
variables are found and used only inside these functions. Since functions are separate from the main code, it's
advisable to use variables that are initialized only when a function is called and die when the execution comes out
of the function. Variables that exist only inside a function are called Local variables. They have no presence
outside the function. The values of such Local variables cannot be changed by the main code or other functions.
This results in easy code maintenance and is especially helpful if many programmers are working together on the
same project.
Variables that exist throughout the script are called Global variables. Their values can be changed anytime in the
code and even by other functions.
In JavaScript, an inner (nested) function stores references to the local variables that are present in the same scope
as the function itself, even after the function returns. This set of references is called a closure.
function myFunction() {
var a = 4;
return a * a;
}
The JavaScript global properties and functions can be used with all the built-in JavaScript objects.
var uri = "my test.asp?name=ståle&car=saab";
var enc = encodeURI(uri);
var dec = decodeURI(enc);
var res = enc + "<br>" + dec;
5. Explain the way in which java script handles arrays with example. (MAY/JUNE 2012)
Array
An array is a special variable, which can hold more than one value at a time.
If you have a list of items (a list of car names, for example), storing the cars in single variables
could look like this:
var car1 = "Saab";
var car2 = "Volvo";
var car3 = "BMW";
Creating an Array
Using an array literal is the easiest way to create a JavaScript Array.
Syntax:
var array-name = [item1, item2, ...];
Example:
var cars = ["Saab", "Volvo", "BMW"];
Using the JavaScript Keyword new
The following example also creates an Array, and assigns values to it:
<head>
<script type="text/javascript">
function factorial(f,n)
{
l=1;
for(i=1;i<=n;i++)
l=l*i;
f.p.value=l;
}
</script>
</head>
<body>
<form>
number:<input type="text" name="t"></br>
<input type="button" value="submit" onClick="factorial(this.form,t.value)"></br>
result:<input type="text" name="p"></br>
</form>
</body>
</html>
ii) Write a Java script to find the prime number between 1 and 100.
<html>
<head>
<script language="javascript">
var n=prompt("Enter User Value")
var x=1;
if(n==0 || n==1) x=0;
for(i=2;i<n;i++)
{
if(n%i==0)
{
x=0;
break;
}
}
if(x==1)
{
alert(n +" "+" is prime");
}
else
{
alert(n +" "+" is not prime");
}
</script>
</head>
<body>
</html>
7. Write a servlet program which displays the different content each time the user visits the page
import java.io.*;
import java.sql.Date;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;
Now let us compile above servlet and create following entries in web.xml
....
<servlet>
<servlet-name>PageHitCounter</servlet-name>
<servlet-class>PageHitCounter</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>PageHitCounter</servlet-name>
<url-pattern>/PageHitCounter</url-pattern>
</servlet-mapping>
....
8. Write a Java script program to create Popup box, alert and confirm box.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml11.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Introduction to pop up box</title>
</head>
<body>
<p>Experiment with the popup boxes by clicking the buttons(OK and Cancel) on them</p>
<script type="text/javascript">
if(confirm("do you agree?"))
alert("You have agreed");
else
input_text=prompt("Enter some string here..."," ");
/*the value entered in prompt box is returned
and stored in the variable text */
alert("Hi "+input_text);
</script>
</body>
</html>
9. Write a Java script program to print the numbers from 0 to 50.
<script type = "text/javascript">
var input;
var i=0;
input= 50;
while ( input > I )
{
document.write (i);
i++
}
</script>
b. Write a Java Script program to create table.
<html>
function createTable(a)
{
document.getElementById("tbl").innerHTML = "<table border = '1'>" +
"<tr>" +
"<td>1</td>" +
"<td>abc</td>" +
"<td>123</td>" +
"</tr>" +
"<tr>" +
"<td>2</td>" +
"<td>def</td>" +
"<td>456</td>" +
"</tr>" +
"<table>";
}
</script>
<div id="cnt"></div>
<div id="tbl"></div>
<input type="text" name="txtRow" style="width:200px;height:25px;" /><button name="cmdRow"
style="width:125px;height:30px;" onclick="createTable()">Create Table</button>
</html>
10. Write a Java script program to create user registration form.
<!DOCTYPE html>
<html lang="en"><head>
<meta charset="utf-8">
<title>JavaScript Form Validation using a sample registration form</title>
<meta name="keywords" content="example, JavaScript Form Validation, Sample registration form" />
<meta name="description" content="This document is an example of JavaScript Form Validation using a sample
registration form. " />
<link rel='stylesheet' href='js-form-validation.css' type='text/css' />
<script src="sample-registration-form-validation.js"></script>
</head>
<body onload="document.registration.userid.focus();">
<h1>Registration Form</h1>
<p>Use tab keys to move from one input field to the next.</p>
<form name='registration' onSubmit="return formValidation();">
<ul>
<li><label for="userid">User id:</label></li>
<li><input type="text" name="userid" size="12" /></li>
<li><label for="passid">Password:</label></li>
<li><input type="password" name="passid" size="12" /></li>
<li><label for="username">Name:</label></li>
<li><input type="text" name="username" size="50" /></li>
<li><label for="address">Address:</label></li>
<p id="demo"></p>
<script>
function myFunction() {
var inpObj = document.getElementById("id1");
if (inpObj.checkValidity() == false) {
document.getElementById("demo").innerHTML = inpObj.validationMessage;
}
}
</script>
iii)Write a java script program to generate Fibonacci series using do while loop.(6)
<html>
<body>
<script type="text/javascript">
var a=0,b=1,c;
document.write("Fibonacci");
while (b<=10)
{
document.write(c);
document.write("<br/>");
c=a+b;
a=b;
b=c;
}
</script>
</body>
</html>
12. i) Explain JavaScript & document object model (DOM ) with example.(8)
import java.io.File;
import java.util.Scanner;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
public class NewClass {
public static void main(String args[]) {
try {
File stocks = new
File("C:\\Users\\Administrator\\Documents\\NetBeansProjects\\WebApplication3\\newXMLDocument.xml");
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(stocks);
doc.getDocumentElement().normalize();
System.out.println("root of xml file" + doc.getDocumentElement().getNodeName());
NodeList nodes = doc.getElementsByTagName("stock");
System.out.println("Enter the user id");
Scanner scan=new Scanner(System.in);
String s=scan.next();
System.out.println("==========================");
for (int i = 0; i < nodes.getLength(); i++) {
Node node = nodes.item(i);
if (node.getNodeType() == Node.ELEMENT_NODE) {
Element element = (Element) node;
if(s.equals(getValue("userid", element)))
{
System.out.println("Stock User Id: " + getValue("userid", element));
System.out.println("Stock Symbol: " + getValue("symbol", element));
System.out.println("Stock Price: " + getValue("price", element));
System.out.println("Stock Quantity: " + getValue("quantity", element));
}
}
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
private static String getValue(String tag, Element element) {
NodeList nodes = element.getElementsByTagName(tag).item(0).getChildNodes();
Node node = (Node) nodes.item(0);
return node.getNodeValue();
}
}
// Database credentials
static final String USER = "root";
static final String PASS = "password";
// Open a connection
conn = DriverManager.getConnection(DB_URL,USER,PASS);
//Display values
out.println("ID: " + id + "<br>");
out.println(", Age: " + age + "<br>");
out.println(", First: " + first + "<br>");
out.println(", Last: " + last + "<br>");
}
out.println("</body></html>");
// Clean-up environment
rs.close();
stmt.close();
conn.close();
}catch(SQLException se){
//Handle errors for JDBC
se.printStackTrace();
}catch(Exception e){
//Handle errors for Class.forName
e.printStackTrace();
}finally{
//finally block used to close resources
try{
if(stmt!=null)
stmt.close();
}catch(SQLException se2){
}// nothing we can do
try{
if(conn!=null)
conn.close();
}catch(SQLException se){
se.printStackTrace();
}//end finally try
} //end try
}
}
13. Explain the JDBC database access in detail. Write a java servlet to conduct online examination. (APR/MAY
2013)
Index.html
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head><title>Database Test</title></head>
<body>
<center>
<h1>Online Examination</h1>
</center>
<form action="Servlet_tier1" method="POST">
<!—SERVLET NAME IN ACTION ATTRIBUTE -->
<div align="left"><br></div>
<b>Seat Number:</b> <input type="text" name="Seat_no">
<div align="Right">
<b>Name:</b> <input type="text" name="Name" size="50"><br>
</div>
<br><br>
<b>1. Every host implements transport layer.</b><br/>
<input type="radio" name="group1" value="True">True
<input type="radio" name="group1" value="False">False<br>
<b>2. It is a network layer's responsibility to forward packets reliably from source to destination</b><br/>
<input type="radio" name="group2" value="True">True
<input type="radio" name="group2" value="False">False<br>
<b>3. Packet switching is more useful in bursty traffic</b><br/>
<input type="radio" name="group3" value="True">True
<input type="radio" name="group3" value="False">False<br>
connect=DriverManager.getConnection(url,"","");
message="Thank you for participating in online Exam";
}
catch(ClassNotFoundException cnfex){
cnfex.printStackTrace();
}
catch(SQLException sqlex){
sqlex.printStackTrace();
}
catch(Exception excp){
excp.printStackTrace();
}
Seat_no=request.getParameter("Seat_no");
Name=request.getParameter("Name");
ans1=request.getParameter("group1");
ans2=request.getParameter("group2");
ans3=request.getParameter("group3");
ans4=request.getParameter("group4");
ans5=request.getParameter("group5");
if(ans1.equals("True"))
Total+=2;
if(ans2.equals("False"))
Total+=2;
if(ans3.equals("True"))
Total+=2;
if(ans4.equals("False"))
Total+=2;
if(ans5.equals("False"))
Total+=2;
try
{
stmt=connect.createStatement();
String query="INSERT INTO
student("+"Seat_no,Name,Total"+")VALUES('"+Seat_no+"','"+Name+"','"+Total+"')";
stmt.executeUpdate(query);
stmt.close();
}catch(SQLException ex){
}
response.setContentType("text/html");
PrintWriter out=response.getWriter();
out.println("<html>");
out.println("<head>");
out.println("</head>");
out.println("<body bgcolor=cyan>");
out.println("<center>");
out.println("<h1>"+message+"</h1>\n");
out.println("<h3>Yours results stored in our database</h3>");
out.print("<br><br>");
out.println("<b>"+"Participants and their Marks"+"</b>");
out.println("<table border=5>");
try
{
java.sql.Statement stmt2=connect.createStatement();
String query="SELECT * FROM student";
rs=stmt2.executeQuery(query);
out.println("<th>"+"Seat_no"+"</th>");
out.println("<th>"+"Name"+"</th>");
out.println("<th>"+"Marks"+"</th>");
while(rs.next())
{
out.println("<tr>");
out.print("<td>"+rs.getString(1)+"</td>");
out.print("<td>"+rs.getString(2)+"</td>");
out.print("<td>"+rs.getString(3)+"</td>");
out.println("</tr>");
}
out.println("</table>");
}
catch(SQLException ex){ }
finally
{
try
{
if(rs!=null)
rs.close();
if(stmt!=null)
stmt.close();
if(connect!=null)
connect.close();
}catch(SQLException e){ }
}
out.println("</center>");
out.println("</body></html>");
Total=0;
}}
14. What is a servlet? Explain briefly the Servlet life cycle and Servlet HTTP package?
A servlet is a Java programming language class that is used to extend the capabilities of servers that host
applications accessed by means of a request-response programming model. Although servlets can respond to any
type of request, they are commonly used to extend the applications hosted by web servers. For such applications,
Java Servlet technology defines HTTP-specific servlet classes.
The javax.servlet and javax.servlet.http packages provide interfaces and classes for writing
servlets. All servlets must implement the Servlet interface, which defines life-cycle methods. When
implementing a generic service, you can use or extend the GenericServlet class provided with the Java
Servlet API. TheHttpServlet class provides methods, such as doGet and doPost, for handling HTTP-
specific services.
– Static: HTML document is retrieved from the file system and returned to the client
– Dynamic: HTML document is generated by a program in response to an HTTP request
– Java servlets are one technology for producing dynamic server responses
– Servlet is a class instantiated by the server to produce a dynamic response
15. List out the classes and interfaces available in javax.servlet.http package?
The javax.servlet.http package contains a number of classes and interfaces that describe and define the contracts
between a servlet class running under the HTTP protocol and the runtime environment provided for an instance of
such a class by a conforming servlet container.
Interface:
You may create a generic servlet by inheriting the GenericServlet class and providing the implementation of the
service method.
Methods of GenericServlet class
There are many methods in GenericServlet class. They are as follows:
1. public void init(ServletConfig config) is used to initialize the servlet.
2. public abstract void service(ServletRequest request, ServletResponse response) provides service for the
incoming request. It is invoked at each time when user requests for a servlet.
3. public void destroy() is invoked only once throughout the life cycle and indicates that servlet is being
destroyed.
4. public ServletConfig getServletConfig() returns the object of ServletConfig.
5. public String getServletInfo() returns information about servlet such as writer, copyright, version etc.
6. public void init() it is a convenient method for the servlet programmers, now there is no need to call
super.init(config)
7. public ServletContext getServletContext() returns the object of ServletContext.
8. public String getInitParameter(String name) returns the parameter value for the given parameter name.
9. public Enumeration getInitParameterNames() returns all the parameters defined in the web.xml file.
10. public String getServletName() returns the name of the servlet object.
11. public void log(String msg) writes the given message in the servlet log file.
12. public void log(String msg,Throwable t) writes the explanatory message in the servlet log file and a stack
trace.
ServletInputStream:
ServletInputStream class provides stream to read binary data such as image etc. from the request object. It is an
abstract class.
The getInputStream() method of ServletRequest interface returns the instance of ServletInputStream class. So can
be get as:
ServletInputStream sin=request.getInputStream();
Method of ServletInputStream class
There are only one method defined in the ServletInputStream class.
int readLine(byte[] b, int off, int len) it reads the input stream.
ServletOutputStream:
ServletOutputStream class provides a stream to write binary data into the response. It is an abstract class.
The getOutputStream() method of ServletResponse interface returns the instance of ServletOutputStream class. It
may be get as:
ServletOutputStream out=response.getOutputStream();
Methods of ServletOutputStream class
The ServletOutputStream class provides print() and println() methods that are overloaded.
1. void print(boolean b){}
2. void print(char c){}
3. void print(int i){}
4. void print(long l){}
5. void print(float f){}
ServletException:
Constructs a new servlet exception when the servlet needs to throw an exception and include a message about the
"root cause" exception that interfered with its normal operation. The exception's message is based on the localized
message of the underlying exception.
This method calls the getLocalizedMessage method on the Throwable exception to get a localized exception
message. When subclassing ServletException, this method can be overridden to create an exception message
designed for a specific locale.
Parameters:
rootCause - the Throwable exception that interfered with the servlet's normal operation, making the servlet
exception necessary
17. Write a servlet program which displays the different image each time the user visits the page and the images
are links
package com.javatpoint;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class DisplayImage extends HttpServlet {
bin.close();
fin.close();
bout.close();
out.close();
} }
18. Explain in detail about Servlet Database Connectivity with an example of Student database.
a. Write a servlet for creating Student Entry form.
Index.html
<html>
<head>
<title>Student Registrion index page </title>
</head>
<body>
<center>
<form action="InsertRecord" method="post">
<fieldset><legend><font face="Courier New" size="+1"
color="red">Student Registration</font></legend>
<table>
<tr>
<td>Student Name :</td>
<td> <input type="text" name="name"> </td>
</tr>
<tr>
<td>Enrollment Number :</td>
<td> <input type="text" name="enrolmentNo"> </td>
</tr>
<tr>
<td>Program Name : </td>
<td> <input type="text" name="program"> </td>
</tr>
<tr>
<td>Gender : </td>
<td><select name="gender">
</select>
</td>
</tr>
<tr>
<td>Address :</td>
<td> <textarea cols="20" rows="2" name="address">
</textarea> </td>
</tr>
<tr>
<td colspan=2>
<input type="submit" value="Register"> </td>
</tr>
</table>
</fieldset>
</form>
</center>
</body>
</html>
InsertRecord.java
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class InsertRecord extends HttpServlet {
public void doPost(HttpServletRequest request,
HttpServletResponse response)
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String name=request.getParameter("name");
String en=request.getParameter("enrolmentNo");
String program=request.getParameter("program");
String gender=request.getParameter("gender");
String address=request.getParameter("address");
int id=0;
int enrol=0;
if(name.equals("") || en.equals("") ||
program.equals("") || gender.equals("") ||
address.equals(""))
{
out.println("Please insert valid data");
RequestDispatcher rd =
request.getRequestDispatcher("/index.html");
rd.include(request, response);
}
else
{
enrol=Integer.parseInt(en);
try{
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con=DriverManager.getConnection(
"jdbc:oracle:thin:@localhost:1521:xe","system","sunil");
PreparedStatement pst=con.prepareStatement(
"SELECT id FROM STUDENT");
ResultSet rs=pst.executeQuery();
while(rs.next())
{
id=rs.getInt(1);
}
PreparedStatement ps=con.prepareStatement(
"insert into STUDENT values(?,?,?,?,?,?)");
ps.setInt(1,id+1);
ps.setString(2,name);
ps.setInt(3,enrol);
ps.setString(4,program);
ps.setString(5,gender);
ps.setString(6,address);
int i=ps.executeUpdate();
if(i>0)
out.print("Student record successfully inserted");
out.print("<BR>");
out.print("Insert another record ...");
RequestDispatcher
rd = request.getRequestDispatcher("/index.html");
rd.include(request, response);
}
catch (Exception e) {
System.out.println(e);
}
}
out.close();
}
}
Web.html
<servlet>
<description></description>
<display-name>InsertRecord</display-name>
<servlet-name>InsertRecord</servlet-name>
<servlet-class>InsertRecord</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>InsertRecord</servlet-name>
<url-pattern>/InsertRecord</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
</welcome-file-list>
</web-app>
19. Explain in detail about JSP with an example of current date and simple message.
<%@page contentType="text/html" import="java.util.*" %>
<html>
<body>
<p> </p>
<div align="center">
<center>
<table border="0" cellpadding="0" cellspacing="0" width="460" bgcolor="#EEFFCA">
<tr>
<td width="100%"><font size="6" color="#008000"> Date Example</font></td>
</tr>
<tr>
<td width="100%"><b> Current Date and time is: <font color="#FF0000">
<%= new java.util.Date() %>
</font></b></td>
</tr>
</table>
</center>
</div>
</body>
</html>
20. Discuss in detail about Action elements in JSP with an example of display current time and color.
ACTION:
• Standard: provided by JSP itself
• Custom: provided by a tag library such as JSTL.
• JSTL is divided into several functional areas, each with its own namespace:
Namespace prefix is
• Common variables:
– var
• Represents name of a scoped variable that is assigned to by the action
• Must be a string literal, not an EL expression
– scope
• Specifies scope of scoped variable as one of the literals page, request, session, or
application
set action
– Setting (and creating) a scoped variable
out action
– Normally used to write a string to the out JSP implicit object
– Automatically escapes XML special characters
if action
– General form includes scoped variable to receive test value
<c:set var="age" value="20" scope="session"></c:set>
<h3><c:out value="${x}"></c:out></h3>
<c:if test="${x}">
<h3><c:out value="WELCOME"></c:out></h3>
</c:if>
Output:
WELCOME
true
WELCOME
remove action
– Only attributes are var and scope
– Removes reference to the specified scoped variable from the scope object
<c:set var="x" value="10" scope="session"></c:set>
<c:set var="y" value="20" scope="session"></c:set>
<h3>Product :<c:out value="${x*y}"></c:out></h3>
<c:remove var="x" scope="session"/>
<c:remove var="y" scope="session"/>
<h3>Product :<c:out value="${x*y}"></c:out></h3>
Output:
Product :200
Product :0
choose action:
<c:set var="salary" scope="session" value="5000"/>
<p>Your salary is : <c:out value="${salary}"/></p>
<c:choose>
<c:when test="${salary > 1000}">
Salary is very good.
</c:when>
<c:otherwise>
Salary is very low
</c:otherwise>
</c:choose>
Output:
Your salary is : 5000
Salary is very good.
forEach action:
Used to increment a variable (writes 2, 4, 6, 8 to the out object)
<c:forEach begin="1" end="10" step="4" var="x">
Begin Index value :${x}<br>
</c:forEach>
Output:
Begin Index value :1
Begin Index value :5
Begin Index value :9
url action
– value attribute is a URL to be written to the out JSP implicit object
– URL’s beginning with / are assumed relative to context path
– param elements can be used to define parameters that will be URL encoded
curl.jsp:
<c:url value="/URLTest.jsp" var="x" >
<c:param name="d1" value="SCJP"/>
<c:param name ="d2" value="SCWCD"/>
</c:url>
<h1>The modified url : ${x},</h1><br>
<a href="${x}">click Here </a>
Output:
The modified url : /JSTL/URLTest.jsp?d1=SCJP&d2=SCWCD,
URLTest.jsp
<h2> This is URLTest JSP </h2>
<h2>First Parameter : : :${param.d1}</h2>
<h2>Second Parameter : : :${param.d2}</h2>
Output:
URL:
This is URLTest JSP
response This is the HttpServletResponse object associated with the response to the client.
out This is the PrintWriter object used to send output to the client.
pageContext This encapsulates use of server-specific features like higher performance JspWriters.
page This is simply a synonym for this, and is used to call the methods defined by the
translated servlet class.
Exception The Exception object allows the exception data to be accessed by designated JSP.
some additional methods designed to deal with buffering. Unlike the PrintWriter object, JspWriter throws
IOExceptions.
Following are the important methods which we would use to write boolean char, int, double, object, String etc.
Method Description
out.println(dataType dt) Print a data type value then terminate the line with new line
character.
config.getServletName();
This returns the servlet name, which is the string contained in the <servlet-name> element defined in the WEB-
INF\web.xml file
The pageContext Object:
The pageContext object is an instance of a javax.servlet.jsp.PageContext object. The pageContext object is used to
represent the entire JSP page.
This object is intended as a means to access information about the page while avoiding most of the implementation
details.
This object stores references to the request and response objects for each request. The application, config, session,
and out objects are derived by accessing attributes of this object.
The pageContext object also contains information about the directives issued to the JSP page, including the
buffering information, the errorPageURL, and page scope.
The PageContext class defines several fields, including PAGE_SCOPE, REQUEST_SCOPE, SESSION_SCOPE,
and APPLICATION_SCOPE, which identify the four scopes. It also supports more than 40 methods, about half of
pageContext.removeAttribute("attrName", PAGE_SCOPE);
You can check a very good usage of pageContext in coming chapter: JSP - File Uploading.
The page Object:
This object is an actual reference to the instance of the page. It can be thought of as an object that represents the
entire JSP page.
The page object is really a direct synonym for the this object.
The exception Object:
The exception object is a wrapper containing the exception thrown from the previous page. It is typically used to
generate an appropriate response to the error condition.
Unit – IV
Part - A
1. What is PHP?
PHP - Hypertext Preprocessor -one of the most popular server-side scripting languages for creating dynamic Web
pages.
- an open-source technology
- platform independent
2. List the data types used in PHP.
Data types Description
Integer Whole numbers (i.e., numbers without a decimal point)
Double Real numbers (i.e., numbers containing a decimal point)
String Text enclosed in either single ('') or double ("") quotes.
Boolean True or false
Array Group of elements of the same type
Object Group of associated data and methods
Resource An external data source
3. How type conversion is done in PHP?
In PHP, data-type conversion can be performed by passing the data type as an argument to function settype.
Function settype takes two arguments: The variable whose data type is to be changed and the variable ’s new data
type.
E.g., settype( $testString, "double" );
4. Write the uses of text manipulation with regular expression in PHP.
PHP processes text data easily and efficiently, enabling straightforward searching, substitution, extraction and
concatenation of strings.
Text manipulation in PHP is usually done with regular expressions — a series of characters that serve as
pattern-matching templates (or search criteria) in strings, text files and databases.
This feature allows complex searching and string processing to be performed using relatively simple
expressions
5. List the important characteristics of PHP.
The main characteristics of PHP are:
• PHP is web-specific and open source
• Scripts are embedded into static HTML files
• Fast execution of scripts
• Fast access to the database tier of applications
• Supported by most web servers and operating systems
• Supports many standard network protocols libraries available for IMAP, NNTP, SMTP, POP3
• Supports many database management systems libraries available for UNIX DBM, MySQL, Oracle,
• Dynamic Output any text, HTML XHTML and any other XML file.
• Also Dynamic Output images, PDF files and even Flash m ovies
• Text processing features, from the POSIX Extended or Perl regular expressions to parsing XML documents.
• A fully featured programming language suitable for complex systems development
6. How to Include PHP in a Web Page?
There are 4 ways of including PHP in a web page
1. <?php echo("Hello world"); ?>
2. <script language = "php"> echo("Hello world");
</script>
3. <? echo("Hello world"); ?>
4. <% echo("Hello world"); %>
we can also use print instead of echo
• Method (1) is clear and unambiguous
• Method (2) is useful in environments supporting mixed scripting languages in the same HTML file
• Methods (3) and (4) depend on the server configuration
7. Write a simple PHP Script.
Here is PHP script which is embedded in HTML using level one header with the PHP output text. The
name of this file is called hello.php.
<html>
<head>
<title>Hello world</title>
</head>
<body>
<h1><?php echo("Hello world"); ?></h1>
<h1><?php print("This prints the same thing!");?></h1>
</body>
<html>
8. How do you include comments in PHP?
PHP supports three types of comments:
1. Shell style comments - denoted #THIS IS A COMMENT
2. C++ style comments - denoted THIS IS A COMMENT—
3. C style comments - denoted /* ALL THIS COMMENTED! */
9. What are variables in PHP?
Variables start with the $ symbol.
E.g.:
$myInteger = 3;
$myString = "Hello world";
$myFloat = 3.145;
10. How do you declare a variable using PHP data types?
Data types are not explicitly defined:
• Variable type is determined by assignment
• Strings can be defined with single ( ’ ) and double ( ") quotes.
• PHP has a Boolean type:
Defined as false
– An integer or float value of 0 or
– The keyword false
– The empty string ‘‘’’ or the string ‘‘0’’
– An empty array or object
?>
<html>
<head>
<title>Welcome</title>
</head>
<body bgcolor = <?php echo($colour) ?>>
<h1>Welcome</h1>
</body>
</html>
19. What is cookie? Give example in PHP
A cookie is a text string stored on the client machine by your script (to track users and manage transactions).
Cookies are automatically returned (by the client), and can be accessed using a variable of the same name
• The following script reads and displays a cookie, and sets it with a new value (string) that was passed to the script
as a parameter.
• The cookie will expire after 20 minutes (1200 seconds)
<?php setCookie("CookieTest", $val, time()+1200); ?>
<html>
<head><title>Welcome</title></head>
<body>
<?php echo("<h2>The cookie is: $CookieTest</h1>
</body>
</html>
20. What is XML ?
Extensible markup language. It offer a standard, flexible and inherently extensible data format, XML significantly
reduces the burden of deploying the many technologies needed to ensure the success of Web services.
21. Define XML attributes
• XML elements can have attributes in the start tag, just like HTML.
• Attributes are used to provide additional information about elements.
• Attributes cannot contain multiple values (child elements can)
• Attributes are not easily expandable (for future changes)
22. Write the main difference between XML and HTML.
Main Difference between XML and HTML
XML was designed to carry data.
XML is not a replacement for HTML.
XML and HTML were designed with different goals:
XML was designed to describe data and to focus on what data is.
HTML was designed to display data and to focus on how data looks.
HTML is about displaying information, while XML is about describing information
23. What is meant by a XML namespace? (APR/MAY 2011)
XML Namespaces provide a method to avoid element name conflicts. When using prefixes in XML, a so-called
namespace for the prefix must be defined. The namespace is defined by the xmlns attribute in the start tag of an
element. The namespace declaration has the following syntax. xmlns:prefix="URI".
<root> <h:table xmlns:h="http://www.w3.org/TR/html4/">
<h:tr>
<h:td>Apples</h:td>
<h:td>Bananas</h:td>
</h:tr> </h:table>
<f:table xmlns:f="http://www.w3schools.com/furniture">
<f:name>African Coffee Table</f:name>
<f:width>80</f:width>
<note date="12/11/2007">
<to>Tove</to>
<from>Jani</from>
</note>
The error in the first document is that the date attribute in the note element is not quoted.
Entity References
Some characters have a special meaning in XML.
If you place a character like "<" inside an XML element, it will generate an error because the parser interprets it as
Comments in XML
The syntax for writing comments in XML is similar to that of HTML.
<!-- This is a comment -->
Another common practice is to use URL – specify the location of a file or a resource on the Internet.
<text:directory
Xmlns : text="http://www.deitel.com/xmlns-text”
Xmlns : image="http://deitel.com/xmlns-image">
Namespace prefix are required for elements such as file, description etc.,
Attributes do not require namespace prefix because each attribute Is already part of an element the specifies the
namespace prfix.
Specifying a Default Namespace:
To eliminate the need to place namespace prefixes in each element, document authors may specify a default
namespace for an element and its children.
<?xml version="1.0"?>
<!--defaultnamespace.xml -->
<file filename="book.xml">
<description>A book list</description>
</file>
</directory>
3. Given an XSLT document and a source XML document explain the XSLT transformation process that produce
a single result XML document. (NOV/DEC 2012)
• The Extensible Stylesheet Language (XSL) is an XML vocabulary typically used to transform
XML documents from one form to another form
• JAXP allows a Java program to use the Extensible Stylesheet Language (XSL) to extract data
from one XML document, process that data, and produce another XML document containing the
processed data.
For example, XSL can be used to extract information from an XML document and embed it within an
XHTML document so that the information can be viewed using a web browser.
TRANSFORMER:
Main.java:
import java.io.FileOutputStream;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;
public class Main
{
static String xml="D://WebTech//trans.XML";
static String xslt="D://WebTech//trans.XSL";
static String output="D://WebTech//trans.HTML";
public static void main(String[] args)
{
try
{
TransformerFactory tf = TransformerFactory.newInstance();
Transformer tr = tf.newTransformer(new StreamSource(xslt));
tr.transform(new StreamSource(xml),new StreamResult(new FileOutputStream(output)));
System.out.println("Output to " + output);
}
catch(Exception e)
{
}
}
}
trans.xsl:
<?xml version="1.0" encoding="ISO-8859-1"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="/">
<html>
<body>
<h1>Indian Languages details</h1>
<table border="1">
<tr>
<th>Language</th>
<th>Family/Origin</th>
<th>No. of speakers</th>
<th>Region</th>
</tr>
<xsl:for-each select="language">
<tr>
<td><xsl:value-of select="name"/></td>
<td><xsl:value-of select="family"/></td>
<td><xsl:value-of select="users"/></td>
<td><xsl:value-of select="region"/></td>
</tr>
</xsl:for-each>
</table>
</body>
</html>
</xsl:template>
</xsl:stylesheet>
trans.xml:
<?xml version="1.0"?>
<!--<?xml-stylesheet type="text/xsl" href="trans.xsl"?>-->
<language>
<name>Kannada</name>
<region>Karnataka</region>
<users>38M</users>
<family>Dravidian</family>
</language>
trans.html:
Indian Languages details
Language Family/Origin No. of speakers Region
Kannada Dravidian 38M Karnataka
4. Write short notes on Event-oriented parsing (MAY/JUNE 2014)
SAX:
An alternative approach is to have the parser interact with an application as it reads an XML
document. This is the approach taken by SAX (Simple API for XML).
SAX allows an application to register event listeners with the XML parser.
SAX parser calls these listeners as events occur and passes them the information about the events.
Main.Java:
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
public class Main
{
public static void main(String args[])
{
try
{
SAXParserFactory factory = SAXParserFactory.newInstance();
SAXParser saxParser = factory.newSAXParser();
saxParser.parse("D://Staff1.XML",new CountHelper());
}
catch(Exception e)
{
e.printStackTrace();
}
}
}
CountHelper.JAVA:
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
public class CountHelper extends DefaultHandler
{
int no_elms;
/*CountHelper()
{
super();
}*/
@Override
public void startDocument() throws SAXException
{
no_elms=0;
//return;
}
@Override
public void startElement(String u,String ln,String qname,Attributes atts)
throws SAXException
{
if(qname.equals("firstname"))
{
no_elms++;
}
// return;
}
@Override
public void endDocument() throws SAXException
{
System.out.println("I/p Doc has " + no_elms + "firstname Elements");
}
}
Staff1.xml:
<?xml version="1.0"?>
<company>
<staff id="1001">
<firstname>yong</firstname>
<lastname>mook kim</lastname>
<nickname>mkyong</nickname>
<salary>100000</salary>
</staff>
<staff id="2001">
<firstname>low</firstname>
<lastname>yin fong</lastname>
<nickname>fong fong</nickname>
<salary>200000</salary>
</staff>
</company>
OUTPUT:
DOM OUTPUT:
RootSystem element :company
Input Elements has:2nodes
SAX OUTPUT:
I/p Doc has 2 firstname Elements
5. Explain the following: i) XML namespace ii) XML style sheet. iii) XML attributes iv) XML Schema
i) XML Namespaces
XML Namespaces provide a method to avoid element name conflicts.
Name Conflicts
In XML, element names are defined by the developer. This often results in a conflict when trying
to mix XML documents from different XML applications. This XML carries HTML table
information:
<table>
<tr>
<td>Apples</td>
<td>Bananas</td>
</tr>
</table>
This XML carries information about a table (a piece of furniture):
<table>
<name>African Coffee Table</name>
<width>80</width>
<length>120</length>
</table>
If these XML fragments were added together, there would be a name conflict. Both contain a
<table> element, but the elements have different content and meaning.
A user or an XML application will not know how to handle these differences.
<h:table>
<h:tr>
<h:td>Apples</h:td>
<h:td>Bananas</h:td>
</h:tr>
</h:table>
<f:table>
<f:name>African Coffee
Table</f:name>
<f:width>80</f:width>
<f:length>120</f:length>
</f:table>
In the example above, there will be no conflict because the two <table> elements have different
names.
When using prefixes in XML, a so-called namespace for the prefix must be defined. The
namespace is defined by the xmlns attribute in the start tag of an element. The namespace
declaration has the following syntax. xmlns:prefix="URI".
<root>
<h:table xmlns:h="http://www.w3.org/TR/html4/">
<h:tr>
<h:td>Apples</h:td>
<h:td>Bananas</h:td>
</h:tr>
</h:table>
<f:table xmlns:f="http://www.w3schools.com/furniture">
<f:name>African Coffee Table</f:name>
<f:width>80</f:width>
<f:length>120</f:length>
</f:table>
</root>
In the example above, the xmlns attribute in the <table> tag give the h: and f: prefixes a qualified
namespace. When a namespace is defined for an element, all child elements with the same prefix are
associated with the same namespace. Namespaces can be declared in the elements where they are used or
in the XML root element:
<root
xmlns:h="http://www.w3.org/TR/html4/"
xmlns:f="http://www.w3schools.com/furnitur
e">
<h:table>
<h:tr>
<h:td>Apples</h:td>
<h:td>Bananas</h:td>
</h:tr>
</h:table>
<f:table>
<f:name>African Coffee Table</f:name>
<f:width>80</f:width>
<f:length>120</f:length>
</f:table>
</root>
A Uniform Resource Identifier (URI) is a string of characters which identifies an Internet Resource.
The most common URI is the Uniform Resource Locator (URL) which identifies an Internet domain
address. Another, not so common type of URI is the Universal Resource Name (URN). In our examples
we will only use URLs.
Default Namespaces
Defining a default namespace for an element saves us from using prefixes in all the child elements. It has
the following syntax:
xmlns="namespaceURI"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform":
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="/">
<html>
<body>
<h2>My CD Collection</h2>
<table border="1">
<tr>
<th style="text-align:left">Title</th>
<th style="text-align:left">Artist</th>
</tr>
<xsl:for-each select="catalog/cd">
<tr>
<td><xsl:value-of select="title"/></td>
<td><xsl:value-of select="artist"/></td>
</tr>
</xsl:for-each>
</table>
</body>
</html>
</xsl:template>
</xsl:stylesheet>
ii) XML Stylesheet
Displaying XML with XSLT
XSLT (eXtensible Stylesheet Language Transformations) is the recommended style sheet language for
XML.
XSLT is far more sophisticated than CSS. With XSLT you can add/remove elements and attributes to or
from the output file. You can also rearrange and sort elements, perform tests and make decisions about
which elements to hide and display, and a lot more.
XSLT uses XPath to find information in an XML document.
XSLT Example
We will use the following XML document:
<?xml version="1.0" encoding="UTF-8"?>
<breakfast_menu>
<food>
<name>Belgian Waffles</name>
<price>$5.95</price>
<description>Two of our famous Belgian Waffles with plenty of real maple syrup</description>
<calories>650</calories>
</food>
<food>
<name>Strawberry Belgian Waffles</name>
<price>$7.95</price>
<description>Light Belgian waffles covered with strawberries and whipped cream</description>
<calories>900</calories>
</food>
<food>
<name>Berry-Berry Belgian Waffles</name>
<price>$8.95</price>
<description>Light Belgian waffles covered with an assortment of fresh berries and whipped
cream</description>
<calories>900</calories>
</food>
<food>
<name>French Toast</name>
<price>$4.50</price>
<description>Thick slices made from our homemade sourdough bread</description>
<calories>600</calories>
</food>
<food>
<name>Homestyle Breakfast</name>
<price>$6.95</price>
<description>Two eggs, bacon or sausage, toast, and our ever-popular hash browns</description>
<calories>950</calories>
</food>
</breakfast_menu>
XML Attributes
In HTML, attributes provide additional information about elements:
<img src="computer.gif">
<a href="demo.asp">
Attributes often provide information that is not a part of the data. In the example below, the file
type is irrelevant to the data, but can be important to the software that wants to manipulate the
element:
<file type="gif">computer.gif</file>
<person gender="female">
<firstname>Anna</firstname>
<lastname>Smith</lastname>
</person>
<person>
<gender>female</gender>
<firstname>Anna</firstname>
<lastname>Smith</lastname>
</person>
In the first example gender is an attribute. In the last, gender is an element. Both examples
provide the same information. There are no rules about when to use attributes or when to use
elements.
<messages>
<note id="501">
<to>Tove</to>
<from>Jani</from>
<heading>Reminder</heading>
<body>Don't forget me this weekend!</body>
</note>
<note id="502">
<to>Jani</to>
<from>Tove</from>
<heading>Re: Reminder</heading>
<body>I will not</body>
</note>
</messages>
The id attributes above are for identifying the different notes. It is not a part of the note itself. The
metadata (data about data) should be stored as attributes, and the data itself should be stored as elements.
<?xml version="1.0"?>
<xs:schema
xmlns:xs="http://www.w3.org/2001/XMLSchema">
<xs:element name="note">
<xs:complexType>
<xs:sequence>
<xs:element name="to" type="xs:string"/>
<xs:element name="from" type="xs:string"/>
<xs:element name="heading" type="xs:string"/>
<xs:element name="body" type="xs:string"/>
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:schema>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/TR/WD-xsl">
<xsl:template match="/">
<xsl:apply-templates select="LANGLIST/TITLE" />
<xsl:template match="TITLE">
<SPAN STYLE="display: 'block'; font-family: 'arial';
color: '#008000'; font-weight: '600'; font-size: '22'; margin-top:
'12pt'; text-align: 'center'">
<xsl:value-of />
</SPAN>
<BR/>
</xsl:template>
<xsl:template match="TITLE1">
<SPAN STYLE="display: 'block'; font-family: 'arial';
color: '#000080'; font-weight: '400'; font-size: '20'; margin-top:
'12pt'">
<xsl:value-of />
</SPAN>
<BR/>
</xsl:template>
<xsl:template match="LIST1">
<UL style="display: 'list-item'; list-style-image:
url('bullet8.gif'); font-family: 'arial'; color: '#000000'; font-
weight: '400'; margin-left: '15pt'; margin-top: '12pt'; font-size:
'18'">
<xsl:for-each select="LANGUAGES">
<LI style="display: 'list-item'; list-style-type:
'square'; list-style-image: url('bullet8.gif'); font-family: 'arial';
color: '#ff0000'; font-weight: '300'; margin-left: '15pt'; margin-
top: '12pt'; font-size: '16'">
<xsl:value-of />
</LI>
</xsl:for-each>
</UL>
</xsl:template>
<xsl:template match="TITLE2">
<SPAN STYLE="display: 'block'; font-family: 'arial';
color: '#000080'; font-weight: '400'; font-size: '20'; margin-top:
'12pt'">
<xsl:value-of />
</SPAN>
<BR/>
</xsl:template>
<xsl:template match="LIST2">
<UL style="display: 'list-item'; list-style-image:
url('bullet8.gif'); font-family: 'arial'; color: '#000000'; font-
weight: '400'; margin-left: '15pt'; margin-top: '12pt'; font-size:
'18'">
<xsl:for-each select="OTHER">
<LI style="display: 'list-item'; list-style-type:
'square'; list-style-image: url('bullet8.gif'); font-family: 'arial';
color: '#0000ff'; font-weight: '200'; margin-left: '15pt'; margin-
top: '12pt'; font-size: '14'">
<xsl:value-of "."/>
</LI>
</xsl:for-each>
</UL>
</xsl:template>
</xsl:stylesheet>
Between the <xsl:template match="/"> tag and </xsl:template> tag, the order of the "apply-templates"
statements is very important since this determines the order they are displayed in. Also note that the text
<xsl:value-of "."/> is used to refer to the XML object currently being processed in order to display the
value of that object.
7. Explain the architectural revolution of XML.
XML: The Three Revolutions
Three areas of impact are i) data, which XML frees from the confines of fixed, ii) program-dependent
formats; architecture, iii) with a change in emphasis from tightly coupled distributed systems to a more
loosely coupled confederation based on the Web; and software, with the realization that software
evolution is a better path to managing complexity than building monolithic applications.
XML's strength is its data independence. XML is pure data description, not tied to any programming
language, operating system, or transport protocol. In the grand scheme of distributed computing this is a
radical idea. The implication is that we don't require lock-in to programmatic infrastructures to make data
available to Web-connected platforms. In effect, data is free to move about globally without the
constraints imposed by tightly coupled transport-dependent architectures. XML's sole focus on data
means that a variety of transport technologies may be used to move XML across the Web. As a result,
protocols such as HTTP have had a tremendous impact on XML's viability and have opened the door to
alternatives to CORBA, RMI, and DCOM, which don't work over TCP/IP. XML does this by focusing on
data and leaving other issues to supporting technologies.
Loosely coupled Web-based systems, on the other hand, provide what has long been considered the Holy
Grail of computing: universal connectivity. Using TCP/IP as the transport, systems can establish
connections with each other using common open-Web protocols. Although it is possible to build software
bridges linking tightly coupled systems with each other and the Web, such efforts are not trivial and add
another layer of complexity on top of an already complex infrastructure.
<?php
$username = "your_name";
$password = "your_password";
$hostname = "localhost";
To create 'results' database on your MySQL server you should run the following script:
<body>
<form method='post' action='calculator.php'>
<?php
if(isset($_POST['submit']))
{$value1 = $_POST['value1'];
$value2 = $_POST['value2'];
$action = $_POST['action'];
if($action=="+"){
echo "<b>Your Answer is:</b><br>";
echo $value1+$value2;
}
if($action=="-"){
echo "<b>Your Answer is:</b><br>";
echo $value1-$value2;
}
if($action=="*"){
echo "<b>Your Answer is:</b><br>";
echo $value1*$value2;
}
if($action=="/"){
echo "<b>Your Answer is:</b><br>";
echo $value1/$value2;
}
}
?>
</body>
</html>
Output:
10 20 * Calculate Now
Your Answer is:
200
---------------------------------------------------------------------------------------------------------------------------------------
b) Design application to send a email using PHP
bool mail ( string $to , string $subject , string $message [, string $additional_headers [, string
$additional_parameters ]] )
<?php
//if "email" variable is filled out, send email
if (isset($_REQUEST['email'])) {
//Email information
$admin_email = "[email protected]";
$email = $_REQUEST['email'];
$subject = $_REQUEST['subject'];
$comment = $_REQUEST['comment'];
//send email
mail($email, "$subject", $comment, "From:" . $admin_email);
//Email response
echo "Thank you for contacting us!";
}
<form method="post">
Email: <input name="email" type="text" /><br />
Subject: <input name="subject" type="text" /><br />
Message:<br />
<textarea name="comment" rows="15" cols="40"></textarea><br />
<input type="submit" value="Submit" />
</form>
<?php
}
?>
Output:
10. Develop a shopping cart application using PHP with use of cookies.
Use of each files and folders in the shopping cart application.
1. config is a folder that contains another file called db_connect.php which is the file used to connect to
the MySQL database for retrieving product information.
2. add_to_cart.php is executed when the user clicks on the “add to cart” button. It processes the product
data by adding it to the cookie JSON string to make it a cart item. Each cart item is processed and
converted to a JSON string to be stored in the cookie.
3. cart.php is where the cart items are read and displayed to the user. We retrieve the JSON string from a
cookie variable, convert it to an associated array and loop through it to be displayed on an HTML table.
4. layout_foot.php is used as a closing HTML wrapper, and is always included the the end of cart.php
and products.php because it closes the tags started by layout_head.php, it also contains any JavaScript
source and jQuery codes used in this script.
5. layout_head.php is used as an opening HTML page wrapper. It is always included at the beginning
of cart.php and products.php because it contains the opening HTML tag, head tags, title tags and any
CSS resource and scripts used.
6. navigation.php contains the links to products.php and cart.php pages that the user can click. The cart
item count is also shown here, beside the “Cart” link.
7. products.php displays all the products retrieve from the database. We are using PDO extension to
connect and retrieve data from the MySQL database.
8. remove_from_cart.php is executed when the user clicks on the “Remove from cart” button. It
removes the product item from the JSON string saved in the cookie variable.
Important note: This source code focuses on using cookies for storing shopping cart items, the
“checkout” is not in its scope.
Step 1: create a database and run the following SQL queries to create the sample tables.
CREATE TABLE IF NOT EXISTS `products` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(32) NOT NULL,
`price` int(11) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=4 ;
--
-- Dumping data for table `products`
--
try {
$con = new PDO("mysql:host={$host};dbname={$db_name}",
$username, $password);
}
else if($action=='exists'){
echo "<div class='alert alert-info'>";
echo "<strong>{$name}</strong> already exists in your
cart!";
echo "</div>";
}
$num = $stmt->rowCount();
if($num>0){
//start table
echo "<table class='table table-hover table-responsive table-
bordered'>";
echo "</table>";
}
include 'layout_foot.php';
?>
Step 5: products.php on step 4 above will not actually work without the layout_head.php and
layout_foot.php, so first, we’ll create the layout_head.php with the following code:
<?php
// connect to database
include 'config/db_connect.php';
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-
scale=1">
<!-- HTML5 Shiv and Respond.js IE8 support of HTML5 elements and
media queries -->
<!-- WARNING: Respond.js doesn't work if you view the page via
file:// -->
<!--[if lt IE 9]>
<script
src="https://oss.maxcdn.com/libs/html5shiv/3.7.0/html5shiv.js"></scrip
t>
<script
src="https://oss.maxcdn.com/libs/respond.js/1.4.2/respond.min.js"></sc
ript>
<![endif]-->
</head>
<body>
<div class="page-header">
<h1><?php echo isset($page_title) ? $page_title : "The
Code of a Ninja"; ?></h1>
</div>
Step 6: layout_head.php includes another PHP file called navigation.php, so we’ll create it and put
the following code.
<!-- navbar -->
<div class="navbar navbar-default navbar-static-top"
role="navigation">
<div class="container">
<div class="navbar-header">
<button type="button" class="navbar-toggle" data-
toggle="collapse" data-target=".navbar-collapse">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href="products.php">Your
Site</a>
</div>
$cart_count=count($saved_cart_items);
?>
Cart <span class="badge"
id="comparison-count"><?php echo $cart_count; ?></span>
</a>
</li>
</ul>
</div><!--/.nav-collapse -->
</div>
</div>
<!-- /navbar -->
Step 7: Now we’ll create the layout_foot.php
</div>
<!-- /container -->
</body>
</html>
Step 8: products.php has links to the add_to_cart.php file, we’ll create that file and put the code
below.
<?php
// initialize empty cart items array
$cart_items=array();
else{
// if cart has contents
if(count($saved_cart_items)>0){
foreach($saved_cart_items as $key=>$value){
// add old item to array, it will prevent duplicate
keys
$cart_items[$key]=$value;
}
}
// redirect
header('Location: products.php?action=added&id=' . $id .
'&name=' . $name);
}
?>
Step 9: Now if the products were able to be added on the cart, we’ll have to view it using cart.php,
we’ll create that file with the following codes.
<?php
$page_title="Cart";
include 'layout_head.php';
if($action=='removed'){
echo "<div class='alert alert-info'>";
echo "<strong>{$name}</strong> was removed from your
cart!";
echo "</div>";
}
$cookie = $_COOKIE['cart_items_cookie'];
$cookie = stripslashes($cookie);
$saved_cart_items = json_decode($cookie, true);
if(count($saved_cart_items)>0){
// get the product ids
$ids = "";
foreach($saved_cart_items as $id=>$name){
$ids = $ids . $id . ",";
}
//start table
echo "<table class='table table-hover table-responsive table-
bordered'>";
$total_price=0;
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)){
extract($row);
echo "<tr>";
echo "<td>{$name}</td>";
echo "<td>${$price}</td>";
echo "<td>";
echo "<a
href='remove_from_cart.php?id={$id}&name={$name}' class='btn btn-
danger'>";
echo "<span class='glyphicon
glyphicon-remove'></span> Remove from cart";
echo "</a>";
echo "</td>";
echo "</tr>";
$total_price+=$price;
}
echo "<tr>";
echo "<td><b>Total</b></td>";
echo "<td>${$total_price}</td>";
echo "<td>";
echo "<a href='#' class='btn btn-
success'>";
echo "<span class='glyphicon
glyphicon-shopping-cart'></span> Checkout";
echo "</a>";
echo "</td>";
echo "</tr>";
echo "</table>";
}
else{
echo "<div class='alert alert-danger'>";
echo "<strong>No products found</strong> in your cart!";
echo "</div>";
}
include 'layout_foot.php';
?>
Step 10: cart.php links to a file called remove_from_cart.php, to remove an item from the cart.
We’ll create remove_from_cart.php with the codes below.
<?php
// get the product id
$id = isset($_GET['id']) ? $_GET['id'] : "";
$name = isset($_GET['name']) ? $_GET['name'] : "";
// read
$cookie = $_COOKIE['cart_items_cookie'];
$cookie = stripslashes($cookie);
$saved_cart_items = json_decode($cookie, true);
// redirect to product list and tell the user it was added to cart
header('Location: cart.php?action=removed&id=' . $id . '&name=' .
$name);
?>
Enter or Update Cart Item Quantity
But what if your users want to enter or update the quantity of items in the cart? It is
possible using cookies.
1 Add a new column named “Quantity” in products.php and cart.php. The word
“Quantity” will be the column header and for the rest of the table row, it will be input or text
boxes where the user can enter the product quantity before clicking the “Add to cart” or
“Update cart” button.
2 On products.php, the “Add to cart” button will not be a direct link to add_to_cart.php
file. It will be a button that will execute a jQuery code because it has to get the quantity
entered by the user.
3 On cart.php, there will be an “Update cart” button beside the quantity textbox. Clicking it
will run a jQuery script that gets the new quantity entered by the user and saves the changes
with the help of a new file called “update_quantity.php”.
11. Explain about the control statements in PHP with example.
PHP Conditional Statements
In PHP we have the following conditional statements:
if statement - executes some code only if a specified condition is true
if...else statement - executes some code if a condition is true and another code if the condition
is false
if...elseif....else statement - specifies a new condition to test, if the first condition is false
switch statement - selects one of many blocks of code to be executed
The if Statement
The if statement is used to execute some code only if a specified condition is true.
Syntax
if (condition) {
code to be executed if condition is true;
}
The example below will output "Have a good day!" if the current time (HOUR) is less than 20:
Example
<?php
$t = date("H");
if ($t < "20") {
echo "Have a good day!";
}
?>
The if...else Statement
Use the if....else statement to execute some code if a condition is true and another code if the
condition is false.
Syntax
if (condition) {
code to be executed if condition is true;
} else {
code to be executed if condition is false;
}
The example below will output "Have a good day!" if the current time is less than 20, and "Have a good
night!" otherwise:
Example
<?php
$t = date("H");
switch ($favcolor) {
case "red":
echo "Your favorite color is red!";
break;
case "blue":
echo "Your favorite color is blue!";
break;
case "green":
echo "Your favorite color is green!";
break;
default:
echo "Your favorite color is neither red, blue, or green!";
}
?>
Only the name parameter is required. All other parameters are optional.
Note: The setcookie() function must appear BEFORE the <html> tag.
Note: The value of the cookie is automatically URLencoded when sending the cookie, and automatically
decoded when received (to prevent URLencoding, use setrawcookie() instead).
Note: You might have to reload the page to see the new value of the cookie.
Delete a Cookie
To delete a cookie, use the setcookie() function with an expiration date in the past:
Example
<?php
// set the expiration date to one hour ago
setcookie("user", "", time() - 3600);
?>
<html>
<body>
<?php
echo "Cookie 'user' is deleted.";
?>
</body>
</html>
Output:
Cookie 'user' is deleted.
a test cookie with the setcookie() function, then count the $_COOKIE array variable:
Example
<?php
setcookie("test_cookie", "test", time() + 3600, '/');
?>
<html>
<body>
<?php
if(count($_COOKIE) > 0) {
echo "Cookies are enabled.";
} else {
echo "Cookies are disabled.";
}
?>
</body>
</html>
Output:
Cookies are enabled.
13. Describe the data base connections in PHP with suitable example.
Before you can get content out of your MySQL database, you must know how to establish a
connection to MySQL from inside a PHP script. To perform basic queries from within MySQL is
very easy.
The first thing to do is connect to the database. The function to connect to MySQL is called
mysql_connect. This function returns a resource which is a pointer to the database connection. It's
also called a database handle, and we'll use it in later functions.
<?php
$username = "your_name";
$password = "your_password";
$hostname = "localhost";
All going well, you should see "Connected to MySQL" when you run this script. If you can't connect to the se
sure your password, username and hostname are correct.
Once you've connected, you're going to want to select a database to work with. Let's assume the database is ca
'examples'. To start working in this database, you'll need the mysql_select_db() function:
<?php
//select a database to work with
$selected = mysql_select_db("examples",$dbhandle)
or die("Could not select examples");
?>
Now that you're connected, let's try and run some queries. The function used to perform queries is named - my
The function returns a resource that contains the results of the query, called the result set. To examine the resul
going to use the mysql_fetch_array function, which returns the results row by row. In the case of a query that d
results, the resource that the function returns is simply a value true or false.
A convenient way to access all the rows is with a while loop. Let's add the code to our script:
<?php
//execute the SQL query and return records
$result = mysql_query("SELECT id, model, year FROM cars");
//fetch tha data from the database
while ($row = mysql_fetch_array($result)) {
echo "ID:".$row{'id'}." Name:".$row{'model'}."
".$row{'year'}."<br>";
}
?>
Finally, we close the connection. Although this isn't strictly speaking necessary, PHP will automatically close
connection when the script ends, you should get into the habit of closing what you open.
<?php
//close the connection
mysql_close($dbhandle);
?>
<?php
$username = "your_name";
$password = "your_password";
$hostname = "localhost";
To create 'examples' database on your MySQL server you should run the following script:
– New Link (mysql_connect only) – reuse database connection created by previous call to
mysql_connect
– Client Flags
• MYSQL_CLIENT_SSL :: Use SSL
• MYSQL_CLIENT_COMPRESS :: Compress data sent to MySQL
Username and password fields imply that database password is sitting there in the source code
– If someone gains access to source code, can compromise the database
– Servers are sometimes configured to view PHP source code when a resource is requested with
“.phps” instead of “.php”
– One approach to avoid this: put this information in Web server config. File
• Then ensure the Web server config. file is not externally accessible
2. Selecting a Database
• mysql_select_db()
– Pass it the database name
• Related:
– mysql_list_dbs()
• List databases available
– Mysql_list_tables()
• List database tables available
3. Perform SQL Query
• Create query string
– $query = ‘SQL formatted string’
– $query = ‘SELECT * FROM table’
• Submit query to database for processing
– $result = mysql_query($query);
– For UPDATE, DELETE, DROP, etc, returns TRUE or FALSE
– For SELECT, SHOW, DESCRIBE or EXPLAIN, $result is an identifier for the results, and
does not contain the results themselves
• $result is called a “resource” in this case
• A result of FALSE indicates an error
• If there is an error
– mysql_error() returns error string from last MySQL call
4. Process Results
• Many functions exist to work with database results
• mysql_num_rows()
– Number of rows in the result set
– Useful for iterating over result set
• mysql_fetch_array()
– Returns a result row as an array
– Can be associative or numeric or both (default)
– $row = mysql_fetch_array($result);
– $row[‘column name’] :: value comes from database row with specified column name
– $row[0] :: value comes from first field in result set
Process Results Loop
• Easy loop for processing results:
$result = mysql_query($qstring);
$num_rows = mysql_num_rows($result);
for ($i=0; $i<$num_rows; $i++)
{
$row = mysql_fetch_array($result);
// take action on database results here
}
5. Closing Database Connection
• mysql_close()
– Closes database connection
– Only works for connections opened with mysql_connect()
– Connections opened with mysql_pconnect() ignore this call
– Often not necessary to call this, as connections created by mysql_connect are closed at the end
of the script anyway
15. With example explain about XSL and XSLT transformation
XSL stands for EXtensible Stylesheet Language.
XSLT:
XSLT Elements
Description of all the XSLT elements from the W3C Recommendation, and information about
browser support.
XSLT Functions
XSLT includes over 100 built-in functions. There are functions for string values, numeric values, date
and time comparison, node and QName manipulation, sequence manipulation, Boolean values, and more.
XSLT is the most important part of XSL. XSLT is used to transform an XML document into
another XML document, or another type of document that is recognized by a browser, like HTML
and XHTML. Normally XSLT does this by transforming each XML element into an (X)HTML
element. With XSLT you can add/remove elements and attributes to or from the output file. You
can also rearrange and sort elements, perform tests and make decisions about which elements to
hide and display, and a lot more. A common way to describe the transformation process is to say
that XSLT transforms an XML source-tree into an XML result-tree.
XSLT uses XPath to find information in an XML document. XPath is used to navigate through
The root element that declares the document to be an XSL style sheet is <xsl:stylesheet> or
<xsl:transform>.
Note: <xsl:stylesheet> and <xsl:transform> are completely synonymous and either can be used!
The correct way to declare an XSL style sheet according to the W3C XSLT Recommendation is:
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
To get access to the XSLT elements, attributes and features we must declare the XSLT namespace
at the top of the document.
The xmlns:xsl="http://www.w3.org/1999/XSL/Transform" points to the official W3C XSLT
namespace. If you use this namespace, you must also include the attribute version="1.0".
Then you create an XSL Style Sheet ("cdcatalog.xsl") with a transformation template:
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="/">
<html>
<body>
<h2>My CD Collection</h2>
<table border="1">
<tr bgcolor="#9acd32">
<th>Title</th>
<th>Artist</th>
</tr>
<xsl:for-each select="catalog/cd">
<tr>
<td><xsl:value-of select="title"/></td>
<td><xsl:value-of select="artist"/></td>
</tr>
</xsl:for-each>
</table>
</body>
</html>
</xsl:template>
</xsl:stylesheet>
Add the XSL style sheet reference to your XML document ("cdcatalog.xml"):
The DOM defines a standard for accessing documents like XML and HTML:
"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."
DOM: an object-oriented representation of the XML parse tree (roughly like the Data Model graph)
DOM objects have methods like “getFirstChild()”, “getNextSibling”
Common way of traversing the tree
Can also modify the DOM tree – alter the XML – via insertAfter(), etc.
The XML DOM is:
A standard object model for XML
A standard programming interface for XML
Platform- and language-independent
A W3C standard
The XML DOM defines the objects and properties of all XML elements, and the methods (interface) to
access them.
DOM Nodes
According to the DOM, everything in an XML document is a node.
The DOM says:
The entire document is a document node
Every XML element is an element node
The text in the XML elements are text nodes
Every attribute is an attribute node
Comments are comment nodes
DOM Example
Look at the following XML file (books.xml):
The root node in the XML above is named <bookstore>. All other nodes in the document are contained
within <bookstore>.
The first <book> node holds four nodes: <title>, <author>, <year>, and <price>, which contains one text
node each, "Everyday Italian", "Giada De Laurentiis", "2005", and "30.00".
holds a text node with the value "2005". "2005" is not the value of the <year> element!
XML Parser
The XML DOM contains methods to traverse XML trees, access, insert, and delete nodes.
However, before an XML document can be accessed and manipulated, it must be loaded into an XML
DOM object.
An XML parser reads XML, and converts it into an XML DOM object that can be accessed with
JavaScript.
Most browsers have a built-in XML parser.
}
else // code for IE
{
xmlDoc=new ActiveXObject("Microsoft.XMLDOM");
xmlDoc.async=false;
xmlDoc.loadXML(text);
}
Accessing Nodes
You can access a node in three ways:
1. By using the getElementsByTagName() method
2. By looping through (traversing) the nodes tree.
3. By navigating the node tree, using the node relationships.
x=xmlDoc.getElementsByTagName("title");
The <title> elements in x can be accessed by index number. To access the third <title> you can write::
y=x[2];
Note: The index starts at 0.
You will learn more about node lists in a later chapter of this tutorial.
document.write(x[i].childNodes[0].nodeValue);
document.write("<br>");
}
Node Types
The documentElement property of the XML document is the root node.
The nodeName property of a node is the name of the node.
The nodeType property of a node is the type of the node.
You will learn more about the node properties in the next chapter of this tutorial.
Traversing Nodes
The following code loops through the child nodes, that are also element nodes, of the root node:
Example
var xmlDoc=loadXMLDoc("books.xml");
var x=xmlDoc.documentElement.childNodes;
for (i=0;i<x.length;i++)
{
// Process only element nodes (type 1)
if (x[i].nodeType==1)
{
document.write(x[i].nodeName);
document.write("<br>");
}
}
Example explained:
1. Load "books.xml" into xmlDoc using loadXMLDoc()
2. Get the child nodes of the root element
3. For each child node, check the node type of the node. If the node type is "1" it is an element
node
4. Output the name of the node if it is an element node
var x=xmlDoc.getElementsByTagName("book")[0].childNodes;
var y=xmlDoc.getElementsByTagName("book")[0].firstChild;
for (i=0;i<x.length;i++)
{
// Process only element nodes (type 1)
if (y.nodeType==1)
{
document.write(y.nodeName + "<br>");
}
y=y.nextSibling;
}
var xmlDoc=loadXMLString(text);
for (i=0;i<x.length;i++)
{
document.write(x[i].nodeName);
document.write(": ");
document.write(x[i].childNodes[0].nodeValue);
document.write("<br>");
}
</script>
</body>
</html>
Output:
title: Everyday Italian
author: Giada De Laurentiis
year: 2005
Example explained:
1. loadXMLString() loads the XML string into xmlDoc
2. Get the child nodes of the root element
3. For each child node, output the node name and the node value of the text node
17. Discuss in detail about the XML DTD
XML DTD
The DOCTYPE declaration, in the example above, is a reference to an external DTD file. The content of
the file is shown in the paragraph below.
The purpose of a DTD is to define the structure of an XML document. It defines the structure with a list
of legal elements:
<!DOCTYPE note
[
<!ELEMENT note (to,from,heading,body)>
<!ELEMENT to (#PCDATA)>
<!ELEMENT from (#PCDATA)>
<!ELEMENT heading (#PCDATA)>
<!ELEMENT body (#PCDATA)>
]>
The DTD above is interpreted like this:
!DOCTYPE note defines that the root element of the document is note
!ELEMENT note defines that the note element must contain four elements: "to, from, heading,
body"
!ELEMENT to defines the to element to be of type "#PCDATA"
!ELEMENT from defines the from element to be of type "#PCDATA"
!ELEMENT heading defines the heading element to be of type "#PCDATA"
!ELEMENT body defines the body element to be of type "#PCDATA"
Example
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE note [
<!ENTITY nbsp " ">
<!ENTITY writer "Writer: Donald Duck.">
<!ENTITY copyright "Copyright: W3Schools.">
]>
<note>
<to>Tove</to>
<from>Jani</from>
<heading>Reminder</heading>
<body>Don't forget me this weekend!</body>
<footer>&writer; ©right;</footer>
</note>
With a DTD, independent groups of people can agree on a standard for interchanging data. With a DTD,
you can verify that the data you receive from the outside world is valid.
Unit-V
Part – A
1. What is 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.
2. What technologies are being used in AJAX?
AJAX uses four technologies, which are as follows:
JavaScript, XMLHttpRequest, Document Object Model (DOM), Extensible HTML (XHTML) and Cascading Style
Sheets (CSS)
3. Explain the limitations of AJAX.
It is difficult to bookmark a particular state of the application,Function provided in the code-behind file do not
work because the dynamic pages cannot register themselves on browsers history engine automatically
<Body> is a mandatory sub element of the SOAP envelope, which contains information intended for the ultimate
recipient of the message; see The SOAP body.
The SOAP fault
<Fault> is a sub element of the SOAP body, which is used for reporting errors; see The SOAP fault.
XML elements in <Header> and <Body> are defined by the applications that make use of them, although the
SOAP specification imposes some constraints on their structure.
29. Define the need for SOAP. (APR/MAY 2013)
Simple Object Access Protocol (SOAP) is a protocol based on XML. It is used by the web services for exchange of
information. The Client- Server communication is based on RPC. The HTTP does not design to handle the
distributed objects that are required by the RPC. Hence another application protocol is build over HTTP which
popularly known as SOAP. SOAP allows talking different applications that are running in two different operating
systems.
30. What are the descriptions in SOAP service?
To describe everything a SOAP service needs to describe the following:
The operations
The schema for each message in an operation
The SOAPAction headers
The URL endpoint of the service
31. Give an example of a web services registry and its function. (NOV/DEC 2012)
It refers to a place in which service providers can impart information about their offered services and potential
clients can search for services
Example: IBM - WebSphere Service Registry, Oracle Service Registry etc.,
32. Mention some of the disadvantageous of web services (MAY/JUNE 2014)
Web services standards features such as transactions are currently nonexistent or still in their infancy compared to
more mature distributed computing open standards such as CORBA. Web services may suffer from poor
performance compared to other distributed computing approaches such as RMI, CORBA, or DCOM.
33. What is JWSDP?
Java Web Service Developer Pack (JWSDP) is a tool. Using the JWSDP tool the simple implementation files
written in java can be converted to Web Service.
34. What are the specifications of web service architecture?
The specifications are
Standards based
Modular
Federated
General purpose
Part-B
1. Explain about the object that helps AJAX reload parts of a web page without reloading the whole page.
(NOV/DEC 2011, MAY/JUNE 2014)
AJAX = Asynchronous JavaScript and XML.
AJAX is a technique for creating fast and dynamic web pages.
AJAX allows web pages to be updated asynchronously by exchanging small amounts of data with the
server behind the scenes. This means that it is possible to update parts of a web page, without reloading
the whole page.
Classic web pages, (which do not use AJAX) must reload the entire page if the content should change.
AJAX is about updating parts of a web page, without reloading the whole page.
b) setRequestHeader(name, value)
Upon successful initialization of a request, the setRequestHeader method of the XMLHttpRequest object
can be invoked to send HTTP headers with the request.
Example:
//Tells server that this call is made for ajax
purposes.
1
xmlhttp.setRequestHeader('X-Requested-With',
2'XMLHttpRequest');
c) send(payload)
To send an HTTP request, the send method of the XMLHttpRequest must be invoked. This method
accepts a single parameter containing the content to be sent with the request.
The content is necessary in POST requests. For GET methods, imply pass null as parameter.
Example:
xmlhttp.send(null); //Request with no data in request body;
1Mostly used in GET requests.
2xmlhttp.send( {"id":"23423"} ); //Request with data in request
body; Mostly used in POST/ PUT requests.
4) abort()
This method aborts the request if the readyState of the XMLHttpRequest object has not yet become
4 (request complete). The abort method ensures that the callback method does not get invoked in an
asynchronous request.
Syntax:
1//Abort the processing
2 xmlhttp.abort();
Apart from above method, onreadystatechange event listener is very important which we will discuss in
next section.
request.onreadystatechange = function() {
if (request.readyState == 4) {
if (request.status == 200)
{
//request succeed
}
else
{
//request failed
}
}
};
request.send(null)
Example code:
if (xmlhttp.readyState == 4) {
if (xmlhttp.status == 200)
{
document.getElementById("message").innerHTML =
xmlhttp.responseText;
}
else {
alert('Something is wrong !!');
}
}
2. Explain technologies are being used in AJAX?
AJAX stands for Asynchronous JavaScript and XML. AJAX is a new technique for creating
better, faster, and more interactive web applications with the help of XML, HTML, CSS, and Java
Script.
Ajax uses XHTML for content, CSS for presentation, along with Document Object Model and
JavaScript for dynamic content display.
Conventional web applications transmit information to and from the sever using synchronous
requests. It means you fill out a form, hit submit, and get directed to a new page with new
information from the server.
With AJAX, when you hit submit, JavaScript will make a request to the server, interpret the
results, and update the current screen. In the purest sense, the user would never know that
anything was even transmitted to the server.
XML is commonly used as the format for receiving server data, although any format, including
plain text, can be used.
AJAX is a web browser technology independent of web server software.
A user can continue to use the application while the client program requests information from the
server in the background.
Intuitive and natural user interaction. Clicking is not required, mouse movement is a sufficient
event trigger.
Data-driven as opposed to page-driven.
AJAX cannot work independently. It is used in combination with other technologies to create
interactive webpages.
JavaScript
Loosely typed scripting language.
JavaScript function is called when an event occurs in a page.
Glue for the whole AJAX operation.
DOM
API for accessing and manipulating structured documents.
Represents the structure of XML and HTML documents.
CSS
Allows for a clear separation of the presentation style from the content and may be changed
programmatically by JavaScript.
XMLHttpRequest
JavaScript object that performs asynchronous interaction with the server.
try{
ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
}catch (e){
ajaxRequest.onreadystatechange = processRequest;
response.getWriter().write("false");
}
}
6. Callback Function processRequest() is Called
The XMLHttpRequest object was configured to call the processRequest() function when there is a state
change to the readyState of the XMLHttpRequest object. Now this function will receive the result from
the server and will do the required processing. As in the following example, it sets a variable message on
true or false based on the returned value from the Webserver.
function processRequest() {
if (req.readyState == 4) {
if (req.status == 200) {
var message = ...;
...
}
7. The HTML DOM is Updated
This is the final step and in this step, your HTML page will be updated. It happens in the following way:
JavaScript gets a reference to any element in a page using DOM API.
The recommended way to gain a reference to an element is to call.
document.getElementById("userIdMessage"),
// where "userIdMessage" is the ID attribute
// of an element appearing in the HTML document
JavaScript may now be used to modify the element's attributes; modify the element's style
properties; or add, remove, or modify the child elements. Here is an example:
<script type="text/javascript">
<!--
function setMessageUsingDOM(message) {
var userMessageElement = document.getElementById("userIdMessage");
var messageText;
if (message == "false") {
userMessageElement.style.color = "red";
messageText = "Invalid User Id";
}
else
{
userMessageElement.style.color = "green";
messageText = "Valid User Id";
}
userMessageElement.childNodes[0]);
}
else
{
userMessageElement.appendChild(messageBody);
}
}
-->
</script>
<body>
<div id="userIdMessage"><div>
</body>
3. Explain the concept of JSON concept with example.
JSON: JavaScript Object Notation.
o JSON is a syntax for storing and exchanging data.
o JSON is an easier-to-use alternative to XML.
o JSON is a lightweight data-interchange format
o JSON is language independent
o JSON is "self-describing" and easy to understand
The following JSON example defines an employees object, with an array of 3 employee records:
JSON Example
{"employees":[
{"firstName":"John", "lastName":"Doe"},
{"firstName":"Anna", "lastName":"Smith"},
{"firstName":"Peter", "lastName":"Jones"}
]}
The following XML example also defines an employees object with 3 employee records:
XML Example
<employees>
<employee>
<firstName>John</firstName> <lastName>Doe</lastName>
</employee>
<employee>
<firstName>Anna</firstName> <lastName>Smith</lastName>
</employee>
<employee>
<firstName>Peter</firstName> <lastName>Jones</lastName>
</employee>
</employees>
JSON Example
<!DOCTYPE html>
<html>
<body>
<p id="demo"></p>
<script>
var text = '{"name":"John Johnson","street":"Oslo West 16","phone":"555 1234567"}';
document.getElementById("demo").innerHTML =
obj.name + "<br>" +
obj.street + "<br>" +
obj.phone;
</script>
</body>
</html>
Output:
A common use of JSON is to read data from a web server, and display the
data in a web page.
The following example reads a menu from myTutorials.txt, and displays the menu in a web page:
JSON Example
<div id="id01"></div>
<script>
var xmlhttp = new XMLHttpRequest();
var url = "myTutorials.txt";
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
var myArr = JSON.parse(xmlhttp.responseText);
myFunction(myArr);
}
}
xmlhttp.open("GET", url, true);
xmlhttp.send();
function myFunction(arr) {
var out = "";
var i;
for(i = 0; i < arr.length; i++) {
out += '<a href="' + arr[i].url + '">' +
arr[i].display + '</a><br>';
}
document.getElementById("id01").innerHTML = out;
}
</script>
Example Explained
1: Create an array of objects.
Use an array literal to declare an array of objects.
Give each object two properties: display and url.
Name the array myArray:
myArray
var myArray = [
{
"display": "JavaScript Tutorial",
"url": "http://www.w3schools.com/js/default.asp"
},
{
"display": "HTML Tutorial",
"url": "http://www.w3schools.com/html/default.asp"
},
{
"display": "CSS Tutorial",
"url": "http://www.w3schools.com/css/default.asp"
}
]
2: Create a JavaScript function to display the array.
Create a function myFunction() that loops the array objects, and display the content as HTML links:
myFunction()
function myFunction(arr) {
var out = "";
var i;
for(i = 0; i < arr.length; i++) {
out += '<a href="' + arr[i].url + '">' + arr[i].display + '</a><br>';
}
document.getElementById("id01").innerHTML = out;
}
Call myFunction() with myArray as argument:
Example
myFunction(myArray);
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
var myArr = JSON.parse(xmlhttp.responseText);
myFunction(myArr);
}
}
The illustration shows the functionality of the client-based Microsoft Ajax Library, which includes
support for creating client components, browser compatibility, and networking and core services. The
illustration also shows the functionality of server-based Microsoft Ajax features, which include script
support, Web services, application services, and server controls. The following sections describe the
illustration in more detail.
Microsoft Ajax Client Architecture
The client architecture includes libraries for component support, browser compatibility, networking, and
core services.
Components
Client components enable rich behaviors in the browser without postbacks. Components fall into three
categories:
Components, which are non-visual objects that encapsulate code.
Behaviors, which extend the behavior of existing DOM elements.
Controls, which represent a new DOM element that has custom behavior.
The type of component that you use depends on the type of client behavior you want. For example, a
watermark for an existing text box can be created by using a behavior that is attached to the text box
Browser Compatibility
The browser compatibility layer provides Microsoft Ajax scripting compatibility for the most frequently
used browsers (including Microsoft Internet Explorer, Mozilla Firefox, and Apple Safari). This enables
you to write the same script regardless of which supported browser you are targeting.
Networking
The networking layer handles communication between script in the browser and Web-based services and
applications. It also manages asynchronous remote method calls. In many scenarios, such as partial-page
updates that use the UpdatePanel control, the networking layer is used automatically and does not require
that you write any code.
The networking layer also provides support for accessing server-based forms authentication, role
information, and profile information in client script. This support is also available to Web applications
that are not created by using ASP.NET, as long as the application has access to the Microsoft Ajax
Library.
Core Services
The Ajax client-script libraries in ASP.NET consist of JavaScript (.js) files that provide features for
object-oriented development. The object-oriented features included in the Microsoft Ajax client-script
libraries enable a high level of consistency and modularity in client scripting. The following core services
are part of the client architecture:
Object-oriented extensions to JavaScript, such as classes, namespaces, event handling,
inheritance, data types, and object serialization.
A base class library, which includes components such as string builders and extended error
handling.
Support for JavaScript libraries that are either embedded in an assembly or are provided as
standalone JavaScript (.js) files. Embedding JavaScript libraries in an assembly can make it easier
to deploy applications and can help solve versioning issues. Debugging and Error Handling
The core services include the Sys.Debug class, which provides methods for displaying objects in readable
form at the end of a Web page. The class also shows trace messages, enables you to use assertions, and
lets you break into the debugger. An extended Error object API provides helpful exception details with
support for release and debug modes.
Globalization
The Ajax server and client architecture in ASP.NET provides a model for localizing and globalizing
client script. This enables you to design applications that use a single code base to provide UI for many
locales (languages and cultures). For example, the Ajax architecture enables JavaScript code to format
Date or Number objects automatically according to culture settings of the user's browser, without
requiring a postback to the server.
Ajax Server Architecture
The server pieces that support Ajax development consist of ASP.NET Web server controls and
components that manage the UI and flow of an application. The server pieces also manage serialization,
validation, and control extensibility. There are also ASP.NET Web services that enable you to access
ASP.NET application services for forms authentication, roles, and user profiles.
Script Support
Ajax features in ASP.NET are commonly implemented by using client script libraries that perform
processing strictly on the client. You can also implement Ajax features by using server controls that
support scripts sent from the server to the client.
You can also create custom client script for your ASP.NET applications. In that case, you can also use
Ajax features to manage your custom script as static .js files (on disk) or as .js files embedded as
resources in an assembly.
Ajax features include a model for release and debug modes. Release mode provides error checking and
exception handling that is optimized for performance, with minimized script size. Debug mode provides
more robust debugging features, such as type and argument checking. ASP.NET runs the debug versions
when the application is in debug mode. This enables you to throw exceptions in debug scripts while
minimizing the size of release code.
Script support for Ajax in ASP.NET is used to provide two important features:
The Microsoft Ajax Library, which is a type system and a set of JavaScript extensions that
provide namespaces, inheritance, interfaces, enumerations, reflection, and additional features.
Partial-page rendering, which updates regions of the page by using an asynchronous postback.
Localization
The Microsoft Ajax architecture builds on the foundation of the ASP.NET 2.0 localization model. It
provides additional support for localized .js files that are embedded in an assembly or that are provided
on disk. ASP.NET can serve localized client scripts and resources automatically for specific languages
and regions.
Web Services
With Ajax functionality in an ASP.NET Web page, you can use client script to call both ASP.NET Web
services (.asmx) and Windows Communication Foundation (WCF) services (.svc). The required script
references are automatically added to the page, and they in turn automatically generate the Web service
proxy classes that you use from client script to call the Web service.
You can also access ASP.NET Web services without using Microsoft Ajax server controls (for example,
if you are using a different Web development environment). To do so, in the page, you can manually
include references to the Microsoft Ajax Library, to script files, and to the Web service itself. At run
time, ASP.NET generates the proxy classes that you can use to call the services.
Application Services
Application services in ASP.NET are built-in Web services that are based on ASP.NET forms
authentication, roles, and user profiles. These services can be called by client script in an Ajax-enabled
Web page, by a Windows client application, or by a WCF-compatible client.
Server Controls
Ajax server controls consist of server and client code that integrate to produce rich client behavior. When
you add an Ajax-enabled control to an ASP.NET Web page, the page automatically sends supporting
client script to the browser for Ajax functionality. You can provide additional client code to customize
the functionality of a control, but this is not required.
The following list describes the most frequently used Ajax server controls.
Control Description
Manages script resources for client components, partial-page rendering,
localization, globalization, and custom user scripts. The ScriptManager control
ScriptManager is required in order to use the UpdatePanel, UpdateProgress, and Timer controls.
However, the ScriptManager control is not required when creating a client-only
solution.
Enables you to refresh selected parts of the page, instead of refreshing the whole
UpdatePanel
page by using a synchronous postback.
UpdateProgress Provides status information about partial-page updates in UpdatePanel controls.
Performs postbacks at defined intervals. You can use the Timer control to post
Timer the whole page, or use it together with the UpdatePanel control to perform
partial-page updates at a defined interval.
You can also create custom ASP.NET server controls that include Ajax client behaviors. Custom controls
that enhance the capabilities of other ASP.NET Web controls are referred to as extender controls.
Ajax Control Toolkit
The Ajax Control Toolkit contains controls that you can use to build highly responsive and interactive
Ajax-enabled Web applications. These controls do not require knowledge of JavaScript or Ajax. They are
designed using concepts that are familiar to ASP.NET Web Forms application developers. Using the
Ajax Control Toolkit, you can build Ajax-enabled ASP.NET Web Forms applications and ASP.NET
MVC Web applications by dragging the controls from the Visual Studio Toolbox onto a page. The Ajax
Control Toolkit is an open-source project that is part of the CodePlex Foundation
5. Develop a web application for Airline Reservation System using AJAX.
Airline Reservation System using AJAX
This example application simulates an online reservation system that allows users to search for the best
flights available between two cities. The system processes requests and provides the flight numbers,
seating information and price for each leg of a three-leg flight, computing the total price at the end.
This Flight Reservation example application consists of two parts:
1. Client-side Frontend Application
A client-side application which accepts end user requests from an AJAX-based graphical user interface
(GUI). This application enables users to to select between one departure city and two possible
destinations.
2. Server-side Backend Application
A server-side application that processes end-user requests.
6. With a simple example illustrate the steps to create a java web service. (NOV/DEC 2012)
Writing a java web service
Currency conversion Service
Writing a server for a service using JWSDP 1.3 tools
Application: currency converter
Three operations:
fromDollars
fromEuros
fromYen
Input: value in specified currency
Output: object containing input value and equivalent values in other two currencies
Writing server software
1. Write service endpoint interface
• May need to write additional classes representing data structures
2. Write class implementing the interface
3. Compile classes
4. Create configuration files and run JWSDP tools to create web service
5. Deploy web service to Tomcat
service endpoint interface
The Web service endpoint interface is used to define the ‘Web services methods’.
A Web service endpoint interface must conform to the rules of a JAX-RPC service definition
interface.
a service endpoint interface (SEI) that defines the interface of the web service.
Configuration files are XML files that can be changed as needed. Developers can use
configuration files to change settings without recompiling applications. Administrators can use
configuration files to set policies that affect how applications run on their computers.
config.xml : Defines the URL for WSDL file location. Each Web services has a corresponding
WSDL (Web service Definition Language) document.
JWSDP: Server
Rules for Service endpoint interface
Must extend java.rmi.Remote
declares a set of methods that may be invoked from a remote Java Virtual
Machine(JVM)
Every method must throw java.rmi.RemoteException
Parameter/return value data types are restricted
No public static final declarations (global constants) It must not have constant declarations
Allowable parameter/return value data types
Java primitives (int, boolean, etc.)
Primitive wrapper classes (Integer, etc.)
String, Date, Calendar, BigDecimal, BigInteger
java.xml.namespace.QName, java.net.URI
Struct: class consisting entirely of public instance variables
Array of any of the above
Struct for currency converter app (data type for return values)
Three files ExchangeValues.java, CurCon.java and CurConImpl.java written for the web service
Class CurConImpl contains methods implements sevice endpoint interface, for example:
Like
servlet
in
web.xml
Like servlet-mapping
in web.xml
Run jar and wsdeploy to create a Web Archive (WAR) file converter.war
The UDDI specification defines open, platform-independent standards that enable businesses to share
information in a global business registry, discover services on the registry, and define how they interact
over the Internet.
WSDL
XML-based open specification that describes the interfaces to and instances of Web services on
the network.
It is extensible, so endpoints can be described regardless of the message formats or network
SOAP
XML-based standard for messaging over HTTP and other Internet protocols.
It is a lightweight protocol for the exchange of information in a decentralized, distributed
environment.
It is based on XML and consists of three parts:
o An envelope that defines a framework for describing what is in a message and how to
process it.
o A set of encoding rules for expressing instances of application-defined data types.
o A convention for representing remote procedure calls and responses.
SOAP enables the binding and usage of discovered Web services by defining a message path for
routing messages.
SOAP may be used to query UDDI for Web services.
A service provider hosts a Web service and makes it accessible using protocols such as SOAP/HTTP or
SOAP/JMS. The Web service is described by a WSDL document that is stored on the provider's server or
in a special repository. The WSDL document may be referenced by the UDDI business registry and
WSIL documents. These contain pointers to the Web service's WSDL files.
8. Explain the creation of a java web service Client in detail with examples. (MAY/JUNE 2012)
Writing a Java Web service Client
Goal: write a JSP-based client
Input: currency and value
Output: table of equivalent values
Use wscompile tool to develop client
• Proxy object is a java object called on by a client software in order to access the web service
JWSDP: Client
Directory structure (wscompile generates content of classes and src)
Run wscompile
Run wscompile
Wscompile –gen –keep –d classes –s src config.xml
Wscompile tool creates a class implementing the interface
Interface is shared between webservice server and clients via the wsdl document.
On server side the class implementing the interface is written
On client side the interface is automatically generated by wscompile tool
Structs will be represented as JavaBeans classes, regardless of how they are defined on the server
Syntax Rules
Here are some important syntax rules:
The optional SOAP Header element contains application specific information (like authentication,
payment, etc) about the SOAP message. If the Header element is present, it must be the first child
element of the Envelope element.
Note: All immediate child elements of the Header element must be namespace-qualified.
<?xml version="1.0"?>
<soap:Envelope
xmlns:soap="http://www.w3.org/2001/12/soap-envelope"
soap:encodingStyle="http://www.w3.org/2001/12/soap-encoding">
<soap:Header>
<m:Trans
xmlns:m="http://www.w3schools.com/transaction/"
soap:mustUnderstand="1">234</m:Trans>
</soap:Header>
...
...
</soap:Envelope>
The example above contains a header with a "Trans" element, a "mustUnderstand" attribute value of "1",
and a value of 234.
SOAP defines three attributes in the default namespace ("http://www.w3.org/2001/12/soap-envelope").
These attributes are: actor, mustUnderstand, and encodingStyle. The attributes defined in the SOAP
Header defines how a recipient should process the SOAP message.
The actor Attribute
A SOAP message may travel from a sender to a receiver by passing different endpoints along the
message path. Not all parts of the SOAP message may be intended for the ultimate endpoint of the SOAP
message but, instead, may be intended for one or more of the endpoints on the message path.
The SOAP actor attribute may be used to address the Header element to a particular endpoint.
Syntax soap:actor="URI"
Example
<?xml version="1.0"?>
The mustUnderstand Attribute
The SOAP mustUnderstand attribute can be used to indicate whether a header entry is mandatory or
optional for the recipient to process.
If you add "mustUnderstand="1" to a child element of the Header element it indicates that the receiver
processing the Header must recognize the element. If the receiver does not recognize the element it must
fail when processing the Header.
Syntax soap:mustUnderstand="0|1"
SOAP Body Element
The mandatory SOAP Body element contains the actual SOAP message.
The required SOAP Body element contains the actual SOAP message intended for the ultimate endpoint
of the message.
Immediate child elements of the SOAP Body element may be namespace-qualified. SOAP defines one
element inside the Body element in the default namespace ("http://www.w3.org/2001/12/soap-
envelope"). This is the SOAP Fault element, which is used to indicate error messages.
<?xml version="1.0"?>
<soap:Envelope
xmlns:soap="http://www.w3.org/2001/12/soap-envelope"
soap:encodingStyle="http://www.w3.org/2001/12/soap-encoding">
<soap:Body>
<m:GetPrice xmlns:m="http://www.w3schools.com/prices">
<m:Item>Apples</m:Item>
</m:GetPrice>
</soap:Body>
</soap:Envelope>
The example above requests the price of apples. Note that the m:GetPrice and the Item elements above
are application-specific elements. They are not a part of the SOAP standard.
A SOAP response could look something like this: <?xml version="1.0"?>
<soap:Envelope
xmlns:soap="http://www.w3.org/2001/12/soap-envelope"
soap:encodingStyle="http://www.w3.org/2001/12/soap-encoding">
<soap:Body>
<m:GetPriceResponse xmlns:m="http://www.w3schools.com/prices">
<m:Price>1.90</m:Price>
</m:GetPriceResponse>
</soap:Body>
</soap:Envelope>
SOAP Fault Element
The optional SOAP Fault element is used to hold error and status information for a SOAP message.
An error message from a SOAP message is carried inside a Fault element.
If a Fault element is present, it must appear as a child element of the Body element. A Fault element can
only appear once in a SOAP message.
The SOAP Fault element has the following sub elements:
Sub Element Description
<faultcode> A code for identifying the fault
<faultstring> A human readable explanation of the
fault
<faultactor> Information about who caused the fault
to happen
<detail> Holds application specific error
information related to the Body element
The businessService document holds information about a specific service for a particular service. It
contains the following data:
serviceKey— A GUID that uniquely identifies the service
name— A friendly, human-readable name for the service
description— A human-readable description of the service and what it offers
bindingTemplates— A set of properties that define the taxonomy of the service
categoryBag— A generic name–value pair that helps to define the categories to which the service
belongs
an example of a businessService document:
<businessService
businessKey="some GUID here" serviceKey="some GUID here">
<name>Keith's Service</name>
<description>This service doesn't do anything</description>
<bindingTemplate>
...
</bindingTemplate>
</businessService>
tModel
The tModel is the hardest to understand and most misunderstood data structure in the UDDI Schema.
it's a generic keyed reference to something.
Arguably, this incredible flexibility makes tModel harder to use. But it enables us to describe all kinds of
things, and then link them to all kinds of other things. (Notice that I have to use the vague word thing
because of this abstraction and flexibility.)
With UDDI, tModels can have many different purposes, but one stands out in my mind: to reference Web
service features in a transparent and generic fashion. I can create separate tModels for services that
implement transactions, that implement reliable messaging, and that are described by WSDLs. I can then
attach all of the tModels that apply to any of my individual Web services. Even better, I can search for
services based on those tModels!
The tModel structure contains the following information:
tModelKey (technical model)
name— The friendly, human-readable name of the service
authorizedName
operator
description(s)— A description of the tModel
Idbag— A set of identifying name–value pairs
category bag— A series of categories to which this tModel belongs, expressed as a set of name–
value pairs
The following Listing shows a sample of what a tModel can look like.
Listing: A tModel Structure in the UDDI Schema
<tModel
xmlns="urn:uddi-org:api"
tModelKey="UUID:1111111-1111-1111-1111-1111111">
<name>KeithBa.Com:PurchaseOrders</name>
<description xml:lang="en">
Purchase orders services
</description>
<overviewDoc>
<overviewURL>http://keithba.com/po.wsdl</overviewURL>
</overviewDoc>
<categoryBag>
<keyedReference
tModelKey="UUID:C1ACF26D-9672-4404-9D70-39B756E62AB4"
keyName="types"
keyValue="wsdlSpec"/>
</categoryBag>
</tModel>
Programmer's API
In addition to defining a series of data structures, UDDI defines how to interact with those data
structures—in other words, how to use them with SOAP. There are two major sets of APIs within UDDI:
Inquiry Operations— For searching for information
Publisher Operations— For saving, editing, and deleting information
Inquiry
The piece of UDDI used the most is the set of inquiry operations, often called the inquiry API. Inquiry
operations with UDDI take two basic forms: browsing operations and retrieval operations.
Browsing operations are used to find something. You use them as broad-based queries to figure out what
you want. All of these operations start with the pattern "find_XXX", where XXX is something specific,
such as find_business or find_service.
There are only four operations in this category of UDDI operations:
find_binding
find_business
find_service
find_tModel
Once you know what you want, you can use the drill-down information retrieval operations to get all of
the details you need about a specific business or service. These operations require specific UUIDs
(Universally Unique Identifiers) that you probably will get via the browsing "find" operations. They all
follow the pattern of "get_XXX," where XXX is the specific information you need. Using Microsoft's
UDDI SDK, you can easily use these find operations:
Inquire.Url = "http://uddi.rte.microsoft.com/inquire";
FindBusiness findBusiness = new FindBusiness();
findBusiness.Names.Add("KeithBa");
BusinessList list = fb.Send();
There are five retrieval operations:
get_bindingDetail
get_businessDetail
get_businessDetailExt
get_serviceDetail
get_tModelDetail
And again, the UDDI SDK from Microsoft makes it easy to call these:
Inquire.Url = "http://uddi.rte.microsoft.com/inquire";
if (list.BusinessInfos.Count > 0)
{
GetBusinessDetail gb = new GetBusinessDetail();
gb.BusinessKeys.Add(bizList.BusinessInfos[0].BusinessKey);
BusinessDetail bizDetail = gb.Send();
if (bizDetail.BusinessEntities.Count > 0)
{
//do something interesting
}
}
WSDL and UDDI
UDDI offers a way to store abstract WSDL documents (WSDLs that don't point to a specific service, but
instead can be implemented by any number of services), as well. Actually, it provides for a specific
tModel structure to which each businessService can point.
The basic idea is that it is possible to create WSDL documents that are abstract. Technically, almost any
WSDL that is missing a service element and the child port pointing to a specific address is abstract. In
practice, the UDDI binding is for abstract WSDLs that are described down through the binding section.
Of course, nothing prevents you from using the true point of abstraction in a WSDL: the portType
section.
Once you've defined this abstract WSDL (e.g., as part of a standards organization), you can then create a
tModel in UDDI that references this WSDL. The important part to remember is that there must be a
keyed-Reference to the tModelKey that represents abstract WSDLs.
Also, the overiewURL element should point to the WSDL file.
Listing: A tModel That References a WSDL Document
<tModel tModelKey="UUID:1111111-1111-1111-111111">
<Name>Standard WSDL for AutoParts</Name>
<OverviewDoc>
<overviewURL>http://autoparts.org/autoparts.wsdl</overviewURL>
</OverviewDoc>
<categoryBag>
<keyedReference
tModelKey="uudi:C1ACF26D-9672-4404-9D70-39B756E62AB4"
keyName="uddi-org:types"
keyValue="wsdlSpec"
/>
</categoryBag>
</tModel>
Now, we can reference this tModel from other tModels or (more likely) from businessService entries that
represent specific implementations of this WSDL.
11. Explain the anatomy of WSDL.
WSDL
• Web Service Description Language.
• An XML language used to describe and locate web services.
• Written in XML.
• Describe functionality of a web service
• Specify how to access the service (binding protocol, message format, and etc.)
Main Structure of WSDL
<definition namespace = “http/… “>
<type> xschema types </type>
<message> … </message>
<port> a set of operations </port>
<binding> communication protocols </binding>
<service> a list of binding and ports </service>
<definition>
Types
• <types> define types used in message declaration
• XML Schema, DTD, and etc.
• XML Schema must be supported by any vendor of WSDL conformant products.
WSDL Messages
• The <message> element defines the data elements of an operation.
• Each messages can consist of one or more parts. The parts can be compared to the parameters of a function
call in a traditional programming language.
WSDL Ports
• The <portType> element is the most important WSDL element.
• It defines a web service, the operations that can be performed, and the messages that are involved.
• The <port> defines the connection point to a web service, an instance of <portType>.
It can be compared to a function library (or a module, or a class) in a traditional programming language. Each
operation can be compared to a function in a traditional programming language
Operation Types
• The request-response type is the most common operation type, but WSDL defines four types:
• One-way: The operation can receive a message but will not return a response
• Request-response:The operation can receive a request and will return a response
• Solicit-response:The operation can send a request and will wait for a response
• Notification:The operation can send a message but will not wait for a response
Binding
• Binding defines how message are transmitted, and the location of the service.
WSDL Example
This is a simplified fraction of a WSDL document:
<message name="getTermRequest">
<part name="term" type="xs:string"/>
</message>
<message name="getTermResponse">
<part name="value" type="xs:string"/>
</message>
<portType name="glossaryTerms">
<operation name="getTerm">
<input message="getTermRequest"/>
<output message="getTermResponse"/>
</operation>
</portType>
In this example the <portType> element defines "glossaryTerms" as the name of a port, and "getTerm"
as the name of an operation.
The "getTerm" operation has an input message called "getTermRequest" and an output message called
"getTermResponse".
The <message> elements define the parts of each message and the associated data types.
12. Describe the major elements of SOAP. (NOV/DEC 2011, MAY/JUNE 2014) (APR/MAY 2013)
SOAP is a simple XML based protocol to let applications exchange information over HTTP.
Or more simply: SOAP is a protocol for accessing a Web Service.
SOAP Building Blocks
A SOAP message is an ordinary XML document containing the following elements:
• A required Envelope element that identifies the XML document as a SOAP message
• An optional Header element that contains header information
• A required Body element that contains call and response information
• An optional Fault element that provides information about errors that occurred while processing the
message
All the elements above are declared in the default namespace for the SOAP envelope:
http://www.w3.org/2001/12/soap-envelope
and the default namespace for SOAP encoding and data types is:
http://www.w3.org/2001/12/soap-encoding
Syntax Rules
Here are some important syntax rules:
• A SOAP message MUST be encoded using XML
• A SOAP message MUST use the SOAP Envelope namespace
• A SOAP message MUST use the SOAP Encoding namespace
• A SOAP message must NOT contain a DTD reference
• A SOAP message must NOT contain XML Processing Instructions
Skeleton SOAP Message
<?xml version="1.0"?>
<soap:Envelope
xmlns:soap="http://www.w3.org/2001/12/soap-envelope"
soap:encodingStyle="http://www.w3.org/2001/12/soap-encoding">
<soap:Header>
...
...
</soap:Header>
<soap:Body>
...
...
<soap:Fault>
...
...
</soap:Fault>
</soap:Body>
</soap:Envelope>
SOAP ElementS:
SOAP Envelope Element
The mandatory SOAP Envelope element is the root element of a SOAP message.
The required SOAP Envelope element is the root element of a SOAP message. It defines the XML
document as a SOAP message.
Note the use of the xmlns:soap namespace. It should always have the value of:
http://www.w3.org/2001/12/soap-envelope
and it defines the Envelope as a SOAP Envelope:
<?xml version="1.0"?>
<soap:Envelope
xmlns:soap="http://www.w3.org/2001/12/soap-envelope"
soap:encodingStyle="http://www.w3.org/2001/12/soap-encoding">
...
Message information goes here
...
</soap:Envelope>
The xmlns:soap Namespace
A SOAP message must always have an Envelope element associated with the
"http://www.w3.org/2001/12/soap-envelope" namespace.
If a different namespace is used, the application must generate an error and discard the message.
The encodingStyle Attribute
The SOAP encodingStyle attribute is used to define the data types used in the document. This attribute
may appear on any SOAP element, and it will apply to that element's contents and all child elements. A
SOAP message has no default encoding.
Syntax
soap:encodingStyle="URI"
The optional SOAP Header element contains application specific information (like authentication,
payment, etc) about the SOAP message. If the Header element is present, it must be the first child
<?xml version="1.0"?>
<soap:Envelope
xmlns:soap="http://www.w3.org/2001/12/soap-envelope"
soap:encodingStyle="http://www.w3.org/2001/12/soap-encoding">
<soap:Header>
<m:Trans
xmlns:m="http://www.w3schools.com/transaction/"
soap:mustUnderstand="1">234</m:Trans>
</soap:Header>
...
...
</soap:Envelope>
The example above contains a header with a "Trans" element, a "mustUnderstand" attribute value of "1",
and a value of 234.
SOAP defines three attributes in the default namespace ("http://www.w3.org/2001/12/soap-envelope").
These attributes are: actor, mustUnderstand, and encodingStyle. The attributes defined in the SOAP
Header defines how a recipient should process the SOAP message.
The actor Attribute
A SOAP message may travel from a sender to a receiver by passing different endpoints along the
message path. Not all parts of the SOAP message may be intended for the ultimate endpoint of the SOAP
message but, instead, may be intended for one or more of the endpoints on the message path.
The SOAP actor attribute may be used to address the Header element to a particular endpoint.
Syntax soap:actor="URI"
Example
<?xml version="1.0"?>
The mustUnderstand Attribute
The SOAP mustUnderstand attribute can be used to indicate whether a header entry is mandatory or
optional for the recipient to process.
If you add "mustUnderstand="1" to a child element of the Header element it indicates that the receiver
processing the Header must recognize the element. If the receiver does not recognize the element it must
fail when processing the Header.
Syntax soap:mustUnderstand="0|1"
SOAP Body Element
The mandatory SOAP Body element contains the actual SOAP message.
The required SOAP Body element contains the actual SOAP message intended for the ultimate endpoint
of the message.
Immediate child elements of the SOAP Body element may be namespace-qualified. SOAP defines one
element inside the Body element in the default namespace ("http://www.w3.org/2001/12/soap-
envelope"). This is the SOAP Fault element, which is used to indicate error messages.
<?xml version="1.0"?>
<soap:Envelope
xmlns:soap="http://www.w3.org/2001/12/soap-envelope"
soap:encodingStyle="http://www.w3.org/2001/12/soap-encoding">
<soap:Body>
<m:GetPrice xmlns:m="http://www.w3schools.com/prices">
<m:Item>Apples</m:Item>
</m:GetPrice>
</soap:Body>
</soap:Envelope>
The example above requests the price of apples. Note that the m:GetPrice and the Item elements above
are application-specific elements. They are not a part of the SOAP standard.
A SOAP response could look something like this: <?xml version="1.0"?>
<soap:Envelope
xmlns:soap="http://www.w3.org/2001/12/soap-envelope"
soap:encodingStyle="http://www.w3.org/2001/12/soap-encoding">
<soap:Body>
<m:GetPriceResponse xmlns:m="http://www.w3schools.com/prices">
<m:Price>1.90</m:Price>
</m:GetPriceResponse>
</soap:Body>
</soap:Envelope>
SOAP Fault Element
The optional SOAP Fault element is used to hold error and status information for a SOAP message.
An error message from a SOAP message is carried inside a Fault element.
If a Fault element is present, it must appear as a child element of the Body element. A Fault element can
only appear once in a SOAP message.
The SOAP Fault element has the following sub elements:
Sub Element Description
<faultcode> A code for identifying the fault
<faultstring> A human readable explanation of the
fault
<faultactor> Information about who caused the fault
to happen
<detail> Holds application specific error
information related to the Body element
Servlets
Servlets provide a component-based, platform-independent method for building Web-based
applications, without the performance limitations of CGI programs. Servlets have access to the
entire family of Java APIs, including the JDBC API to access enterprise databases.
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
Servlets Architecture:
Servlets Tasks:
Like any other Java program, you need to compile a servlet by using the Java compiler javac
and after compilation the servlet application, it would be deployed in a configured
environment to test and run.
www.rejinpaul.com
www.rejinpaul.com
This step involves downloading an implementation of the Java Software Development Kit
(SDK) and setting up PATH environment variable appropriately.
You can download SDK from Oracle's Java site: Java SE Downloads.
Once you download your Java implementation, follow the given instructions to install and
configure the setup. Finally set PATH and JAVA_HOME environment variables to refer to
the directory that contains java and javac, typically java_install_dir/bin and java_install_dir
respectively.
If you are running Windows and installed the SDK in C:\jdk1.5.0_20, you would put the
following line in your C:\autoexec.bat file.
set PATH=C:\jdk1.5.0_20\bin;%PATH%
set JAVA_HOME=C:\jdk1.5.0_20
On Unix (Solaris, Linux, etc.), if the SDK is installed in /usr/local/jdk1.5.0_20 and you use
the C shell, you would put the following into your .cshrc file.
A number of Web Servers that support servlets are available in the market. Some web servers
are freely downloadable and Tomcat is one of them.
Apache Tomcat is an open source software implementation of the Java Servlet and
JavaServer Pages technologies and can act as a standalone server for testing servlets and can
be integrated with the Apache Web Server. Here are the steps to setup Tomcat on your
machine:
%CATALINA_HOME%\bin\startup.bat
or
C:\apache-tomcat-5.5.29\bin\startup.bat
Tomcat can be started by executing the following commands on Unix (Solaris, Linux, etc.)
machine:
$CATALINA_HOME/bin/startup.sh
or
/usr/local/apache-tomcat-5.5.29/bin/startup.sh
After startup, the default web applications included with Tomcat will be available by visiting
http://localhost:8080/. If everything is fine then it should display following result:
Further information about configuring and running Tomcat can be found in the
documentation included here, as well as on the Tomcat web site: http://tomcat.apache.org
C:\apache-tomcat-5.5.29\bin\shutdown
Tomcat can be stopped by executing the following commands on Unix (Solaris, Linux, etc.)
machine:
/usr/local/apache-tomcat-5.5.29/bin/shutdown.sh
www.rejinpaul.com
www.rejinpaul.com
Setting up CLASSPATH
Since servlets are not part of the Java Platform, Standard Edition, you must identify the
servlet classes to the compiler.
If you are running Windows, you need to put the following lines in your C:\autoexec.bat file.
set CATALINA=C:\apache-tomcat-5.5.29
set CLASSPATH=%CATALINA%\common\lib\servlet-api.jar;%CLASSPATH%
On Unix (Solaris, Linux, etc.), if you are using the C shell, you would put the following lines
into your .cshrc file.
setenv CATALINA=/usr/local/apache-tomcat-5.5.29
setenv CLASSPATH $CATALINA/common/lib/servlet-api.jar:$CLASSPATH
The init method is designed to be called only once. It is called when the servlet is first
created, and not called again for each user request. So, it is used for one-time initializations,
just as with the init method of applets.
The servlet is normally created when a user first invokes a URL corresponding to the servlet,
but you can also specify that the servlet be loaded when the server is first started.
When a user invokes a servlet, a single instance of each servlet gets created, with each user
request resulting in a new thread that is handed off to doGet or doPost as appropriate. The
init() method simply creates or loads some data that will be used throughout the life of the
servlet.
www.rejinpaul.com
www.rejinpaul.com
The service() method is the main method to perform the actual task. The servlet container
(i.e. web server) calls the service() method to handle requests coming from the client(
browsers) and to write the formatted response back to the client.
Each time the server receives a request for a servlet, the server spawns a new thread and calls
service. The service() method checks the HTTP request type (GET, POST, PUT, DELETE,
etc.) and calls doGet, doPost, doPut, doDelete, etc. methods as appropriate.
The service () method is called by the container and service method invokes doGe, doPost,
doPut, doDelete, etc. methods as appropriate. So you have nothing to do with service()
method but you override either doGet() or doPost() depending on what type of request you
receive from the client.
The doGet() and doPost() are most frequently used methods with in each service request.
Here is the signature of these two methods.
A GET request results from a normal request for a URL or from an HTML form that has no
METHOD specified and it should be handled by doGet() method.
A POST request results from an HTML form that specifically lists POST as the METHOD
and it should be handled by doPost() method.
The destroy() method is called only once at the end of the life cycle of a servlet. This method
gives your servlet a chance to close database connections, halt background threads, write
cookie lists or hit counts to disk, and perform other such cleanup activities.
After the destroy() method is called, the servlet object is marked for garbage collection. The
destroy method definition looks like this:
Architecture Digram:
First the HTTP requests coming to the server are delegated to the servlet container.
The servlet container loads the servlet before invoking the service() method.
Then the servlet container handles multiple requests by spawning multiple threads,
each thread executing the service() method of a single instance of the servlet.
Examples
Servlets are Java classes which service HTTP requests and implement the
javax.servlet.Servlet interface. Web application developers typically write servlets that
extend javax.servlet.http.HttpServlet, an abstract class that implements the Servlet interface
and is specially designed to handle HTTP requests.
www.rejinpaul.com
www.rejinpaul.com
Following is the sample source code structure of a servlet example to write Hello World:
Compiling a Servlet:
Let us put above code if HelloWorld.java file and put this file in C:\ServletDevel (Windows)
or /usr/ServletDevel (Unix) then you would need to add these directories as well in
CLASSPATH.
$ javac HelloWorld.java
If the servlet depends on any other libraries, you have to include those JAR files on your
CLASSPATH as well. I have included only servlet-api.jar JAR file because I'm not using any
other library in Hello World program.
This command line uses the built-in javac compiler that comes with the Sun Microsystems
Java Software Development Kit (JDK). For this command to work properly, you have to
include the location of the Java SDK that you are using in the PATH environment variable.
www.rejinpaul.com
www.rejinpaul.com
If everything goes fine, above compilation would produce HelloWorld.class file in the same
directory. Next section would explain how a compiled servlet would be deployed in
production.
Servlet Deployment:
If you have a fully qualified class name of com.myorg.MyServlet, then this servlet class
must be located in WEB-INF/classes/com/myorg/MyServlet.class.
<servlet>
<servlet-name>HelloWorld</servlet-name>
<servlet-class>HelloWorld</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>HelloWorld</servlet-name>
<url-pattern>/HelloWorld</url-pattern>
</servlet-mapping>
You are almost done, now let us start tomcat server using <Tomcat-installation-
directory>\bin\startup.bat (on windows) or <Tomcat-installation-directory>/bin/startup.sh (on
Linux/Solaris etc.) and finally type http://localhost:8080/HelloWorld in browser's address
box. If everything goes fine, you would get following result:
www.rejinpaul.com
www.rejinpaul.com
You must have come across many situations when you need to pass some information from
your browser to web server and ultimately to your backend program. The browser uses two
methods to pass this information to web server. These methods are GET Method and POST
Method.
GET method:
The GET method sends the encoded user information appended to the page request. The page
and the encoded information are separated by the ? character as follows:
http://www.test.com/hello?key1=value1&key2=value2
The GET method is the defualt method to pass information from browser to web server and it
produces a long string that appears in your browser's Location:box. Never use the GET
method if you have password or other sensitive information to pass to the server. The GET
method has size limtation: only 1024 characters can be in a request string.
This information is passed using QUERY_STRING header and will be accessible through
QUERY_STRING environment variable and Servlet handles this type of requests using
doGet() method.
POST method:
A generally more reliable method of passing information to a backend program is the POST
method. This packages the information in exactly the same way as GET methods, but instead
of sending it as a text string after a ? in the URL it sends it as a separate message. This
message comes to the backend program in the form of the standard input which you can parse
and use for your processing. Servlet handles this type of requests using doPost() method.
Servlets handles form data parsing automatically using the following methods depending on
the situation:
Here is a simple URL which will pass two values to HelloForm program using GET method.
http://localhost:8080/HelloForm?first_name=ZARA&last_name=ALI
www.rejinpaul.com
www.rejinpaul.com
Below is HelloForm.java servlet program to handle input given by web browser. We are
going to use getParameter() method which makes it very easy to access passed information:
$ javac HelloForm.java
If everything goes fine, above compilation would produce HelloForm.class file. Next you
would have to copy this class file in <Tomcat-installation-directory>/webapps/ROOT/WEB-
INF/classes and create following entries in web.xml file located in <Tomcat-installation-
directory>/webapps/ROOT/WEB-INF/
<servlet>
<servlet-name>HelloForm</servlet-name>
<servlet-class>HelloForm</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>HelloForm</servlet-name>
<url-pattern>/HelloForm</url-pattern>
</servlet-mapping>
www.rejinpaul.com
www.rejinpaul.com
Here is a simple example which passes two values using HTML FORM and submit button.
We are going to use same Servlet HelloForm to handle this imput.
<html>
<body>
<form action="HelloForm" method="GET">
First Name: <input type="text" name="first_name">
<br />
Last Name: <input type="text" name="last_name" />
<input type="submit" value="Submit" />
</form>
</body>
</html>
Try to enter First Name and Last Name and then click submit button to see the result on your
local machine where tomcat is running. Based on the input provided, it will generate similar
result as mentioned in the above example.
Let us do little modification in the above servlet, so that it can handle GET as well as POST
methods. Below is HelloForm.java servlet program to handle input given by web browser
using GET or POST methods.
Now compile, deploy the above Servlet and test it using Hello.htm with the POST method as
follows:
<html>
<body>
<form action="HelloForm" method="POST">
First Name: <input type="text" name="first_name">
<br />
Last Name: <input type="text" name="last_name" />
<input type="submit" value="Submit" />
</form>
</body>
</html>
Here is the actual output of the above form, Try to enter First and Last Name and then click
submit button to see the result on your local machine where tomcat is running.
Based on the input provided, it would generate similar result as mentioned in the above
examples.
Checkboxes are used when more than one option is required to be selected.
Here is example HTML code, CheckBox.htm, for a form with two checkboxes
<html>
<body>
<form action="CheckBox" method="POST" target="_blank">
<input type="checkbox" name="maths" checked="checked" /> Maths
<input type="checkbox" name="physics" /> Physics
<input type="checkbox" name="chemistry" checked="checked" />
Chemistry
<input type="submit" value="Select Subject" />
</form>
</body>
</html>
Below is CheckBox.java servlet program to handle input given by web browser for checkbox
button.
+ request.getParameter("maths") + "\n" +
" <li><b>Physics Flag: </b>: "
+ request.getParameter("physics") + "\n" +
" <li><b>Chemistry Flag: </b>: "
+ request.getParameter("chemistry") + "\n" +
"</ul>\n" +
"</body></html>");
}
// Method to handle POST method request.
public void doPost(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
}
Maths Flag : : on
Chemistry Flag: : on
Once we have an Enumeration, we can loop down the Enumeration in the standard manner,
using hasMoreElements() method to determine when to stop and using nextElement() method
to get each parameter name.
while(paramNames.hasMoreElements()) {
String paramName = (String)paramNames.nextElement();
out.print("<tr><td>" + paramName + "</td>\n<td>");
String[] paramValues =
request.getParameterValues(paramName);
// Read single valued data
if (paramValues.length == 1) {
String paramValue = paramValues[0];
if (paramValue.length() == 0)
out.println("<i>No Value</i>");
else
out.println(paramValue);
} else {
// Read multiple valued data
out.println("<ul>");
for(int i=0; i < paramValues.length; i++) {
out.println("<li>" + paramValues[i]);
}
out.println("</ul>");
}
}
out.println("</tr>\n</table>\n</body></html>");
}
// Method to handle POST method request.
public void doPost(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
}
<html>
<body>
<form action="ReadParams" method="POST" target="_blank">
<input type="checkbox" name="maths" checked="checked" /> Maths
<input type="checkbox" name="physics" /> Physics
<input type="checkbox" name="chemistry" checked="checked" /> Chem
<input type="submit" value="Select Subject" />
www.rejinpaul.com
www.rejinpaul.com
</form>
</body>
</html>
Now calling servlet using above form would generate following result:
maths on
chemistry on
You can try above servlet to read any other form's data which is having other objects like text
box, radio button or drop down box etc.
Cookies are text files stored on the client computer and they are kept for various information
tracking purpose. Java Servlets transparently supports HTTP cookies.
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.
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.
This chapter will teach you how to set or reset cookies, how to access them and how to delete
them.
Cookies are usually set in an HTTP header (although JavaScript can also set a cookie directly
on a browser). A servlet 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
www.rejinpaul.com
www.rejinpaul.com
As you can see, 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 servlet will then have access to the cookie through the request method request.getCookies()
which returns an array of Cookie objects.
Following is the list of useful methods which you can use while manipulating cookies in
servlet.
(1) Creating a Cookie object: You call the Cookie constructor with a cookie name and a
cookie value, both of which are strings.
Keep in mind, neither the name nor the value should contain white space or any of the
following characters:
[ ] ( ) = , " / ? @ : ;
(2) Setting the maximum age: You use setMaxAge to specify how long (in seconds) the
cookie should be valid. Following would set up a cookie for 24 hours.
cookie.setMaxAge(60*60*24);
(3) Sending the Cookie into the HTTP response headers: You use response.addCookie to
add cookies in the HTTP response header as follows:
response.addCookie(cookie);
www.rejinpaul.com
www.rejinpaul.com
Example:
// Import required java libraries
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
Compile above servlet HelloForm and create appropriate entry in web.xml file and finally try
following HTML page to call servlet.
<html>
<body>
<form action="HelloForm" method="GET">
First Name: <input type="text" name="first_name">
<br />
Last Name: <input type="text" name="last_name" />
www.rejinpaul.com
www.rejinpaul.com
First Name:
Last Name:
Try to enter First Name and Last Name and then click submit button. This would display first
name and last name on your screen and same time it would set two cookies firstName and
lastName which would be passed back to the server when next time you would press Submit
button.
Next section would explain you how you would access these cookies back in your web
application.
Example:
Compile above servlet ReadCookies and create appropriate entry in web.xml file. If you
would have set first_name cookie as "John" and last_name cookie as "Player" then running
http://localhost:8080/ReadCookies would display the following result:
To delete cookies is very simple. If you want to delete a cookie then you simply need to
follow up following three steps:
Example:
Following example would delete and existing cookie named "first_name" and when you
would run ReadCookies servlet next time it would return null value for first_name.
Compile above servlet DeleteCookies and create appropriate entry in web.xml file. Now
running http://localhost:8080/DeleteCookies would display the following result:
Now try to run http://localhost:8080/ReadCookies and it would display only one cookie as
follows:
www.rejinpaul.com
www.rejinpaul.com
You can delete your cookies in Internet Explorer manually. Start at the Tools menu and select
Internet Options. To delete all cookies, press Delete Cookies.
Still there are following three ways to maintain session between web client and web server:
Cookies:
A webserver can assign a unique session ID as a cookie to each web client and for subsequent
requests from the client they can be recognized using the recieved cookie.
This may not be an effective way because many time browser does not support a cookie, so I
would not recommend to use this procedure to maintain the sessions.
A web server can send a hidden HTML form field along with a unique session ID as follows:
This entry means that, when the form is submitted, the specified name and value are
automatically included in the GET or POST data. Each time when web browser sends request
back, then session_id value can be used to keep the track of different web browsers.
This could be an effective way of keeping track of the session but clicking on a regular (<A
HREF...>) hypertext link does not result in a form submission, so hidden form fields also
cannot support general session tracking.
URL Rewriting:
You can append some extra data on the end of each URL that identifies the session, and the
server can associate that session identifier with data it has stored about that session.
URL rewriting is a better way to maintain sessions and works for the browsers when they
don't support cookies but here drawback is that you would have generate every URL
dynamically to assign a session ID though page is simple static HTML page.
www.rejinpaul.com
www.rejinpaul.com
Apart from the above mentioned three ways, servlet provides HttpSession Interface which
provides a way to identify a user across more than one page request or visit to a Web site and
to store information about that user.
The servlet container uses this interface to create a session between an HTTP client and an
HTTP server. The session persists for a specified time period, across more than one
connection or page request from the user.
You would get HttpSession object by calling the public method getSession() of
HttpServletRequest, as below:
You need to call request.getSession() before you send any document content to the client.
Here is a summary of the important methods available through HttpSession object:
This example describes how to use the HttpSession object to find out the creation time and
the last-accessed time for a session. We would associate a new session with the request if one
does not already exist.
userID = (String)session.getAttribute(userIDKey);
}
session.setAttribute(visitCountKey, visitCount);
String docType =
"<!doctype html public \"-//w3c//dtd html 4.0 " +
"transitional//en\">\n";
out.println(docType +
"<html>\n" +
"<head><title>" + title + "</title></head>\n" +
"<body bgcolor=\"#f0f0f0\">\n" +
"<h1 align=\"center\">" + title + "</h1>\n" +
"<h2 align=\"center\">Session Infomation</h2>\n" +
"<table border=\"1\" align=\"center\">\n" +
"<tr bgcolor=\"#949494\">\n" +
" <th>Session info</th><th>value</th></tr>\n" +
"<tr>\n" +
" <td>id</td>\n" +
" <td>" + session.getId() + "</td></tr>\n" +
"<tr>\n" +
" <td>Creation Time</td>\n" +
" <td>" + createTime +
" </td></tr>\n" +
"<tr>\n" +
" <td>Time of Last Access</td>\n" +
" <td>" + lastAccessTime +
" </td></tr>\n" +
"<tr>\n" +
" <td>User ID</td>\n" +
" <td>" + userID +
" </td></tr>\n" +
"<tr>\n" +
" <td>Number of visits</td>\n" +
" <td>" + visitCount + "</td></tr>\n" +
"</table>\n" +
"</body></html>");
}
}
Compile above servlet SessionTrack and create appropriate entry in web.xml file. Now
running http://localhost:8080/SessionTrack would display the following result when you
would run for the first time:
Welcome to my website
Session Infomation
id 0AE3EC93FF44E3C525B4351B77ABB2D5
User ID ABCD
Number of visits 0
Now try to run the same servlet for second time, it would display following result.
Session Infomation
id 0AE3EC93FF44E3C525B4351B77ABB2D5
User ID ABCD
Number of visits 1
When you are done with a user's session data, you have several options:
<session-config>
<session-timeout>15</session-timeout>
</session-config>
The timeout is expressed as minutes, and overrides the default timeout which is 30 minutes in
Tomcat.
The getMaxInactiveInterval( ) method in a servlet returns the timeout period for that session
in seconds. So if your session is configured in web.xml for 15 minutes,
getMaxInactiveInterval( ) returns 900.
www.rejinpaul.com
www.rejinpaul.com
CS6501-Internet Programming 2015-2016
JDBC
JDBC API is a Java API that can access any kind of tabular data, especially data stored in a
Relational Database. JDBC works with Java on a variety of platforms, such as Windows,
Mac OS, and the various versions of UNIX.
What is JDBC?
JDBC stands for Java Database Connectivity, which is a standard Java API for database-
independent connectivity between the Java programming language and a wide range of
databases.
The JDBC library includes APIs for each of the tasks mentioned below that are commonly
associated with database usage.
Fundamentally, JDBC is a specification that provides a complete set of interfaces that allows
for portable access to an underlying database. Java can be used to write different types of
executables, such as −
Java Applications
Java Applets
Java Servlets
Java ServerPages (JSPs)
Enterprise JavaBeans (EJBs).
All of these different executables are able to use a JDBC driver to access a database, and take
advantage of the stored data.
JDBC provides the same capabilities as ODBC, allowing Java programs to contain database-
independent code.
JDBC Architecture
The JDBC API supports both two-tier and three-tier processing models for database access
but in general, JDBC Architecture consists of two layers −
The JDBC API uses a driver manager and database-specific drivers to provide transparent
connectivity to heterogeneous databases.
www.rejinpaul.com
www.rejinpaul.com
CS6501-Internet Programming 2015-2016
The JDBC driver manager ensures that the correct driver is used to access each data source.
The driver manager is capable of supporting multiple concurrent drivers connected to
multiple heterogeneous databases.
Following is the architectural diagram, which shows the location of the driver manager with
respect to the JDBC drivers and the Java application −
an example of how to create a simple JDBC application. This will show you how to open a
database connection, execute a SQL query, and display the results.
All the steps mentioned in this template example, would be explained in subsequent chapters
of this tutorial.
Import the packages: Requires that you include the packages containing the JDBC
classes needed for database programming. Most often, using import java.sql.* will
suffice.
Register the JDBC driver: Requires that you initialize a driver so you can open a
communication channel with the database.
Open a connection: Requires using the DriverManager.getConnection() method to
create a Connection object, which represents a physical connection with the database.
Execute a query: Requires using an object of type Statement for building and
submitting an SQL statement to the database.
Extract data from result set: Requires that you use the appropriate
ResultSet.getXXX() method to retrieve the data from the result set.
Clean up the environment: Requires explicitly closing all database resources versus
relying on the JVM's garbage collection.
Sample Code
This sample example can serve as a template when you need to create your own JDBC
application in the future.
This sample code has been written based on the environment and database setup done in the
previous chapter.
Copy and past the following example in FirstExample.java, compile and run as follows −
// Database credentials
static final String USER = "username";
static final String PASS = "password";
//Display values
System.out.print("ID: " + id);
System.out.print(", Age: " + age);
System.out.print(", First: " + first);
System.out.println(", Last: " + last);
}
//STEP 6: Clean-up environment
rs.close();
stmt.close();
conn.close();
}catch(SQLException se){
//Handle errors for JDBC
se.printStackTrace();
}catch(Exception e){
//Handle errors for Class.forName
e.printStackTrace();
}finally{
//finally block used to close resources
try{
if(stmt!=null)
stmt.close();
}catch(SQLException se2){
}// nothing we can do
try{
if(conn!=null)
conn.close();
}catch(SQLException se){
se.printStackTrace();
}//end finally try
}//end try
System.out.println("Goodbye!");
}//end main
}//end FirstExample
C:\>javac FirstExample.java
C:\>
C:\>java FirstExample
Connecting to database...
Creating statement...
ID: 100, Age: 18, First: Zara, Last: Ali
ID: 101, Age: 25, First: Mahnaz, Last: Fatma
ID: 102, Age: 30, First: Zaid, Last: Khan
ID: 103, Age: 28, First: Sumit, Last: Mittal
C:\>
fter you've installed the appropriate driver, it is time to establish a database connection using
JDBC.
The programming involved to establish a JDBC connection is fairly simple. Here are these
simple four steps −
Import JDBC Packages: Add import statements to your Java program to import
required classes in your Java code.
Register JDBC Driver: This step causes the JVM to load the desired driver
implementation into memory so it can fulfill your JDBC requests.
Database URL Formulation: This is to create a properly formatted address that
points to the database to which you wish to connect.
Create Connection Object: Finally, code a call to the DriverManager object's
getConnection( ) method to establish actual database connection.
The Import statements tell the Java compiler where to find the classes you reference in your
code and are placed at the very beginning of your source code.
To use the standard JDBC package, which allows you to select, insert, update, and delete data
in SQL tables, add the following imports to your source code −
You must register the driver in your program before you use it. Registering the driver is the
process by which the Oracle driver's class file is loaded into the memory, so it can be utilized
as an implementation of the JDBC interfaces.
You need to do this registration only once in your program. You can register a driver in one
of two ways.
Approach I - Class.forName()
The most common approach to register a driver is to use Java's Class.forName() method, to
dynamically load the driver's class file into memory, which automatically registers it. This
www.rejinpaul.com
www.rejinpaul.com
CS6501-Internet Programming 2015-2016
method is preferable because it allows you to make the driver registration configurable and
portable.
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
}
catch(ClassNotFoundException ex) {
System.out.println("Error: unable to load driver class!");
System.exit(1);
}
You can use getInstance() method to work around noncompliant JVMs, but then you'll have
to code for two extra Exceptions as follows −
try {
Class.forName("oracle.jdbc.driver.OracleDriver").newInstance();
}
catch(ClassNotFoundException ex) {
System.out.println("Error: unable to load driver class!");
System.exit(1);
catch(IllegalAccessException ex) {
System.out.println("Error: access problem while loading!");
System.exit(2);
catch(InstantiationException ex) {
System.out.println("Error: unable to instantiate driver!");
System.exit(3);
}
Approach II - DriverManager.registerDriver()
The second approach you can use to register a driver, is to use the static
DriverManager.registerDriver() method.
You should use the registerDriver() method if you are using a non-JDK compliant JVM, such
as the one provided by Microsoft.
try {
Driver myDriver = new oracle.jdbc.driver.OracleDriver();
DriverManager.registerDriver( myDriver );
}
catch(ClassNotFoundException ex) {
System.out.println("Error: unable to load driver class!");
System.exit(1);
}
After you've loaded the driver, you can establish a connection using the
DriverManager.getConnection() method. For easy reference, let me list the three
overloaded DriverManager.getConnection() methods −
www.rejinpaul.com
www.rejinpaul.com
CS6501-Internet Programming 2015-2016
getConnection(String url)
getConnection(String url, Properties prop)
getConnection(String url, String user, String password)
Here each form requires a database URL. A database URL is an address that points to your
database.
Formulating a database URL is where most of the problems associated with establishing a
connection occurs.
Following table lists down the popular JDBC driver names and database URL.
jdbc:oracle:thin:@hostname:port
ORACLE oracle.jdbc.driver.OracleDriver
Number:databaseName
jdbc:sybase:Tds:hostname: port
Sybase com.sybase.jdbc.SybDriver
Number/databaseName
All the highlighted part in URL format is static and you need to change only the remaining
part as per your database setup.
The most commonly used form of getConnection() requires you to pass a database URL, a
username, and a password:
Assuming you are using Oracle's thin driver, you'll specify a host:port:databaseName value
for the database portion of the URL.
If you have a host at TCP/IP address 192.0.0.1 with a host name of amrood, and your Oracle
listener is configured to listen on port 1521, and your database name is EMP, then complete
database URL would be −
jdbc:oracle:thin:@amrood:1521:EMP
Now you have to call getConnection() method with appropriate username and password to
get a Connection object as follows −
www.rejinpaul.com
www.rejinpaul.com
CS6501-Internet Programming 2015-2016
DriverManager.getConnection(String url);
However, in this case, the database URL includes the username and password and has the
following general form −
jdbc:oracle:driver:username/password@database
A Properties object holds a set of keyword-value pairs. It is used to pass driver properties to
the driver during a call to the getConnection() method.
To make the same connection made by the previous examples, use the following code −
import java.util.*;
At the end of your JDBC program, it is required explicitly to close all the connections to the
database to end each database session. However, if you forget, Java's garbage collector will
close the connection when it cleans up stale objects.
To ensure that a connection is closed, you could provide a 'finally' block in your code. A
finally block always executes, regardless of an exception occurs or not.
To close the above opened connection, you should call close() method as follows −
conn.close();
Explicitly closing a connection conserves DBMS resources, which will make your database
administrator happy.
he JavaServer Pages Standard Tag Library (JSTL) is a collection of useful JSP tags which
encapsulates core functionality common to many JSP applications.
JSTL has support for common, structural tasks such as iteration and conditionals, tags for
manipulating XML documents, internationalization tags, and SQL tags. It also provides a
framework for integrating existing custom tags with JSTL tags.
The JSTL tags can be classified, according to their functions, into following JSTL tag library
groups that can be used when creating a JSP page:
Core Tags
Formatting tags
SQL tags
XML tags
JSTL Functions
If you are using Apache Tomcat container then follow the following two simple steps:
Download the binary distribution from Apache Standard Taglib and unpack the
compressed file.
To use the Standard Taglib from its Jakarta Taglibs distribution, simply copy the JAR
files in the distribution's 'lib' directory to your application's webapps\ROOT\WEB-
INF\lib directory.
To use any of the libraries, you must include a <taglib> directive at the top of each JSP that
uses the library.
www.rejinpaul.com
www.rejinpaul.com
CS6501-Internet Programming 2015-2016
Core Tags:
The core group of tags are the most frequently used JSTL tags. Following is the syntax to
include JSTL Core library in your JSP:
Tag Description
Catches any Throwable that occurs in its body and optionally exposes
<c:catch>
it.
Subtag of <choose> that follows <when> tags and runs only if all of
<c:otherwise >
the prior conditions evaluated to 'false'.
The basic iteration tag, accepting many different collection types and
<c:forEach >
supporting subsetting and other functionality .
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
Specifies the time zone for any time formatting or parsing actions
<fmt:timeZone>
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.
Tag Description
Executes the SQL query defined in its body or through the sql
<sql:query>
attribute.
Executes the SQL update defined in its body or through the sql
<sql:update>
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.
Before you proceed with the examples, you would need to copy following two XML and
XPath related libraries into your <Tomcat Installation Directory>\lib:
Tag Description
Use to parse XML data specified either via an attribute or in the tag
<x:parse>
body.
www.rejinpaul.com
www.rejinpaul.com
CS6501-Internet Programming 2015-2016
Subtag of <choose> that follows <when> tags and runs only if all of
<x:otherwise >
the prior conditions evaluated to 'false'
Use along with the transform tag to set a parameter in the XSLT
<x:param >
stylesheet
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:
Function Description
JSP Processing:
The following steps explain how the web server creates the web page using JSP:
As with a normal page, your browser sends an HTTP request to the web server.
The web server recognizes that the HTTP request is for a JSP page and forwards it to
a JSP engine. This is done by using the URL or JSP page which ends with .jsp instead
of .html.
The JSP engine loads the JSP page from disk and converts it into a servlet content.
This conversion is very simple in which all template text is converted to println( )
statements and all JSP elements are converted to Java code that implements the
corresponding dynamic behavior of the page.
The JSP engine compiles the servlet into an executable class and forwards the original
request to a servlet engine.
A part of the web server called the servlet engine loads the Servlet class and executes
it. During execution, the servlet produces an output in HTML format, which the
servlet engine passes to the web server inside an HTTP response.
The web server forwards the HTTP response to your browser in terms of static HTML
content.
Finally web browser handles the dynamically generated HTML page inside the HTTP
response exactly as if it were a static page.
www.rejinpaul.com
www.rejinpaul.com
CS6501-Internet Programming 2015-2016
All the above mentioned steps can be shown below in the following diagram:
The Scriptlet:
A scriptlet can contain any number of JAVA language statements, variable or method
declarations, or expressions that are valid in the page scripting language.
<jsp:scriptlet>
code fragment
</jsp:scriptlet>
Any text, HTML tags, or JSP elements you write must be outside the scriptlet. Following is
the simple and first example for JSP:
<html>
<head><title>Hello World</title></head>
<body>
Hello World!<br/>
<%
out.println("Your IP address is " + request.getRemoteAddr());
%>
</body>
</html>
Let us keep above code in JSP file hello.jsp and put this file in C:\apache-tomcat-
7.0.2\webapps\ROOT directory and try to browse it by giving URL
http://localhost:8080/hello.jsp. This would generate following result:
www.rejinpaul.com
www.rejinpaul.com
CS6501-Internet Programming 2015-2016
JSP Declarations:
A declaration declares one or more variables or methods that you can use in Java code later in
the JSP file. You must declare the variable or method before you use it in the JSP file.
<jsp:declaration>
code fragment
</jsp:declaration>
JSP Expression:
Because the value of an expression is converted to a String, you can use an expression within
a line of text, whether or not it is tagged with HTML, in a JSP file.
The expression element can contain any expression that is valid according to the Java
Language Specification but you cannot use a semicolon to end an expression.
<jsp:expression>
expression
</jsp:expression>
www.rejinpaul.com
www.rejinpaul.com
CS6501-Internet Programming 2015-2016
<html>
<head><title>A Comment Test</title></head>
<body>
<p>
Today's date: <%= (new java.util.Date()).toLocaleString()%>
</p>
</body>
</html>
JSP Comments:
JSP comment marks text or statements that the JSP container should ignore. A JSP comment
is useful when you want to hide or "comment out" part of your JSP page.
<html>
<head><title>A Comment Test</title></head>
<body>
<h2>A Test of Comments</h2>
<%-- This comment will not be visible in the page source --%>
</body>
</html>
A Test of Comments
There are a small number of special constructs you can use in various cases to insert
comments or characters that would otherwise be treated specially. Here's a summary:
Syntax Purpose
PHP
PHP Introduction
PHP scripts are executed on the server.
What is PHP?
PHP files can contain text, HTML, CSS, JavaScript, and PHP code
PHP code are executed on the server, and the result is returned to the browser as plain
HTML
PHP files have extension ".php"
With PHP you are not limited to output HTML. You can output images, PDF files, and even
Flash movies. You can also output any text, such as XHTML and XML.
Why PHP?
PHP Syntax
A PHP script is executed on the server, and the plain HTML result is sent back to the browser.
<?php
// PHP code goes here
?>
A PHP file normally contains HTML tags, and some PHP scripting code.
Below, we have an example of a simple PHP file, with a PHP script that uses a built-in PHP
function "echo" to output the text "Hello World!" on a web page:
Example
<!DOCTYPE html>
<html>
<body>
<?php
echo "Hello World!";
?>
</body>
</html>
Note: PHP statements end with a semicolon (;).
Comments in PHP
A comment in PHP code is a line that is not read/executed as part of the program. Its only
purpose is to be read by someone who is looking at the code.
<?php
// This is a single-line comment
/*
This is a multiple-lines comment block
that spans over multiple
lines
*/
// You can also use comments to leave out parts of a code line
$x = 5 /* + 15 */ + 5;
echo $x;
?>
</body>
</html>
In PHP, all keywords (e.g. if, else, while, echo, etc.), classes, functions, and user-defined
functions are NOT case-sensitive.
In the example below, all three echo statements below are legal (and equal):
Example
<!DOCTYPE html>
<html>
<body>
<?php
ECHO "Hello World!<br>";
echo "Hello World!<br>";
EcHo "Hello World!<br>";
?>
</body>
</html>
In the example below, only the first statement will display the value of the $color variable (this is
because $color, $COLOR, and $coLOR are treated as three different variables):
Example
<!DOCTYPE html>
<html>
<body>
<?php
$color = "red";
echo "My car is " . $color . "<br>";
echo "My house is " . $COLOR . "<br>";
echo "My boat is " . $coLOR . "<br>";
?>
Download Useful Materials from Rejinpaul.com
www.rejinpaul.com
www.rejinpaul.com
</body>
</html>
PHP Variables
Variables are "containers" for storing information.
In PHP, a variable starts with the $ sign, followed by the name of the variable:
Example
<?php
$txt = "Hello world!";
$x = 5;
$y = 10.5;
?>
After the execution of the statements above, the variable $txt will hold the value Hello world!,
the variable $x will hold the value 5, and the variable $y will hold the value10.5.
Note: When you assign a text value to a variable, put quotes around the value.
Note: Unlike other programming languages, PHP has no command for declaring a variable. It is
created the moment you first assign a value to it.
PHP Variables
A variable can have a short name (like x and y) or a more descriptive name (age, carname,
total_volume).
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)
Output Variables
The PHP echo statement is often used to output data to the screen.
The following example will show how to output text and a variable:
Example
<?php
$txt = "W3Schools.com";
In the example above, notice that we did not have to tell PHP which data type the variable is.
PHP automatically converts the variable to the correct data type, depending on its value.
In other languages such as C, C++, and Java, the programmer must declare the name and type of
the variable before using it.
The scope of a variable is the part of the script where the variable can be referenced/used.
local
global
static
A variable declared outside a function has a GLOBAL SCOPE and can only be accessed outside
a function:
Example
<?php
$x = 5; // global scope
function myTest() {
// using x inside this function will generate an error
The global keyword is used to access a global variable from within a function.
To do this, use the global keyword before the variables (inside the function):
Example
<?php
$x = 5;
$y = 10;
function myTest() {
global $x, $y;
$y = $x + $y;
}
myTest();
echo $y; // outputs 15
?>
PHP also stores all global variables in an array called $GLOBALS[index]. The index holds the
name of the variable. This array is also accessible from within functions and can be used to
update global variables directly.
function myTest() {
myTest();
echo $y; // outputs 15
?>
Normally, when a function is completed/executed, all of its variables are deleted. However,
sometimes we want a local variable NOT to be deleted. We need it for a further job.
To do this, use the static keyword when you first declare the variable:
Example
<?php
function myTest() {
static $x = 0;
echo $x;
$x++;
}
myTest();
myTest();
myTest();
?>
Then, each time the function is called, that variable will still have the information it contained
from the last time the function was called.
print "<h2>$txt1</h2>";
print "Study PHP at $txt2<br>";
print $x + $y;
?>
Variables can store data of different types, and different data types can do different things.
String
Integer
Float (floating point numbers - also called double)
Boolean
Array
Object
NULL
Resource
PHP String
A string can be any text inside quotes. You can use single or double quotes:
Example
<?php
$x = "Hello world!";
$y = 'Hello world!';
echo $x;
echo "<br>";
echo $y;
?>
PHP Integer
In the following example $x is an integer. The PHP var_dump() function returns the data type
and value:
Example
PHP Float
A float (floating point number) is a number with a decimal point or a number in exponential
form.
In the following example $x is a float. The PHP var_dump() function returns the data type and
value:
Example
<?php
$x = 10.365;
var_dump($x);
?>
PHP Boolean
$x = true;
$y = false;
Booleans are often used in conditional testing. You will learn more about conditional testing in a
later chapter of this tutorial.
PHP Array
In the following example $cars is an array. The PHP var_dump() function returns the data type
and value:
Example
<?php
$cars = array("Volvo","BMW","Toyota");
var_dump($cars);
?>
PHP Object
An object is a data type which stores data and information on how to process that data.
First we must declare a class of object. For this, we use the class keyword. A class is a structure
that can contain properties and methods:
Example
// create an object
$herbie = new Car();
Null is a special data type which can have only one value: NULL.
A variable of data type NULL is a variable that has no value assigned to it.
PHP Strings
A string is a sequence of characters, like "Hello world!".
Reverse a String
The PHP strrev() function reverses a string:
Example
<?php
echo strrev("Hello world!"); // outputs !dlrow olleH
?>
The output of the code above will be: !dlrow olleH.
PHP Constants
Constants are like variables except that once they are defined they cannot be changed or
undefined.
PHP Constants
A constant is an identifier (name) for a simple value. The value cannot be changed during the
script.
A valid constant name starts with a letter or underscore (no $ sign before the constant name).
Syntax
Parameters:
function myTest() {
echo GREETING;
}
myTest();
?>
PHP Operators
Operators are used to perform operations on variables and values.
Arithmetic operators
Assignment operators
Comparison operators
Increment/Decrement operators
Logical operators
String operators
Array operators
x=y x=y The left operand gets set to the value of the Show it »
expression on the right
!== Not identical $x !== $y Returns true if $x is not equal to $y, or Show it »
they are not of the same type
<= Less than or $x <= $y Returns true if $x is less than or equal Show it »
equal to to $y
=== Identity $x === $y Returns true if $x and $y have the same Show it
key/value pairs in the same order and of the »
same types
Syntax
if (condition) {
code to be executed if condition is true;
}
The example below will output "Have a good day!" if the current time (HOUR) is less than 20:
Example
Syntax
if (condition) {
code to be executed if condition is true;
} else {
code to be executed if condition is false;
}
The example below will output "Have a good day!" if the current time is less than 20, and "Have
a good night!" otherwise:
Example
<?php
$t = date("H");
Use the if....elseif...else statement to specify a new condition to test, if the first condition is
false.
Syntax
if (condition) {
code to be executed if condition is true;
} elseif (condition) {
code to be executed if condition is true;
} else {
code to be executed if condition is false;
}
Use the switch statement to select one of many blocks of code to be executed.
Syntax
switch (n) {
case label1:
code to be executed if n=label1;
break;
case label2:
code to be executed if n=label2;
break;
case label3:
code to be executed if n=label3;
break;
...
default:
code to be executed if n is different from all labels;
}
This is how it works: First we have a single expression n (most often a variable), that is
evaluated once. The value of the expression is then compared with the values for each case in the
structure. If there is a match, the block of code associated with that case is executed.
Use break to prevent the code from running into the next case automatically.
The default statement is used if no match is found.
switch ($favcolor) {
case "red":
echo "Your favorite color is red!";
break;
case "blue":
echo "Your favorite color is blue!";
break;
case "green":
echo "Your favorite color is green!";
break;
default:
echo "Your favorite color is neither red, blue, nor green!";
}
?>
PHP Loops
Often when you write code, you want the same block of code to run over and over again in a
row. Instead of adding several almost equal code-lines in a script, we can use loops to perform a
task like this.
In PHP, we have the following looping statements:
while - loops through a block of code as long as the specified condition is true
do...while - loops through a block of code once, and then repeats the loop as long as the
specified condition is true
for - loops through a block of code a specified number of times
foreach - loops through a block of code for each element in an array
Syntax
The example below first sets a variable $x to 1 ($x = 1). Then, the while loop will continue to
run as long as $x is less than, or equal to 5 ($x <= 5). $x will increase by 1 each time the loop
runs ($x++):
Example
while($x <= 5) {
echo "The number is: $x <br>";
$x++;
}
?>
Syntax
do {
code to be executed;
} while (condition is true);
The example below first sets a variable $x to 1 ($x = 1). Then, the do while loop will write some
output, and then increment the variable $x with 1. Then the condition is checked (is $x less than,
or equal to 5?), and the loop will continue to run as long as $x is less than, or equal to 5:
Example
<?php
$x = 1;
do {
echo "The number is: $x <br>";
$x++;
} while ($x <= 5);
?>
Notice that in a do while loop the condition is tested AFTER executing the statements within the
loop. This means that the do while loop would execute its statements at least once, even if the
condition is false the first time.
The example below sets the $x variable to 6, then it runs the loop, and then the condition is
checked:
Example
<?php
$x = 6;
do {
echo "The number is: $x <br>";
$x++;
} while ($x<=5);
?>
The for loop and the foreach loop will be explained in the next chapter.
Syntax
Parameters:
Syntax
For every loop iteration, the value of the current array element is assigned to $value and the array
pointer is moved by one, until it reaches the last array element.
The following example demonstrates a loop that will output the values of the given array
($colors):
Example
<?php
$colors = array("red", "green", "blue", "yellow");
The for loop is used when you know in advance how many times the script should run.
Syntax
Parameters:
The foreach loop works only on arrays, and is used to loop through each key/value pair in an
array.
Syntax
For every loop iteration, the value of the current array element is assigned to $value and the array
pointer is moved by one, until it reaches the last array element.
The following example demonstrates a loop that will output the values of the given array
($colors):
Before we can access data in the MySQL database, we need to be able to connect to the server:
Example (MySQLi Object-Oriented)
<?php
$servername = "localhost";
$username = "username";
$password = "password";
// Create connection
$conn = new mysqli($servername, $username, $password);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully";
?>
// Create connection
$conn = mysqli_connect($servername, $username, $password);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
echo "Connected successfully";
?>
Example (PDO)
<?php
$servername = "localhost";
$username = "username";
try {
$conn = new PDO("mysql:host=$servername;dbname=myDB", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
echo "Connected successfully";
}
catch(PDOException $e)
{
echo "Connection failed: " . $e->getMessage();
}
?>
The connection will be closed automatically when the script ends. To close the connection
before, use the following:
Example (MySQLi Object-Oriented)
$conn->close();
Example (PDO)
$conn = null;
PHP Cookies
A cookie is often used to identify a user.
What is a Cookie?
A cookie is often used to identify a user. A cookie is a small file that the server embeds on the
user's computer. Each time the same computer requests a page with a browser, it will send the
cookie too. With PHP, you can both create and retrieve cookie values.
Syntax
Only the name parameter is required. All other parameters are optional.
The following example creates a cookie named "user" with the value "John Doe". The cookie
will expire after 30 days (86400 * 30). The "/" means that the cookie is available in entire
website (otherwise, select the directory you prefer).
We then retrieve the value of the cookie "user" (using the global variable $_COOKIE). We also
use the isset() function to find out if the cookie is set:
Example
<?php
$cookie_name = "user";
$cookie_value = "John Doe";
setcookie($cookie_name, $cookie_value, time() + (86400 * 30), "/"); // 86400 = 1 day
?>
<html>
<body>
<?php
if(!isset($_COOKIE[$cookie_name])) {
echo "Cookie named '" . $cookie_name . "' is not set!";
} else {
echo "Cookie '" . $cookie_name . "' is set!<br>";
echo "Value is: " . $_COOKIE[$cookie_name];
}
?>
</body>
</html>
To modify a cookie, just set (again) the cookie using the setcookie() function:
Example
<?php
$cookie_name = "user";
$cookie_value = "Alex Porter";
setcookie($cookie_name, $cookie_value, time() + (86400 * 30), "/");
?>
<html>
<body>
<?php
if(!isset($_COOKIE[$cookie_name])) {
echo "Cookie named '" . $cookie_name . "' is not set!";
} else {
echo "Cookie '" . $cookie_name . "' is set!<br>";
echo "Value is: " . $_COOKIE[$cookie_name];
}
?>
Delete a Cookie
To delete a cookie, use the setcookie() function with an expiration date in the past:
Example
<?php
// set the expiration date to one hour ago
setcookie("user", "", time() - 3600);
?>
<html>
<body>
<?php
echo "Cookie 'user' is deleted.";
?>
</body>
</html>
The following example creates a small script that checks whether cookies are enabled. First, try
to create a test cookie with the setcookie() function, then count the $_COOKIE array variable:
Example
<?php
setcookie("test_cookie", "test", time() + 3600, '/');
?>
<html>
<body>
<?php
if(count($_COOKIE) > 0) {
echo "Cookies are enabled.";
} else {
echo "Cookies are disabled.";
}
?>
</body>
</html>
Regular expressions are nothing more than a sequence or pattern of characters itself. They
provide the foundation for pattern-matching functionality.
Using regular expression you can search a particular string inside a another string, you can
replace one string by another string and you can split a string into many chunks.
The simplest regular expression is one that matches a single character, such as g, inside strings
such as g, haggle, or bag.
Lets give explanation for few concepts being used in POSIX regular expression. After that we
will introduce you with regular expression related functions.
Brackets
Brackets ([]) have a special meaning when used in the context of regular expressions. They are
used to find a range of characters.
Expression Description
The ranges shown above are general; you 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.
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.
Examples
Following examples will clear your concepts about matching characters.
Expression Description
[^a-zA-Z] It matches any string not containing any of the characters ranging
from a through z and A through Z.
Expression Description
Function Description
split() The split() function will divide a string into various elements, the
boundaries of each element based on the occurrence of pattern in
string.
spliti() The spliti() function operates exactly in the same manner as its
sibling split(), except that it is not case sensitive.
Lets give explanation for few concepts being used in PERL regular expressions. After that we
will introduce you wih regular expression related functions.
Meta characters
A meta character is simply an alphabetical character preceded by a backslash that acts to give
the combination a special meaning.
For instance, you can search for large money sums using the '\d' meta character: /([\d]+)000/,
Here \d will search for any string of numerical character.
Following is the list of meta characters which can be used in PERL Style Regular Expressions.
Character Description
. a single character
\s a whitespace character (space, tab, newline)
\S non-whitespace character
Modifiers
Several modifiers are available that can make your work with regexps much easier, like case
sensitivity, searching in multiple lines etc.
Modifier Description
i Makes the match case insensitive
m Specifies that if the string has newline or carriage
return characters, the ^ and $ operators will now
match against a newline boundary, instead of a
string boundary
o Evaluates the expression only once
s Allows use of . to match a newline character
x Allows you to use white space in the expression for clarity
g Globally finds all matches
cg Allows a search to continue even after a global match fails
Function Description
Introduction to XML
XML was designed to describe data.
HTML was designed to display data.
HTML
JavaScript
If you want to study these subjects first, find the tutorials on our Home page.
What is XML?
XML stands for EXtensible Markup Language
XML is a markup language much like HTML
XML was designed to describe data, not to display data
XML tags are not predefined. You must define your own tags
XML is designed to be self-descriptive
XML is a W3C Recommendation
But still, this XML document does not DO anything. It is just information wrapped in tags. Someone
must write a piece of software to send, receive or display it.
The tags used in HTML are predefined. HTML documents can only use tags defined in the HTML
standard (like <p>, <h1>, etc.).
XML allows the author to define his/her own tags and his/her own document structure.
It is important to understand that XML is not a replacement for HTML. In most web applications,
XML is used to describe data, while HTML is used to format and display the data.
With XML, data can be stored in separate XML files. This way you can concentrate on using
HTML/CSS for display and layout, and be sure that changes in the underlying data will not
require any changes to the HTML.
With a few lines of JavaScript code, you can read an external XML file and update the data
content of your web page.
XML data is stored in plain text format. This provides a software- and hardware-independent
way of storing data.
This makes it much easier to create data that can be shared by different applications.
Exchanging data as XML greatly reduces this complexity, since the data can be read by
different incompatible applications.
XML data is stored in text format. This makes it easier to expand or upgrade to new
operating systems, new applications, or new browsers, without losing data.
With XML, your data can be available to all kinds of "reading machines" (Handheld
computers, voice machines, news feeds, etc.), and make it more available for blind people, or
people with other disabilities.
XHTML
XML Schema
SVG
WSDL
RSS
XML Tree
Download Useful Materials from Rejinpaul.com
www.rejinpaul.com
www.rejinpaul.com
XML documents form a tree structure that starts at "the root" and branches to "the
leaves".
An Example XML Document
XML documents use a self-describing and simple syntax:
<?xml version="1.0" encoding="UTF-8"?>
<note>
<to>Tove</to>
<from>Jani</from>
<heading>Reminder</heading>
<body>Don't forget me this weekend!</body>
</note>
The first line is the XML declaration. It defines the XML version (1.0).
The next line describes the root element of the document (like saying: "this document is a
note"):
<note>
The next 4 lines describe 4 child elements of the root (to, from, heading, and body):
<to>Tove</to>
<from>Jani</from>
<heading>Reminder</heading>
<body>Don't forget me this weekend!</body>
And finally the last line defines the end of the root element:
</note>
You can assume, from this example, that the XML document contains a note to Tove from
Jani.
Don't you agree that XML is pretty self-descriptive?
Example:
The image above represents one book in the XML below:
<bookstore>
<book category="COOKING">
<title lang="en">Everyday Italian</title>
<author>Giada De Laurentiis</author>
<year>2005</year>
<price>30.00</price>
</book>
<book category="CHILDREN">
<title lang="en">Harry Potter</title>
<author>J K. Rowling</author>
<year>2005</year>
<price>29.99</price>
</book>
<book category="WEB">
<title lang="en">Learning XML</title>
<author>Erik T. Ray</author>
<year>2003</year>
<price>39.95</price>
</book>
</bookstore>
The root element in the example is <bookstore>. All <book> elements in the document are
contained within <bookstore>.
The <book> element has 4 children: <title>,< author>, <year>, <price>
XML DTD
An XML document with correct syntax is called "Well Formed".
An XML document validated against a DTD is "Well Formed" and "Valid".
The DOCTYPE declaration, in the example above, is a reference to an external DTD file. The
content of the file is shown in the paragraph below.
XML DTD
The purpose of a DTD is to define the structure of an XML document. It defines the structure with a
list of legal elements:
<!DOCTYPE note
[
<!ELEMENT note (to,from,heading,body)>
<!ELEMENT to (#PCDATA)>
<!ELEMENT from (#PCDATA)>
<!ELEMENT heading (#PCDATA)>
<!ELEMENT body (#PCDATA)>
]>
!DOCTYPE note defines that the root element of the document is note
!ELEMENT note defines that the note element must contain four elements: "to, from,
heading, body"
!ELEMENT to defines the to element to be of type "#PCDATA"
!ELEMENT from defines the from element to be of type "#PCDATA"
!ELEMENT heading defines the heading element to be of type "#PCDATA"
!ELEMENT body defines the body element to be of type "#PCDATA"
Example
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE note [
<!ENTITY nbsp " ">
<!ENTITY writer "Writer: Donald Duck.">
<note>
<to>Tove</to>
<from>Jani</from>
<heading>Reminder</heading>
<body>Don't forget me this weekend!</body>
<footer>&writer; ©right;</footer>
</note>
With a DTD, you can verify that the data you receive from the outside world is valid.
XML Schema
An XML Schema describes the structure of an XML document, just like a DTD.
An XML document with correct syntax is called "Well Formed".
An XML document validated against an XML Schema is both "Well Formed" and "Valid".
XML Schema
XML Schema is an XML-based alternative to DTD:
<xs:element name="note">
<xs:complexType>
<xs:sequence>
<xs:element name="to" type="xs:string"/>
<xs:element name="from" type="xs:string"/>
<xs:element name="heading" type="xs:string"/>
<xs:element name="body" type="xs:string"/>
</xs:sequence>
</xs:complexType>
</xs:element>
With XML Schema, independent groups of people can agree on a standard for interchanging data.
XML DOM
A DOM (Document Object Model) defines a standard way for accessing and
manipulating documents.
All elements can be accessed through the DOM tree. Their content (text and attributes) can
be modified or deleted, and new elements can be created. The elements, their text, and their
attributes are all known as nodes.
You can learn more about the HTML DOM in our JavaScript tutorial.
Example
<html>
<body>
<h1>W3Schools Internal Note</h1>
<div>
<b>To:</b> <span id="to"></span><br />
<b>From:</b> <span id="from"></span><br />
<b>Message:</b> <span id="message"></span>
</div>
<script>
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.open("GET","note.xml",false);
xmlhttp.send();
xmlDoc=xmlhttp.responseXML;
document.getElementById("to").innerHTML=
xmlDoc.getElementsByTagName("to")[0].childNodes[0].nodeValue;
document.getElementById("from").innerHTML=
xmlDoc.getElementsByTagName("from")[0].childNodes[0].nodeValue;
document.getElementById("message").innerHTML=
xmlDoc.getElementsByTagName("body")[0].childNodes[0].nodeValue;
</script>
</body>
</html>
Important Note!
Notice that even if the XML file contains only ONE <to> element you still have to specify
the array index [0]. This is because the getElementsByTagName() method returns an array.
Example
<html>
<body>
<h1>W3Schools Internal Note</h1>
<div>
<b>To:</b> <span id="to"></span><br />
<b>From:</b> <span id="from"></span><br />
<b>Message:</b> <span id="message"></span>
</div>
<script>
txt="<note>";
txt=txt+"<to>Tove</to>";
txt=txt+"<from>Jani</from>";
txt=txt+"<heading>Reminder</heading>";
txt=txt+"<body>Don't forget me this weekend!</body>";
txt=txt+"</note>";
if (window.DOMParser)
{
parser=new DOMParser();
xmlDoc=parser.parseFromString(txt,"text/xml");
}
else // Internet Explorer
{
xmlDoc=new ActiveXObject("Microsoft.XMLDOM");
xmlDoc.async=false;
xmlDoc.loadXML(txt);
}
document.getElementById("to").innerHTML=
xmlDoc.getElementsByTagName("to")[0].childNodes[0].nodeValue;
document.getElementById("from").innerHTML=
xmlDoc.getElementsByTagName("from")[0].childNodes[0].nodeValue;
document.getElementById("message").innerHTML=
xmlDoc.getElementsByTagName("body")[0].childNodes[0].nodeValue;
</script>
</body>
</html>
XML Parser
All modern browsers have a built-in XML parser.
An XML parser converts an XML document into an XML DOM object - which can
then be manipulated with JavaScript.
if (window.DOMParser)
{
parser=new DOMParser();
xmlDoc=parser.parseFromString(txt,"text/xml");
}
else // Internet Explorer
{
xmlDoc=new ActiveXObject("Microsoft.XMLDOM");
xmlDoc.async=false;
xmlDoc.loadXML(txt);
}
XML Validator
The W3C XML specification states that a program should stop processing an XML document if it
finds an error. The reason is that XML software should be small, fast, and compatible.
HTML browsers will display HTML documents with errors (like missing end tags).
Bottom of Form
The file "note_error.xml" demonstrates your browsers error handling. If you want to see an error-free
message, substitute the "note_error.xml" with "cd_catalog.xml".
What is XSL?
XSL is a language for expressing style sheets. An XSL style sheet is, like with CSS, a file that
describes how to display an XML document of a given type. XSL shares the functionality and is
compatible with CSS2 (although it uses a different syntax). It also adds:
A transformation language for XML documents: XSLT. Originally intended to perform complex
styling operations, like the generation of tables of contents and indexes, it is now used as a general
purpose XML processing language. XSLT is thus widely used for purposes other than XSL, like
generating HTML web pages from XML data.
Advanced styling features, expressed by an XML document type which defines a set of elements
called Formatting Objects, and attributes (in part borrowed from CSS2 properties and adding more
complex ones.
Styling requires a source XML documents, containing the information that the style sheet will
display and the style sheet itself which describes how to display a document of a given type.
The following shows a sample XML file and how it can be transformed and rendered.
<scene>
<speech speaker="Prosser">
</speech>
<speech speaker="Arthur">
It's overrated
</speech>
</scene>
This XML file doesn't contain any presentation information, which is contained in the stylesheet.
Separating the document's content and the document's styling information allows displaying the same
Download Useful Materials from Rejinpaul.com
www.rejinpaul.com
www.rejinpaul.com
document on different media (like screen, paper, cell phone), and it also enables users to view the
document according to their preferences and abilities, just by modifying the style sheet.
The Stylesheet
Here are two templates from the stylesheet used to format the XML file. The full stylesheet (which
includes extra information on pagination and margins) is available.
...
<xsl:template match="FX">
<fo:block font-weight="bold">
<xsl:apply-templates/>
</fo:block>
</xsl:template>
<xsl:template match="speech[@speaker='Arthur']">
<fo:block background-color="blue">
<xsl:value-of select="@speaker"/>:
<xsl:apply-templates/>
</fo:block>
</xsl:template>
...
The stylesheet can be used to transform any instance of the DTD it was designed for. The first rule
says that an FX element will be transformed into a block with a bold font. <xsl:apply-templates/> is a
recursive call to the template rules for the contents of the current element. The second template
applies to all speech elements that have the speaker attribute set to Arthur, and formats them as blue
blocks within which the value speaker attribute is added before the text.
Rendering
The figure below shows a rendering of the Formatting Objects generated by the XML file and the
stylesheet. The XSL-FO vocabulary is designed to be displayed on a wide variety of media: screen,
paper, or even voice. The full PDF document is also available.
XSLT Tutorial
XSL stands for EXtensible Stylesheet Language, and is a style sheet language for XML documents.
XSLT stands for XSL Transformations. In this tutorial you will learn how to use XSLT to transform
XML documents into other formats, like XHTML.
With our online editor, you can edit the XML and the XSL source code, and click on a button to view
the result.
Download Useful Materials from Rejinpaul.com
www.rejinpaul.com
www.rejinpaul.com
XSLT Example
<?xml version="1.0"?>
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="/">
<html>
<body>
<h2>My CD Collection</h2>
<table border="1">
<tr bgcolor="#9acd32">
<th>Title</th>
<th>Artist</th>
</tr>
<xsl:for-each select="catalog/cd">
<tr>
<td><xsl:value-of select="title"/></td>
<td><xsl:value-of select="artist"/></td>
</tr>
</xsl:for-each>
</table>
</body>
</html>
</xsl:template>
</xsl:stylesheet>
RSS
RSS stands for both Rich Site Summary and Really Simple Syndication but it always refers to the
same technology.
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.
Reading RSS
To take advantage of an RSS feed you would use a piece of software called an RSS aggregator. Most
of them are very similar to email client programs, but instead of incoming emails, they display news
from various sources (from all the feeds you have registered with, or "subscribed to" as is commonly
said but it has nothing to do with money). Unread news typically appear in bold, just as unread
emails do.
Just like there is webmail, there are also are web-RSS-aggregators. Bloglines is such an online
aggregator. Il allows you to track all your news from a single place you can access with a regular
web browser.
Also, most modern web browsers will also handle RSS feeds, but in a limited manner. They will use
an RSS feed as a dynamic bookmark folder with automatic bookmarks to all the news in the feed.
Unlike aggregators, browsers will not save the news if you don't check on them every day.
Finally, on a more professional level, some websites will aggregate news from different sources onto
a single site. Hence the "syndication" in the name.
Producing RSS
While you could theoretically write an RSS file by hand and update it regularly, writing XML
manually is a tedious task.
Most RSS feeds are produced automatically by the same content management software which also
generates the web pages dynamically. All blog tools for example can generate RSS feeds on the
fly. b2evolution is an example of such a blog tool.
Distributing RSS
Whether you generate your RSS by hand or have a tool generate it automatically, you need to make it
available on the web for users (and their "client" software) to consume.
Just like with regular web content, you need to host it on a website with a web hosting provider. Note
that until you get hundreds of thousands of users consuming your feeds every day, cheap web
hosting is perfectly suited for distributing RSS/Atom feeds.
Different flavours
There are different versions of RSS in use. RSS 2.0 is the most common. It is used for news/blog
feeds as well as for Podcasting.
A newer format, called Atom, is a more standardized way of providing XML content updates.
However, it has not gotten wide acceptance yet outside of the blog communities. (Again, almost all
blog tools can generate an Atom feed on the fly.)
The Atom
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.
Web feeds allow software programs to check for updates published on a website. To provide a web
feed, the site owner may use specialized software (such as a content management system) that
publishes a list (or "feed") of recent articles or content in a standardized, machine-readable format.
The feed can then be downloaded by programs that use it, like websites that syndicate content from
the feed, or by feed reader programs that allow Internet users to subscribe to feeds and view their
content.
The Atom format was developed as an alternative to RSS. Ben Trott, an advocate of the new format
that became Atom, believed that RSS had limitations and flaws—such as lack of on-going innovation
and its necessity to remain backward compatible— and that there were advantages to a fresh
design.[1]
Proponents of the new format formed the IETF Atom Publishing Format and Protocol Workgroup.
The Atom syndication format was published as an IETF proposed standard in RFC 4287(December
2005), and the Atom Publishing Protocol was published as RFC 5023 (October 2007).
XML SCHEMA
The XML Schema language is also referred to as XML Schema Definition (XSD).
The purpose of an XML Schema is to define the legal building blocks of an XML document, just like a
DTD.
An XML Schema:
<?xml version="1.0"?>
<note>
<to>Tove</to>
<from>Jani</from>
<heading>Reminder</heading>
<body>Don't forget me this weekend!</body>
</note>
DTD FILE:
note.xsd:
<?xml version="1.0"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"
targetNamespace="http://www.w3schools.com"
xmlns="http://www.w3schools.com"
elementFormDefault="qualified">
<xs:element name="note">
<xs:complexType>
<xs:sequence>
<xs:element name="to" type="xs:string"/>
<xs:element name="from" type="xs:string"/>
<xs:element name="heading" type="xs:string"/>
<xs:element name="body" type="xs:string"/>
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:schema>
Reference to Schema:
<?xml version="1.0"?>
<note
xmlns="http://www.w3schools.com"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.w3schools.com note.xsd">
<to>Tove</to>
<from>Jani</from>
<heading>Reminder</heading>
<body>Don't forget me this weekend!</body>
</note>
Simple Element
A simple element is an XML element that contains only text. It cannot contain any other elements
or attributes.
A default value is automatically assigned to the element when no other value is specified.
A fixed value is also automatically assigned to the element, and you cannot specify another value.
Complex Element
A complex element is an XML element that contains other elements and/or attributes.
Empty elements
Elements that contain only other elements
<product pid="1345"/>
<employee>
<firstname>John</firstname>
<lastname>Smith</lastname>
</employee>
Define a complex element that contain other elements in an XML Schema two different ways
1. Only the "employee" element can use the specified complex type
<xs:element name="employee">
<xs:complexType>
<xs:sequence>
<xs:element name="firstname" type="xs:string"/>
<xs:element name="lastname" type="xs:string"/>
</xs:sequence>
</xs:complexType>
</xs:element>
<xs:complexType name="personinfo">
<xs:sequence>
<xs:element name="firstname" type="xs:string"/>
<xs:element name="lastname" type="xs:string"/>
</xs:sequence>
</xs:complexType>
Indicators
Order indicators:
All
The <all> indicator specifies that the child elements can appear in any order, and that
each child element must occur only once:
Choice
The <choice> indicator specifies that either one child element or another can occur:
Sequence
The <sequence> indicator specifies that the child elements must appear in a specific
order:
Occurrence indicators:
maxOccurs
The <maxOccurs> indicator specifies the maximum number of times an element can
occur:
minOccurs
The <minOccurs> indicator specifies the minimum number of times an element can
occur:
Schema:
<xs:element name="person">
<xs:complexType>
<xs:sequence> or <xs:choice> or <xs:all>
<xs:element name="full_name" type="xs:string"/>
<xs:element name="child_name" type="xs:string"
maxOccurs="10" minOccurs="0"/>
</xs:sequence>
</xs:complexType>
</xs:element>
Xml:
<person>
<full_name>Tove Refsnes</full_name>
<child_name>Hege</child_name>
<child_name>Stale</child_name>
<child_name>Jim</child_name>
<child_name>Borge</child_name>
</person>
fractionDigits Specifies the maximum number of decimal places allowed. Must be equal to or greater than zero
length Specifies the exact number of characters or list items allowed. Must be equal to or greater than zero
maxExclusive Specifies the upper bounds for numeric values (the value must be less than this value)
maxInclusive Specifies the upper bounds for numeric values (the value must be less than or equal to this value)
maxLength Specifies the maximum number of characters or list items allowed. Must be equal to or greater than
zero
minExclusive Specifies the lower bounds for numeric values (the value must be greater than this value)
minInclusive Specifies the lower bounds for numeric values (the value must be greater than or equal to this value)
minLength Specifies the minimum number of characters or list items allowed. Must be equal to or greater than
zero
totalDigits Specifies the exact number of digits allowed. Must be greater than zero
whiteSpace Specifies how white space (line feeds, tabs, spaces, and carriage returns) is handled
<xs:element name="age">
<xs:simpleType>
<xs:restriction base="xs:integer">
<xs:minInclusive value="0"/>
<xs:maxExclusive value="120"/>
</xs:restriction>
</xs:simpleType>
</xs:element>
Enumeration:
<xs:element name="car">
<xs:simpleType>
<xs:restriction base="xs:string">
<xs:enumeration value="Audi"/>
<xs:enumeration value="Golf"/>
<xs:enumeration value="BMW"/>
</xs:restriction>
</xs:simpleType>
</xs:element>
Pattern:
<xs:element name="letter">
<xs:simpleType>
<xs:restriction base="xs:string">
<xs:pattern value="[a-z]"/>
</xs:restriction>
</xs:simpleType>
</xs:element>
<xs:element name="password">
<xs:simpleType>
<xs:restriction base="xs:string">
<xs:minLength value="5"/>
<xs:maxLength value="8"/>
</xs:restriction>
</xs:simpleType>
</xs:element>
AJAX:
AJAX, is a web development technique for creating interactive web applications.
AJAX cannot work independently. It is used in combination with other technologies to create
interactive webpages.
JavaScript
Loosely typed scripting language.
JavaScript function is called when an event occurs in a page.
Glue for the whole AJAX operation.
DOM
API for accessing and manipulating structured documents.
Represents the structure of XML and HTML documents.
CSS
Allows for a clear separation of the presentation style from the content and may be
changed programmatically by JavaScript.
XMLHttpRequest
JavaScript object that performs asynchronous interaction with the server.
AJAX – Examples
Here is a list of some famous web applications that make use of AJAX.
Google Maps
A user can drag an entire map by using the mouse, rather than clicking on a button.
http://maps.google.com/
Google Suggest
As you type, Google will offer suggestions. Use the arrow keys to navigate the results.
http://www.google.com/webhp?complete=1&hl=en
www.rejinpaul.com
www.rejinpaul.com
Gmail
Gmail is a webmail, built on the idea that email can be more intuitive, efficient and useful.
http://gmail.com/
Yahoo Maps (new)
Now it's even easier and more fun to get where you're going!
http://maps.yahoo.com/
try{
// Opera 8.0+, Firefox, Safari
ajaxRequest = new XMLHttpRequest();
}catch (e){
<form name='myForm'>
www.rejinpaul.com
www.rejinpaul.com
</body>
</html>
In the above JavaScript code, we try three times to make our XMLHttpRequest object. Our
first attempt:
ajaxRequest = new XMLHttpRequest();
It is for Opera 8.0+, Firefox, and Safari browsers. If it fails, we try two more times to make
the correct object for an Internet Explorer browser with:
ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
If it doesn't work, then we can use a very outdated browser that doesn't support
XMLHttpRequest, which also means it doesn't support Ajax.
AJAX - XMLHttpRequest
The XMLHttpRequest object is the key to AJAX. It has been available ever since Internet
Explorer 5.5 was released in July 2000, but was not fully discovered until AJAX and Web 2.0
in 2005 became popular.
XMLHttpRequest (XHR) is an API that can be used by JavaScript, JScript, VBScript, and
other web browser scripting languages to transfer and manipulate XML data to and from a
webserver using HTTP, establishing an independent connection channel between a webpage's
Client-Side and Server-Side.
The data returned from XMLHttpRequest calls will often be provided by back-end databases.
Besides XML, XMLHttpRequest can be used to fetch data in other formats, e.g. JSON or
even plain text.
Listed below is listed are some of the methods and properties that you have to get familiar
with.
XMLHttpRequest Methods
abort()
Cancels the current request.
getAllResponseHeaders()
Returns the complete set of HTTP headers as a string.
getResponseHeader( headerName )
Returns the value of the specified HTTP header.
open( method, URL )
open( method, URL, async )
open( method, URL, async, userName )
open( method, URL, async, userName, password )
Specifies the method, URL, and other optional attributes of a request.
The method parameter can have a value of "GET", "POST", or "HEAD". Other HTTP
methods, such as "PUT" and "DELETE" (primarily used in REST applications) may
be possible.
The "async" parameter specifies whether the request should be handled
asynchronously or not. "true" means that the script processing carries on after the
www.rejinpaul.com
www.rejinpaul.com
send() method without waiting for a response, and "false" means that the script waits
for a response before continuing script processing.
send( content )
Sends the request.
setRequestHeader( label, value )
Adds a label/value pair to the HTTP header to be sent.
XMLHttpRequest Properties
onreadystatechange
An event handler for an event that fires at every state change.
readyState
The readyState property defines the current state of the XMLHttpRequest object.
The following table provides a list of the possible values for the readyState property:
State Description
0 The request is not initialized.
1 The request has been set up.
2 The request has been sent.
3 The request is in process.
4 The request is completed.
readyState = 0 After you have created the XMLHttpRequest object, but before you
have called the open() method.
readyState = 1 After you have called the open() method, but before you have called
send().
readyState = 2 After you have called send().
readyState = 3 After the browser has established a communication with the server,
but before the server has completed the response.
readyState = 4 After the request has been completed, and the response data has been
completely received from the server.
responseText
Returns the response as a string.
responseXML
Returns the response as XML. This property returns an XML document object, which
can be examined and parsed using the W3C DOM node tree methods and properties.
status
Returns the status as a number (e.g., 404 for "Not Found" and 200 for "OK").
statusText
Returns the status as a string (e.g., "Not Found" or "OK").
AJAX - Action
Steps of AJAX Operation
try{
ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
}catch (e){
function validateUserId() {
ajaxFunction();
function validateUserId() {
ajaxFunction();
ajaxRequest.onreadystatechange = processRequest;
If we assume that you are going to write a servlet, then here is the piece of code.
function processRequest() {
if (req.readyState == 4) {
if (req.status == 200) {
var message = ...;
...
}
www.rejinpaul.com
www.rejinpaul.com
document.getElementById("userIdMessage"),
// where "userIdMessage" is the ID attribute
// of an element appearing in the HTML document
JavaScript may now be used to modify the element's attributes; modify the element's
style properties; or add, remove, or modify the child elements. Here is an example:
<script type="text/javascript">
<!--
function setMessageUsingDOM(message) {
var userMessageElement = document.getElementById("userIdMessage");
var messageText;
if (message == "false") {
userMessageElement.style.color = "red";
messageText = "Invalid User Id";
}
else
{
userMessageElement.style.color = "green";
messageText = "Valid User Id";
}