0% found this document useful (0 votes)
29 views213 pages

CS6501 SCAD MSM by WWW - Learnengineering.in

Uploaded by

monke.hrishi
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
29 views213 pages

CS6501 SCAD MSM by WWW - Learnengineering.in

Uploaded by

monke.hrishi
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 213

Visit & Downloaded from : www.LearnEngineering.

in

ENGINEERING COLLEGES

2016 – 17 Odd Semester

IMPORTANT QUESTIONS & ANSWERS

Department of CSE

SUBJECT CODE: CS6501

SUBJECT NAME: Internet Programming

Regulation: 2013 Semester and Year: 05 and III

Visit & Downloaded from : www.LearnEngineering.in


Visit & Downloaded from : www.LearnEngineering.in

ANNA UNIVERSITY
SYLLABUS COPY (REGULATION 2013)

CS6501 INTERNET PROGRAMMING L T P C


3 1 0 4
UNIT I JAVA PROGRAMMING 9
An overview of Java – Data Types – Variables and Arrays – Operators – Control
Statements – Classes – Objects – Methods – Inheritance - Packages – Abstract classes –
Interfaces and Inner classes – Exception handling - Introduction to Threads –
Multithreading – String handling – Streams and I/O – Applets.
UNIT II WEBSITES BASICS, HTML 5, CSS 3, WEB 2.0 8
Web 2.0: Basics-RIA Rich Internet Applications - Collaborations tools - Understanding
websites and web servers: Understanding Internet – Difference between websites and
web server- Internet technologies Overview –Understanding the difference between
internet and intranet; HTML and CSS: HTML 5.0 , XHTML, CSS 3.
UNIT III CLIENT SIDE AND SERVER SIDE PROGRAMMING 11
Java Script: An introduction to JavaScript–JavaScript DOM Model-Date and
Objects,-Regular Expressions- Exception Handling-Validation-Built-in objects-Event
Handling- DHTML with JavaScript. Servlets: Java Servlet Architecture- Servlet Life
Cycle- Form GET and POST actions- Session Handling- Understanding Cookies-
Installing and Configuring Apache Tomcat Web Server;- DATABASE
CONNECTIVITY: JDBC perspectives, JDBC program example - JSP: Understanding
Java Server Pages-JSP Standard Tag Library(JSTL)-Creating HTML forms by
embedding JSP code.
UNIT IV PHP and XML 8 An
introduction to PHP: PHP- Using PHP- Variables- Program control- Built-in functions-
Connecting to Database – Using Cookies-Regular Expressions; XML: Basic XML-
Document Type Definition- XML Schema DOM and Presenting XML, XML Parsers and
Validation, XSL and XSLT Transformation, News Feed (RSS and ATOM).

UNIT V INTRODUCTION TO AJAX and WEB SERVICES 9


AJAX: Ajax Client Server Architecture-XML Http Request Object-Call Back Methods;
Web Services: Introduction- Java web services Basics – Creating, Publishing ,Testing
and Describing a Web services (WSDL)-Consuming a web service, Database Driven web
service from an application –SOAP.
TOTAL (L:45+T:15): 60
TEXT BOOKS
1. Deitel and Deitel and Nieto, “Internet and World Wide Web - How to Program”,
Prentice Hall, 5th Edition, 2011.

Visit & Downloaded from : www.LearnEngineering.in


Visit & Downloaded from : www.LearnEngineering.in

2. Herbert Schildt, “Java-The Complete Reference”, Eighth Edition, Mc Graw Hill


Professional, 2011.
REFERENCES
1. Stephen Wynkoop and John Burke “Running a Perfect Website”, QUE, 2nd
Edition,1999.
2. Chris Bates, Web Programming – Building Intranet Applications, 3rd Edition, Wiley
Publications, 2009.
3. Jeffrey C and Jackson, “Web Technologies A Computer Science Perspective”, Pearson
Education, 2011.
4. Gopalan N.P. and Akilandeswari J., “Web Technology”, Prentice Hall of India, 2011.
5. Paul Dietel and Harvey Deitel, “Java How to Program”, , 8th Edition Prentice Hall of
India.
6. Mahesh P. Matha, “Core Java A Comprehensive Study”, Prentice Hall of India, 2011.
7. Uttam K.Roy, “Web Technologies”, Oxford University Press, 2011.

Visit & Downloaded from : www.LearnEngineering.in


Visit & Downloaded from : www.LearnEngineering.in

TABLE OF CONTENTS
Sl.No Topic Page No
a Aim and Objective of the Subject 1
b Detailed Lesson Plan 2
UNIT I JAVA PROGRAMMING
c Part A 6
d Part B 8
1 Multithreading 8
2 Exception Handling 11
3 Data types and Array 16
4 Inheritance 19
5 Operators 22
6 String handling 30
7 Applet 31
UNIT II WEBSITES BASICS, HTML 5, CSS 3, WEB 2.0
e Part A 37
f Part B 39
8 Rich Internet Applications 39
9 HTML 48
10 Cascading Style Sheet 55
11 XHTML 58
12 Tables 66
UNIT III CLIENT SIDE AND SERVER SIDE PROGRAMMING
g Part A 71
h Part B 72
13 Document Object Model 77
14 Database connectivity 79
15 Javascript 80
16 Java Servlet 88
17 Cookies 90
UNIT IV PHP and XML
i Part A 98
j Part B 101
18 XML 102
19 XML Parser and Validation 105
20 XSL and XSLT 107
21 PHP 110
22 Cookies 116
23 Regular Expression 118
UNIT V INTRODUCTION TO AJAX and WEB SERVICES
k Part A 122
l Part B 124
24 AJAX 124
25 AJAX with XMLHttpRequest and call back 125
26 Webservices 128
27 WSDL 131
28 SOAP 136
m Industrial/Practical Connectivity of the subject 139
29 University Question Bank 140
30 University Question Programs 143

Visit & Downloaded from : www.LearnEngineering.in


Visit & Downloaded from : www.LearnEngineering.in

AIM AND OBJECTIVE OF THE SUBJECT

 To introduce the basics and advanced concepts of Java programming


language

 To become familiar with writing programs using techniques in Java


programming.

 Understand different Internet Technologies.

 Be exposed to java specific web services architecture.

 Learn to create website using HTML and Cascading Style Sheets.

 To learn JavaScript objects and by applying different event handling


mechanisms.

 To create web page in PHP, and to present data in XML format.

 To learn server side programs using Servlets and JSP.

 To learn how to design rich client presentation using AJAX.

Visit & Downloaded from : www.LearnEngineering.in


Visit & Downloaded from : www.LearnEngineering.in

DETAILED LESSON PLAN


TEXT BOOKS
1. Deitel and Deitel and Nieto, “Internet and World Wide Web - How to Program”,
Prentice Hall, 5th Edition, 2011.
2. Herbert Schildt, “Java-The Complete Reference”, Eighth Edition, Mc Graw Hill
Professional, 2011.
REFERENCES
1. Stephen Wynkoop and John Burke “Running a Perfect Website”, QUE, 2nd
Edition,1999.
2. Chris Bates, Web Programming – Building Intranet Applications, 3rd Edition, Wiley
Publications, 2009.
3. Jeffrey C and Jackson, “Web Technologies A Computer Science Perspective”, Pearson
Education, 2011.
4. Gopalan N.P. and Akilandeswari J., “Web Technology”, Prentice Hall of India, 2011.
5. Paul Dietel and Harvey Deitel, “Java How to Program”, , 8th Edition Prentice Hall of
India.
6. Mahesh P. Matha, “Core Java A Comprehensive Study”, Prentice Hall of India, 2011.
7. Uttam K.Roy, “Web Technologies”, Oxford University Press, 2011.

Sl. Hours Cum


Book No
No Topics Required / ulativ
( Page No)
. Planned e Hrs
UNIT I JAVA PROGRAMMING
T2
1 An Overview of java, Data Types 1 1
(73-95,96-107)
T2(107-
2 Variables and Arrays , Operators 1 2
125,126-147)
T2(148-
3 Control Statements , Classes 1 3
180,181-206)
T2(185-189,
4 Objects , Methods 1 4
189-206)
5 Java T(1) 5 NPTEL
T2(244-
6 Inheritance, Packages 1 6
271,272-282)
T2(265-
Abstract classes, Interfaces and Inner
7 1 7 269,282-
classes
294,229-233)
8 Inheritance T(1) 8 PPT
Exception handling , Introduction to T2(295-
9 1 9
Threads 316,318-330)

Visit & Downloaded from : www.LearnEngineering.in


Visit & Downloaded from : www.LearnEngineering.in

Sl. Hours Cum


Book No
No Topics Required / ulativ
( Page No)
. Planned e Hrs
T2(330-
10 Multithreading , String handling 1 10
357,491-520)
T2(724-
11 Streams and I/O, Applets 1 11
767,415-418)
12 Applets T(1) 12 T2(832-854)
UNIT II WEBSITES BASICS, HTML 5, CSS 3, WEB 2.0
13 Web 2.0: Basics- 1 13 T1(51-55)
RIA Rich Internet Applications -
14 1 14 T1(80-82)WEB
Collaborations tools -
Understanding websites and web
15 1 15 R3(1-44)
servers: Understanding Internet
Difference between websites and web
16 1 16 WEB
server- Internet technologies Overview
17 Internet technologies Overview 1 17 R3(1-44)
Understanding the difference between WEB,R3(56-
18 1 18
internet and intranet; HTML and CSS 107)
19 HTML 5.0, XHTML 1 19 WEB,
T1(118-
20 XHTML, CSS 3. 1 20
151,159-190)
21 HTML 5.0 T(1) 21 NPTEL
22 XHTML T(1) 22 WEB
23 CSS T(1) 23 PPT

UNIT III CLIENT SIDE AND SERVER SIDE PROGRAMMING


Java Script: An introduction to R3(193,249-
24 1 24
JavaScript, JavaScript DOM Model 268)
T1(453-
25 Date and Objects, Regular Expressions 1 25 459),R3(233-
254)
26 Exception Handling, Validation 1 26 R3(280-281)
T1(403-
27 Built-in objects, Event Handling 1 27 405),R3(268-
282)
28 DHTML with JavaScript 1 28 WEB
29 Java Script T(1) 29 PPT
Servlet: Java Servlet Architecture, R3(307-
30 1 30
Servlet Life Cycle 309,311-314)
Form GET and POST actions- Session R3(319-
31 1 31
Handling 322,322-327)
Understanding Cookies- Installing and
R3(329-
32 Configuring Apache Tomcat Web 1 32
332,)NPTEL
Server
33 DATABASE CONNECTIVITY: JDBC 1 33 R3(545-550)

Visit & Downloaded from : www.LearnEngineering.in


Visit & Downloaded from : www.LearnEngineering.in

Sl. Hours Cum


Book No
No Topics Required / ulativ
( Page No)
. Planned e Hrs
perspectives, JDBC program example
DATABASE CONNECTIVITY: JDBC
34 T(1) 34 WEB
program
Exceptions JSP: Understanding Java
R3(433-
35 Server Pages-JSP Standard Tag 1 35
457,463-466)
Library(JSTL)
Creating HTML forms by embedding
36 1 36 WEB
JSP code
37 JSP T(1) 37 T1(1123-1166)
UNIT IV PHP and XML
An introduction to PHP: PHP- Using T1(906-
38 1 38
PHP 907),WEB
39 Using PHP- Variables 1 39 T1(907-917)
40 Program control- Built-in functions 1 40 PPT
41 PHP T(1) 41 WEB
Connecting to Database – Using T1(929-
42 1 42
Cookies 933,933-939)
43 Connecting to Database T(1) 43 NPTEL
WEB, T1(516-
44 Regular Expressions; XML: Basic XML 1 44
519)
T1(529-
- Document Type Definition, XML
45 1 45 533,533-
Schema DOM and Presenting XML
540,553-570)
46 XML T(1) 46 R3(364-370)
47 XML Parsers and Validation 1 47 R3(383-396)
T1(544-
XSL and XSLT Transformation, News
48 1 48 553,570-
Feed (RSS and ATOM).
578),WEB
UNIT V INTRODUCTION TO AJAX and WEB SERVICES
49 AJAX: Ajax Client Server Architecture 1 49 T1(588-627)
50 AJAX T(1) 50 NPTEL
51 XML Http Request Object 1 51 R3(390-395)
52 XML Http Request Object T(1) 52 PPT
53 Call Back Methods 1 53 WEB
54 Web Services: Introduction 1 54 T1(1226-1228)
55 Java web services Basics 1 55 T1(1228)
Creating, Publishing, Testing and
56 1 56 T1(1228-1239)
Describing a Webservices (WSDL)
57 Consuming a web service, 1 57 T1(1239-1248)
Database Driven web service from an
58 1 58 T1(1265-1273)
application
59 Web Services T(1) 59 R3(486-502)

Visit & Downloaded from : www.LearnEngineering.in


Visit & Downloaded from : www.LearnEngineering.in

Sl. Hours Cum


Book No
No Topics Required / ulativ
( Page No)
. Planned e Hrs
60 SOAP. 1 60 T1(1248-1249,

Visit & Downloaded from : www.LearnEngineering.in


Visit & Downloaded from : www.LearnEngineering.in

Unit I
JAVA PROGRAMMING
PART A (2 marks)
1. Define an abstract class. Give example. [Nov/Dec 2015]
A class that is declared with abstract keyword, is known as abstract class in java. It
can have abstract and non-abstract methods (method with body).
Example
abstract class Bike
{
abstract void run();
}
class Honda4 extends Bike
{
void run(){System.out.println("running safely..");
}
public static void main(String args[])
{
Bike obj = new Honda4();
obj.run();
}
2. Expand DOM, AJAX, AWT, JDBC. [Nov/Dec 2015]
DOM – Document Object Model
AJAX - Asynchronous JavaScript and XML
AWT - Abstract Window Toolkit
JDBC - Java Database Connectivity
3. Differentiate Method overriding and Overloading?
When a method in a subclass has the same name & type signature as a method in the
subclass is said to override the method in the super class. When an overridden method is
called from within a subclass it will always refer to the version of that method defined by
the subclass.
class A{
…….
void show(){
System.out.println(“Super class”)
}
class B extends A{
…….
Void show(){

Visit & Downloaded from : www.LearnEngineering.in


Visit & Downloaded from : www.LearnEngineering.in

System.out.println(“sub class”)
}
class override{
B sub = new B( );
Sub. show( );
}
Method Overloading is the nothing but function overloading. It is the process of having
same name to more than one function but differing in the number of arguments or the
type of arguments.
4. Give two examples for Java Modifiers.
Access Control Modifiers
o private
o public
o protected
o default
Non Access Modifiers
o static
o final
o abstract
o synchronized and volatile
5. How do we allocate an array dynamically in Java?
An array can be created dynamically with an initializer.
For example
int numbers[] = {1, 2, 4, 8, 16, 32, 64, 128};
This syntax dynamically creates an array and initializes its elements to the specified
values.
6. What are the advantages of Packages?
 Java package is used to categorize the classes and interfaces so that they can be
easily maintained.
 Java package provides access protection.
 Java package removes naming collision.

7. Define interface.
An interface is nothing but a class which has some distinct features. An interface is
denoted by the keyword interface. Interface can contain final (constant) variables and
Function declaration. The class which implements the interface must define the function.
8. Define Exception. List out its types.
A java exception is an object that describes an exceptional condition that has occurred in
a piece of code. The types are

Visit & Downloaded from : www.LearnEngineering.in


Visit & Downloaded from : www.LearnEngineering.in

 User Defined
 Pre Defined Exception

9. Write short notes on throw.


When an exception occurs it is thrown from try block. It is done using the keyword
throw.
10. What is a package? List out its types
Package is a collection of classes and methods. The package statement defines a name
space in which classes are stored.
Syntax: package pkg;
Pkg _ name of the package.
We can create a hierarchy of classes. For that separate each package name from the one
above it by use of a period.
Syntax: package pkg1.[pkg2.[pkg3]];
Its types are
 User Defined Package
 Java API Package

Java includes the import statements to bring certain classes ,or entire packages in to
visibility. import statements occur immediately following the package statements &
before any class definitions.
Syntax: import pkg1[.pkg2].( class name| *);
Pkg1 _name of the Top level package.
pkg2 _name of the subordinate package inside the outer package separated by a dot.
11. States of Thread?
• Newborn state
• Runnable state
• Running state
• Blocked state
• Dead state
12. What is Java API package?
An Application Programming Interface (API), in the context of Java, is a collection of
prewritten packages, classes, and interfaces with their respective methods
Eg
java.io
java.net
13. Define Multithreaded Programming?
A Multithreaded program contains two or more parts that can run concurrently. Each part
of such a program is called a thread and each thread defines a separate path of execution.

Visit & Downloaded from : www.LearnEngineering.in


Visit & Downloaded from : www.LearnEngineering.in

Thus Multi threading is a specialized form of multitasking.


It can be implemented
 By implementing the runnable interface.
Class Newthread implements Runnable
 By Extending the Thread class
Class Newthread extends Thread
14. How multiple inheritances are implemented in java?
A class can implement more than one interface (the Java platform supports multiple
inheritance for interfaces), so the implements keyword is followed by a comma-separated
list of the interfaces implemented by the class.
15. List the unique features of java
Features of Java
There is given many features of java. They are also known as java buzzwords.
1. Simple
2. Object-Oriented
3. Platform independent
4. Secured
5. Robust
6. Architecture neutral
7. Portable
8. Dynamic
9. Interpreted
10. High Performance
11. Multithreaded
12. Distributed

PART-B
1. Describe the following
(i) Multithreading in java
(ii) Exception handling in java [Nov/Dec 2015]
(Or)
(i) Explain how the multiple programs are running simultaneously.
(ii) Explain how exceptions are handled in JAVA.
(Or)
(i) Explain about the life cycle of threads.
(ii) Describe about the method of handling the errors in JAVA.
(i) Multithreading

Visit & Downloaded from : www.LearnEngineering.in


Visit & Downloaded from : www.LearnEngineering.in

Thread is a tiny program or light weight process running continuously. During


multithreading the processor switches between multiple threads of the program. The
various states of thread are
New state - Thread is created
Runnable state - Thread is executing
Waiting state - Another thread is executing
Timed Waiting state - Waiting for some time
Blocked state - I/O Request
Terminated State - Finished

Java Thread Model


In java we can implement the thread program in two ways
 Using Thread Class
 Using Runnable interface

Thread Class
The main class must extend the thread class. A thread is created in the constructor.
It must me initialized in the constructor using super() call. Then override the run()
method
Eg
class ThreadDemo extends Thread
{
String str="";
ThreadDemo(String s)
{
super(s);
str=s;
start();
}
public void run()
{

10

Visit & Downloaded from : www.LearnEngineering.in


Visit & Downloaded from : www.LearnEngineering.in

System.out.println(str);
}
}
class Main
{
public static void main(String []args)
{
ThreadDemo t=new ThreadDemo("ONE");
}
}
Runnable Interface
The main class must implement the runnable interface and overide the run()
method.
Example
class ThreadDemo implements Runnable
{
Thread t;
String str="";
ThreadDemo(String s)
{
t=new Thread(this);
str=s;
t.start();
}
public void run()
{
System.out.println(str);
}
}
class Main
{
public static void main(String []args)
{
ThreadDemo t=new ThreadDemo("ONE");
}
}

11

Visit & Downloaded from : www.LearnEngineering.in


Visit & Downloaded from : www.LearnEngineering.in

Multiple Threads
Thread Class
The main class must extend the thread class. A thread is created in the constructor.
It must me initialized in the constructor using super() call. Then override the run()
method
Example
class ThreadDemo extends Thread
{
String str="";
ThreadDemo(String s)
{
super(s);
str=s;
start();
}
public void run()
{
for(int i=0;i<3;i++)
System.out.println(str);
}
}
class Main
{
public static void main(String []args)
{
ThreadDemo t=new ThreadDemo("ONE");
ThreadDemo t=new ThreadDemo("TWO");
ThreadDemo t=new ThreadDemo("THREE");
}
}
Output: (Order can change)
ONE
ONE
TWO
TWO
TWO
THREE
THREE

12

Visit & Downloaded from : www.LearnEngineering.in


Visit & Downloaded from : www.LearnEngineering.in

THREE
ONE
(ii) Exception handling in java [Nov/Dec 2015]
Exceptions are runtime anomalies or unusual conditions that a program may
encounter while executing. It is caused due to run time error in the program
Example Divide by zero
Array Index out of Bounds
Steps involved in Exception Handling
1. Find the problem (Hit the Exception)
2. Inform that an error occurred (Throw the Exception)
3. Receive the error information (Catch the Exception)
4. Take corrective action (Handle the Exception)

Try

Detects and Throws


Exception
Exception
Object

Catch

Catches and Handles


the Exception

It consists of three statements. They are


 try
 catch
 throw

The syntax is
try
{
......
throw exception;
}
catch(type arg)
{
.....
.....
}
 The catch block must be present immediately after the try block.

13

Visit & Downloaded from : www.LearnEngineering.in


Visit & Downloaded from : www.LearnEngineering.in

 Try is used to group the statements which may generate Exception.


 If no exception is generated the catch block won't get executed.
 When an exception occurs it is thrown from try block.
 The thrown exception is caught by the catch block and handles it.

Few inbuilt exception available in java are


ArithmeticException - Divide by zero
IOException - Illegal Input/Output operation
IndexOutOfBoundsException - An index out of bound
Exception - General type of Exception
Eg
class ExcepDemo
{
public static void main(String []args)
{
int a,b,c;
a=10;
b=0;
try
{
c=a/b;
System.out.println("Quotient :"+c);
}
catch(ArithmeticException e)
{
System.out.println("Divide by 0");
}
}
}
Multiple Catch Statement
It is not possible for the try block to throw a single exception always. To handle situation
in which multiple catch blocks are needed, there must be multiple catch.
try
{
// Statements
}
catch(ExceptionType e)
{
// Statements

14

Visit & Downloaded from : www.LearnEngineering.in


Visit & Downloaded from : www.LearnEngineering.in

}
catch(ExceptionType e1)
{
//Statements
}
catch(ExceptionType e2)
{
//Statements
}
class Exception
{
public static void main(String []args)
{
int a;
Scanner obj=new Scanner(System.in);
a=obj.nextInt();
try
{
if(a==0)
throw a;
else if(a==1)
throw 1.0;
else
throw 'a';
}
catch(int a)
{
System.out.println("Integer catch");
}
catch(float a)
{
System.out.println("Floating catch");
}
catch(char a)
{
System.out.println("Character catch");
}
}

15

Visit & Downloaded from : www.LearnEngineering.in


Visit & Downloaded from : www.LearnEngineering.in

}
Finally
Finally block gets executed after try block. It is assured of execution of some important
code that must be executed after the try block.
The syntax is
finally
{
//statements
}
class sample
{
public static void main(String args[])
{
int a=10,b=0,c;
try
{
c=a/b;
}
catch(ArithmeticException e)
{
System.out.println("Divide by 0");
}
finally
{
System.out.println("Exiting..");
}
}
}
User Defined Exception
We can throw our own exception using the keyword throw
throw new classname
Example
import java.lang.Exception
class MyOwnException extends Exception
{
MyOwnException(String s)
{
super(s);

16

Visit & Downloaded from : www.LearnEngineering.in


Visit & Downloaded from : www.LearnEngineering.in

}
}
class Demo
{
public static void main(String []args)
{
try
{
throw new MyOwnException("Exception");
}
catch(MyOwnException e)
{
System.out.println(e.getMessage());
}
}
}
Output
Exception
2. (i) Write a java program to draw smiley using applet. [Nov/Dec 2015]
import java.awt.*;
import java.applet.*;
public class Smiley extends Applet
{
public void paint(Graphics g)
{
Font f = new Font("Helvetica", Font.BOLD,20);
g.setFont(f);
g.drawString("Keep Smiling!!!", 50, 30);
g.drawOval(60, 60, 200, 200);
g.fillOval(90, 120, 50, 20);
g.fillOval(190, 120, 50, 20);
g.drawLine(165, 125, 165, 175);
g.drawArc(110, 130, 95, 95, 0, -180);
}
}

(ii) Compare Overloading and Overriding in Java [Nov/Dec 2015]


Or

17

Visit & Downloaded from : www.LearnEngineering.in


Visit & Downloaded from : www.LearnEngineering.in

Give atleast three differences between overriding and overloading of


methods in java. [May/June 2016]

1. Overloading happens at compile-time while Overriding happens at runtime: The


binding of overloaded method call to its definition has happens at compile-time
however binding of overridden method call to its definition happens at runtime.
2. Static methods can be overloaded which means a class can have more than one
static method of same name. Static methods cannot be overridden, even if you
declare a same static method in child class it has nothing to do with the same
method of parent class.
3. The most basic difference is that overloading is being done in the same class while
for overriding base and child classes are required. Overriding is all about giving a
specific implementation to the inherited method of parent class.
4. Static binding is being used for overloaded methods and dynamic binding is being
used for overridden/overriding methods.
5. Performance: Overloading gives better performance compared to overriding. The
reason is that the binding of overridden methods is being done at runtime.
6. private and final methods can be overloaded but they cannot be overridden. It
means a class can have more than one private/final methods of same name but a
child class cannot override the private/final methods of their base class.
7. Return type of method does not matter in case of method overloading, it can be
same or different. However in case of method overriding the overriding method can
have more specific return type .
8. Argument list should be different while doing method overloading. Argument list
should be same in method Overriding.

Overloading example
//A class for adding upto 5 numbers
class Sum
{
int add(int n1, int n2)
{
return n1+n2;
}
int add(int n1, int n2, int n3)
{
return n1+n2+n3;
}
int add(int n1, int n2, int n3, int n4)
{

18

Visit & Downloaded from : www.LearnEngineering.in


Visit & Downloaded from : www.LearnEngineering.in

return n1+n2+n3+n4;
}
int add(int n1, int n2, int n3, int n4, int n5)
{
return n1+n2+n3+n4+n5;
}
public static void main(String args[])
{
Sum obj = new Sum();
System.out.println("Sum of two numbers: "+obj.add(20, 21));
System.out.println("Sum of three numbers: "+obj.add(20, 21, 22));
System.out.println("Sum of four numbers: "+obj.add(20, 21, 22, 23));
System.out.println("Sum of five numbers: "+obj.add(20, 21, 22, 23, 24));
}
}
Output
Sum of two numbers: 41
Sum of three numbers: 63
Sum of four numbers: 86
Sum of five numbers: 110
Overriding example
package beginnersbook.com;
class CarClass
{
public int speedLimit()
{
return 100;
}
}
class Ford extends CarClass
{
public int speedLimit()
{
return 150;
}
public static void main(String args[])
{
CarClass obj = new Ford();
int num= obj.speedLimit();
System.out.println("Speed Limit is: "+num);
}

19

Visit & Downloaded from : www.LearnEngineering.in


Visit & Downloaded from : www.LearnEngineering.in

}
Output
Speed Limit is: 150
3 (i) Write short notes about data types in java.
(or)
How do you represent the data in java? Explain with example
There are two data types available in Java:
 Primitive Data Types
 Reference/Object Data Types
Primitive Data Types
There are eight primitive data types supported by Java. Primitive data types are
predefined by the language and named by a keyword. Let us now look into detail about
the eight primitive data types.
Byte
 Byte data type is an 8-bit signed two's complement integer.
 Minimum value is -128 (-2^7)
 Maximum value is 127 (inclusive)(2^7 -1)
 Default value is 0
 Byte data type is used to save space in large arrays, mainly in place of integers,
since a byte is four times smaller than an int.
 Example: byte a = 100 , byte b = -50
short
 Short data type is a 16-bit signed two's complement integer.
 Minimum value is -32,768 (-2^15)
 Maximum value is 32,767 (inclusive) (2^15 -1)
 Short data type can also be used to save memory as byte data type. A short is 2
times smaller than an int
 Default value is 0.
 Example: short s = 10000, short r = -20000
int
 Int data type is a 32-bit signed two's complement integer.
 Minimum value is - 2,147,483,648.(-2^31)
 Maximum value is 2,147,483,647(inclusive).(2^31 -1)
 Int is generally used as the default data type for integral values unless there is a
concern about memory.
 The default value is 0.
 Example: int a = 100000, int b = -200000
long
 Long data type is a 64-bit signed two's complement integer.
20

Visit & Downloaded from : www.LearnEngineering.in


Visit & Downloaded from : www.LearnEngineering.in

 Minimum value is -9,223,372,036,854,775,808.(-2^63)


 Maximum value is 9,223,372,036,854,775,807 (inclusive). (2^63 -1)
 This type is used when a wider range than int is needed.
 Default value is 0L.
 Example: long a = 100000L, long b = -200000L
float
 Float data type is a single-precision 32-bit IEEE 754 floating point.
 Float is mainly used to save memory in large arrays of floating point numbers.
 Default value is 0.0f.
 Float data type is never used for precise values such as currency.
 Example: float f1 = 234.5f
double
 double data type is a double-precision 64-bit IEEE 754 floating point.
 This data type is generally used as the default data type for decimal values,
generally the default choice.
 Double data type should never be used for precise values such as currency.
 Default value is 0.0d.
 Example: double d1 = 123.4
boolean
 boolean data type represents one bit of information.
 There are only two possible values: true and false.
 This data type is used for simple flags that track true/false conditions.
 Default value is false.
 Example: boolean one = true
char
 char data type is a single 16-bit Unicode character.
 Minimum value is '\u0000' (or 0).
 Maximum value is '\uffff' (or 65,535 inclusive).
 Char data type is used to store any character.
 Example: char letterA ='A'
Reference Data Types
 Reference variables are created using defined constructors of the classes. They are
used to access objects. These variables are declared to be of a specific type that
cannot be changed. For example, Employee, Puppy etc.
 Class objects, and various type of array variables come under reference data type.
 Default value of any reference variable is null.
 A reference variable can be used to refer to any object of the declared type or any
compatible type.

21

Visit & Downloaded from : www.LearnEngineering.in


Visit & Downloaded from : www.LearnEngineering.in

 Example: Animal animal = new Animal("giraffe");

3(ii) Explain in detail about Array with syntax and example.


(or)
Can we save the multiple data in a single variable? If so explain it with
examples.
 Java provides a data structure, the array, which stores a fixed-size sequential
collection of elements of the same type.
 An array is used to store a collection of data, but it is often more useful to think of
an array as a collection of variables of the same type.
 Instead of declaring individual variables, such as number0, number1, ..., and
number99, we can declare one array variable such as numbers and use numbers[0],
numbers[1], and ..., numbers[99] to represent individual variables.
Declaring Array Variables:
 To use an array in a program, we must declare a variable to reference the array,
and specify the type of array the variable can reference.

Syntax
dataType[] arrayRefVar;
Example
double[] myList;
Creating Arrays
 We can create an array by using the new operator with the following syntax:
arrayRefVar =new dataType[arraySize];
• It creates an array using new dataType[arraySize];
• It assigns the reference of the newly created array to the variable arrayRefVar.
 Declaring an array variable, creating an array, and assigning the reference of the
array to the variable can be combined in one statement, as shown below:

dataType[] arrayRefVar =new dataType[arraySize];


Alternatively you can create arrays as follows:
dataType[] arrayRefVar ={value0, value1,..., valuek};
Processing Arrays
When processing array elements, we often use either for loop or for each loop because all
of the elements in an array are of the same type and the size of the array is known.
Example
public class TestArray
{
public static void main(String[] args)

22

Visit & Downloaded from : www.LearnEngineering.in


Visit & Downloaded from : www.LearnEngineering.in

{
double[] myList ={1.9,2.9,3.4,3.5};
// Print all the array elements
for(int i =0; i < myList.length; i++)
{
System.out.println(myList[i]+" ");
}
// Summing all elements
double total =0;
for(int i =0; i < myList.length; i++)
{
total += myList[i];
}
System.out.println("Total is "+ total);
// Finding the largest element
double max = myList[0];
for(int i =1; i < myList.length; i++)
{
if(myList[i]> max) max = myList[i];
}
System.out.println("Max is "+ max);
}
}
Output
1.9
2.9
3.4
3.5
Total is11.7
Max is3.5

3(iii) Explain in detail about the inheritance mechanism in java with an example
programs.
(or)
Describe in detail about the method of deriving the properties of one class from
another class
(or)

23

Visit & Downloaded from : www.LearnEngineering.in


Visit & Downloaded from : www.LearnEngineering.in

Explain about the base and derived class mechanism used in java with suitable
programs.
(or)
Describe in detail about the types of inheritance in java.
It is a process by which the object of one class acquires the properties of objects of
another class. The new class is called as derived class whereas the already existing one is
called as base class.
The various types of inheritance are
 Single Inheritance
 Multilevel Inheritance

The syntax is
class derivedclassname extends baseclassname
{
//STS;
}
Single Inheritance
It is an inheritance where a derived class has only one base class.

A BASE CLASS

B
DERIVED CLASS
Example
class A
{
public:
int a;
void seta(int i)
{
a=i;
}
void puta()
{
System.out.println(a);
}
}
class B extends A
{
public:
int b;

24

Visit & Downloaded from : www.LearnEngineering.in


Visit & Downloaded from : www.LearnEngineering.in

void setb(int i)
{
b=i;
}
void putb()
{
System.out.println(b);
}
}
class Demo
{
public static void main(String []s)
{
B obj=new B();
obj.seta(10);
obj.setb(15);
obj.puta();
obj.putb();
}
}
Here the variable 'a' and puta() in class A are inherited to class B with public visibility
mode.
Multilevel Inheritance
Here the derived class is derived from intermediate base class which is already
derived from a base class.
A

B
Intermediate Base Class

Example C
class A
{
public:
int a;
void seta(int i)
{
a=i;
}

25

Visit & Downloaded from : www.LearnEngineering.in


Visit & Downloaded from : www.LearnEngineering.in

void puta()
{
System.out.println(a);
}
}
class B extends A
{
public:
int b;
void setb(int i)
{
b=i;
}
void putb()
{
System.out.println(b);
}
}
class C extends B
{
public:
int c;
void setc(int i)
{
c=i;
}
void putc()
{
System.out.println(c);
}
}
class demo
{
public static void main(String []s)
{
C obj=new C();
obj.seta(10);
obj.setb(15);

26

Visit & Downloaded from : www.LearnEngineering.in


Visit & Downloaded from : www.LearnEngineering.in

obj.setc(20);
obj.puta();
obj.putb();
obj.putc();
}
}
Here the variables 'a' from class A is inherited to class B. Then variable 'a' and 'b' from
class B are inherited to class C with public visibility mode.
4(i) Explain the various types of operators in Java and explain with suitable
examples.
(or)
What are all the various types of operators used in Java?
OPERATORS AND EXPRESSIONS
An expression is a sequence of operators and operands that specifies computation of a
value, or that designates an object or a function, or that generates side effects, or that
performs a combination.
ARITHMETIC OPERATORS:
The symbols of the arithmetic operators are
Operation Operator Comment Value of Sum before Value of sum after
Multiply * sum = sum * 2; 4 8
Divide / sum = sum / 2; 4 2
Addition + sum = sum + 2; 4 6
Subtraction - sum = sum -2; 4 2
Increment ++ ++sum; 4 5
Decrement -- --sum; 4 3
Modulus % sum = sum % 3; 4 1
Example
import java.io.*;
class sample
{
public static void main(String []args)
{
int sum = 50;
float rem;
rem = sum % 10;
System.out.println("The Remainder is: "+rem);
}
}

27

Visit & Downloaded from : www.LearnEngineering.in


Visit & Downloaded from : www.LearnEngineering.in

PRE/POST INCREMENT/DECREMENT OPERATORS

PRE means do the operation first followed by any assignment operation. POST means do
the operation after any assignment operation. Consider the following statements

++count; /* PRE Increment, means add one to count */

count++; /* POST Increment, means add one to count */

Example

import java.io.*;
class sample
{
public static void main(String []args)
{
int count = 0, loop;
loop = ++count; /* same as count = count + 1; loop = count; */
System.out.println("Loop:"+loop+"\nCount:"+count);
loop = count++; /* same as loop = count; count = count + 1; */
System.out.println("Loop:"+loop+"\nCount:"+count);
}
}
If the operator is on the left hand side of the variable, the operation is performed first, so
the statements loop = ++count; really means increment count first, then assign the new
value of count to loop.

THE RELATIONAL OPERATORS

These allow the comparison of two or more variables.


== equal to
!= not equal
< less than
<= less than or equal to
> greater than
>= greater than or equal to

Example

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

28

Visit & Downloaded from : www.LearnEngineering.in


Visit & Downloaded from : www.LearnEngineering.in

{
int count;
for( count = 1; count <= 10; count = count + 1 )
System.out.println(count);
}
}
RELATIONALS (AND, NOT, OR, EOR)
Combining more than one condition
These allow the testing of more than one condition as part of selection statements. The
symbols are
LOGICAL AND &&
Logical and requires all conditions to evaluate as TRUE (non-zero).
LOGICAL OR ||
Logical or will be executed if any ONE of the conditions is TRUE (non-zero).
LOGICAL NOT !
logical not negates (changes from TRUE to FALSE, vice versa) a condition.
LOGICAL EOR ^
Logical eor will be executed if either condition is TRUE, but NOT if they are all true.
Example
The following program uses an if statement with logical AND to validate the users input
to be in the range 1-10.
import java.io.*;
class sample
{
public static void main(String []args)
{
int number, valid = 0;
Scanner cin=new Scanner(System.in);
while( valid == 0 )
{
System.out.println("Enter a number between 1 and 10 -->");
number=cin.nextInt();
if( (number < 1 ) || (number > 10) )
{
System.out.println("Number is outside range 1-10. Please re-enter\n");
valid = 0;
}
else

29

Visit & Downloaded from : www.LearnEngineering.in


Visit & Downloaded from : www.LearnEngineering.in

valid = 1;
}
System.out.println("The number is "+number );
}
}
Example: NEGATION
class sample
{
public static void main(String []args)
{
int flag = 0;
if( ! flag )
{
System.out.println("The flag is not set.\n");
flag = ! flag;
}
System.out.println("The value of flag is "+ flag);
}
}
THE CONDITIONAL EXPRESSION OPERATOR or TERNARY OPERATOR
 This conditional expression operator takes THREE operators.
 The two symbols used to denote this operator are the ? and the :.
 The first operand is placed before the ?, the second operand between the ? and the :
, and the third after the : . The general format is
condition ? expression1 : expression2
 If the result of condition is TRUE ( non-zero ), expression1 is evaluated and the
result of the evaluation becomes the result of the operation.
 If the condition is FALSE (zero), then expression2 is evaluated and its result
becomes the result of the operation. An example will help,
s = ( x < 0 ) ? -1 : x * x;
 If x is less than zero then s = -1. If x is greater than zero then s = x * x
BIT OPERATIONS
Java has the advantage of direct bit manipulation and the operations available are,

Operation Operator Comment Value of Sum Value of sum

AND & sum = sum & 2; before


4 after
0
OR | sum = sum | 2; 4 6
Exclusive OR ^ sum = sum ^ 2; 4 6
1's Complement ~ sum = ~sum; 4 -5
Left Shift << sum = sum << 2; 4 16

30

Visit & Downloaded from : www.LearnEngineering.in


Visit & Downloaded from : www.LearnEngineering.in

Right Shift >> sum = sum >> 2; 4 0


Example
Write a java program to find factorial of a given number.
import java.util.Scanner;
class Factorial
{
public static void main(String args[])
{
int n, c, fact = 1;
System.out.println("Enter an integer to calculate it's factorial");
Scanner in = new Scanner(System.in);
n = in.nextInt();
if ( n < 0 )
System.out.println("Number should be non-negative.");
else
{
for ( c = 1 ; c <= n ; c++ )
fact = fact*c;
System.out.println("Factorial of "+n+" is = "+fact);
}
}
}
4(ii) Explain in detail about an access modifier.
(or)
Differentiate between private, protected and public access modifier.
Access Modifiers is the way of specifying the accessibility of a class and its members
with respective to other classes and members.
The basic Accessibility Modifiers are of 4 types in Java. They are
1. public
2. protected
3. package/default
4. private

A private member variable or function cannot be accessed, or even viewed from outside
the class. Only the class and friend functions can access private members.
A public member is accessible from anywhere outside the class but within a program.
You can set and get the value of public variables without any member function.

31

Visit & Downloaded from : www.LearnEngineering.in


Visit & Downloaded from : www.LearnEngineering.in

A protected member variable or function is very similar to a private member but it


provided one additional benefit that they can be accessed in child classes which are called
derived classes.
4(iii) Explain about Packages in detail.
Or
Illustrate the concept of user defined package with the syntax and example.
Packages
It is a mechanism in which a group of classes and interfaces can be grouped
together. The main advantage of packages are
 The classes in one package can be reused by a different program
 Two classes of two different packages can have the same name
 It provides separation of design and coding. It also provides possibility of hiding
classes

Packages are classified into two different types. They are


 Java API Package
 User Defined Package

Java API Package


Java API is a collection of various packages in which several classes and methods
are grouped together according to their functionality,
java.applet -> Creating & Implementing Applet
java.awt -> Used for implementing GUI
java.lang -> Strings, math function, threads
java.net -> Network related classes
java.util -> Vectors, date, random numbers
java.io -> Input / Output operations
A java package can be used in a program i.e. the classes stored in the packages can be
used in two ways.
 Import a particular class in a package by specifying the name of t

import java.io.
 Importing all the classes in a package

import java.util.*;
Creating User Defined Packages
Create a folder with the name as package name. For eg if the package name is
my_package then create a folder named my_package. Write the coding of the classes and
interface and save it in it.

32

Visit & Downloaded from : www.LearnEngineering.in


Visit & Downloaded from : www.LearnEngineering.in

Syntax
Package packagename;
{
/*Classes
Sub packages
Block of statements*/
}
Example
package mypackage;
public class A
{
int a;
void seta(int i)
{
a=i;
}
void showa()
{
System.out.println("A="+a);
}
}
class Main
{
public static void main(String []args)
{
A obj=new A();
obj.seta(10);
obj.showa();
}
}
Save the above coding as Main.java in the mypackage folder.
To run
 Move into the package folder - cd mypackage;
 Compile the java file - javac Main.java
 Move one folder back - cd ..
 Run the java file - java mypackage.Main

33

Visit & Downloaded from : www.LearnEngineering.in


Visit & Downloaded from : www.LearnEngineering.in

Another way of using a package is using import statement. Create a package named
mypackage and save the file in it. Create the Main class in bin and use the import
statement to use it.
Example
package mypackage;
public class A
{
int a;
void seta(int i)
{
a=i;
}
void showa()
{
System.out.println("A="+a);
}
}
Save the above file as A.java in the mypackage folder. To use this in another program
then.
import mypackage.A;
class Main
{
public static void main(String []args)
{
A obj=new A();
obj.seta(10);
obj.showa();
}
}

4(iv) Write a java program to implement multiple inheritance using interface.


(or)
Whether java supports multiple inheritance? Explain how the multiple inheritance
is done in java.
Interface
An interface is nothing but a class which has some distinct features. An interface
is denoted by the keyword interface. Interface can contain final(constant) variables and
Function declaration. The class which implements the interface must define the function.

34

Visit & Downloaded from : www.LearnEngineering.in


Visit & Downloaded from : www.LearnEngineering.in

The syntax for creating an interface is


interface interfacename
{
static final type var1=val;
static final type var2=val;
.
.
returntype functionname(args);
.
.
}
Extending an Interface
Interfaces can be extended similar to classes. That means we can derive a interface
from another interface using the keyword extends.
The syntax is
interface interface1 extends interface2
{
.....
.....
}

Example
interface A
{
static final int val=10;
}
interface B extends A
{
void display();
}
The contents of interface A will be transferred to interface B.
Implementing an Interface
Class can implement an interface using the keyword implements. Once it has
implemented then the class must define the function declared in the interface.
class classname implements interface1,interface2,...
{
...
...

35

Visit & Downloaded from : www.LearnEngineering.in


Visit & Downloaded from : www.LearnEngineering.in

}
For Example
public interface myinterface
{
void disp(int i);
}
class A implements myinterface
{
public void disp(int i)
{
System.out.println("Value is:"+i);
}
}
class Main
{
public static void main(String []args)
{
A obj=new A();
(or)
myinterface obj= new A();
obj.disp(10);
}
}
Multiple Inheritance using Interface
It is a kind of inheritance in which more than one super class exists for a subclass.

A B

In java it is made possible using interface.


Example
class A
{
int v;
void setv(int i)

36

Visit & Downloaded from : www.LearnEngineering.in


Visit & Downloaded from : www.LearnEngineering.in

{
v=i;
}
}
interface B
{
public void showv();
}
class C extends A implements B
{
public void showv()
{
System.out.println("V="+v);
}
}

5 (i) Explain the various String operations in java.


It is a collection of characters. It is created in two ways i.e using a) String class or
b)String Buffer class.
In the case of String class, a String can be created in two ways
a) String name="value";
b) String name=new String(char_array);
Example
String s1="Hello";
(or)
char a={'H','e','l','l','o'};
String s1=new String(a);
The various methods are
Length
The length of the string can be found using the length() method.
Syntax
s.length();
Example String s1="Hello;
s1.length(); will produce 5 as output
Concatenation
We can join two string either using + operator (or) concat() method.
Syntax
s1+s2 (or) s1.concat(s2)

37

Visit & Downloaded from : www.LearnEngineering.in


Visit & Downloaded from : www.LearnEngineering.in

String s1="Hello";
String s2="Sam";
System.out.println(s1.concat(s2));
(or)
System.out.println(s1+s2); will produce HelloSam
CharAt
Individual characters of a string can be accessed using charAt().
Syntax
s.charAt(positon);
Example String s="Hello";
s.charAt(3);
will produce l as output
Equals
Two strings can be compared using equals() method.
Syntax
s1.equals(s2);
Sub String
We can derive a substring from a given string using substring method.
Syntax
s.substring(start_pos,end_pos);
Example String s="Algorithm";
s.substring(2,3);
will produce "go"
Replace
We can replace a character in a string but some character.
Syntax
s.replace(old_char,new_char)
Example String s="Hai";
s.replace('a','i');
will produce "Hii"
Upper Case & Lower Case
It converts the character of the string to uppercase and lower case respectively.
s.toLowerCase(); - Small Letters
s.toUpperCase(); - Capital Letters
String Buffer
It is more flexible than the String class. It has some additional methods like
 append(str) - Joins the string
 capacity - Return the capacity of the buffer

38

Visit & Downloaded from : www.LearnEngineering.in


Visit & Downloaded from : www.LearnEngineering.in

 insert(pos,ch) - Insert the character 'ch' at position pos


 delete(start,end) - Deletes the character from start to end

(ii) Explain in detail about Applet and its life cycle


(or)
How do we create applet and explain its usage with example.
An applet is a Java program that runs in a Web browser. An applet can be a fully
functional Java application because it has the entire Java API at its disposal.
There are some important differences between an applet and a standalone Java
application, including the following:
 An applet is a Java class that extends the java.applet.Applet class.
 A main() method is not invoked on an applet, and an applet class will not define
main().
 Applets are designed to be embedded within an HTML page.
 When a user views an HTML page that contains an applet, the code for the applet
is downloaded to the user's machine.
 A JVM is required to view an applet. The JVM can be either a plug-in of the Web
browser or a separate runtime environment.
 The JVM on the user's machine creates an instance of the applet class and invokes
various methods during the applet's lifetime.
 Applets have strict security rules that are enforced by the Web browser. The
security of an applet is often referred to as sandbox security, comparing the applet
to a child playing in a sandbox with various rules that must be followed.
 Other classes that the applet needs can be downloaded in a single Java Archive
(JAR) file.
Life Cycle of an Applet
Four methods in the Applet class give you the framework on which you build any
serious applet:
 init: This method is intended for whatever initialization is needed for your applet.
It is called after the param tags inside the applet tag have been processed.
 start: This method is automatically called after the browser calls the init method.
It is also called whenever the user returns to the page containing the applet after
having gone off to other pages.
 stop: This method is automatically called when the user moves off the page on
which the applet sits. It can, therefore, be called repeatedly in the same applet.
 destroy: This method is only called when the browser shuts down normally.
Because applets are meant to live on an HTML page, you should not normally
leave resources behind after a user leaves the page that contains the applet.

39

Visit & Downloaded from : www.LearnEngineering.in


Visit & Downloaded from : www.LearnEngineering.in

 paint: Invoked immediately after the start() method, and also any time the applet
needs to repaint itself in the browser. The paint() method is actually inherited
from the java.awt.

A "Hello World" Applet


The following is a simple applet named HelloWorldApplet.java:
import java.applet.*;
import java.awt.*;
public class HelloWorldApplet extends Applet
{
public void paint (Graphics g)
{
g.drawString ("Hello World", 25, 50);
}
}
These import statements bring the classes into the scope of our applet class:
 java.applet.Applet.
 java.awt.Graphics.
Without those import statements, the Java compiler would not recognize the classes
Applet and Graphics, which the applet class refers to.
The Applet CLASS
Every applet is an extension of the java.applet.Applet class. The base Applet class
provides methods that a derived Applet class may call to obtain information and services
from the browser context.
These include methods that do the following:
 Get applet parameters
 Get the network location of the HTML file that contains the applet
 Get the network location of the applet class directory
 Print a status message in the browser

40

Visit & Downloaded from : www.LearnEngineering.in


Visit & Downloaded from : www.LearnEngineering.in

 Fetch an image
 Fetch an audio clip
 Play an audio clip
 Resize the applet
Additionally, the Applet class provides an interface by which the viewer or browser
obtains information about the applet and controls the applet's execution. The viewer
may:
 request information about the author, version and copyright of the applet
 request a description of the parameters the applet recognizes
 initialize the applet
 destroy the applet
 start the applet's execution
 stop the applet's execution
The Applet class provides default implementations of each of these methods. Those
implementations may be overridden as necessary.
The "Hello, World" applet is complete as it stands. The only method overridden is the
paint method.
Invoking an Applet
An applet may be invoked by embedding directives in an HTML file and viewing the
file through an applet viewer or Java-enabled browser.
The <applet> tag is the basis for embedding an applet in an HTML file. Below is an
example that invokes the "Hello, World" applet:
<html>
<title>The Hello, World Applet</title>
<hr>
<applet code="HelloWorldApplet.class" width="320" height="120">
If your browser was Java-enabled, a "Hello, World"
message would appear here.
</applet>
<hr>
</html>
 The code attribute of the <applet> tag is required.
 It specifies the Applet class to run.
 Width and height are also required to specify the initial size of the panel in which an
applet runs.
 The applet directive must be closed with a </applet> tag.
 If an applet takes parameters, values may be passed for the parameters by adding
<param> tags between <applet> and </applet>.
 The browser ignores text and other tags between the applet tags.

41

Visit & Downloaded from : www.LearnEngineering.in


Visit & Downloaded from : www.LearnEngineering.in

 Non-Java-enabled browsers do not process <applet> and </applet>.


 Therefore, anything that appears between the tags, not related to the applet, is visible in
non-Java-enabled browsers.
Getting Applet Parameters
 The following applet displays a checkerboard pattern of black and a second
color.
 The second color and the size of each square may be specified as parameters to
the applet within the document.
 CheckerApplet gets its parameters in the init() method.
 It may also get its parameters in the paint() method.
 The applet viewer or browser calls the init() method of each applet it runs.
 The viewer calls init() once, immediately after loading the applet. (Applet.init() is
implemented to do nothing.)
 Override the default implementation to insert custom initialization code.
 The Applet.getParameter() method fetches a parameter given the parameter's
name (the value of a parameter is always a string).
 If the value is numeric or other non-character data, the string must be parsed.
The following is a skeleton of CheckerApplet.java:
import java.applet.*;
import java.awt.*;
public class CheckerApplet extends Applet
{
int squareSize = 50;// initialized to default size
public void init () {}
private void parseSquareSize (String param) {}
private Color parseColor (String param) {}
public void paint (Graphics g) {}
}
Here are CheckerApplet's init() and private parseSquareSize() methods:
public void init ()
{
String squareSizeParam = getParameter ("squareSize");
parseSquareSize (squareSizeParam);
String colorParam = getParameter ("color");
Color fg = parseColor (colorParam);
setBackground (Color.black);
setForeground (fg);
}
private void parseSquareSize (String param)
{

42

Visit & Downloaded from : www.LearnEngineering.in


Visit & Downloaded from : www.LearnEngineering.in

if (param == null) return;


try {
squareSize = Integer.parseInt (param);
}
catch (Exception e) {
// Let default value remain
}
}
 The applet calls parseSquareSize() to parse the squareSize parameter.
parseSquareSize() calls the library method Integer.parseInt(), which parses a
string and returns an integer.
 Integer.parseInt() throws an exception whenever its argument is invalid.
 Therefore, parseSquareSize() catches exceptions, rather than allowing the applet
to fail on bad input.
 The applet calls parseColor() to parse the color parameter into a Color value.
parseColor() does a series of string comparisons to match the parameter value to
the name of a predefined color.
Specifying Applet Parameters
The following is an example of an HTML file with a CheckerApplet embedded in it.
The HTML file specifies both parameters to the applet by means of the <param> tag.
<html>
<title>Checkerboard Applet</title>
<hr>
<applet code="CheckerApplet.class" width="480" height="320">
<param name="color" value="blue">
<param name="squaresize" value="30">
</applet>
<hr>
</html>
Application Conversion to Applets
It is easy to convert a graphical Java application (that is, an application that uses the
AWT and that you can start with the java program launcher) into an applet that you can
embed in a web page.
Here are the specific steps for converting an application to an applet.
 Make an HTML page with the appropriate tag to load the applet code.
 Supply a subclass of the JApplet class. Make this class public. Otherwise, the
applet cannot be loaded.
 Eliminate the main method in the application. Do not construct a frame window
for the application. Your application will be displayed inside the browser.

43

Visit & Downloaded from : www.LearnEngineering.in


Visit & Downloaded from : www.LearnEngineering.in

 Move any initialization code from the frame window constructor to the init
method of the applet. You don't need to explicitly construct the applet object.the
browser instantiates it for you and calls the init method.
 Remove the call to setSize; for applets, sizing is done with the width and height
parameters in the HTML file.
 Remove the call to setDefaultCloseOperation. An applet cannot be closed; it
terminates when the browser exits.
 If the application calls setTitle, eliminate the call to the method. Applets cannot
have title bars. (You can, of course, title the web page itself, using the HTML title
tag.)
 Don't call setVisible(true). The applet is displayed automatically.
Event Handling
Applets inherit a group of event-handling methods from the Container class. The
Container class defines several methods, such as process KeyEvent and process
MouseEvent, for handling particular types of events, and then one catch-all method
called process Event.
In order to react an event, an applet must override the appropriate event-specific method.
import java.awt.event.MouseListener;
import java.awt.event.MouseEvent;
import java.applet.Applet;
import java.awt.Graphics;
public class ExampleEventHandling extends Applet implements MouseListener {
StringBuffer strBuffer;
public void init() {
addMouseListener(this);
strBuffer = new StringBuffer();
addItem("initializing the apple ");
}
public void start() {
addItem("starting the applet ");
}
public void stop() {
addItem("stopping the applet ");
}
public void destroy() {
addItem("unloading the applet");
}
void addItem(String word) {
System.out.println(word);
strBuffer.append(word);

44

Visit & Downloaded from : www.LearnEngineering.in


Visit & Downloaded from : www.LearnEngineering.in

repaint();
}
public void paint(Graphics g) {
//Draw a Rectangle around the applet's display area.
g.drawRect(0, 0, getWidth() - 1, getHeight() - 1);
//display the string inside the rectangle.
g.drawString(strBuffer.toString(), 10, 20);
}
public void mouseEntered(MouseEvent event) {
}
public void mouseExited(MouseEvent event) {
}
public void mousePressed(MouseEvent event) {
}
public void mouseReleased(MouseEvent event) {
}
public void mouseClicked(MouseEvent event) {
addItem("mouse clicked! ");
}
}
Now, let us call this applet as follows:
<html>
<title>Event Handling</title>
<hr>
<applet code="ExampleEventHandling.class"
width="300" height="300">
</applet>
<hr>
</html>
Initially, the applet will display "initializing the applet. Starting the applet." Then once
you click inside the rectangle "mouse clicked" will be displayed as well.

45

Visit & Downloaded from : www.LearnEngineering.in


Visit & Downloaded from : www.LearnEngineering.in

UNIT II
WEBSITES BASICS, HTML 5, CSS 3, WEB 2.0
Part-A (2marks)
1. What is XHTML?
XHTML stands for "Extensible HyperText Markup Language".
It was developed by the World Wide Web Consortium (W3C) and is now a W3C
Recommendation.
XHTML is a reformulation of HTML 4 in XML 1.0.
This means that the benefits provided by XML will be available to XHTML.
2. How is XHTML different from HTML?
• XHTML is case-sensitive, HTML is not. All tags and attributes must be lowercase in
XHTML.
• XHTML, being XML, must be well-formed. Every element must have an end tag, or
use the self-closing tag syntax. HTML allows some end tags and even some start tags to
be omitted.
• If an XML parser encounters a well-formedness error, it must abort. An SGML or
HTML parser is expected to try to salvage what it can and keep going.
• All attributes must have a value in XHTML. HTML allows some attributes (e.g.,
selected) to be minimised.
• All attribute values must be surrounded by double or single quotes. HTML allows
quotes to be omitted if the value contains only alphanumeric characters.
• The comment syntax is more limited in XHTML, but that's rarely an issue for most
designers/developers.
3. What is the need for DOCTYPE declaration?
 The DOCTYPE declaration serves two purposes: it tells a validator against which
DTD the document claims conformance, and it is used by browsers to determine
the rendering mode to use.
 Browsers that support XHTML use the 'strict standards' rendering mode for
XHTML documents, provided that they are served as such.
4.Why we use XHTML?
We use XHTML because of some important reasons those are given below:
• XHTML can run on all new browsers.
• It is a combination of HTML and XML so, it support many important features of them.
• XHTML also gives us facility to write well formed document.
• XHTML has facility to extend. We perform this task with use of extra modules to do
things without pages where as this facility not provided by HTML.
5.What are the rules essential for XHTML Syntax?
Rule1: Write attribute names only in lower case letters.

46

Visit & Downloaded from : www.LearnEngineering.in


Visit & Downloaded from : www.LearnEngineering.in

Rule2: Assigned attribute values must be quoted.


Rule3: Attribute minimization must be prohibited.
Rule4: In XHTML name attribute is replaced by id attribute.
Rule5: In XHTML DTD must set mandatory elements.
6.How you define DTD in XHTML?
DTD: Its stand for Document Type Declaration. It specifies the syntax of web page in
SGML. We use DTD on SGML applications like: HTML, XML etc.
In XHTML we can say that DTD is an computer readable language which is used to
allow syntax of XHTML.
In XHTML we use These three DTD's,
1.STRICT
2.TRANSITIONAL
3.FRAMESET
7. What are Cascading Style Sheets (CSS)?
CSS allows document authors to specify the presentation of elements on a web page
(fonts, spacing, margins etc.) separately from the structure of the document (section
header, body, links etc.). It is used to give same look and feel to the displayed text and
background elements.
8. List down the ways of including style information in a document.
1. Linked Styles -Style information is read from a separate .css file that is specified in
the tag
2. Embedded Styles -Style information is defined in the document head using the tags.
3. Inline Styles -Style information is placed inside an HTML tag and applies to all
content between that tag and it companion closing tag.
9. What is the precedence in CSS to avoid conflicting styles?
• The precedence order is author > user > user agent.
• The styles defined by child element take more precedence than styles defined by parent
element.
10. What are Text Flow and Box Model in CSS?
Text Model allows to move an element to one side of the screen ant the other content in
the document flows around the floated element.
Box Model draws a virtual box around each element. The properties of the box can be
adjusted to control the amount of padding inside the element and the margins outside the
element.
11. Difference between Internet and Intranet.
Intranet Internet

Localized Network. Worldwide Network

47

Visit & Downloaded from : www.LearnEngineering.in


Visit & Downloaded from : www.LearnEngineering.in

Doesn't have access to Intranet Have access to Internet.

More Expensive Less Expensive

More Safe Less Safe

More Reliability Less Reliability

12. How does RIA different from traditional web applications?(May/Jun2016)


RIA (Rich Internet Applications) are a special breed of web applications where the user
interface has much richer functionality than what the first and second generation web
applications
13. What is dynamic positioning?
We can change an element‟s style dynamically. Most HTML elements have a style object
as a property. Suppose an element‟s CSS position property is declared to be either
absolute or relative. Then we can move it by manipulating any of the top, left, right, or
bottom CSS properties of its style object. This is dynamic positioning
14. State the difference between absolute and relative positioning.
Absolute positioning
• An element which is positioned absolute does not obtain any space in the document.
This means that it does not leave an empty space after being positioned.
• To position an element absolutely, the position property is set as absolute. You can
subsequently use the properties left, right, top, and bottom to place the box.
Relative positioning
• To position an element relatively, the property position is set as relative. The difference
between absolute and relative positioning is how the position is being calculated.
• The position for an element which is relatively positioned is calculated from the original
position in the document. That means that you move the element to the right, to the left,
up or down. This way, the element still obtains a space in the document after it is
positioned.
15. Define HTML.
HTML is expanded as HyperText Markup Language. It is a simple page description
language, which enables document creation for the web.
PART –B
1. Explain about Rich Internet Applications in detail (May / June 2016)
Rich Internet Applications
 RIA (Rich Internet Applications) are a special breed of web applications where the
user interface has much richer functionality than what the first and second generation
web applications.

48

Visit & Downloaded from : www.LearnEngineering.in


Visit & Downloaded from : www.LearnEngineering.in

 They look and feel more like desktop applications. RIA user interfaces are
typically developed using HTML5 + JavaScript + CSS3, Flex (Flash), JavaFX, GWT,
Dart or some other RIA tool.
 The richer GUI client of RIA user interfaces also results in a somewhat different
internal architecture and design of the web applications.
 RIA user interfaces and their back ends are typically more cleanly separated than
for first and second generation web applications. This makes the RIA GUI more
independent of the server side, and also makes it easier for GUI and server developers
to work in parallel.
First Generation Web Applications
 First generation web applications were page oriented. We would include all GUI
logic and application logic inside the same web page.
 The web page would be a script which was executed by the web server, when
requested by the browser.
 GUI logic and application logic were mixed up inside the same page script. Here
is an illustration of this architecture and design

 Being page oriented every action the application allowed was typically embedded
in its own web page script.
 Each script was like a separate transaction which executed the application logic,
and generated the GUI to be sent back to the browser after the application logic
was executed.
 The GUI was pretty dumb. The browser showed a page.
 When the user clicked something in the page, the browser was typically redirected
to a new page (script).
 First generation web page technologies include Servlets (Java), JSP (JavaServer
Pages), ASP, PHP and CGI scripts in Perl etc.
 GUI logic and application logic was interleaved, making it hard to locate either
one when we needed to make changes to either the GUI or application logic.
 Code reuse was low, because the code was spread over a large amount of web
page scripts.

49

Visit & Downloaded from : www.LearnEngineering.in


Visit & Downloaded from : www.LearnEngineering.in

 GUI state (like pressed down buttons) which had to be maintained across multiple
pages, had to be kept either in the session data on the server, or be sent along to
each page and back to the browser again.
 If we wanted to change the programming language of the web page scripts (like
from PHP to Java Server Pages (JSP)), that would often require a complete rewrite
of the web application. It was a nightmare.
Second Generation Web Applications
 In second generation web applications developers found ways to separate the GUI
logic from the application logic on the server.
 Web applications also became more object oriented than they had been when the
code was spread over multiple pages.
 Often, web page scripts were used for the GUI logic, and real classes and objects
were used for the application logic.

 Frameworks were developed to help make second generation web applications


easier to develop. Examples of such frameworks are ASP.NET (.NET), Struts +
Struts 2 (Java), Spring MVC (Java), JSF (JavaServer Faces), Wicket (Java)
Tapestry (Java) and many others.
 In the Java community two types of framework designs emerged.
 Second generation web applications were easier to develop than first generation
web applications, but they still had some problems.

50

Visit & Downloaded from : www.LearnEngineering.in


Visit & Downloaded from : www.LearnEngineering.in

 Despite the better separation of GUI and application logic, the two domains still
often got intertwined in each other. Also, since the GUI logic was written in the
same language as the application logic, changing the programming language
meant rewriting the whole application again.
 Additionally, due to the limits of second generation web application technologies,
the GUIs developed were often more primitive than what people were used to
from desktop applications.
RIA Web Applications
 RIA (Rich Internet Applications) web applications are the third generation of web
applications.
 RIA web applications were first and foremost known for having a user interface
that looked much closer to desktop applications.
 To achieve these more advanced user interfaces, RIA technologies are typically
executed in the browser using either JavaScript, Flash, JavaFX or Silverlight.

 As we can see, the GUI logic is now moved from the web server to the browser.
 This complete split from the server logic has some positive and negative
consequences for the design and architecture of the application.
 First of all, the GUIs can become much more advanced with RIA technologies.
That by itself is an advantage.
 Second, because the GUI logic is executed in the browser, the CPU time needed to
generate the GUI is lifted off the server, freeing up more CPU cycles for executing
application logic.
 Third, GUI state can be kept in the browser, thus further cleaning up the server
side of RIA web applications.
 Fourth, the GUI logic completely separated from the application logic, it becomes
easier to develop reusable GUI components, which can be reused no matter what
server side programming language is used for the application logic.
 Fifth, RIA technologies typically communicate with the web server by exchanging
data, not GUI code (HTML, CSS and JavaScript). The data exchange is typically
XML sent via HTTP, or JSON sent via HTTP. This changes the server side from
being "pages" to being "services" that perform some part of the application logic
(create user, login, store task etc.).

51

Visit & Downloaded from : www.LearnEngineering.in


Visit & Downloaded from : www.LearnEngineering.in

 Sixth, the GUI and application logic on the server typically communicate via
HTTP + JSON, or HTTP + XML, the GUI is 100% independent of programming
language that is used on the server. The GUI logic's interface to the server is just
HTTP calls.
 Seventh, GUI logic and application logic are completely separated, and the only
interface between them is HTTP + JSON / XML, the GUI and application logic
can also be developed independently of each other. The application logic
developer can implement the services and test them independently of the GUI.
 Eighth, because the back end just consists of services that send and receive data, it
is much easier add a different type of client in the future, if needed. For instance,
we might want to add a native mobile iOS or Android application client, which
also interacts with your back end services.
 Ninth, the back end now consist of simple services receiving and sending data, our
web application is naturally prepared for the "open application" trend, where web
applications can be accessed both via a GUI and via an API (in case your users
need to write a program to interact with your web application).
 Tenth, the GUI and back end services only exchange data, the traffic load is often
smaller than if the back end had to send both the data and HTML, CSS and
JavaScript.

 The complete split of GUI logic from application logic sometimes means that the
GUI logic is implemented using a different programming language than the
application logic.
 GUI logic might be implemented in JavaScript, ActionScript (Flash) or Dart, and
the application logic in Java, C# or PHP.
 Java developers can use Google Web Toolkit (GWT) to program JavaScript GUIs
using Java.
 The new RIA technologies mean that the developer team must master more
technologies.

52

Visit & Downloaded from : www.LearnEngineering.in


Visit & Downloaded from : www.LearnEngineering.in

RIA Technologies
Here is a list of a few well-known RIA technologies:
 HTML5 + CSS3 + JavaScript + JavaScript frameworks
o jQuery
o jQuery Mobile
o AngularJS
o Sencha EXT-JS
o SmartClient
o D3
o Dart
 GWT (Google Web Toolkit)
 JavaFX
 Flex (Flash)
 Silverlight
Silverlight
Silverlight is a powerful development tool for creating engaging, interactive user
experiences for Web and mobile applications. Silverlight is a free plug-in, powered by
the .NET framework and compatible with multiple browsers, devices and operating
systems, bringing a new level of interactivity wherever the Web works.
JavaFx
JavaFX (is) replacing Swing as the new client UI library for Java” which is why it makes
sense as Java developers that we start taking JavaFx seriously and start embracing it as
the best way to build applications in Java.
Main features of JavaFx
 New and improved interface tools that way beyond our standard buttons,
checkboxes, etc. (Think bar and pie charts and cool things you can find using
JQuery like date-pickers, accordion panes, tabbed panes etc.). This includes new
media player and web rendering controls.
 A new „language‟ called FXML, which like HTML is used only to define the
interface of an application, keeping it completely separate from the code logic.
 An outstanding application called „Scene Builder‟ which can be integrated into
NetBeans and Eclipse to allow you to create and generate FXML documents using
a drag-and-drop design interface .
 A new powerful way to control the design of your application with CSS-like
syntax and precision.
 An integrated library for graphics (both 2D and 3D) as well as animation tools that
rival Flash, JQuery and CSS animations

53

Visit & Downloaded from : www.LearnEngineering.in


Visit & Downloaded from : www.LearnEngineering.in

 Mobile platform development tools. There is an open-source project


called JavaFx ports that helps bridge the path to mobile application development
with JavaFx
Flex
Flex is a highly productive, open source application framework for building and
maintaining expressive web applications that deploy consistently on all major browsers,
desktops, and devices. It provides a modern, standards-based language and programming
model that supports common design patterns suitable for developers from many
backgrounds.
Enterprise-class programming model
Use constructs like strong typing, inheritance, and interfaces to program more efficiently.
Extensive mobile and traditional components help speed development. Flex applications
can access device capabilities such as GPS, accelerometer, camera, and local database.
Cross-platform and native experience
Create applications that run consistently across Android™, BlackBerry® Tablet OS, and
iOS devices, as well as inside the browser and on traditional desktop computers.
Although cross platform, with Flex we get an uncompromised native experience on each
platform.
End-to-end tooling
Build Flex applications more easily using Adobe® Flash® Builder® software, an
enterprise-class Eclipse™ based IDE. Productivity features include on-device debugging
and mobile simulators for testing across screen sizes and resolutions.

1 (ii). What are Collaboration Tools and explain it.

 Collaboration is commonly defined as working with another individual or group in


order to achieve something.
 We can define a collaboration tool: a technology tool that can be used to help
people work together to achieve a common goal or objective.
 A collaboration tool can be something as simple as a whiteboard in a conference
room that people gather around and use to brainstorm and solve problems.
 Another collaboration tool is a conference call, during which multiple people get
together over the phone to hash out an issue.

How Do Collaboration Tools Work?

Collaboration tools can route work through a process, distribute pieces and tasks to
involved parties, and help to coordinate activities.

Consider this example: A business wants to draft a contract to sell a product to a


customer. Sales and marketing provide documentation about quantities, types and maybe

54

Visit & Downloaded from : www.LearnEngineering.in


Visit & Downloaded from : www.LearnEngineering.in

the specifications. The accounting department specifies the terms for purchase, and the
legal department inserts language in the contract to protect both parties in the transaction.
Everyone uses a collaborative software platform to work together to get the job done,
regardless of where they're located.

Collaboration tools allow people to work on a common project wherever they are.

1(iii). Difference between website and web server


 A Web server is a technology that, using the client/server model and the
World Wide Web's Hypertext Transfer Protocol (HTTP), serves the files
that form Web pages to Web users (whose computers contain HTTP clients
that forward their requests).
 Every computer on the Internet that contains a Web site must have a Web
server program. Two leading Web servers are Apache, the most widely-
installed Web server, and Microsoft's Internet Information Server ( IIS ).
 A website, also written as web site, or simply site, is a set of related web
pages typically served from a single web domain.
1(iv). Explain about the internet and intranet in detail.
Internet technologies
 Internet refers to network of networks. In this network each computer is
recognized by a globally unique address known as IP address.
 A special computer DNS (Domain Name Server) is used to give name to
the IP Address so that user can locate a computer by a name.
Internet
Internet is defined as an Information super Highway, to access information over the web.
However, It can be defined in many ways as follows:
 Internet is a world-wide global system of interconnected computer networks.
 Internet uses the standard Internet Protocol (TCP/IP).
 Every computer in internet is identified by a unique IP address.
 IP Address is a unique set of numbers (such as 110.22.33.114) which identifies a
computer location.

55

Visit & Downloaded from : www.LearnEngineering.in


Visit & Downloaded from : www.LearnEngineering.in

 A special computer DNS (Domain Name Server) is used to give name to the IP
address so that user can locate a computer by a name.
 For example, a DNS server will resolve a name to a particular IP address to
uniquely identify the computer on which this website is hosted.
 Internet is accessible to every user all over the world.
Advantages
Internet covers almost every aspect of life, one can think of.
 Internet allows us to communicate with the people sitting at remote locations.
There are various apps available on the wed that uses Internet as a medium for
communication. One can find various social networking sites such as:
o Facebook
o Twitter
o Yahoo
o Google+
o Flickr
o Orkut
 One can surf for any kind of information over the internet. Information regarding
various topics such as Technology, Health & Science, Social Studies,
Geographical Information, Information Technology, Products etc can be surfed
with help of a search engine.
 Apart from communication and source of information, internet also serves a
medium for entertainment. Following are the various modes for entertainment
over internet.
o Online Television
o Online Games
o Songs
o Videos
o Social Networking Apps
 Internet allows us to use many services like:
o Internet Banking
o Matrimonial Services
o Online Shopping
o Online Ticket Booking
o Online Bill Payment
o Data Sharing
o E-mail
 Internet provides concept of electronic commerce, that allows the business deals
to be conducted on electronic systems

56

Visit & Downloaded from : www.LearnEngineering.in


Visit & Downloaded from : www.LearnEngineering.in

Disadvantages
Internet has proved to be a powerful source of information in almost every field, yet
there exists many disadvantages discussed below:
 There are always chances to lose personal information such as name, address,
credit card number. Therefore, one should be very careful while sharing such
information.
 Another disadvantage is the Spamming. Spamming corresponds to the unwanted
e-mails in bulk. These e-mails serve no purpose and lead to obstruction of entire
system.
 Virus can easily be spread to the computers connected to internet. Such virus
attacks may cause your system to crash or your important data may get deleted.
 There are various websites that do not provide the authenticated information. This
leads to misconception among many people.
Intranet
Intranet is defined as private network of computers within an organization with its own
server and firewall. Moreover we can define Intranet as:
 Intranet is system in which multiple PCs are networked to be connected to each
other. PCs in intranet are not available to the world outside of the intranet.
 Usually each company or organization has their own Intranet network and
members/employees of that company can access the computers in their intranet.
 Every computer in internet is identified by a unique IP address.
 Each computer in Intranet is also identified by a IP Address, which is unique
among the computers in that Intranet.

Benefits
Intranet is very efficient and reliable network system for any organization. It is
beneficial in every aspect such as collaboration, cost-effectiveness, security, productivity
and much more.
Communication
Intranet offers easy and cheap communication within an organization. Employees can
communicate using chat, e-mail or blogs.

57

Visit & Downloaded from : www.LearnEngineering.in


Visit & Downloaded from : www.LearnEngineering.in

Time Saving
Information on Intranet is shared in real time.
Collaboration
Information is distributed among the employees as according to requirement and it can
be accessed by the authorized users, resulting in enhanced teamwork.
Platform Independency
Intranet can connect computers and other devices with different architecture.
Cost Effective
Employees can see the data and other documents using browser rather than printing
them and distributing duplicate copies among the employees, which certainly decreases
the cost.
Workforce Productivity
Data is available at every time and can be accessed using company workstation. This
helps the employees work faster.
Business Management
It is also possible to deploy applications that support business operations.
Security
Since information shared on intranet can only be accessed within an organization,
therefore there is almost no chance of being theft.
Specific Users
Intranet targets only specific users within an organization therefore, once can exactly
know whom he is interacting.
Immediate Updates
Any changes made to information are reflected immediately to all the users.
Issues
Apart from several benefits of Intranet, there also exist some issues.
Applications
Intranet applications are same as that of Internet applications. Intranet applications are
also accessed through a web browser. The only difference is that, Intranet applications
reside on local server while Internet applications reside on remote server. Here, we've
discussed some of these applications:
Document publication applications
Document publication applications allow publishing documents such as manuals,
software guide, employee profits etc without use of paper.
Electronic resources applications
It offers electronic resources such as software applications, templates and tools, to be
shared across the network.
Interactive Communication applications

58

Visit & Downloaded from : www.LearnEngineering.in


Visit & Downloaded from : www.LearnEngineering.in

Like on internet, we have e-mail and chat like applications for Intranet, hence offering
an interactive communication among employees.
Support for Internet Applications
Intranet offers an environment to deploy and test applications before placing them on
Internet.
Internet vs. Intranet
Apart from similarities there are some differences between the two. Following are the
differences between Internet and Intranet:

Intranet Internet

Localized Network. Worldwide Network

Doesn't have access to Intranet Have access to Internet.

More Expensive Less Expensive

More Safe Less Safe

More Reliability Less Reliability

1(v) Discuss on webserver.


Web server" can refer to hardware or software, or both of them working together.
1. On the hardware side, a web server is a computer that stores a website's
component files (e.g. HTML documents, images, CSS stylesheets, and JavaScript
files) and delivers them to the end-user's device. It is connected to the Internet and
can be accessed through a domain name like mozilla.org.
2. On the software side, a web server includes several parts that control how web
users access hosted files, at minimum an HTTP server. An HTTP server is a piece
of software that understands URLs (web addresses) and HTTP (the protocol our
browser uses to view webpages).
At the most basic level, whenever a browser needs a file hosted on a web server, the
browser requests the file via HTTP. When the request reaches the correct web server
(hardware), the HTTP server (software) sends the requested document back, also through
HTTP.
To publish a website, we need either a static or a dynamic web server.
A static web server, or stack, consists of a computer (hardware) with an HTTP server
(software). We call it "static" because the server sends its hosted files "as-is" to our
browser.
A dynamic web server consists of a static web server plus extra software, most
commonly an application server and a database. We call it "dynamic" because the
application server updates the hosted files before sending them to your browser via the
HTTP server.
59

Visit & Downloaded from : www.LearnEngineering.in


Visit & Downloaded from : www.LearnEngineering.in

2. Describe in detail about HTML.


HTML
HTML5 is cooperation between the World Wide Web Consortium (W3C) and the Web
Hypertext Application Technology Working Group (WHATWG).
The new standard incorporates features like video playback and drag-and-drop that have
been previously dependent on third-party browser plug-ins such as Adobe Flash,
Microsoft Silverlight, and Google Gears.
New Features
HTML5 introduces a number of new elements and attributes that helps in building a
modern website. Following are great features introduced in HTML5.
 New Semantic Elements − These are like <header>, <footer>, and <section>.
 Forms 2.0 − Improvements to HTML web forms where new attributes have been
introduced for <input> tag.
 Persistent Local Storage − To achieve without resorting to third-party plugins.
 WebSocket − A a next-generation bidirectional communication technology for
web applications.
 Server-Sent Events − HTML5 introduces events which flow from web server to
the web browsers and they are called Server-Sent Events (SSE).
 Canvas − This supports a two-dimensional drawing surface that we can program
with JavaScript.
 Audio & Video − We can embed audio or video on our web pages without
resorting to third-party plugins.
 Geolocation − Now visitors can choose to share their physical location with our
web application.
 Microdata − This lets us create our own vocabularies beyond HTML5 and extend
our web pages with custom semantics.
 Drag and drop − Drag and drop the items from one location to another location
on a the same webpage.
But HTML5 is coming with lots of flexibility and would support the followings −
 Uppercase tag names.
 Quotes are optional for attributes.
 Attribute values are optional.
 Closing empty elements are optional.
The DOCTYPE
DOCTYPEs in older versions of HTML were longer because the HTML language was
SGML based and therefore required a reference to a DTD.
Simple syntax to specify DOCTYPE as follows −

60

Visit & Downloaded from : www.LearnEngineering.in


Visit & Downloaded from : www.LearnEngineering.in

<!DOCTYPE html>
Character Encoding
Simple syntax to specify Character Encoding as follows −
<meta charset="UTF-8">
The <script> tag
It's common practice to add a type attribute with a value of "text/javascript" to script
elements as follows −
<script type="text/javascript" src="scriptfile.js"></script>
HTML 5 removes extra information required and we can use simply following syntax −
<script src="scriptfile.js"></script>
The <link> tag
So far we were writing <link> as follows −
<link rel="stylesheet" type="text/css" href="stylefile.css">
HTML 5 removes extra information required and we can use simply following syntax −
<link rel="stylesheet" href="stylefile.css">
HTML5 Elements
HTML5 elements are marked up using start tags and end tags. Tags are delimited using
angle brackets with the tag name in between.
The difference between start tags and end tags is that the latter includes a slash before
the tag name.
Following is the example of an HTML5 element −
<p>...</p>
HTML5 tag names are case insensitive and may be written in all uppercase or mixed
case, although the most common convention is to stick with lower case.
Most of the elements contain some content like <p>...</p> contains a paragraph. For
example, br, hr, link and meta etc.
HTML5 Attributes
 Elements may contain attributes that are used to set various properties of an
element.
 Some attributes are defined globally and can be used on any element, while
others are defined for specific elements only.
 All attributes have a name and a value and look like as shown below in the
example.
The example of attributes which illustrates how to mark up a div element with an
attribute named class using a value of "example" −
<div class="example">...</div>
 Attributes may only be specified within start tags and must never be used in end
tags.

61

Visit & Downloaded from : www.LearnEngineering.in


Visit & Downloaded from : www.LearnEngineering.in

 HTML5 attributes are case insensitive and may be written in all upper case or
mixed case, although the most common convention is to stick with lower case.
HTML5 Document
The following tags have been introduced for better structure −
 section − This tag represents a generic document or application section. It can be
used together with h1-h6 to indicate the document structure.
 article − This tag represents an independent piece of content of a document, such
as a blog entry or newspaper article.
 aside − This tag represents a piece of content that is only slightly related to the
rest of the page.
 header − This tag represents the header of a section.
 footer − This tag represents a footer for a section and can contain information
about the author, copyright information, etc.
 nav − This tag represents a section of the document intended for navigation.
 dialog − This tag can be used to mark up a conversation.
 figure − This tag can be used to associate a caption together with some embedded
content, such as a graphic or video.
The markup for an HTML 5 document would look like the following −
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>...</title>
</head>
<body>
<header>...</header>
<nav>...</nav>
<article>
<section>
...
</section>
</article>
<aside>...</aside>
<figure>...</figure>
<footer>...</footer>
</body>
</html>
Example

62

Visit & Downloaded from : www.LearnEngineering.in


Visit & Downloaded from : www.LearnEngineering.in

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>...</title>
</head>
<body>
<header role="banner">
<h1>HTML5 Document Structure Example</h1>
<p>This page should be tried in safari, chrome or Mozila.</p>
</header>
<nav>
<ul>
<li><a href="#">HTML Tutorial</a></li>
<li><a href="#">CSS Tutorial</a></li>
<li><a href="#">JavaScript Tutorial</a></li>
</ul>
</nav>
<article>
<section>
<p>Once article can have multiple sections</p>
</section>
</article>
<aside>
<p>This is aside part of the web page</p>
</aside>
<figure align="right">
<img src="/html5/images/logo.png" alt="SCAD" width="200" height="100">
</figure>
<footer>
<p>Created by <a href="#">SCAD Group</a></p>
</footer>
</body>
</html>

This will produce following result −


HTML5 Document Structure Example
This page should be tried in safari, chrome or Mozila.
 HTML Tutorial

63

Visit & Downloaded from : www.LearnEngineering.in


Visit & Downloaded from : www.LearnEngineering.in

 CSS Tutorial
 JavaScript Tutorial
Once article can have multiple sections
This is aside part of the web page
Created by SCAD Group
 Some attributes are defined globally and can be used on any element, while
others are defined for specific elements only. All attributes have a name and a
value and look like as shown below in the example.
Following is the example of an HTML5 attributes which illustrates how to mark up a div
element with an attribute named class using a value of "example" −
<div class="example">...</div>
 Attributes may only be specified within start tags and must never be used in end
tags.
 HTML5 attributes are case insensitive and may be written in all uppercase or
mixed case, although the most common convention is to stick with lowercase.
Standard Attributes
The attributes listed below are supported by almost all the HTML 5 tags.

Attribute Options Function

accesskey User Defined Specifies a keyboard shortcut to access an


element.

Align right, left, center Horizontally aligns tags

background URL Places an background image behind an element

Bgcolor numeric, hexidecimal, Places a background color behind an element


RGB values

Class User Defined Classifies an element for use with Cascading


Style Sheets.

contenteditable true, false Specifies if the user can edit the element's content
or not.

contextmenu Menu id Specifies the context menu for an element.

data-XXXX User Defined Custom attributes. Authors of a HTML document


can define their own attributes. Must start with
"data-".

draggable true,false, auto Specifies whether or not a user is allowed to drag


an element.

Height Numeric Value Specifies the height of tables, images, or table


cells.

64

Visit & Downloaded from : www.LearnEngineering.in


Visit & Downloaded from : www.LearnEngineering.in

Hidden hidden Specifies whether element should be visible or


not.

Id User Defined Names an element for use with Cascading Style


Sheets.

Item List of elements Used to group elements.

itemprop List of items Used to group items.

spellcheck true, false Specifies if the element must have it's spelling or
grammar checked.

Style CSS Style sheet Specifies an inline style for an element.

Subject User define id Specifies the element's corresponding item.

tabindex Tab number Specifies the tab order of an element.

Title User Defined "Pop-up" title for your elements.

Valign top, middle, bottom Vertically aligns tags within an HTML element.

Width Numeric Value Specifies the width of tables, images, or table


cells.

The <input> element in HTML5


Apart from the above mentioned attributes, we can use several new values for
the type attribute are as follows

Type Description

datetime A date and time (year, month, day, hour, minute, second, fractions of a
second) encoded according to ISO 8601 with the time zone set to UTC.

datetime- A date and time (year, month, day, hour, minute, second, fractions of a
local second) encoded according to ISO 8601, with no time zone information.

date A date (year, month, day) encoded according to ISO 8601.

month A date consisting of a year and a month encoded according to ISO 8601.

week A date consisting of a year and a week number encoded according to ISO
8601.

time A time (hour, minute, seconds, fractional seconds) encoded according to ISO
8601.

number This accepts only numerical value. The step attribute specifies the precision,
defaulting to 1.

range The range type is used for input fields that should contain a value from a

65

Visit & Downloaded from : www.LearnEngineering.in


Visit & Downloaded from : www.LearnEngineering.in

range of numbers.

email This accepts only email value. This type is used for input fields that should
contain an e-mail address. If you try to submit a simple text, it forces to enter
only email address in [email protected] format.

url This accepts only URL value. This type is used for input fields that should
contain a URL address. If you try to submit a simple text, it forces to enter
only URL address either in http://www.example.com format or in
http://example.com format.

Image Size - Width and Height


We can use the style attribute to specify the width and height of an image. The values are
specified in pixels (use px after the value):
Example
<img src="html5.gif" alt="HTML5 Icon" style="width:128px;height:128px;">
The <output> element
The element <output> which is used to represent the result of different types of output,
such as output written by a script.

We can use the for attribute to specify a relationship between the output element and
other elements in the document that affected the calculation (for example, as inputs or
parameters). The value of the for attribute is a space-separated list of IDs of other
elements.

<!DOCTYPE HTML>

<html>

<head>

<script type="text/javascript">

function showResult()

x = document.forms["myform"]["newinput"].value;

document.forms["myform"]["result"].value=x;

</script>

</head>

<body>

66

Visit & Downloaded from : www.LearnEngineering.in


Visit & Downloaded from : www.LearnEngineering.in

<form action="/cgi-bin/html5.cgi" method="get" name="myform">

Enter a value : <input type="text" name="newinput" />

<input type="button" value="Result" onclick="showResult();" />

<output name="result"></output>

</form>

</body>

</html>

The placeholder attribute


Another new attribute called placeholder is used in HTML5. This attribute on <input>
and <textarea> elements provides a hint to the user of what can be entered in the field.
The place holder text must not contain carriage returns or line-feeds.
Here is the simple syntax for placeholder attribute −
<input type="text" name="search" placeholder="search the web"/>
This attribute is supported by latest versions of Mozilla, Safari and Chrome browsers
only.
<!DOCTYPE HTML>
<html>
<body>
<form action="/cgi-bin/html5.cgi" method="get">
Enter email : <input type="email" name="newinput"
placeholder = "[email protected]"/>
<input type="submit" value="submit" />
</form>
</body>
</html>
The autofocus attribute
This is a simple one-step pattern, easily programmed in JavaScript at the time of
document load, automatically focus one particular form field.
HTML5 introduced a new attribute called autofocus which would be used as follows −
<input type="text" name="search" autofocus/>
<!DOCTYPE HTML>
<html>
<body>
<form action="/cgi-bin/html5.cgi" method="get">
Enter email : <input type="text" name="newinput" autofocus/>

67

Visit & Downloaded from : www.LearnEngineering.in


Visit & Downloaded from : www.LearnEngineering.in

<p>Try to submit using Submit button</p>


<input type="submit" value="submit" />
</form>
</body>
</html>
The required attribute
Now we are not in need to have javascript for client side validations like empty text box
would never be submitted because HTML5 introduced a new attribute
called required which would be used as follows and would insist to have a value

<input type="text" name="search" required/>


<!DOCTYPE HTML>
<html>
<body>
<form action="/cgi-bin/html5.cgi" method="get">
Enter email : <input type="text" name="newinput" required/>
<p>Try to submit using Submit button</p>
<input type="submit" value="submit" />
</form>
</body>
</html>

2b. Explain in detail about CSS. (Nov/ Dec 2015)

Styling HTML with CSS


CSS stands for Cascading Style Sheets
Styling can be added to HTML elements in 3 ways:
 Inline - using a style attribute in HTML elements
 Internal - using a <style> element in the HTML <head> section
 External - using one or more external CSS files
The most common way to add styling, is to keep the styles in separate CSS files. But, in
this tutorial, we use internal styling, because it is easier to demonstrate, and easier for us.
Inline Styling (Inline CSS)
Inline styling is used to apply a unique style to a single HTML element. Inline styling
uses the style attribute. This example changes the text color of the <h1> element to blue:
Example
<h1 style="color:blue;">This is a Blue Heading</h1>
Internal Styling (Internal CSS)
Internal styling is used to define a style for one HTML page.

68

Visit & Downloaded from : www.LearnEngineering.in


Visit & Downloaded from : www.LearnEngineering.in

Internal styling is defined in the <head> section of an HTML page, within a <style>
element:
Example
<!DOCTYPE html>
<html>
<head>
<style>
body {background-color:lightgrey;}
h1 {color:blue;}
p {color:green;}
</style>
</head>
<body>
<h1>This is a heading</h1>
<p>This is a paragraph.</p>
</body>
</html>
External Styling (External CSS)
An external style sheet is used to define the style for many pages.
With an external style sheet, we can change the look of an entire web site by changing
one file!
To use an external style sheet, add a link to it in the <head> section of the HTML page:
Example
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<h1>This is a heading</h1>
<p>This is a paragraph.</p>
</body>
</html>
An external style sheet can be written in any text editor. The file should not contain any
html tags. The style sheet file must be saved with a .css extension.
Here is how the "styles.css" looks:
body {
background-color: lightgrey;

69

Visit & Downloaded from : www.LearnEngineering.in


Visit & Downloaded from : www.LearnEngineering.in

}
h1 {
color: blue;
}
p{
color:green;
}
CSS Fonts
 The CSS color property defines the text color to be used for the HTML element.
 The CSS font-family property defines the font to be used for the HTML element.
 The CSS font-size property defines the text size to be used for the HTML element.
Example
<!DOCTYPE html>
<html>
<head>
<style>
h1 {
color: blue;
font-family: verdana;
font-size: 300%;
}
p {
color: red;
font-family: courier;
font-size: 160%;
}
</style>
</head>
<body>
<h1>This is a heading</h1>
<p>This is a paragraph.</p>
</body>
</html>
The CSS Box Model
Every HTML element has a box around it, even if we cannot see it.
The CSS border property defines a visible border around an HTML element:

70

Visit & Downloaded from : www.LearnEngineering.in


Visit & Downloaded from : www.LearnEngineering.in

Example
p{
border: 1px solid black;
}
The CSS padding property defines a padding (space) inside the border:
Example
p{
border: 1px solid black;
padding: 10px;
}
The CSS margin property defines a margin (space) outside the border:
Example
p{
border: 1px solid black;
padding: 10px;
margin: 30px;
}
The id Attribute
To define a special style for one special element, first add an id attribute to the element:
<p id="p01">I am different</p>
then define a style for the element with the specific id:
Example
#p01 {
color: blue;
}
The class Attribute
To define a style for a special type (class) of elements, add a class attribute to the
element:
<p class="error">I am different</p>
We can also define a different style for elements with the specific class:
Example
p.error {
color: red;
}
3. Explain about XHTML in detail.
OR
Discuss on XHTML (Nov/Dec 2015)

71

Visit & Downloaded from : www.LearnEngineering.in


Visit & Downloaded from : www.LearnEngineering.in

What Is XHTML
 XHTML stands for EXtensible HyperText Markup Language
 XHTML is almost identical to HTML
 XHTML is stricter than HTML
 XHTML is HTML defined as an XML application
 XHTML is supported by all major browsers
Need of XHTML
Many pages on the internet contain "bad" HTML.
This HTML code works fine in most browsers (even if it does not follow the HTML
rules):
<html>
<head>
<title>This is bad HTML</title>
<body>
<h1>Bad HTML
<p>This is a paragraph
</body>
</html>
XML is a markup language where documents must be marked up correctly (be "well-
formed"). By combining the strengths of HTML and XML, XHTML was developed.
XHTML is HTML redesigned as XML.
The Most Important Differences from HTML
Document Structure
 XHTML DOCTYPE is mandatory
 The xmlns attribute in <html> is mandatory
 <html>, <head>, <title>, and <body> are mandatory
XHTML Elements
 XHTML elements must be properly nested
 XHTML elements must always be closed
 XHTML elements must be in lowercase
 XHTML documents must have one root element
XHTML Attributes
 Attribute names must be in lower case
 Attribute values must be quoted
 Attribute minimization is forbidden
<!DOCTYPE ....> Is Mandatory
An XHTML document must have an XHTML DOCTYPE declaration.

72

Visit & Downloaded from : www.LearnEngineering.in


Visit & Downloaded from : www.LearnEngineering.in

The <html>, <head>, <title>, and <body> elements must also be present, and the xmlns
attribute in <html> must specify the xml namespace for the document.
This example shows an XHTML document with a minimum of required tags:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Title of document</title>
</head>
<body>
some content
</body>
</html>
 XHTML Elements Must Be Properly Nested
In HTML, some elements can be improperly nested within each other, like this:
<b><i>This text is bold and italic</b></i>
In XHTML, all elements must be properly nested within each other, like this:
<b><i>This text is bold and italic</i></b>
 XHTML Elements Must Always Be Closed
Example
<p>This is a paragraph</p>
<p>This is another paragraph</p>
 Empty Elements Must Also Be Closed
Example
A break: <br />
A horizontal rule: <hr />
An image: <img src="happy.gif" alt="Happy face" />
 XHTML Elements Must Be In Lower Case
Example
<body>
<p>This is a paragraph</p>
</body>
 XHTML Attribute Names Must Be In Lower Case
<table width="100%">
 Attribute Values Must Be Quoted
<table width="100%">
 Attribute Minimization Is Forbidden
<input type="checkbox" name="vehicle" value="car" checked="checked" />

73

Visit & Downloaded from : www.LearnEngineering.in


Visit & Downloaded from : www.LearnEngineering.in

<input type="text" name="lastname" disabled="disabled" />


How to Convert from HTML to XHTML
1. Add an XHTML <!DOCTYPE> to the first line of every page
2. Add an xmlns attribute to the html element of every page
3. Change all element names to lowercase
4. Close all empty elements
5. Change all attribute names to lowercase
6. Quote all attribute values
7. HTML documents are made up by HTML elements.
4(i). Explain about the HTML Elements in detail
HTML elements are written with a start tag, with an end tag, with the content in
between:
<tagname>content</tagname>
The HTML element is everything from the start tag to the end tag:
<p>My first HTML paragraph.</p>

Start tag Element content End tag

<h1> My First Heading </h1>

<p> My first paragraph. </p>

<br>

Nested HTML Elements


HTML elements can be nested (elements can contain elements).
All HTML documents consist of nested HTML elements.
Example
<!DOCTYPE html>
<html>
<body>
<h1>My First Heading</h1>
<p>My first paragraph.</p>
</body>
</html>
Explanation
The <html> element defines the whole document.
It has a start tag <html> and an end tag </html>.
The element content is another HTML element (the <body> element).
<html>
<body>

74

Visit & Downloaded from : www.LearnEngineering.in


Visit & Downloaded from : www.LearnEngineering.in

<h1>My First Heading</h1>


<p>My first paragraph.</p>
</body>
</html>
 The <body> element defines the document body.
 It has a start tag <body> and an end tag </body>.
 The element content is two other HTML elements (<h1> and <p>).
<body>
<h1>My First Heading</h1>
<p>My first paragraph.</p>
</body>
 The <h1> element defines a heading.
 It has a start tag <h1> and an end tag </h1>.
 The element content is: My First Heading.
<h1>My First Heading</h1>
 The <p> element defines a paragraph.
 It has a start tag <p> and an end tag </p>.
 The element content is: My first paragraph.
<p>My first paragraph.</p>
Example
<html>
<body>
<p>This is a paragraph
<p>This is a paragraph
</body>
</html>
Empty HTML Elements
 HTML elements with no content are called empty elements.
 <br> is an empty element without a closing tag (the <br> tag defines a line
break).
 Empty elements can be "closed" in the opening tag like this: <br />.
 HTML5 does not require empty elements to be closed. But if we want
stricter validation, or we need to make your document readable by XML
parsers, you should close all HTML elements.
 HTML Tip: Use Lowercase Tags
 HTML tags are not case sensitive: <P> means the same as <p>.

75

Visit & Downloaded from : www.LearnEngineering.in


Visit & Downloaded from : www.LearnEngineering.in

 The HTML5 standard does not require lowercase tags, but


W3C recommends lowercase in HTML4, and demands lowercase for
stricter document types like XHTML.
HTML Formatting Elements
HTML also defines special elements for defining text with a special meaning.
HTML uses elements like <b> and <i> for formatting output, like bold or italic text.
Formatting elements were designed to display special types of text:
 Bold text
 Important text
 Italic text
 Emphasized text
 Marked text
 Small text
 Deleted text
 Inserted text
 Subscripts
 Superscripts
HTML Bold and Strong Formatting
The HTML <b> element defines bold text, without any extra importance.
Example
<p>This text is normal.</p>
<p><b>This text is bold</b>.</p>
The HTML <strong> element defines strong text, with added semantic "strong"
importance.
Example
<p>This text is normal.</p>
<p><strong>This text is strong</strong>.</p>
HTML Italic and Emphasized Formatting
The HTML <i> element defines italic text, without any extra importance.
Example
<p>This text is normal.</p>
<p><i>This text is italic</i>.</p>
The HTML <em> element defines emphasized text, with added semantic importance.
Example
<p>This text is normal.</p>
<p><em>This text is emphasized</em>.</p>
HTML Small Formatting
The HTML <small> element defines small text:

76

Visit & Downloaded from : www.LearnEngineering.in


Visit & Downloaded from : www.LearnEngineering.in

Example
<h2>HTML <small>Small</small> Formatting</h2>
HTML Marked Formatting
The HTML <mark> element defines marked or highlighted text:
Example
<h2>HTML <mark>Marked</mark> Formatting</h2>HTML Formatting
The HTML <del> element defines deleted (removed) text.
Example
<p>My favorite color is <del>blue</del> red.</p>
HTML Inserted Formatting
The HTML <ins> element defines inserted (added) text.
Example
<p>My favorite <ins>color</ins> is red.</p>
HTML Subscript Formatting
The HTML <sub> element defines subscripted text.
Example
<p>This is <sub>subscripted</sub> text.</p>
HTML Superscript Formatting
The HTML <sup> element defines superscripted text.
Example
<p>This is <sup>superscripted</sup> text.</p>
HTML Text Formatting Elements

Tag Description

<b> Defines bold text

<em> Defines emphasized text

<i> Defines italic text

<small> Defines smaller text

<strong> Defines important text

<sub> Defines subscripted text

<sup> Defines superscripted text

<ins> Defines inserted text

<del> Defines deleted text

<mark> Defines marked/highlighted text

77

Visit & Downloaded from : www.LearnEngineering.in


Visit & Downloaded from : www.LearnEngineering.in

4(ii). Explain about the links in HTML


HTML Links - Hyperlinks
HTML links are hyperlinks.
A hyperlink is a text or an image you can click on, and jump to another document.
HTML Links - Syntax
In HTML, links are defined with the <a> tag:
<a href="url">link text</a>
Example
<a href="http://www.w3schools.com/html/">Visit our SCAD Group</a>
The href attribute specifies the destination address.
The link text is the visible part.
Local Links
The example above used an absolute URL (A full web address).
A local link (link to the same web site) is specified with a relative URL (without
http://www....).
Example
<a href="html_images.asp">HTML Images</a>
HTML Links - Colors
When we move the mouse over a link, two things will normally happen:
 The mouse arrow will turn into a little hand
 The color of the link element will change
By default, a link will appear like this (in all browsers):
 An unvisited link is underlined and blue
 A visited link is underlined and purple
 An active link is underlined and red
We can change the default colors, by using styles:
Example
<style>
a:link {color:green; background-color:transparent; text-decoration:none}
a:visited {color:pink; background-color:transparent; text-decoration:none}
a:hover {color:red; background-color:transparent; text-decoration:underline}
a:active {color:yellow; background-color:transparent; text-decoration:underline}
</style>
HTML Links - The target Attribute
The target attribute specifies where to open the linked document.
This example will open the linked document in a new browser window or in a new tab:
Example
<a href="http://www.w3schools.com/" target="_blank">Visit W3Schools!</a>

78

Visit & Downloaded from : www.LearnEngineering.in


Visit & Downloaded from : www.LearnEngineering.in

Target Description
Value

_blank Opens the linked document in a new window or tab

_self Opens the linked document in the same frame as it was clicked
(this is default)

_parent Opens the linked document in the parent frame

_top Opens the linked document in the full body of the window

framename Opens the linked document in a named frame

If our webpage is locked in a frame, you can use target="_top" to break out of the frame:
Example
<a href="http://www.w3schools.com/html/" target="_top">HTML5 </a>
HTML Links - Image as Link
It is common to use images as links
Example
<a href="default.asp">
<img src="smiley.gif" alt="HTML tutorial" style="width:42px;height:42px;border:0">
</a>
HTML Links - Create a Bookmark
HTML bookmarks are used to allow readers to jump to specific parts of a Web page.
Bookmarks are practical if the website has long pages.
To make a bookmark, we must first create the bookmark, and then add a link to it.
When the link is clicked, the page will scroll to the location with the bookmark.
Example
First, create a bookmark with the id attribute:
<h2 id="tips">Useful Tips Section</h2>
Then, add a link to the bookmark ("Useful Tips Section"), from within the same page:
<a href="#tips">Visit the Useful Tips Section</a>
Or, add a link to the bookmark ("Useful Tips Section"), from another page:
Example
<a href="html_tips.html#tips">Visit the Useful Tips Section</a>
HTML Images
In HTML, images are defined with the <img> tag.
The <img> tag is empty, it contains attributes only, and does not have a closing tag.
The src attribute specifies the URL (web address) of the image:
<img src="url" alt="some_text">

79

Visit & Downloaded from : www.LearnEngineering.in


Visit & Downloaded from : www.LearnEngineering.in

The alt Attribute


The alt attribute specifies an alternate text for an image, if the image cannot be displayed.
The alt attribute provides alternative information for an image if a user for some reason
cannot view it (because of slow connection, an error in the src attribute, or if the user uses
a screen reader).
If a browser cannot find an image, it will display the alt text:
Example
<img src="wrongname.gif" alt="HTML5 Icon" style="width:128px;height:128px;">
The alt attribute is required. A web page will not validate correctly without it.
HTML Screen Readers
A screen reader is a software program that can read what is displayed on a screen.
Screen readers are useful to people who are blind, visually impaired, or learning disabled.
Image Size - Width and Height
We can use the style attribute to specify the width and height of an image.
The values are specified in pixels (use px after the value):
Example
<img src="html5.gif" alt="HTML5 Icon" style="width:128px;height:128px;">
Alternatively, we can use width and height attributes. Here, the values are specified in
pixels by default:
Example
<img src="html5.gif" alt="HTML5 Icon" width="128" height="128">
It prevents styles sheets from changing the original size of images:
Example
<!DOCTYPE html>
<html>
<head>
<style>
img {
width:100%;
}
</style>
</head>
<body>
<img src="html5.gif" alt="HTML5 Icon" style="width:128px;height:128px;">
<img src="html5.gif" alt="HTML5 Icon" width="128" height="128">
</body>
</html>
Images in Another Folder
If not specified, the browser expects to find the image in the same folder as the web page.

80

Visit & Downloaded from : www.LearnEngineering.in


Visit & Downloaded from : www.LearnEngineering.in

However, it is common to store images in a sub-folder. We must then include the folder
name in the src attribute:
Example
<img src="/images/html5.gif" alt="HTML5 Icon" style="width:128px;height:128px;">
Images on Another Server
Some web sites store their images on image servers.
Actually,we can access images from any web address in the world:
Example
<img src="http://www.w3schools.com/images/w3schools_green.jpg" alt="W3Schools.co
m">
Animated Images
The GIF standard allows animated images:
Example
<img src="programming.gif" alt="Computer Man" style="width:48px;height:48px;">
Using an Image as a Link
To use an image as a link, simply nest the <img> tag inside the <a> tag:
Example
<a href="default.asp">
<img src="smiley.gif" alt="HTML tutorial" style="width:42px;height:42px;border:0;">
</a>
Image Floating
Use the CSS float property to let the image float.
The image can float to the right or to the left of a text:
Example
<p>
<img src="smiley.gif" alt="Smiley face" style="float:right;width:42px;height:42px;">
The image will float to the right of the text.
</p>
<p>
<img src="smiley.gif" alt="Smiley face" style="float:left;width:42px;height:42px;">
The image will float to the left of the text.
</p>
Image Maps
Use the <map> tag to define an image-map. An image-map is an image with clickable
areas. The name attribute of the <map> tag is associated with the <img>'s usemap
attribute and creates a relationship between the image and the map.
The <map> tag contains a number of <area> tags, that defines the clickable areas in the
image-map:
Example

81

Visit & Downloaded from : www.LearnEngineering.in


Visit & Downloaded from : www.LearnEngineering.in

<img src="planets.gif" alt="Planets" usemap="#planetmap" style="width:145px;height:1


26px;">
<map name="planetmap">
<area shape="rect" coords="0,0,82,126" alt="Sun" href="sun.htm">
<area shape="circle" coords="90,58,3" alt="Mercury" href="mercur.htm">
<area shape="circle" coords="124,58,8" alt="Venus" href="venus.htm">
</map>

HTML Image Tags

Tag Description

<img> Defines an image

<map> Defines an image-map

<area> Defines a clickable area inside an image-map

5. Explain about the HTML Tables

In HTML we can create the table in the web page using tag name table. We can add the rows and
columns as per our requirements.
Example
<table style="width:100%">
<tr>
<td>Jill</td>
<td>Smith</td>
<td>50</td>
</tr>
<tr>
<td>Eve</td>
<td>Jackson</td>
<td>94</td>
</tr>
</table>
Explanataion
Tables are defined with the <table> tag.
Tables are divided into table rows with the <tr> tag.
Table rows are divided into table data with the <td> tag.
A table row can also be divided into table headings with the <th> tag.

82

Visit & Downloaded from : www.LearnEngineering.in


Visit & Downloaded from : www.LearnEngineering.in

An HTML Table with a Border Attribute


If we do not specify a border for the table, it will be displayed without borders. A border
can be added using the border attribute:
Example
<table border="1" style="width:100%">
<tr>
<td>Jill</td>
<td>Smith</td>
<td>50</td>
</tr>
<tr>
<td>Eve</td>
<td>Jackson</td>
<td>94</td>
</tr>
</table>
To add borders, use the CSS border property:
Example
table, th, td {
border: 1px solid black;
}
An HTML Table with Collapsed Borders
If we want the borders to collapse into one border, add CSS border-collapse:
Example
table, th, td {
border: 1px solid black;
border-collapse: collapse;
}
An HTML Table with Cell Padding
Cell padding specifies the space between the cell content and its borders. If we do not
specify a padding, the table cells will be displayed without padding. To set the padding,
use the CSS padding property:
Example
table, th, td {
border: 1px solid black;
border-collapse: collapse;
}
th, td {

83

Visit & Downloaded from : www.LearnEngineering.in


Visit & Downloaded from : www.LearnEngineering.in

padding: 15px;
}
HTML Table Headings
Table headings are defined with the <th> tag.
By default, all major browsers display table headings as bold and centered:
Example
<table style="width:100%">
<tr>
<th>Firstname</th>
<th>Lastname</th>
<th>Points</th>
</tr>
<tr>
<td>Eve</td>
<td>Jackson</td>
<td>94</td>
</tr>
</table>
To left-align the table headings, use the CSS text-align property:
Example
th {
text-align: left;
}
An HTML Table with Border Spacing
Border spacing specifies the space between the cells.
To set the border spacing for a table, use the CSS border-spacing property:
Example
table {
border-spacing: 5px;
}
Table Cells that Span Many Columns
To make a cell span more than one column, use the colspan attribute:
Example
<table style="width:100%">
<tr>
<th>Name</th>
<th colspan="2">Telephone</th>
</tr>
<tr>

84

Visit & Downloaded from : www.LearnEngineering.in


Visit & Downloaded from : www.LearnEngineering.in

<td>Bill Gates</td>
<td>555 77 854</td>
<td>555 77 855</td>
</tr>
</table>
Table Cells that Span Many Rows
To make a cell span more than one row, use the rowspan attribute:
Example
<table style="width:100%">
<tr>
<th>Name:</th>
<td>Bill Gates</td>
</tr>
<tr>
<th rowspan="2">Telephone:</th>
<td>555 77 854</td>
</tr>
<tr>
<td>555 77 855</td>
</tr>
</table>
An HTML Table With a Caption
To add a caption to a table, use the <caption> tag:
Example
<table style="width:100%">
<caption>Monthly savings</caption>
<tr>
<th>Month</th>
<th>Savings</th>
</tr>
<tr>
<td>January</td>
<td>$100</td>
</tr>
<tr>
<td>February</td>
<td>$50</td>
</tr>
</table>
85

Visit & Downloaded from : www.LearnEngineering.in


Visit & Downloaded from : www.LearnEngineering.in

A Special Style for One Table


To define a special style for a special table, add an id attribute to the table:
Example
<table id="t01">
<tr>
<th>Firstname</th>
<th>Lastname</th>
<th>Points</th>
</tr>
<tr>
<td>Eve</td>
<td>Jackson</td>
<td>94</td>
</tr>
</table>
Now we can define a special style for this table:
table#t01 {
width: 100%;
background-color: #f1f1c1;
To add more styles:
table#t01 tr:nth-child(even) {
background-color: #eee;
}
table#t01 tr:nth-child(odd) {
background-color: #fff;
}
table#t01 th {
color: white;
background-color: black;
}

HTML Table Tags

Tag Description

<table> Defines a table

<th> Defines a header cell in a table

<tr> Defines a row in a table

86

Visit & Downloaded from : www.LearnEngineering.in


Visit & Downloaded from : www.LearnEngineering.in

<td> Defines a cell in a table

<caption> Defines a table caption

<colgroup> Specifies a group of one or more columns in a table for formatting

<col> Specifies column properties for each column within a <colgroup> element

<thead> Groups the header content in a table

<tbody> Groups the body content in a table

<tfoot> Groups the footer content in a table

87

Visit & Downloaded from : www.LearnEngineering.in


Visit & Downloaded from : www.LearnEngineering.in

UNIT III
CLIENT SIDE AND SERVER SIDE PROGRAMMING
Part – A (2 marks)
1. What are the primitive data types in javascript?
JavaScript supports five primitive data types: number, string, Boolean,
undefined, and null. These types are referred to as primitive types because they are
the basic building blocks from which more complex types can be built. Of the five,
only number, string, and Boolean are real data types in the sense of actually
storing data. Undefined and null are types that arise under special circumstances.
2. Define event programming. Name any 2 of its techniques.(Nov/Dec 2015)
In computer programming, event-driven programming is a programming
paradigm in which the flow of the program is determined by events such as user
actions (mouse clicks, key presses), sensor outputs, or messages from other
programs/threads
3. How to create arrays in Javascript?
 We can declare an array like this Var scripts = new Array();
 We can add elements to this array like this scripts[0] = "PHP";
scripts[1] = "ASP";
scripts[2] = "JavaScript";
scripts[3] = "HTML";
Now our array scripts have 4 elements inside it and we can print or access
them by using their index number. Note that index number starts from 0. To get
the third element of the array we have to use the index number 2. Here is the way
to get the third element of an array. document.write (scripts [2]);
We also can create an array like this
var no_array = new Array(21, 22, 23, 24, 25);
4. Write short notes on JDBC.
JDBC standard is intented for people developing industrial-strength
database applications. JDBC makes java effective for developing enterprise
information system.java.sql is the JDBC package that contains classes &
interfaces that enable a java program to interact with a database.
5. Write short notes on JDBC drivers.
A JDBC driver is basically an implementation of the function calls
specified in the JDBC API for a particular vendor„s RDBMS. Hence, a java
program with JDBC function calls can access any RDBMS that has a JDBC driver
available. A driver manager is used to keep track of all the installed drivers on the
system. The operations of driver manager are getDriver, registerDriver,
deregisterDriver.

88

Visit & Downloaded from : www.LearnEngineering.in


Visit & Downloaded from : www.LearnEngineering.in

6. What is the difference between CGI and servlets?


 Performance is significantly better, servlet execute within the address space
of a web server.
 Servlets are platform independent
 The java security manager on the server enforces a set of restrictions to
protect the resources on a server machine.
 The full functionality of java class libraries is available to a servlet.
7. Define Servlet Life Cycle?
 init( ) method - invoked when the servlet is first loaded into memory
 service( ) - called for each HTTP request (for processing)
 destroy( ) - unloads the servlet from its memory.
8. Write down the methods of servlet interface
 void destroy() –called when the servlet is unloaded.
 ServletConfig getServletConfig() –returns a ServletConfig object that
contains any initialization parameters.
 String get ServletInfo() – returns a string describing the servlet.
 void init(ServletConfig sc) throws ServletException –called when the
servlet is initialized. Initialization parameters for servlet can be obtained
from sc. An unavailable exception should be thrown if the servlet is not
initialized.
 Void Service(ServletRequest req, ServletResponse res) throws
ServletException, IOException - Called to process a request from a client. The
request from the client can be read from req. response to the client can be
written to res. An exception is generated if a servlet or IO problem occurs.
9. Define event bubbling.
Suppose, there is an element present inside another element. Then during
the event handling, if the event which is present in the inner element is handled
and then the event of the outer element is handled. This process of event handling
is called event bubbling
10. What is meant by cookies? List out its types. (Nov/Dec 2015)
A cookie is a small piece of information that is persisted between the multiple
client requests. A cookie has a name, a single value, and optional attributes such as
a comment, path and domain qualifiers, a maximum age, and a version number.
There are 2 types of cookies in servlets.
 Non-persistent cookie
 Persistent cookie
Non-persistent cookie

89

Visit & Downloaded from : www.LearnEngineering.in


Visit & Downloaded from : www.LearnEngineering.in

It is valid for single session only. It is removed each time when user closes
the browser.
Persistent cookie
It is valid for multiple session . It is not removed each time when user
closes the browser. It is removed only if user logout or signout.
Part-B (16 marks)
1. Using HTMl and JSP, design a scientific calculator [Nov/Dec 15]
Step-1: Creating the HTML file
Here, we are just creating a bunch of buttons and getting its values when they are
clicked.
<html>
<body>
<div id=”big_wrapper”>
<h1 id=”heading”>SIMPLE SCIENTIFIC CALCULATOR</h1>
<div id=”form_wrapper”>
<form id=”formone” name=”calc”>
<input id=”display” type=”text” name=”display” value=” ” disabled
contenteditable=”false” >
<br>
<input class=”button number” type=”button” value=”1” onClick=
”calc.display.value+=1”>
<input class=”button number” type=”button” value=”2” onClick=
”calc.display.value+=2”>
<input class=”button number” type=”button” value=”3” onClick=
”calc.display.value+=3”>
<input class=”button three” type=”button” value=”C” onClick=
”Resetfunction(this.form)”>
<input class=”button three” type=”button” value=”<-” onClick=
”backspace(this.form)”>
<input class=”button three” type=”button” value=”=” onClick=
”evaluation(this.form)”>
<br>
<input class=”button number” type=”button” value=”4” onClick=
”calc.display.value+=4”>
<input class=”button number” type=”button” value=”5” onClick=
”calc.display.value+=5”>
<input class=”button number” type=”button” value=”6” onClick=
”calc.display.value+=6”>

90

Visit & Downloaded from : www.LearnEngineering.in


Visit & Downloaded from : www.LearnEngineering.in

<input class=”button opps” type=”button” value=”-” onClick=


”calc.display.value+=‟-„”>
<input class=”button opps” type=”button” value=”%” onClick=
”calc.display.value+=‟%‟”>
<input class=”button” type=”button” value=”cos” onClick=”cos_function()”>
<br>
<input class=”button number” type=”button” value=”7” onClick=
”calc.display.value+=7”>
<input class=”button number” type=”button” value=”8” onClick=
”calc.display.value+=8”>
<input class=”button number” type=”button” value=”9” onClick=
”calc.display.value+=9”>
<input class=”button opps” type=”button” value=”*” onClick=
”calc.display.value+=‟*‟”>
<input class=”button” type=”button” value=”n!” onClick=”fact_function()”>
<input class=”button” type=”button” value=”sin” onClick=”sin_function()”>
<br>
<input class=”button opps” type=”button” value=”.”
onClick=”calc.display.value+=‟.‟”>
<input class=”button number” type=”button” value=”0”
onClick=”calc.display.value+=0”>
<input class=”button opps” type=”button” value=”,”
onClick=”calc.display.value+=‟,‟”>
<input class=”button opps” type=”button” value=”+”
onClick=”calc.display.value+=‟+‟”>
<input class=”button opps” type=”button” value=”/” onClick=
”calc.display.value+=‟/‟”>
<input class=”button” type=”button” value=”tan” onClick=”tan_function()”>
<br>
<input class=”button” type=”button” value=”E” onClick=
”calc.display.value+=2.718”>
<input class=”button” type=”button” value=”pi” onClick=
”calc.display.value+=3.141”>
<input class=”button” type=”button” value=”x^y” onClick=”power_function()”>
<input class=”button” type=”button” value=”(” onClick=”openpara(this.value)”>
<input class=”button” type=”button” value=”)” onClick=”closepara(this.value)”>
<input class=”button” type=”button” value=”log” onClick=”log_function()”>
<br>

91

Visit & Downloaded from : www.LearnEngineering.in


Visit & Downloaded from : www.LearnEngineering.in

<input class=”button” type=”button” value=”sqrt” onClick=”sqrt_function()”>


<input class=”button” type=”button” value=”LN2”
onClick=”calc.display.value+=0.693”>
<input class=”button” type=”button” value=”LN10”
onClick=”calc.display.value+=2.302”>
<input class=”button” type=”button” value=”log2E”
onClick=”calc.display.value+=1.442”>
<input class=”button” type=”button” value=”log10E”
onClick=”calc.display.value+=0.434”>
<input class=”button” type=”button” value=”EXP” onClick=”exp_function”>
</form>
</div>
</div>
</body>
At this point we should get an output like this,

Step-2: JavaScript to carry on the operations


As we can see there is a global variable called flag set to 0 initially. This variable checks
the number of opening parenthesis and the closing ones to avoid errors due to
parenthesis. Each time an opening bracket is clicked, the flag is incremented and each
time a closing bracket is clicked, it is decremented so that finally its value will become 0.
We are making use of the javaScript‟s inbuilt functions wherever possible
like cos(), sin(),tan(), sqrt(), log(), etc,. These functions belong to the Math object and
hence we access them using it like this “Math.cos()”. And in the display of the calculator,
when any of these operations is clicked, it displays the function along with the Math
object like this “Math.function()”.
<script>
flag = 0;
function openpara(val)
{
calc.display.value+=val;
flag+=1;
}

92

Visit & Downloaded from : www.LearnEngineering.in


Visit & Downloaded from : www.LearnEngineering.in

function closepara(valval)
{
calc.display.value+=valval;
flag-=1;
}
function backspace(calc)
{
var size = calc.display.value.length;
calc.display.value=calc.display.value.substring(0,size-1);
}
function Resetfunction(calc)
{
calc.display.value=” “;
flag=0;
}
function cos_function()
{
flag+=1;
calc.display.value+=‟Math.cos(„;
}
function sin_function()
{
flag+=1;
calc.display.value+=‟Math.sin(„;
}
function tan_function()
{
flag+=1;
calc.display.value+=‟Math.tan(„;
}
function log_function()
{
flag+=1;
calc.display.value+=‟Math.log(„;
}
function sqrt_function()
{
flag+=1;

93

Visit & Downloaded from : www.LearnEngineering.in


Visit & Downloaded from : www.LearnEngineering.in

calc.display.value+=‟Math.sqrt(„;
}
function exp_function()
{
flag+=1;
calc.display.value+=‟Math.exp(„;
}
function fact(x)
{
factvar=1;
for (i=1;i<=x;i++)
{
factvar=factvar*i;
}
return factvar;
}
function fact_function(x)
{
flag+=1;
calc.display.value+=‟fact(„;
}
function power_function(x)
{
flag+=1;
calc.display.value+=‟Math.pow(x,y‟;
}
function evaluation(calc) {
n = calc.display.value;
var size = calc.display.value.length;
var lastchar = calc.display.value.charAt(size)
if(isNaN(lastchar) && lastchar!=”)” && lastchar!=”!”)
{calc.display.value=”syntax error”;}
else if(flag!=0){calc.display.value=”error:paranthesis”;}
else {
result=eval(n);
calc.display.value=result;}
}
</script>

94

Visit & Downloaded from : www.LearnEngineering.in


Visit & Downloaded from : www.LearnEngineering.in

Step-3: Making the calculator look pretty


Now that the important part of our calculator is over, it is all up to css to make it look
beautiful. You can also toss in some of your own ideas to make it look even better.
<style>
*{ padding:0;
margin:0;
}
body {text-align:center;
background-color:#637ACB;
}
#heading {margin-top:30px;}
#form_wrapper {width:405px;
height:450px;
margin:30px auto auto 420px;
background-color:#000;
text-align:center;
border-radius:10px;
border-right:2px groove #333;
box-shadow:4px 4px 2px #666666;}
#formone{padding-top:10px;}
#display {width:380px;
height:40px;
font-size:18px;
color:black;
margin:4px;
border:2px inset black;
border-bottom:1px inset #FFF;
border-right:1px inset #FFF;
background-color:#D5F192;}
.button {width:60px;
height:60px;
margin:1px;}
.number {font-size:16px;
font-weight:bold;}
.opps {font-size:18px;}
.three {font-weight:bold;
background-color:#FBB9A8;

95

Visit & Downloaded from : www.LearnEngineering.in


Visit & Downloaded from : www.LearnEngineering.in

}
.three:hover{background-color:#F66;}
</style>

2. Explain DOM Model [Nov / Dec 15]


(or)
Explain the logical structure of documents and the way a document is accessed and
manipulated.
 The Document Object Model (DOM) is a programming API for HTML and XML
documents.
 It defines the logical structure of documents and the way a document is accessed
and manipulated.
 In the DOM specification, the term "document" is used in the broad sense -
increasingly, XML is being used as a way of representing many different kinds of
information that may be stored in diverse systems, and much of this would
traditionally be seen as data rather than as documents.
 Nevertheless, XML presents this data as documents, and the DOM may be used to
manage this data.
 With the Document Object Model, programmers can create and build documents,
navigate their structure, and add, modify, or delete elements and content.
 Anything found in an HTML or XML document can be accessed, changed,
deleted, or added using the Document Object Model, with a few exceptions - in
particular, the DOM interfaces for the internal subset and external subset have not
yet been specified.
 The Document Object Model is a programming API for documents.
 The object model itself closely resembles the structure of the documents it models.
For instance, consider this table, taken from an HTML document:
<TABLE>
<ROWS>
<TR>
<TD>Shady Grove</TD>

96

Visit & Downloaded from : www.LearnEngineering.in


Visit & Downloaded from : www.LearnEngineering.in

<TD>Aeolian</TD>
</TR>
<TR>
<TD>Over the River, Charlie</TD>
<TD>Dorian</TD>
</TR>
</ROWS>
</TABLE>

The Document Object Model represents this table like this:

 In the Document Object Model, documents have a logical structure which is very
much like a tree; to be more precise, it is like a "forest" or "grove" which can
contain more than one tree.
 The object model specifies the logical model for the programming interface, and
this logical model may be implemented in any way that a particular
implementation finds convenient.
 In this specification, we use the term structure model to describe the tree-like
representation of a document; we specifically avoid terms like "tree" or "grove" in
order to avoid implying a particular implementation. One important property of
DOM structure models is structural isomorphism: if any two Document Object
Model implementations are used to create a representation of the same document,
they will create the same structure model, with precisely the same objects and
relationships.
 The name "Document Object Model" was chosen because it is an "object model"
is used in the traditional object oriented design sense: documents are modeled
using objects, and the model encompasses not only the structure of a document,
but also the behavior of a document and the objects of which it is composed. As an
object model, the Document Object Model identifies:
 The interfaces and objects used to represent and manipulate a document
 The semantics of these interfaces and objects - including both behavior and
attributes.

97

Visit & Downloaded from : www.LearnEngineering.in


Visit & Downloaded from : www.LearnEngineering.in

 The structure of SGML documents has traditionally been represented by an


abstract data model, not by an object model. In an abstract data model, the model
is centered around the data.
 In object oriented programming languages, the data itself is encapsulated in
objects which hide the data, protecting it from direct external manipulation.
 The functions associated with these objects determine how the objects may be
manipulated, and they are part of the object model.
 The Document Object Model currently consists of two parts, DOM Core and
DOM HTML.
 The DOM Core represents the functionality used for XML documents, and also
serves as the basis for DOM HTML.
 All DOM implementations must support the interfaces listed as "fundamental" in
the Core specification; in addition, XML implementations must support the
interfaces listed as "extended" in the Core specification.
 The Level 1 DOM HTML specification defines additional functionality needed for
HTML documents.
3. Explain about database connectivity. [Nov/ Dec 15]
(or)
Explain how the database is connected using JBDC.
 Java Database Connectivity (JDBC) is an application programming interface
(API) for the programming language Java, which defines how a client may access
adatabase.
 It is part of the Java Standard Edition platform, from Oracle Corporation.
There are 5 steps to connect any java application with the database in java using JDBC.
They are as follows:
 Register the driver class
 Creating connection
 Creating statement
 Executing queries
 Closing connection

1) Register the driver class


The forName() method of Class class is used to register the driver class. This method
is used to dynamically load the driver class.
Syntax of forName() method
public static void forName(String className)throws ClassNotFoundException
Example to register the OracleDriver class
Class.forName("oracle.jdbc.driver.OracleDriver");

98

Visit & Downloaded from : www.LearnEngineering.in


Visit & Downloaded from : www.LearnEngineering.in

2)Create the connection object


The getConnection() method of DriverManager class is used to establish connection with
the database.
Syntax of getConnection() method
public static Connection getConnection(String url)throws SQLException
public static Connection getConnection(String url,String name,String password)
throws SQLException
Example to establish connection with the Oracle database
Connection con=DriverManager.getConnection(
"jdbc:oracle:thin:@localhost:1521:xe","system","password");
3) Create the Statement object
The createStatement() method of Connection interface is used to create statement. The
object of statement is responsible to execute queries with the database.
Syntax of createStatement() method
public Statement createStatement()throws SQLException
Example to create the statement object
Statement stmt=con.createStatement();
4) Execute the query
The executeQuery() method of Statement interface is used to execute queries to the
database. This method returns the object of ResultSet that can be used to get all the
records of a table.
Syntax of executeQuery() method
public ResultSet executeQuery(String sql)throws SQLException
Example to execute query
ResultSet rs=stmt.executeQuery("select * from emp");
while(rs.next()){
System.out.println(rs.getInt(1)+" "+rs.getString(2));
}
5) Close the connection object
By closing connection object statement and ResultSet will be closed automatically. The
close() method of Connection interface is used to close the connection.
Syntax of close() method
public void close()throws SQLException
Example to close connection
con.close();

99

Visit & Downloaded from : www.LearnEngineering.in


Visit & Downloaded from : www.LearnEngineering.in

4 (i). How do you write Javascript? What are its advantages and limitations?
JavaScript is a lightweight, interpreted programming language. It is designed for creating
network-centric applications. It is complimentary to and integrated with Java. JavaScript
is very easy to implement because it is integrated with HTML. It is open and cross-
platform.
Sample Code

<html>
<body>
<script language="javascript" type="text/javascript">
<!--
document.write("Hello World!")
//-->
</script>
</body>
</html>

CLIENT-SIDE JAVASCRIPT
 Client-side JavaScript is the most common form of the language.
 The script should be included in or referenced by an HTML document for the
code to be interpreted by the browser.
 It means that a web page need not be a static HTML, but can include programs
that interact with the user, control the browser, and dynamically create HTML
content.
 The JavaScript client-side mechanism provides many advantages over traditional
CGI server-side scripts. For example, you might use JavaScript to check if the
user has entered a valid e-mail address in a form field.
 The JavaScript code is executed when the user submits the form, and only if all
the entries are valid, they would be submitted to the Web Server.
JavaScript can be used to trap user-initiated events such as button clicks, link navigation,
and other actions that the user initiates explicitly or implicitly.
ADVANTAGES OF JAVASCRIPT
The merits of using JavaScript are −
 Less server interaction − We can validate user input before sending the page off
to the server. This saves server traffic, which means less load on your server.
 Immediate feedback to the visitors − They don't have to wait for a page reload
to see if they have forgotten to enter something.
 Increased interactivity − We can create interfaces that react when the user
hovers over them with a mouse or activates them via the keyboard.

100

Visit & Downloaded from : www.LearnEngineering.in


Visit & Downloaded from : www.LearnEngineering.in

 Richer interfaces − We can use JavaScript to include such items as drag-and-


drop components and sliders to give a Rich Interface to your site visitors.
LIMITATIONS OF JAVASCRIPT
We cannot treat JavaScript as a full-fledged programming language. It lacks the
following important features −
 Client-side JavaScript does not allow the reading or writing of files. This has been
kept for security reason.
 JavaScript cannot be used for networking applications because there is no such
support available.
 JavaScript doesn't have any multithreading or multiprocessor capabilities.
 A simple syntax of your JavaScript will appear as follows.
<script ...>
JavaScript code
</script>
JavaScript can be implemented using JavaScript statements that are placed within
the <script>... </script> HTML tags in a web page.
 We can place the <script> tags, containing your JavaScript, anywhere within you
web page, but it is normally recommended that you should keep it within
the <head> tags.
 The <script> tag alerts the browser program to start interpreting all the text
between these tags as a script. The script tag takes two important attributes.
 Language − This attribute specifies what scripting language you are using.
Typically, its value will be javascript. Although recent versions of HTML (and
XHTML, its successor) have phased out the use of this attribute.
 Type − This attribute is what is now recommended to indicate the scripting
language in use and its value should be set to "text/javascript".
So our JavaScript segment will look like −
<script language="javascript" type="text/javascript">
JavaScript code
</script>
<html>
<body>
<script language="javascript" type="text/javascript">
<!--
document.write("Hello World!")
//-->
</script>
</body>

101

Visit & Downloaded from : www.LearnEngineering.in


Visit & Downloaded from : www.LearnEngineering.in

</html>
This code will produce the following result −
Hello World!
4(ii). Explain in detail about Date object method in Javascript.
The Date object is used to work with dates and times.
Date objects are created with new Date().
There are four ways of instantiating a date:
var d = new Date();
var d = new Date(milliseconds);
var d = new Date(dateString);
var d = new Date(year, month, day, hours, minutes, seconds, milliseconds);

DATE OBJECT PROPERTIES

Property Description

constructor Returns the function that created the Date object's prototype

prototype Allows you to add properties and methods to an object

DATE OBJECT METHODS

Method Description

getDate() Returns the day of the month (from 1-31)

getDay() Returns the day of the week (from 0-6)

getFullYear() Returns the year

getHours() Returns the hour (from 0-23)

getMilliseconds() Returns the milliseconds (from 0-999)

getMinutes() Returns the minutes (from 0-59)

getMonth() Returns the month (from 0-11)

getSeconds() Returns the seconds (from 0-59)

getTime() Returns the number of milliseconds since midnight Jan 1 1970, and
a specified date

getTimezoneOffset() Returns the time difference between UTC time and local time, in
minutes

102

Visit & Downloaded from : www.LearnEngineering.in


Visit & Downloaded from : www.LearnEngineering.in

getUTCDate() Returns the day of the month, according to universal time (from 1-
31)

getUTCDay() Returns the day of the week, according to universal time (from 0-
6)

getUTCFullYear() Returns the year, according to universal time

getUTCHours() Returns the hour, according to universal time (from 0-23)

getUTCMilliseconds() Returns the milliseconds, according to universal time (from 0-999)

getUTCMinutes() Returns the minutes, according to universal time (from 0-59)

getUTCMonth() Returns the month, according to universal time (from 0-11)

getUTCSeconds() Returns the seconds, according to universal time (from 0-59)

4(iii) Explain in detail about Regular Expression in Javascript.

REGEXP OBJECT
A regular expression is an object that describes a pattern of characters.
Regular expressions are used to perform pattern-matching and "search-and-replace"
functions on text.
Syntax
/pattern/modifiers;
Example
var patt = /w3schools/i
Example explained:
 /w3schools/i is a regular expression.
 w3schools is a pattern (to be used in a search).
 i is a modifier (modifies the search to be case-insensitive).
MODIFIERS
Modifiers are used to perform case-insensitive and global searches:

Modifier Description

i Perform case-insensitive matching

g Perform a global match (find all matches rather than


stopping after the first match)

m Perform multiline matching

103

Visit & Downloaded from : www.LearnEngineering.in


Visit & Downloaded from : www.LearnEngineering.in

BRACKETS
Brackets are used to find a range of characters:

Expression Description

[abc] Find any character between the brackets

[^abc] Find any character NOT between the brackets

[0-9] Find any digit between the brackets

[^0-9] Find any digit NOT between the brackets

(x|y) Find any of the alternatives specified

METACHARACTERS
Metacharacters are characters with a special meaning:

Metacharacter Description

. Find a single character, except newline or line


terminator

\w Find a word character

\W Find a non-word character

\d Find a digit

\D Find a non-digit character

\s Find a whitespace character

\S Find a non-whitespace character

\b Find a match at the beginning/end of a word

\B Find a match not at the beginning/end of a word

\0 Find a NUL character

\n Find a new line character

\f Find a form feed character

\r Find a carriage return character

\t Find a tab character

104

Visit & Downloaded from : www.LearnEngineering.in


Visit & Downloaded from : www.LearnEngineering.in

\v Find a vertical tab character

\xxx Find the character specified by an octal number xxx

\xdd Find the character specified by a hexadecimal


number dd

\uxxxx Find the Unicode character specified by a


hexadecimal number xxxx

QUANTIFIERS

Quantifier Description

n+ Matches any string that contains at least one n

n* Matches any string that contains zero or more


occurrences of n

n? Matches any string that contains zero or one


occurrences of n

n{X} Matches any string that contains a sequence of X n's

n{X,Y} Matches any string that contains a sequence of X to


Y n's

n{X,} Matches any string that contains a sequence of at


least X n's

n$ Matches any string with n at the end of it

^n Matches any string with n at the beginning of it

?=n Matches any string that is followed by a specific


string n

?!n Matches any string that is not followed by a specific


string n

REGEXP OBJECT PROPERTIES

Property Description

constructor Returns the function that created the RegExp object's


prototype

global Checks whether the "g" modifier is set

105

Visit & Downloaded from : www.LearnEngineering.in


Visit & Downloaded from : www.LearnEngineering.in

ignoreCase Checks whether the "i" modifier is set

lastIndex Specifies the index at which to start the next match

multiline Checks whether the "m" modifier is set

source Returns the text of the RegExp pattern

REGEXP OBJECT METHODS

Method Description

compile() Compiles a regular expression

exec() Tests for a match in a string. Returns the first match

test() Tests for a match in a string. Returns true or false

toString() Returns the string value of the regular expression

4(iv). Explain Event handling in Javascript


 JavaScript's interaction with HTML is handled through events that occur when the
user or the browser manipulates a page.When the page loads, it is called an event.
 When the user clicks a button, that click too is an event. Other examples include
events like pressing any key, closing a window, resizing a window, etc.
 Developers can use these events to execute JavaScript coded responses, which
cause buttons to close windows, messages to be displayed to users, data to be
validated, and virtually any other type of response imaginable.
 Events are a part of the Document Object Model (DOM) Level 3 and every
HTML element contains a set of events which can trigger JavaScript Code.
ONCLICK EVENT TYPE
This is the most frequently used event type which occurs when a user clicks the left
button of his mouse. We can put our validation, warning etc., against this event type.
EXAMPLE

<html>
<head>

<script type="text/javascript">
<!--
function sayHello() {
alert("Hello World")
}
//-->
106

Visit & Downloaded from : www.LearnEngineering.in


Visit & Downloaded from : www.LearnEngineering.in

</script>

</head>

<body>
<p>Click the following button and see result</p>

<form>
<input type="button" onclick="sayHello()" value="Say Hello" />
</form>

</body>
</html>

OUTPUT
onsubmit Event type
onsubmit is an event that occurs when you try to submit a form. You can put your form
validation against this event type.
EXAMPLE
The following example shows how to use onsubmit. Here we are calling
avalidate() function before submitting a form data to the webserver.
Ifvalidate() function returns true, the form will be submitted, otherwise it will not
submit the data.
<html>
<head>

<script type="text/javascript">
<!--
function validation() {
all validation goes here
.........
return either true or false
}
//-->
</script>

</head>
<body>

<form method="POST" action="t.cgi" onsubmit="return validate()">

107

Visit & Downloaded from : www.LearnEngineering.in


Visit & Downloaded from : www.LearnEngineering.in

.......
<input type="submit" value="Submit" />
</form>

</body>
</html>
ONMOUSEOVER AND ONMOUSEOUT
These two event types will help us create nice effects with images or even with text as
well. The onmouseover event triggers when we bring your mouse over any element and
the onmouseout triggers when our move your mouse out from that element. Try the
following example.

<html>
<head>

<script type="text/javascript">
<!--
function over() {
document.write ("Mouse Over");
}

function out() {
document.write ("Mouse Out");
}

//-->
</script>

</head>
<body>
<p>Bring your mouse inside the division to see the result:</p>

<div onmouseover="over()" onmouseout="out()">


<h2> This is inside the division </h2>
</div>

</body>
</html>

108

Visit & Downloaded from : www.LearnEngineering.in


Visit & Downloaded from : www.LearnEngineering.in

HTML 5 STANDARD EVENTS


The standard HTML events are listed here.

Attribute Description

Offline Triggers when the document goes offline

Onabort Triggers on an abort event

onafterprint Triggers after the document is printed

onbeforeonload Triggers before the document loads

onbeforeprint Triggers before the document is printed

onblur Triggers when the window loses focus

oncanplay Triggers when media can start play, but might has to stop for
buffering

oncanplaythrough Triggers when media can be played to the end, without


stopping for buffering

onchange Triggers when an element changes

onclick Triggers on a mouse click

oncontextmenu Triggers when a context menu is triggered

ondblclick Triggers on a mouse double-click

ondrag Triggers when an element is dragged

ondragend Triggers at the end of a drag operation

ondragenter Triggers when an element has been dragged to a valid drop


target

ondragleave Triggers when an element is being dragged over a valid drop


target

ondragover Triggers at the start of a drag operation

ondragstart Triggers at the start of a drag operation

ondrop Triggers when dragged element is being dropped

ondurationchange Triggers when the length of the media is changed

109

Visit & Downloaded from : www.LearnEngineering.in


Visit & Downloaded from : www.LearnEngineering.in

onemptied Triggers when a media resource element suddenly becomes


empty.

onended Triggers when media has reach the end

onerror Triggers when an error occur

onfocus Triggers when the window gets focus

8. Explain in detail about Java servlet architecture and its life cycle.
 Java Servlets are programs that run on a Web or Application server and act as a
middle layer between a request coming from a Web browser or other HTTP client
and databases or applications on the HTTP server.
 Using Servlets, you can collect input from users through web page forms, present
records from a database or another source, and create web pages dynamically.
 Java Servlets often serve the same purpose as programs implemented using the
Common Gateway Interface (CGI). But Servlets offer several advantages in
comparison with the CGI.
 Performance is significantly better.
 Servlets execute within the address space of a Web server. It is not necessary to
create a separate process to handle each client request.
 Servlets are platform-independent because they are written in Java.
 Java security manager on the server enforces a set of restrictions to protect the
resources on a server machine. So servlets are trusted.
 The full functionality of the Java class libraries is available to a servlet. It can
communicate with applets, databases, or other software via the sockets and RMI
mechanisms that you have seen already.
SERVLETS ARCHITECTURE
Following diagram shows the position of Servelts in a Web Application.

servlet life-cycle scenario

110

Visit & Downloaded from : www.LearnEngineering.in


Visit & Downloaded from : www.LearnEngineering.in

 First the HTTP requests coming to the server are delegated to the servlet
container.
 The servlet container loads the servlet before invoking the service() method.
 Then the servlet container handles multiple requests by spawning multiple
threads, each thread executing the service() method of a single instance of the
servlet.

SERVLETS TASKS
Servlets perform the following major tasks:
 Read the explicit data sent by the clients (browsers). This includes an HTML form
on a Web page or it could also come from an applet or a custom HTTP client
program.
 Read the implicit HTTP request data sent by the clients (browsers). This includes
cookies, media types and compression schemes the browser understands, and so
forth.
 Process the data and generate the results. This process may require talking to a
database, executing an RMI or CORBA call, invoking a Web service, or
computing the response directly.
 Send the explicit data (i.e., the document) to the clients (browsers). This
document can be sent in a variety of formats, including text (HTML or XML),
binary (GIF images), Excel, etc.
 Send the implicit HTTP response to the clients (browsers). This includes telling
the browsers or other clients what type of document is being returned (e.g.,
HTML), setting cookies and caching parameters, and other such tasks.
SERVLETS PACKAGES
 Java Servlets are Java classes run by a web server that has an interpreter that
supports the Java Servlet specification.
 Servlets can be created using the javax.servlet and javax.servlet.http
packages, which are a standard part of the Java's enterprise edition, an expanded
version of the Java class library that supports large-scale development projects.

111

Visit & Downloaded from : www.LearnEngineering.in


Visit & Downloaded from : www.LearnEngineering.in

 These classes implement the Java Servlet and JSP specifications. At the time of
writing this tutorial, the versions are Java Servlet 2.5 and JSP 2.1.
 Java servlets have been created and compiled just like any other Java class. After
you install the servlet packages and add them to our computer's Classpath, we
can compile servlets with the JDK's Java compiler or any other current compiler.
LIFE CYCLE OF THE SERVLET
The web container maintains the life cycle of a servlet instance.
1. Servlet class is loaded.
2. Servlet instance is created.
3. init method is invoked.
4. service method is invoked.
5. destroy method is invoked.

As displayed in the above diagram, there are three states of a servlet: new, ready and end.
The servlet is in new state if servlet instance is created. After invoking the init() method,
Servlet comes in the ready state. In the ready state, servlet performs all the tasks. When
the web container invokes the destroy() method, it shifts to the end state.
1) Servlet class is loaded
The classloader is responsible to load the servlet class. The servlet class is loaded when
the first request for the servlet is received by the web container.
2) Servlet instance is created
The web container creates the instance of a servlet after loading the servlet class. The
servlet instance is created only once in the servlet life cycle.
3) init method is invoked
The web container calls the init method only once after creating the servlet instance.
The init method is used to initialize the servlet. It is the life cycle method of the
javax.servlet.Servlet interface. Syntax of the init method is given below:
public void init(ServletConfig config) throws ServletException

112

Visit & Downloaded from : www.LearnEngineering.in


Visit & Downloaded from : www.LearnEngineering.in

4) service method is invoked


The web container calls the service method each time when request for the servlet is
received. If servlet is not initialized, it follows the first three steps as described above
then calls the service method. If servlet is initialized, it calls the service method. Notice
that servlet is initialized only once. The syntax of the service method of the Servlet
interface is given below:
public void service(ServletRequest request, ServletResponse response)
throws ServletException, IOException
5) destroy method is invoked
The web container calls the destroy method before removing the servlet instance from the
service. It gives the servlet an opportunity to clean up any resource for example memory,
thread etc. The syntax of the destroy method of the Servlet interface is given below:
public void destroy()
6(i). Write in detail about cookies in servlet.
A cookie is a small piece of information that is persisted between the multiple client
requests.
A cookie has a name, a single value, and optional attributes such as a comment, path and
domain qualifiers, a maximum age, and a version number.
How Cookie works
By default, each request is considered as a new request. In cookies technique, we add
cookie with response from the servlet. So cookie is stored in the cache of the browser.
After that if request is sent by the user, cookie is added with request by default. Thus, we
recognize the user as the old user.

Types of Cookie
There are 2 types of cookies in servlets.
1. Non-persistent cookie
2. Persistent cookie
Non-persistent cookie
It is valid for single session only. It is removed each time when user closes the browser.
Persistent cookie
It is valid for multiple session . It is not removed each time when user closes the
browser. It is removed only if user logout or signout.

113

Visit & Downloaded from : www.LearnEngineering.in


Visit & Downloaded from : www.LearnEngineering.in

Advantage of Cookies
1. Simplest technique of maintaining the state.
2. Cookies are maintained at client side.
Disadvantage of Cookies
1. It will not work if cookie is disabled from the browser.
2. Only textual information can be set in Cookie object.
COOKIE CLASS
javax.servlet.http.Cookie class provides the functionality of using cookies. It provides a
lot of useful methods for cookies.
Constructor of Cookie class
Constructor Description

Cookie() constructs a cookie.

Cookie(String name, String value) constructs a cookie with a specified name


and value.

Useful Methods of Cookie class


There are given some commonly used methods of the Cookie class.

Method Description

public void setMaxAge(int expiry) Sets the maximum age of the cookie in seconds.

public String getName() Returns the name of the cookie. The name cannot
be changed after creation.

public String getValue() Returns the value of the cookie.

public void setName(String name) changes the name of the cookie.

public void setValue(String value) changes the value of the cookie.

Other methods required for using Cookies


For adding cookie or getting the value from the cookie, we need some methods
provided by other interfaces. They are:
1. public void addCookie(Cookie ck):method of HttpServletResponse interface
is used to add cookie in response object.
2. public Cookie[] getCookies():method of HttpServletRequest interface is used
to return all the cookies from the browser.

Creation of Cookie
Let's see the simple code to create cookie.
1. Cookie ck=new Cookie("user","sonoo jaiswal");//creating cookie object

114

Visit & Downloaded from : www.LearnEngineering.in


Visit & Downloaded from : www.LearnEngineering.in

2. response.addCookie(ck);//adding cookie in the response


Deletion of Cookie
Let's see the simple code to delete cookie. It is mainly used to logout or signout the user.
1. Cookie ck=new Cookie("user","");//deleting value of cookie
2. ck.setMaxAge(0);//changing the maximum age to 0 seconds
3. response.addCookie(ck);//adding cookie in the response

6b. How to Install and Configuring Apache Tomcat Web Server?

STEP 1: Download and Install Tomcat

NOTE: At the time of writing, Tomcat 9 is at the alpha stage, not stable release. We shall
install Tomcat 8.0.30.

For Windows
 Goto http://tomcat.apache.org ⇒ Downloads ⇒ Tomcat 8.0 ⇒ "8.0.{xx}"
(where {xx} is the latest upgrade number) ⇒ Binary Distributions ⇒ Core ⇒
"ZIP" package (e.g., "apache-tomcat-8.0.{xx}.zip", about 8 MB).
 Create our project directory, say "d:\myProject" or "c:\myProject". UNZIP the
downloaded file into your project directory. Tomcat will be unzipped into
directory "d:\myProject\apache-tomcat-8.0.{xx}".
 For ease of use, we shall shorten and rename this directory to
"d:\myProject\tomcat".
 Take note of our Tomcat Installed Directory. Tomcat installed directory
as <TOMCAT_HOME>.
STEP 2: Create an Environment Variable JAVA_HOME (For Windows)
 We need to create an environment variable called "JAVA_HOME" and set it to
our JDK installed directory.
 First, find your JDK installed directory. The default is "c:\Program
Files\Java\jdk1.8.0_{xx}", where {xx} is the upgrade number. Take note of your
JDK installed directory.
 To set the environment variable JAVA_HOME in Windows 7/8/10: Start "Control
Panel" ⇒ System ⇒ Advanced system settings ⇒ Switch to "Advanced" tab ⇒
Environment Variables ⇒ System Variables ⇒ "New" ⇒ In "Variable Name",
enter "JAVA_HOME" ⇒ In "Variable Value", enter your JDK installed directory
as noted in Step 1.
 To verify, RE-START a CMD shell (restart needed to refresh the environment)
and issue:
SET JAVA_HOME
 JAVA_HOME=c:\Program Files\Java\jdk1.8.0_{xx} <== Verify that this is
YOUR JDK installed directory

115

Visit & Downloaded from : www.LearnEngineering.in


Visit & Downloaded from : www.LearnEngineering.in

STEP 3: Configure Tomcat Server

The Tomcat configuration files are located in the "conf" sub-directory of your Tomcat
installed directory, e.g. "d:\myProject\tomcat\conf" (for Windows) or
"/Applications/tomcat/conf" (for Mac OS X). There are 4 configuration XML files:
1. server.xml
2. web.xml
3. context.xml
4. tomcat-users.xml

Make a BACKUP of the configuration files before we proceed.

Step 3(a) "conf\server.xml" - Set the TCP Port Number


 Use a programming text editor (e.g., NotePad++, TextPad for Windows; or gEdit,
jEdit for Mac OS X) to open the configuration file "server.xml", under the "conf"
sub-directory of Tomcat installed directory.

 The default TCP port number configured in Tomcat is 8080, you may choose any
number between 1024 and 65535, which is not used by an existing application.
We shall choose 9999 in this article. (For production server, you should use port
80, which is pre-assigned to HTTP server as the default port number.)

Locate the following lines (around Line 69) that define the HTTP connector, and
change port="8080" to port="9999".
<!-- A "Connector" represents an endpoint by which requests are received
and responses are returned. Documentation at :
Java HTTP Connector: /docs/config/http.html (blocking & non-blocking)
Java AJP Connector: /docs/config/ajp.html
APR (HTTP/AJP) Connector: /docs/apr.html
Define a non-SSL HTTP/1.1 Connector on port 8080
-->
<Connector port="9999" protocol="HTTP/1.1"
connectionTimeout="20000"
redirectPort="8443" />
Step 3(b) "conf\web.xml" - Enabling Directory Listing
Again, use a programming text editor to open the configuration file "web.xml", under the
"conf" sub-directory of Tomcat installed directory.
We shall enable directory listing by changing "listings" from "false" to "true" for the
"default" servlet. This is handy for test system, but not for production system for security
reasons.
Locate the following lines (around Line 103) that define the "default" servlet; and change
the "listings" from "false" to "true".

116

Visit & Downloaded from : www.LearnEngineering.in


Visit & Downloaded from : www.LearnEngineering.in

<!-- The default servlet for all web applications, that serves static -->
<!-- resources. It processes all requests that are not mapped to other -->
<!-- servlets with servlet mappings. -->
<servlet>
<servlet-name>default</servlet-name>
<servlet-class>org.apache.catalina.servlets.DefaultServlet</servlet-class>
<init-param>
<param-name>debug</param-name>
<param-value>0</param-value>
</init-param>
<init-param>
<param-name>listings</param-name>
<param-value>true</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
Step 3(c) "conf\context.xml" - Enabling Automatic Reload
We shall add the attribute reloadable="true" to the <Context> element to enable
automatic reload after code changes. Again, this is handy for test system but not for
production, due to the overhead of detecting changes.
Locate the <Context> start element (around Line 19), and change it to <Context
reloadable="true">.
<Context reloadable="true">
......
......
</Context>
Step 3(d) (Optional) "conf\tomcat-users.xml"
Enable the Tomcat's manager by adding the highlighted lines, inside the <tomcat-
users> elements:
<tomcat-users>
<role rolename="manager-gui"/>
<user username="manager" password="xxxx" roles="manager-gui"/>
</tomcat-users>

This enables the manager GUI app for managing Tomcat server.

STEP 4: Start Tomcat Server

The Tomcat's executable programs and scripts are kept in the "bin" sub-directory of the
Tomcat installed directory, e.g., "d:\myProject\tomcat\bin" (for Windows) or
"/Applications/tomcat/bin" (for Mac OS X).

117

Visit & Downloaded from : www.LearnEngineering.in


Visit & Downloaded from : www.LearnEngineering.in

Step 4(a) Start Server


For Windows
Launch a CMD shell. Set the current directory to "<TOMCAT_HOME>\bin", and run
"startup.bat" as follows:
// Change the current directory to Tomcat's "bin"
// Assume that Tomcat is installed in "d:\myProject\tomcat"
d: // Change the current drive
cd \myProject\tomcat\bin // Change Directory to YOUR Tomcat's "bin" directory

// Start Tomcat Server


startup
A new Tomcat console window appears. Study the messages on the console. Look out for
the Tomcat's port number (double check that Tomcat is running on port 9999). Future
error messages will be send to this console. System.out.println() issued by your Java
servlets will also be sent to this console.
......
......
xxx xx, xxxx x:xx:xx xx org.apache.coyote.AbstractProtocol start
INFO: Starting ProtocolHandler ["http-bio-9999"]
xxx xx, xxxx x:xx:xx xx org.apache.coyote.AbstractProtocol start
INFO: Starting ProtocolHandler ["ajp-bio-8009"]
xxx xx, xxxx x:xx:xx xx org.apache.catalina.startup.Catalina start
INFO: Server startup in 2477 ms
Step 4(b) Start a Client to Access the Server
Start a browser (as HTTP client). Issue URL "http://localhost:9999" to access the Tomcat
server's welcome page. The hostname "localhost" (with IP address of 127.0.0.1) is meant
for local loop-back testing inside the same machine. For users on the other machines over
the net, they have to use the server's IP address or DNS domain name or hostname in the
format of "http://serverHostnameOrIPAddress:9999".
Try issuing URL http://localhost:9999/examples to view the servlet and JSP examples.
Try running some of the servlet examples.
Step 4(c) Shutdown Server
For Windows
We can shutdown the tomcat server by either:
 Press Ctrl-C on the Tomcat console; OR
 Run "<TOMCAT_HOME>\bin\shutdown.bat" script. Open a new "cmd" and
issue:
 // Change the current directory to Tomcat's "bin"

118

Visit & Downloaded from : www.LearnEngineering.in


Visit & Downloaded from : www.LearnEngineering.in

 d: // Change the current drive


 cd \myProject\tomcat\bin // Change Directory to YOUR Tomcat's "bin" directory
 // Shutdown the server
 shutdown

6c. Explain about JSP Standard Tag Library.


 The JavaServer Pages Standard Tag Library (JSTL) is a collection of useful JSP
tags which encapsulates core functionality common to many JSP
applications.JSTL has support for common, structural tasks such as iteration and
conditionals, tags for manipulating XML documents, internationalization tags,
and SQL tags. It also provides a framework for integrating existing custom tags
with JSTL tags.
 The JSTL tags can be classified, according to their functions, into following JSTL
tag library groups that can be used when creating a JSP page:
 Core Tags
 Formatting tags
 SQL tags
 XML tags
 JSTL Functions
Install JSTL Library
If we 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 our application's
webapps\ROOT\WEB-INF\lib directory.
To use any of the libraries, we must include a <taglib> directive at the top of each JSP
that uses the library.
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:

<%@ taglib prefix="c"


uri="http://java.sun.com/jsp/jstl/core" %>
There are following Core JSTL Tags:

119

Visit & Downloaded from : www.LearnEngineering.in


Visit & Downloaded from : www.LearnEngineering.in

Tag Description

<c:out > Like <%= ... >, but for expressions.

<c:set > Sets the result of an expression evaluation in a 'scope'

<c:remove > Removes a scoped variable (from a particular scope, if specified).

<c:catch> Catches any Throwable that occurs in its body and optionally
exposes it.

<c:if> Simple conditional tag which evalutes its body if the supplied
condition is true.

<c:choose> Simple conditional tag that establishes a context for mutually


exclusive conditional operations, marked by <when> and
<otherwise>

<c:when> Subtag of <choose> that includes its body if its condition evalutes
to 'true'.

<c:otherwise > Subtag of <choose> that follows <when> tags and runs only if all
of the prior conditions evaluated to 'false'.

Formatting tags
The JSTL formatting tags are used to format and display text, the date, the time, and
numbers for internationalized Web sites. Following is the syntax to include Formatting
library in your JSP:

<%@ taglib prefix="fmt"


uri="http://java.sun.com/jsp/jstl/fmt" %>
Following is the list of Formatting JSTL Tags:

Tag Description

<fmt:formatNumber> To render numerical value with specific precision or format.

<fmt:parseNumber> Parses the string representation of a number, currency, or


percentage.

<fmt:formatDate> Formats a date and/or time using the supplied styles and pattern

<fmt:parseDate> Parses the string representation of a date and/or time

<fmt:bundle> Loads a resource bundle to be used by its tag body.

<fmt:setLocale> Stores the given locale in the locale configuration variable.

120

Visit & Downloaded from : www.LearnEngineering.in


Visit & Downloaded from : www.LearnEngineering.in

<fmt:setBundle> Loads a resource bundle and stores it in the named scoped


variable or the bundle configuration variable.

<fmt:timeZone> Specifies the time zone for any time formatting or parsing
actions nested in its body.

<fmt:setTimeZone> Stores the given time zone in the time zone configuration
variable

SQL tags
The JSTL SQL tag library provides tags for interacting with relational databases
(RDBMSs) such as Oracle, mySQL, or Microsoft SQL Server.
Following is the syntax to include JSTL SQL library in your JSP:
<%@ taglib prefix="sql" uri="http://java.sun.com/jsp/jstl/sql" %>
Following is the list of SQL JSTL Tags:

Tag Description

<sql:setDataSource> Creates a simple DataSource suitable only for prototyping

<sql:query> Executes the SQL query defined in its body or through the sql
attribute.

<sql:update> Executes the SQL update defined in its body or through the sql
attribute.

<sql:param> Sets a parameter in an SQL statement to the specified value.

<sql:dateParam> Sets a parameter in an SQL statement to the specified


java.util.Date value.

<sql:transaction > Provides nested database action elements with a shared


Connection, set up to execute all statements as one transaction.

XML tags
The JSTL XML tags provide a JSP-centric way of creating and manipulating XML
documents. Following is the syntax to include JSTL XML library in your JSP.
The JSTL XML tag library has custom tags for interacting with XML data. This
includes parsing XML, transforming XML data, and flow control based on XPath
expressions.
<%@ taglib prefix="x"
uri="http://java.sun.com/jsp/jstl/xml" %>
Before you proceed with the examples, you would need to copy following two XML and
XPath related libraries into your <Tomcat Installation Directory>\lib:
 XercesImpl.jar: Download it fromhttp://www.apache.org/dist/xerces/j/

121

Visit & Downloaded from : www.LearnEngineering.in


Visit & Downloaded from : www.LearnEngineering.in

 xalan.jar: Download it from http://xml.apache.org/xalan-j/index.html


Following is the list of XML JSTL Tags:

Tag Description

<x:out> Like <%= ... >, but for XPath expressions.

<x:parse> Use to parse XML data specified either via an attribute or in the tag
body.

<x:set > Sets a variable to the value of an XPath expression.

<x:if > Evaluates a test XPath expression and if it is true, it processes its body.
If the test condition is false, the body is ignored.

<x:forEach> To loop over nodes in an XML document.

JSTL Functions
JSTL includes a number of standard functions, most of which are common string
manipulation functions. Following is the syntax to include JSTL Functions library in
your JSP:
<%@ taglib prefix="fn"
uri="http://java.sun.com/jsp/jstl/functions" %>
Following is the list of JSTL Functions:

Function Description

fn:contains() Tests if an input string contains the specified substring.

fn:containsIgnoreCase() Tests if an input string contains the specified substring in a case


insensitive way.

fn:endsWith() Tests if an input string ends with the specified suffix.

fn:escapeXml() Escapes characters that could be interpreted as XML markup.

fn:indexOf() Returns the index withing a string of the first occurrence of a


specified substring.

fn:join() Joins all elements of an array into a string.

fn:replace() Returns a string resulting from replacing in an input string all


occurrences with a given string.

fn:split() Splits a string into an array of substrings.

fn:startsWith() Tests if an input string starts with the specified prefix.

122

Visit & Downloaded from : www.LearnEngineering.in


Visit & Downloaded from : www.LearnEngineering.in

UNIT IV
PHP and XML
PART - A
1. What is XML parse tree? [Nov/Dec 15]

XML documents form a tree structure that starts at "the root" and branches to "the
leaves".
XML documents are formed as element trees.
An XML tree starts at a root element and branches from the root to child
elements.
All elements can have sub elements (child elements)
<root>
<child>
<subchild>.....</subchild>
</child>
</root>
2. Why is XSLT an important tool in development of web applications?
[May/June 16]
The original document is not changed; rather, a new document is created based on
the content of an existing one.Typically, input documents are XML files, but
anything from which the processor can build an XQuery and XPath Data
Model can be used, for example relational database tables, or geographical
information systems.
3. When should the super global arrays in PHP be used? Which super global
array in PHP would contain a HTML form’s POST data? [May/June 16]

$GLOBALS is a PHP super global variable which is used to access global


variables from anywhere in the PHP script (also from within functions or
methods).
PHP stores all global variables in an array called $GLOBALS[index].
The index holds the name of the variable.
The example below shows how to use the super global variable $GLOBALS:
<?php
$x= 75;
$y= 25;
function addition() {
$GLOBALS['z']= $GLOBALS['x']+ $GLOBALS['y'];
}

123

Visit & Downloaded from : www.LearnEngineering.in


Visit & Downloaded from : www.LearnEngineering.in

addition();
echo $z;
?>
In the example above, since z is a variable present within the $GLOBALS array, it
is also accessible from outside the function
PHP $_POST is widely used to collect form data after submitting an HTML form
with method="post". $_POST is also widely used to pass variables.
$_SERVER['REQUEST_METHOD'] - Returns the request method used to access
the page (such as POST)
4. Name any four built-in functions in PHP. [Nov/Dec 15]
array() - Creates an array
cal_days_in_month() - Returns the number of days in a month for a specified year
and calendar
date.timezone - The default timezone (used by all date/time functions)
chdir() - Changes the current directory
5. Define XML.
Extensible Markup Language (XML) is a markup language that defines a set of
rules for encoding documents in a format that is both human-
readable and machine-readable. It is defined by the W3C's XML 1.0
Specification and by several other related specifications, all of which are free open
standards. The basic building block of an XML document is an element, defined
by tags. An element has a beginning and an ending tag. All elements in an XML
document are contained in an outermost element known as the root element.
6. Define DTD.
A document type definition (DTD) is a set of markup declarations that define a
document type for an SGML-family markup language (SGML, XML, and
HTML). A Document Type Definition (DTD) defines the legal building blocks
of an XML document. It defines the document structure with a list of legal
elements and attributes.
7. What are the XML rules for distinguishing between the content of a
document and the XML markup element?
 The start of XML markup elements is identified by either the less than
symbol (<) or the ampersand (&) character.
 Three other characters, the greater than symbol (>), the apostrophe or single
quote („) and the double quotation marks (“) are used by XML for markup.
 To use these special characters as content within your document, you must
use the corresponding general XML entity.

124

Visit & Downloaded from : www.LearnEngineering.in


Visit & Downloaded from : www.LearnEngineering.in

8. What is DOM?
The DOM is a W3C (World Wide Web Consortium) standard. The DOM defines
a standard for accessing documents: "The W3C Document Object Model (DOM)
is a platform and language-neutral interface that allows programs and scripts to
dynamically access and update the content, structure, and style of a document."
9. What is XSLT?
XSLT (ExtensibleStylesheet Language Transformations) is a language
for transforming XML documents into other XML documents, or other formats
such as HTML for web pages, plain text or into XSL Formatting Objects, which
may subsequently be converted to other formats, such
as PDF, PostScript and PNG.
10. What is metadata?
Metadata is simply data about data, or, to put it another way, data that describes
other data. Take, for example, an XML document. An XML document contains
markup, which is a form of metadata. Consider this fragment:
<p>The <library-name>foobar</library-name> library contains the routines
<routine-name>foo()</routine-name> and <routine-name>bar()</routine-
name>.</p>
The <p> tag is metadata that tells us that the string it contains is a paragraph. The
<library-name> and <routine-name> tags are metadata that tell us that the strings
they contain are library names and routine names respectively.
11. What are the uses of XLink,Xpath,Xquery?.
XLink is used to create hyperlinks in XML documents.
XPath: provides a common syntax and semantics for functionality shared between
XSLT and XPointer.
XQuery: query language. It facilitates the data extraction from XML documents.
12. Define PHP.
PHP: Hypertext Preprocessor is a server-side scripting language designed for web
development but also used as a general-purpose programming language. PHP code
may be embedded into HTML code, or it can be used in combination with
various web template systems, web content management systems and web
frameworks.
PHP code is usually processed by a PHP interpreter implemented as a module in
the web server or as a Common Gateway Interface (CGI) executable.
13. What are the rules to write variables in PHP?
A variable can have a short name (like x and y) or a more descriptive name (age,
carname, total_volume).
Rules for PHP variables:

125

Visit & Downloaded from : www.LearnEngineering.in


Visit & Downloaded from : www.LearnEngineering.in

 A variable starts with the $ sign, followed by the name of the variable
 A variable name must start with a letter or the underscore character
 A variable name cannot start with a number
 A variable name can only contain alpha-numeric characters and
underscores (A-z, 0-9, and _ )
 Variable names are case-sensitive ($age and $AGE are two different
variables)
14. What is meant by RSS and ATOM?
RSS stands for both Rich Site Summary and Really Simple Syndication but it
always refers to the same technology. It is a mean of transmitting and updating
news in an automated way. Most news sites (including virtually all blogs) will
publish what is called an RSS feed which is regularly updated with the latest
available headlines and/or articles.
The RSS feed is not human readable. It is an XML format which is designed to be
read by machines rather than humans.
The name Atom applies to a pair of related Web standards. The Atom Syndication
Format is an XML language used for web feeds, while the Atom Publishing
Protocol (AtomPub or APP) is a simple HTTP-based protocol for creating and
updating web resources. A feed contains entries, which may be headlines, full-text
articles, excerpts, summaries, and/or links to content on a website, along with
various metadata. The Atom format was developed as an alternative to RSS.
15. How to connect a database in PHP?
We should establish a connection to the MySQL database. This is an extremely
important step because if our script cannot connect to its database, our queries to
the database will fail. A good practice when using databases is to set the username,
the password and the database name values at the beginning of the script code. If
we need to change them later, it will be an easy task.
$username="our_username";
$password="our_password";
$database="our_database";
We should replace "our_username", "our_password" and "our_database" with the
MySQL username, password and database that will be used by our script.
Next we should connect our PHP script to the database. This can be done with the
mysql_connect PHP function:
mysql_connect(localhost,$username,$password);

126

Visit & Downloaded from : www.LearnEngineering.in


Visit & Downloaded from : www.LearnEngineering.in

Part – B (16 marks)


1. Write a PHP program to do string manipulations. [Nov/Dec15]
Following are valid examples of string
$string_1 = "This is a string in double quotes";
$string_2 = "This is a somewhat longer, singly quoted string";
$string_39 = "This string has thirty-nine characters";
$string_0 = ""; // a string with zero characters
Singly quoted strings are treated almost literally, whereas doubly quoted strings replace
variables with their values as well as specially interpreting certain character sequences.
<?php
$variable = "name";
$literally = 'My $variable will not print!\\n';
print($literally);
print "<br />";
$literally = "My $variable will print!\\n";
print($literally);
?>
This will produce the following result −
My $variable will not print!\n
My name will print
String Concatenation Operator
To concatenate two string variables together, use the dot (.) operator –
<?php
$string1="Hello World";
$string2="1234";
echo $string1 . " " . $string2;
?>
This will produce the following result −
Hello World 1234

strlen() function
The strlen() function is used to find the length of a string.
Let's find the length of our string "Hello world!":
<?php
echo strlen("Hello world!");
?>
This will produce the following result −
12

127

Visit & Downloaded from : www.LearnEngineering.in


Visit & Downloaded from : www.LearnEngineering.in

strpos() function
The strpos() function is used to search for a string or character within a string. If a match
is found in the string, this function will return the position of the first match. If no match
is found, it will return FALSE. Let's see if we can find the string "world" in our string −
<?php
echo strpos("Hello world!","world");
?>
This will produce the following result −
6
To ensure all the letters in a specific string were uppercase, we can use
the strtoupper()function as follows:
<?php
$str = "Like a puppet on a string.";
$cased = strtoupper($str);
// Displays: LIKE A PUPPET ON A STRING.
echo $cased;
?>
It is perhaps obvious but still worth noting that numbers and other non-alphabet
characters will not be converted.
The strtolower() function does the exact opposite of strtoupper() and converts a string
into all lowercase letters:
<?php
$str = "LIKE A PUPPET ON A STRING.";
$cased = strtolower($str);
// Displays: like a puppet on a string.
echo $cased;
?>
Likewise when we want to ensure certain words, such as names or titles, just have the
first letter of each word capitalized. For this we can use the ucwords() function:
<?php
$str = "a knot";
$cased = ucwords($str);
// Displays: A Knot
echo $cased;
?>
It is also possible to manipulate the case of just the first letter of a string using
the lcfirst() and ucfirst() functions. If we want the first letter to be lowercase, use lcfirst().

128

Visit & Downloaded from : www.LearnEngineering.in


Visit & Downloaded from : www.LearnEngineering.in

If we want the first letter to be uppercase, use ucfirst(). The ucfirst() function is probably
the most useful since we can use it to ensure a sentence always starts with a capital letter.
<?php
$str = "how long is a piece of string?";
$cased = ucfirst($str);
//Displays: How long is a piece of string?
echo $cased;
?>
2(i).Explain in detail about i) XML Schema [Nov / Dec 15]
Let's have a look at this XML document called "shiporder.xml"
<?xml version="1.0" encoding="UTF-8"?>
<shiporder orderid="889923"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="shiporder.xsd">
<orderperson>JohnSmith</orderperson>
<shipto>
<name>OlaNordmann</name>
<address>Langgt23</address>
<city>4000Stavanger</city>
<country>Norway</country>
</shipto>
<item>
<title>EmpireBurlesque</title>
<note>SpecialEdition</note>
<quantity>1</quantity>
<price>10.90</price>
</item>
<item>
<title>Hideyourheart</title>
<quantity>1</quantity>
<price>9.90</price>
</item>
</shiporder>
 The XML document above consists of a root element, "shiporder", that contains a
required attribute called "orderid".
 The "shiporder" element contains three different child elements: "orderperson",
"shipto" and "item".

129

Visit & Downloaded from : www.LearnEngineering.in


Visit & Downloaded from : www.LearnEngineering.in

 The "item" element appears twice, and it contains a "title", an optional "note"
element, a "quantity", and a "price" element.
 The line above: xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" tells
the XML parser that this document should be validated against a schema.
 The line: xsi:noNamespaceSchemaLocation="shiporder.xsd" specifies WHERE
the schema resides (here it is in the same folder as "shiporder.xml").
Create an XML Schema
Now we want to create a schema for the XML document above.
 We start by opening a new file that we will call "shiporder.xsd".
 To create the schema we could simply follow the structure in the XML document
and define each element as we find it.
 We will start with the standard XML declaration followed by the xs:s element that
defines a schema:
<?xml version="1.0" encoding="UTF-8" ?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
...
</xs:schema>
 In the schema above we use the standard namespace (xs), and the URI associated
with this namespace is the Schema language definition, which has the standard
value of http://www.w3.org/2001/XMLSchema.
 Next, we have to define the "shiporder" element.
 This element has an attribute and it contains other elements, therefore we consider
it as a complex type.
 The child elements of the "shiporder" element is surrounded by a xs:sequence
element that defines an ordered sequence of sub elements:
<xs:element name="shiporder">
<xs:complexType>
<xs:sequence>
...
</xs:sequence>
</xs:complexType>
</xs:element>
2(ii) List at least five significant differences between DTD and XML schema for
defining XML document structures with appropriate examples [May/June 16]

XML Schema vs. DTD


 DTD, or Document Type Definition, and XML Schema, which is also
known as XSD, are two ways of describing the structure and content of an
XML document.
130

Visit & Downloaded from : www.LearnEngineering.in


Visit & Downloaded from : www.LearnEngineering.in

 DTD is the older of the two, and as such, it has limitations that XML
Schema has tried to improve.
 The first difference between DTD and XML Schema, is namespace
awareness; XML Schema is, while DTD is not.
 Namespace awareness removes the ambiguity that can result in having
certain elements and attributes from multiple XML vocabularies, by giving
them namespaces that put the element or attribute into context.
 Part of the reason why XML Schema is namespace aware while DTD is
not, is the fact that XML Schema is written in XML, and DTD is not.
 Therefore, XML Schemas can be programmatically processed just like any
XML document.
 XML Schema also eliminates the need to learn another language, as it is
written in XML, unlike DTD.
 Another key advantage of XML Schema, is its ability to implement strong
typing.
 An XML Schema can define the data type of certain elements, and even
constrain it to within specific lengths or values.
 This ability ensures that the data stored in the XML document is accurate.
 DTD lacks strong typing capabilities, and has no way of validating the
content to data types.
 XML Schema has a wealth of derived and built-in data types to validate
content.
 It also has uniform data types, but as all processors and validators need to
support these data types, it often causes older XML parsers to fail.
 A characteristic of DTD that people often consider both as an advantage
and disadvantage, is the ability to define DTDs inline, which XML Schema
lacks.
 This is good when working with small files, as it allows you to contain both
the content and the schema within the same document, but when it comes to
larger documents, we have to pull content every time while we retrieve the
schema. This can lead to serious overhead that can degrade performance.
1. XML Schema is namespace aware, while DTD is not.
2. XML Schemas are written in XML, while DTDs are not.
3. XML Schema is strongly typed, while DTD is not.
4. XML Schema has a wealth of derived and built-in data types that are not
available in DTD.
5. XML Schema does not allow inline definitions, while DTD does.

131

Visit & Downloaded from : www.LearnEngineering.in


Visit & Downloaded from : www.LearnEngineering.in

No. DTD XSD

1) DTD stands for Document Type XSD stands for XML Schema Definition.
Definition.

2) DTDs are derived XSDs are written in XML.


from SGML syntax.

3) DTD doesn't support datatypes. XSD supports datatypes for elements and
attributes.

4) DTD doesn't support namespace. XSD supports namespace.

5) DTD doesn't define order for child XSD defines order for child elements.
elements.

6) DTD is not extensible. XSD is extensible.

7) DTD is not simple to learn.. XSD is simple to learn because you don't need to
learn new language..

8) DTD provides less control on XSD provides more control on XML structure
XML structure.

3(i). Explain in detail about XML parsers and Validation [Nov / Dec 15]
XML PARSERS
An XML parser is a software library or package that provides interfaces for client
applications to work with an XML document. The XML Parser is designed to read the
XML and create a way for programs to use XML.
XML parser validates the document and check that the document is well formatted.
Let's understand the working of XML parser by the figure given below:

Types of XML Parsers


These are the two main types of XML Parsers:
1. DOM
2. SAX

132

Visit & Downloaded from : www.LearnEngineering.in


Visit & Downloaded from : www.LearnEngineering.in

DOM (Document Object Model)


A DOM document is an object which contains all the information of an XML document.
It is composed like a tree structure. The DOM Parser implements a DOM API. This API
is very simple to use.
Features of DOM Parser
A DOM Parser creates an internal structure in memory which is a DOM document object
and the client applications get information of the original XML document by invoking
methods on this document object.
DOM Parser has a tree based structure.
Advantages
1) It supports both read and write operations and the API is very simple to use.
2) It is preferred when random access to widely separated parts of a document is required.
Disadvantages
1) It is memory inefficient. (Consumes more memory because the whole XML document
needs to loaded into memory).
2) It is comparatively slower than other parsers.
SAX (Simple API for XML)
A SAX Parser implements SAX API. This API is an event based API and less intuitive.
Features of SAX Parser
 It does not create any internal structure.
 Clients does not know what methods to call, they just overrides the methods of the
API and place his own code inside method.
 It is an event based parser, it works like an event handler in Java.
Advantages
1) It is simple and memory efficient.
2) It is very fast and works for huge documents.
Disadvantages
1) It is event-based so its API is less intuitive.
2) Clients never know the full information because the data is broken into pieces.
XML VALIDATION
A well formed XML document can be validated against DTD or Schema.
A well-formed XML document is an XML document with correct syntax. It is very
necessary to know about valid XML document before knowing XML validation.
Valid XML document
 It must be well formed (satisfy all the basic syntax condition)
 It should be behave according to predefined DTD or XML schema
Rules for well formed XML
o It must begin with the XML declaration.

133

Visit & Downloaded from : www.LearnEngineering.in


Visit & Downloaded from : www.LearnEngineering.in

o It must have one unique root element.


o All start tags of XML documents must match end tags.
o XML tags are case sensitive.
o All elements must be closed.
o All elements must be properly nested.
o All attributes values must be quoted.
o XML entities must be used for special characters.
3(ii) List the essential features of XML parsers. [May/June 16]
XML is widely used in the era of web development. It is also used to simplify data
storage and data sharing.
The main features or advantages of XML are given below.
1) XML separates data from HTML
 If we need to display dynamic data in your HTML document, it will take a lot of
work to edit the HTML each time the data changes.
 With XML, data can be stored in separate XML files. This way we can focus on
using HTML/CSS for display and layout, and be sure that changes in the
underlying data will not require any changes to the HTML.
 With a few lines of JavaScript code, we can read an external XML file and update
the data content of your web page.
2) XML simplifies data sharing
 In the real world, computer systems and databases contain data in incompatible
formats.
 XML data is stored in plain text format. This provides a software- and hardware-
independent way of storing data.
 This makes it much easier to create data that can be shared by different
applications.
3) XML simplifies data transport
 One of the most time-consuming challenges for developers is to exchange data
between incompatible systems over the Internet.
 Exchanging data as XML greatly reduces this complexity, since the data can be
read by different incompatible applications.
4) XML simplifies Platform change
 Upgrading to new systems (hardware or software platforms), is always time
consuming.
 Large amounts of data must be converted and incompatible data is often lost.
 XML data is stored in text format. This makes it easier to expand or upgrade to
new operating systems, new applications, or new browsers, without losing data.

134

Visit & Downloaded from : www.LearnEngineering.in


Visit & Downloaded from : www.LearnEngineering.in

5) XML increases data availability


 Different applications can access your data, not only in HTML pages, but also
from XML data sources.
 With XML, your data can be available to all kinds of "reading machines"
(Handheld computers, voice machines, news feeds, etc), and make it more
available for blind people, or people with other disabilities.
6) XML can be used to create new internet languages
A lot of new Internet languages are created with XML.
Here are some examples:
o XHTML
o WSDL for describing available web services
o WAP and WML as markup languages for handheld devices
o RSS languages for news feeds
o RDF and OWL for describing resources and ontology
o SMIL for describing multimedia for the web
4. Write notes on XSL and XSL Transformation. (16)
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).
 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.
Working of XSL
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.
The XML file
<scene>
<FX>General Road Building noises.</FX>
<speech speaker="Prosser">

135

Visit & Downloaded from : www.LearnEngineering.in


Visit & Downloaded from : www.LearnEngineering.in

Come off it Mr Dent, you can't win


you know. There's no point in lying
down in the path of progress.
</speech>
<speech speaker="Arthur">
I've gone off the idea of progress.
It's overrated
</speech>
</scene>
 This XML file doesn't contain any presentation information, which is contained in
the stylesheet.
 Separating the document's content and the document's styling information allows
displaying the same document on different media (like screen, paper, cell phone),
and it also enables users to view the document according to their preferences and
abilities, just by modifying the style sheet.
The Stylesheet
Here are two templates from the stylesheet used to format the XML file. The full
stylesheet (which includes extra information on pagination and margins) is available.
...
<xsl:template match="FX">
<fo:block font-weight="bold">
<xsl:apply-templates/>
</fo:block>
</xsl:template>
<xsl:template match="speech[@speaker='Arthur']">
<fo:block background-color="blue">
<xsl:value-of select="@speaker"/>:
<xsl:apply-templates/>
</fo:block>
</xsl:template>
...
 The stylesheet can be used to transform any instance of the DTD it was designed
for.
 The first rule says that an FX element will be transformed into a block with a bold
font. <xsl:apply-templates/> is a recursive call to the template rules for the
contents of the current element.

136

Visit & Downloaded from : www.LearnEngineering.in


Visit & Downloaded from : www.LearnEngineering.in

 The second template applies to all speech elements that have the speaker attribute
set to Arthur, and formats them as blue blocks within which the value speaker
attribute is added before the text.
XSL TRANSFORMATION
XSLT essentials and goals
 XSLT is a transformation language for XML. That means, using XSLT, we could
generate any sort of other document from an XML document.
 XSLT is a W3C XML language (the usual XML well-formedness criteria apply)
 XSLT can translate XML into almost anything , e.g.:
 wellformed HTML (closed tags)
 any XML, e.g. yours or other XML languages like SVG, X3D
 non XML, e.g. RTF (this is a bit more complicated)

 In principle, the input data to be transformed is always XML.

 With XSLT we then can produce some "enriched" or otherwise transformed XML
or directly some other format that is used to render the contents.

An XSLT program is an XML document. It's top-level skeleton looks like this:

<?xml version="1.0"?>
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
....
</xsl:stylesheet>
Mandatory "elements"
 An XML declaration on top of the file
 A stylesheet root tag, including version and namespace attributes (as seen in the
example above):
version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"

Association of XML and an XSLT file

XSLT was already implemented in IE 5.5., i.e. in the last millenium...

137

Visit & Downloaded from : www.LearnEngineering.in


Visit & Downloaded from : www.LearnEngineering.in

<?xml version="1.0" encoding="ISO-8859-1"?>


<?xml-stylesheet href="project.xsl" type="text/xsl" ?>
<yourxml>
....
</yourxml>

There exist various so-called XSLT processors. Most programming languages and all
well-know server-side scripting languages like PHP include an XSLT library. XML
editors usually include an XSLT processor.

Below is the complete code for a simple "Hello XSLT" example.

XML file (source)


 hello.xml
<?xml version="1.0"?>
<?xml-stylesheet href="hello.xsl" type="text/xsl"?>
<page>
<title>Hello</title>
<content>Here is some content</content>
<comment>Written by DKS.</comment>
</page>
Wanted result document
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN"
"http://www.w3.org/TR/REC-html40/strict.dtd">
<html>
<head>
<title>Hello</title>
</head>
<body bgcolor="#ffffff">
<h1 align="center">Hello</h1>
<p align="center"> Here is some content</p>
<hr><i>Written by DKS</i>
</body>
</html>
The XSLT Stylesheet
 hello.xslt
<?xml version="1.0"?>
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="page">
<html>
138

Visit & Downloaded from : www.LearnEngineering.in


Visit & Downloaded from : www.LearnEngineering.in

<head>
<title> <xsl:value-of select="title"/>
</title>
</head>
<body bgcolor="#ffffff">
<xsl:apply-templates/>
</body>
</html>
</xsl:template>

<xsl:template match="title">
<h1 align="center"> <xsl:apply-templates/> </h1>
</xsl:template>

<xsl:template match="content">
<p align="center"> <xsl:apply-templates/> </p>
</xsl:template>

<xsl:template match="comment">
<hr/> <i><xsl:apply-templates/> </i>
</xsl:template>
</xsl:stylesheet>
5(i). Explain in details about variables in PHP.
The main way to store information in the middle of a PHP program is by using a
variable.
Here are the most important things to know about variables in PHP.
 All variables in PHP are denoted with a leading dollar sign ($).
 The value of a variable is the value of its most recent assignment.
 Variables are assigned with the = operator, with the variable on the left-hand side
and the expression to be evaluated on the right.
 Variables can, but do not need, to be declared before assignment.
 Variables in PHP do not have intrinsic types - a variable does not know in
advance whether it will be used to store a number or a string of characters.
 Variables used before they are assigned have default values.
 PHP does a good job of automatically converting types from one to another when
necessary.
 PHP variables are Perl-like.
PHP has a total of eight data types which we use to construct our variables −

139

Visit & Downloaded from : www.LearnEngineering.in


Visit & Downloaded from : www.LearnEngineering.in

 Integers − are whole numbers, without a decimal point, like 4195.


 Doubles − are floating-point numbers, like 3.14159 or 49.1.
 Booleans − have only two possible values either true or false.
 NULL − is a special type that only has one value: NULL.
 Strings − are sequences of characters, like 'PHP supports string operations.'
 Arrays − are named and indexed collections of other values.
 Objects − are instances of programmer-defined classes, which can package up
both other kinds of values and functions that are specific to the class.
 Resources − are special variables that hold references to resources external to
PHP (such as database connections).
The first five are simple types, and the next two (arrays and objects) are compound - the
compound types can package up other arbitrary values of arbitrary type, whereas the
simple types cannot.
Integers
 They are whole numbers, without a decimal point, like 4195.
 They are the simplest type .
 They correspond to simple whole numbers, both positive and negative.
 Integers can be assigned to variables, or they can be used in expressions
$int_var = 12345;
$another_int = -12345 + 12345;
 Integer can be in decimal (base 10), octal (base 8), and hexadecimal (base 16)
format. Decimal format is the default, octal integers are specified with a leading
0, and hexadecimals have a leading 0x.
 For most common platforms, the largest integer is (2**31 . 1) (or 2,147,483,647),
and the smallest (most negative) integer is . (2**31 . 1) (or .2,147,483,647).
Doubles
 They like 3.14159 or 49.1. By default, doubles print with the minimum number of
decimal places needed. For example

<?php
$many = 2.2888800;
$many_2 = 2.2111200;
$few = $many + $many_2;
print("$many + $many_2 = $few <br>");
?>

It produces the following browser output −


2.28888 + 2.21112 = 4.5

140

Visit & Downloaded from : www.LearnEngineering.in


Visit & Downloaded from : www.LearnEngineering.in

Boolean
 They have only two possible values either true or false. PHP provides a couple of
constants especially for use as Booleans: TRUE and FALSE.
if (TRUE)
print("This will always print<br>");
else
print("This will never print<br>");
Interpreting other types as Booleans
Here are the rules for determine the "truth" of any value not already of the Boolean type
 If the value is a number, it is false if exactly equal to zero and true otherwise.
 If the value is a string, it is false if the string is empty (has zero characters) or is
the string "0", and is true otherwise.
 Values of type NULL are always false.
 If the value is an array, it is false if it contains no other values, and it is true
otherwise. For an object, containing a value means having a member variable that
has been assigned a value.
 Valid resources are true (although some functions that return resources when they
are successful will return FALSE when unsuccessful).
 Don't use double as Booleans.
Each of the following variables has the truth value embedded in its name when it is used
in a Boolean context.
$true_num = 3 + 0.14159;
$true_str = "Tried and true"
$true_array[49] = "An array element";
$false_array = array();
$false_null = NULL;
$false_num = 999 - 999;
$false_str = "";

NULL
NULL is a special type that only has one value: NULL. To give a variable the NULL
value, we can simply assign it like this −
$my_var = NULL;
The special constant NULL is capitalized by convention, but actually it is case
insensitive.
$my_var = null;
A variable that has been assigned NULL has the following properties −
 It evaluates to FALSE in a Boolean context.
 It returns FALSE when tested with IsSet() function.

141

Visit & Downloaded from : www.LearnEngineering.in


Visit & Downloaded from : www.LearnEngineering.in

Strings
They are sequences of characters, like "PHP supports string operations". Following are
valid examples of string
$string_1 = "This is a string in double quotes";
$string_2 = "This is a somewhat longer, singly quoted string";
$string_39 = "This string has thirty-nine characters";
$string_0 = ""; // a string with zero characters
Singly quoted strings are treated almost literally, whereas doubly quoted strings replace
variables with their values as well as specially interpreting certain character sequences.

<?php
$variable = "name";
$literally = 'My $variable will not print!';
print($literally);
print "<br>";
$literally = "My $variable will print!";
print($literally);
?>

This will produce following result −


My $variable will not print!\n
My name will print
There are no artificial limits on string length - within the bounds of available memory,
you ought to be able to make arbitrarily long strings.
Strings that are delimited by double quotes (as in "this") are preprocessed in both the
following two ways by PHP −
 Certain character sequences beginning with backslash (\) are replaced with special
characters
 Variable names (starting with $) are replaced with string representations of their
values.
The escape-sequence replacements are −
 \n is replaced by the newline character
 \r is replaced by the carriage-return character
 \t is replaced by the tab character
 \$ is replaced by the dollar sign itself ($)
 \" is replaced by a single double-quote (")
 \\ is replaced by a single backslash (\)
5(ii). Explain in detail about built – in functions in PHP.
 Functions are reusable bits of code that you use throughout a project.

142

Visit & Downloaded from : www.LearnEngineering.in


Visit & Downloaded from : www.LearnEngineering.in

 They help to better organize your application as well as eliminate the need to
copy/paste repetitive pieces of code.
 In an ideal world an application should not have multiple functions doing the same
thing.
 PHP has a lot of built in functions.

STRING MANIPULATION FUNCTIONS


Some of the most useful PHP functions are string manipulation functions. As the name
suggests they manipulate strings.
FINDING THE LENGTH OF A STRING
The strlen() functions works by passing a string or variable and then returns the total
number of characters including spaces.
<?php
$name = "Matthew ";
echo strlen($name); // 8
?>
RETURN PART OF A STRING
The substr() function is used to return a substring or part of a string. This function has 3
parameters which we can pass along.
Syntax
substr($string, $start,$length);
$string – a string of text or a variable containing a string of text. Input must be at least
one character.
$start – think of the string as an array starting from [0]. If we wanted to start from the
first character you would enter 0. A negative value will go to the end of the string.
$length – (Optional) is the number of characters returned after the start character. If this
value is less than or equal to the start value then it will return false.
<?php
$name = "Matthew ";
echo substr($name, 0, 5); // Matth
echo substr($name, 2); // tthew
echo substr($name, -6, 5); // tthew
?>
CONVERTING STRINGS TO UPPER OR LOWER CASE
Two useful string functions that are simple to use are strtoupper() and strtolower(), these
functions can convert your strings to all UPPERCASE or all lowercase.
They are very useful for case sensitive operations where you may require all characters to
be lowercase for example.

143

Visit & Downloaded from : www.LearnEngineering.in


Visit & Downloaded from : www.LearnEngineering.in

<?php
$name = "Matthew ";
echo strtoupper($name); // MATTHEW
echo strtolower($name); // matthew
?>
Searching for a needle in a haystack!
Sometimes we need to find a substring within a string and to do that we can use strpos.
Syntax
strpos ($haystack,$needle,$offset)
$haystack – this is the string in which you are going to find the $needlestarting from [0].
$needle – this is what you are going to search for in the $haystack.
$offset – (Optional) search will start from this number of characters counted from the
beginning of the string.It cannot be negative.
<?php
$name = "Matthew ";
echo strpos($name, "M"); // 0
echo strpos($name, "hew"); // 4
echo strpos($name, "m"); // false
?>
This function is case sensitive and could not find a match.
We can almost make use of an if statement and some variables to make the strops
function more useful and meaningful.
<?php
$string = "I am learning how to use PHP string functions!";
$search = "JavaScript";
if(strpos($string, $search) === false) {
echo "Sorry we could not find '$search' in '$string'.";
}
?>
This would echo “Sorry we could not find „JavaScript‟ in „I am learning how to use PHP
string functions!‟“.
ARITHMETIC MANIPULATION FUNCTIONS
As well as string manipulation function, PHP also has functions to manipulate numbers.
ROUNDING NUMBERS
One of the most commonly used math function is round(). This function rounds numbers
with decimal points up or down. We can round a number to an integer (whole number) or to a
floating point (decimal numbers).
Syntax
round($val, $precision, $mode)
144

Visit & Downloaded from : www.LearnEngineering.in


Visit & Downloaded from : www.LearnEngineering.in

$val – is the value to be rounded.


$precision – (optional) number of decimal places to round to.
$mode – the type of rounding that occurs
<?php
$number = 3.55776232;
echo
round($number) . "<br/>". // 4
round($number, 1) . "<br/>". // 3.6
round($number, 3) . "<br/>"; // 3.558
?>
Other math functions for rounding are ceil() and floor() . To round a number to the
nearest whole number, these functions are better suited to that purpose.
ceil() – rounds fractions up.
floor() – rounds fractions down.
<?php
$number = 3.55776232;
echo
ceil($number) . "<br/>". // 4
floor($number) . "<br/>"; // 3
?>
Both functions require a value and unlike round(), do not have any additional parameters.
GENERATING RANDOM NUMBERS
Another very common math function is rand() which returns a random number between
two numbers.
Syntax
rand($min, $max)
$min – (optional) sets the lowest value to be returned. Default is 0
$max – (optional) sets the maximum value to be returned. Default returns get randmax().
We will need to specify a $max value in order to return a larger number.
<?php
echo rand(). "\n"; //10884
echo rand(). "\n"; // 621
echo rand(2, 10); //2
?>
ARRAY FUNCTIONS
Array or array() is itself a function that stores multiple values in to a single variable.
Aside from the array() function there are a number of other functions to manipulate
arrays, here we will look at some of the most common ones.

145

Visit & Downloaded from : www.LearnEngineering.in


Visit & Downloaded from : www.LearnEngineering.in

ADDING NEW ELEMENTS


Adding new elements to the end of an array can be achieved by calling the
array_push() function.
Syntax
array_push($array, $value1, $value2)
$array – the array in which you are adding new elements to.
$value1 – (required) is the first value to push onto the end of the $array.
$value2 – (optional) is the second value to push onto the end of the $array.
You can push as many values as you need.
<?php
$games = array();
$array = array_push($games, "Farcry 4");
$array = array_push($games, "Fallout 4");
$array = array_push($games, "Metal Gear");
$array = array_push($games, "Witcher 3");
echo $array; // returns 4
var_dump($games);
?>
However it is better to list each element in a single call like this:
<?php
$games = array(); // target array
$array = array_push($games,
"Farcry 4",
"Fallout 4",
"Metal Gear",
"Witcher 3");
echo $array; // returns 4
var_dump($games);
?>
Both methods result in the same outcome. If you echo or print array_push() it will return
the number of items to be pushed in to the array.
If you var_dump() the target array you you will see something like this.
array(4) {
[0] => string(8) "Farcry 4"
[1] => string(9) "Fallout 4"
[2] => string(10) "Metal Gear"
[3] => string(9) "Witcher 3"
}

146

Visit & Downloaded from : www.LearnEngineering.in


Visit & Downloaded from : www.LearnEngineering.in

SORTING AN ARRAY
As well as adding items to an array we sometimes need to be able to sort them. PHP has a
handy function called “funnily enough” sort() to do just that.
Syntax
sort($array, $sort_flags)
$array – the array in which you wish to sort.
$sort_flags – (optional) modifies the sorting behavior.
By default the sorting behavior will reorganize an array alphabetically or numerically.
<?php
$games = array( "Farcry 4", "Metal Gear", "Fallout 4", "Witcher 3", "Batman");
sort($games); // array to sort
echo join(", ", $games);
//output - Batman, Fallout 4, Farcry 4, Metal Gear, Witcher 3
?>
In order to echo or print out sorted arrays we can use a function called join() which is an
alias of another function called implode().
join(glue, array) or implode(glue, array) functions return a string from the elements of an
array and both have the same syntax.
glue – (optional) also known as a separator is what to put between the array elements.
array – (required) is the array to join to a string.
If you need to sort and reverse the order of any array then you can use a function
called rsort(). It works exactly the same way as sort() except the output is reversed.
<?php
$games = array( "Farcry 4", "Metal Gear", "Fallout 4", "Witcher 3",
"Batman");
rsort($games); // array to sort
echo join(", ", $games);
//output - Witcher 3, Metal Gear, Farcry 4, Fallout 4, Batman
?>
5(iii) Explain in detail about Cookies.
 Cookies are text files stored on the client computer and they are kept of use
tracking purpose. PHP transparently supports HTTP cookies.
There are three steps involved in identifying returning users −
 Server script sends a set of cookies to the browser. For example name, age, or
identification number etc.
 Browser stores this information on local machine for future use.

147

Visit & Downloaded from : www.LearnEngineering.in


Visit & Downloaded from : www.LearnEngineering.in

 When next time browser sends any request to web server then it sends those
cookies information to the server and server uses that information to identify the
user.
 Cookies are usually set in an HTTP header (although JavaScript can also set a
cookie directly on a browser). A PHP script that sets a cookie might send headers
that look something like this
HTTP/1.1 200 OK
Date: Fri, 04 Feb 2000 21:03:38 GMT
Server: Apache/1.3.9 (UNIX) PHP/4.0b3
Set-Cookie: name=xyz; expires=Friday, 04-Feb-07 22:03:38 GMT;
path=/; domain=tutorialspoint.com
Connection: close
Content-Type: text/html
 The Set-Cookie header contains a name value pair, a GMT date, a path and a
domain. The name and value will be URL encoded.
 The expires field is an instruction to the browser to "forget" the cookie after the
given time and date.
 If the browser is configured to store cookies, it will then keep this information
until the expiry date.
 If the user points the browser at any page that matches the path and domain of the
cookie, it will resend the cookie to the server.
The browser's headers might look something like this −
GET / HTTP/1.0
Connection: Keep-Alive
User-Agent: Mozilla/4.6 (X11; I; Linux 2.2.6-15apmac ppc)
Host: zink.demon.co.uk:1126
Accept: image/gif, */*
Accept-Encoding: gzip
Accept-Language: en
Accept-Charset: iso-8859-1,*,utf-8
Cookie: name=xyz
 A PHP script will then have access to the cookie in the environmental variables
$_COOKIE or $HTTP_COOKIE_VARS[] which holds all cookie names and
values. Above cookie can be accessed using $HTTP_COOKIE_VARS["name"].
SETTING COOKIES WITH PHP
 PHP provided setcookie() function to set a cookie. This function requires upto six
arguments and should be called before <html> tag. For each cookie this function
has to be called separately.

148

Visit & Downloaded from : www.LearnEngineering.in


Visit & Downloaded from : www.LearnEngineering.in

setcookie(name, value, expire, path, domain, security);


Here is the detail of all the arguments −
Name − This sets the name of the cookie and is stored in an environment variable called
HTTP_COOKIE_VARS. This variable is used while accessing cookies.
Value − This sets the value of the named variable and is the content that you actually
want to store.
Expiry − This specify a future time in seconds since 00:00:00 GMT on 1st Jan 1970.
After this time cookie will become inaccessible. If this parameter is not set then cookie
will automatically expire when the Web Browser is closed.
Path − This specifies the directories for which the cookie is valid. A single forward slash
character permits the cookie to be valid for all directories.
Domain − This can be used to specify the domain name in very large domains and must
contain at least two periods to be valid. All cookies are only valid for the host and domain
which created them.
Security − This can be set to 1 to specify that the cookie should only be sent by secure
transmission using HTTPS otherwise set to 0 which mean cookie can be sent by regular
HTTP.
Following example will create two cookies name and age these cookies will be expired
after one hour.
<?php
setcookie("name", "John Watkin", time()+3600, "/","", 0);
setcookie("age", "36", time()+3600, "/", "", 0);
?>
<html>
<head>
<title>Setting Cookies with PHP</title>
</head>
<body>
<?php echo "Set Cookies"?>
</body>
</html>
ACCESSING COOKIES WITH PHP
PHP provides many ways to access cookies. Simplest way is to use either $_COOKIE or
$HTTP_COOKIE_VARS variables. Following example will access all the cookies set in
above example.
<html>
<head>
<title>Accessing Cookies with PHP</title>

149

Visit & Downloaded from : www.LearnEngineering.in


Visit & Downloaded from : www.LearnEngineering.in

</head>
<body>
<?php
echo $_COOKIE["name"]. "<br />";
/* is equivalent to */
echo $HTTP_COOKIE_VARS["name"]. "<br />";
echo $_COOKIE["age"] . "<br />";
/* is equivalent to */
echo $HTTP_COOKIE_VARS["name"] . "<br />";
?>
</body>
</html>
We can use isset() function to check if a cookie is set or not.
<html>
<head>
<title>Accessing Cookies with PHP</title>
</head>
<body>
<?php
if( isset($_COOKIE["name"]))
echo "Welcome " . $_COOKIE["name"] . "<br />";
else
echo "Sorry... Not recognized" . "<br />";
?>
</body>
</html>
DELETING COOKIE WITH PHP
Officially, to delete a cookie you should call setcookie() with the name argument only but
this does not always work well, however, and should not be relied on.
It is safest to set the cookie with a date that has already expired −
<?php
setcookie( "name", "", time()- 60, "/","", 0);
setcookie( "age", "", time()- 60, "/","", 0);
?>
<html>
<head>
<title>Deleting Cookies with PHP</title>
</head>

150

Visit & Downloaded from : www.LearnEngineering.in


Visit & Downloaded from : www.LearnEngineering.in

<body>
<?php echo "Deleted Cookies" ?>
</body>
</html>

5(iv). Explain in detail about Regular Expressions


 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,
we can replace one string by another string and you can split a string into many
chunks.
 PHP offers functions specific to two sets of regular expression functions, each
corresponding to a certain type of regular expression.
 POSIX Regular Expressions
 PERL Style Regular Expressions
POSIX Regular Expressions
 The structure of a POSIX regular expression is not dissimilar to that of a typical
arithmetic expression: various elements (operators) are combined to form more
complex expressions.
 The simplest regular expression is one that matches a single character, such as g,
inside strings such as g, haggle, or bag.
Brackets
Brackets ([]) have a special meaning when used in the context of regular expressions.
They are used to find a range of characters.

Sr.No Expression & Description

1 [0-9] It matches any decimal digit from 0 through 9.

2 [a-z] It matches any character from lower-case a through lowercase z.

3 [A-Z] It matches any character from uppercase A through uppercase Z.

4 [a-Z] It matches any character from lowercase a through uppercase Z.

The ranges shown above are general; we could also use the range [0-3] to match any
decimal digit ranging from 0 through 3, or the range [b-v] to match any lowercase
character ranging from b through v.

151

Visit & Downloaded from : www.LearnEngineering.in


Visit & Downloaded from : www.LearnEngineering.in

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.

Sr.No Expression & Description

1 p+ It matches any string containing at least one p.

2 p* It matches any string containing zero or more p's.

3 p? It matches any string containing zero or more p's. This is just an alternative way
to use p*.

4 p{N} It matches any string containing a sequence of N p's

5 p{2,3} It matches any string containing a sequence of two or three p's.

6 p{2, } It matches any string containing a sequence of at least two p's.

7 p$ It matches any string with p at the end of it.

8 ^p It matches any string with p at the beginning of it.

Examples
Following examples will clear our concepts about matching characters.

Sr.No Expression & Description

1 [^a-zA-Z]
It matches any string not containing any of the characters ranging from a through z
and A through Z.

2 p.p
It matches any string containing p, followed by any character, in turn followed by
another p.

3 ^.{2}$
It matches any string containing exactly two characters.

4 <b>(.*)</b>
It matches any string enclosed within <b> and </b>.

5 p(hp)*
It matches any string containing a p followed by zero or more instances of the
sequence php.

152

Visit & Downloaded from : www.LearnEngineering.in


Visit & Downloaded from : www.LearnEngineering.in

Predefined Character Ranges


For our programming convenience several predefined character ranges, also known as
character classes, are available. Character classes specify an entire range of characters,
for example, the alphabet or an integer set

Sr.No Expression & Description

1 [[:alpha:]] It matches any string containing alphabetic characters aA through zZ.

2 [[:digit:]] It matches any string containing numerical digits 0 through 9.

3 [[:alnum:]] It matches any string containing alphanumeric characters aA through zZ and


0 through 9.

4 [[:space:]] It matches any string containing a space.

PHP's Regexp POSIX Functions


PHP currently offers seven functions for searching strings using POSIX-style regular
expressions −

Sr.No Function & Description

1 ereg()
The ereg() function searches a string specified by string for a string specified by
pattern, returning true if the pattern is found, and false otherwise.

2 ereg_replace()
The ereg_replace() function searches for string specified by pattern and replaces
pattern with replacement if found.

3 eregi()
The eregi() function searches throughout a string specified by pattern for a string
specified by string. The search is not case sensitive.

4 eregi_replace()
The eregi_replace() function operates exactly like ereg_replace(), except that the
search for pattern in string is not case sensitive.

5 split()
The split() function will divide a string into various elements, the boundaries of
each element based on the occurrence of pattern in string.

6 spliti()
The spliti() function operates exactly in the same manner as its sibling split(),
except that it is not case sensitive.

153

Visit & Downloaded from : www.LearnEngineering.in


Visit & Downloaded from : www.LearnEngineering.in

7 sql_regcase()
The sql_regcase() function can be thought of as a utility function, converting
each character in the input parameter string into a bracketed expression
containing two characters.

PERL Style Regular Expressions


 Perl-style regular expressions are similar to their POSIX counterparts.
 The POSIX syntax can be used almost interchangeably with the Perl-style regular
expression 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, we can search for large money sums using the '\d' meta
character: /([\d]+)000/, Here \d will search for any string of numerical character.
Modifiers
Several modifiers are available that can make your work with regexps much easier, like
case sensitivity, searching in multiple lines etc.
PHP's Regexp PERL Compatible Functions
PHP offers following functions for searching strings using Perl-compatible regular
expressions −

Sr.No Function & Description

1 preg_match()
The preg_match() function searches string for pattern, returning true if pattern
exists, and false otherwise.

2 preg_match_all()
The preg_match_all() function matches all occurrences of pattern in string.

3 preg_replace()
The preg_replace() function operates just like ereg_replace(), except that regular
expressions can be used in the pattern and replacement input parameters.

4 preg_split()
The preg_split() function operates exactly like split(), except that regular
expressions are accepted as input parameters for pattern.

5 preg_grep()
The preg_grep() function searches all elements of input_array, returning all

154

Visit & Downloaded from : www.LearnEngineering.in


Visit & Downloaded from : www.LearnEngineering.in

elements matching the regexp pattern.

6 preg_ quote()
Quote regular expression characters

155

Visit & Downloaded from : www.LearnEngineering.in


Visit & Downloaded from : www.LearnEngineering.in

UNIT V
INTRODUCTION TO AJAX and WEB SERVICES
Part –A (2marks)
1. What is Ajax? What technologies are being used in AJAX?
Ajax is a set of client side technologies that provides asynchronous
communication between user interfaces and web server. So the advantages of using
Ajax are asynchronous communication, minimal data transfer and server is not
overloaded with unnecessary load.
AJAX uses four technologies, which are as follows:
 JavaScript,
 XMLHttpRequest,
 Document Object Model (DOM),
 Extensible HTML (XHTML) and
 Cascading Style
 Sheets (CSS)
2. What is the syntax to create AJAX objects?
AJAX uses the following syntax to create an object:
Var myobject = new AjaxObject("page path");
The page path is the URL of the Web page containing the object that you want
to call. The URL must be of the same domain as the Web page.
3. What are the different ways to pass parameters to the server?
We can pass parameters to the server using either the GET or POST method.
The following code snippets show the example of both the
methods:
 Get: XmlHttpObject.Open("GET","file1.txt", true);
 Post: XmlHttpObject.Open("POST", "file2.txt", true);
4. What is a web service? Give any four examples (Nov/Dec 2015)
A Web service is a method of communication between two electronic devices
over the web. The W3C defines a "Web service" as "a software system designed
to support interoperable machine-to-machine interaction over a network". It has
an interface described in a machine-processable format specifically Web Services
Description Language (WSDL). Four examples are
SOAP
WSDL
UDDI
AJAX
5. What is meant by WSDL?
 WSDL stands for Web Services Description Language

156

Visit & Downloaded from : www.LearnEngineering.in


Visit & Downloaded from : www.LearnEngineering.in

 WSDL is based on XML


 WSDL is used to describe Web services
 WSDL is used to locate Web services
 WSDL is an XML-based language for locating and describing Web
services
6. What is UDDI?
 UDDI means Universal Description, Discovery and Integration.
 UDDI - platform-independent framework for describing services, discovering
businesses, and integrating business services by using the Internet.
- directory for storing information about web services
- directory of web service interfaces described by WSDL
- communicates via SOAP
7. What are the core elements of UDDI?
UDDI defines four core data elements within the data model:
o businessEntity (modeling business information)
o businessService (describing a service)
o tModel (describing specifications, classifications, or identifications)
o binding Template (mapping between a businessService and the set of
tModels that describe its technical fingerprint)
8. What is SOAP?
SOAP - Simple Object Access Protocol
- protocol specification for exchanging structured information in the
implementation of Web Services in computer networks.
- relies on Extensible Markup Language (XML) for its message format,
and usually relies on other Application Layer protocols, most notably
Hypertext Transfer Protocol (HTTP) and Simple Mail Transfer
Protocol (SMTP), for message negotiation and transmission.
9. What are the specifications of web service architecture?
The specifications are
 Standards based
 Modular
 Federated
 General purpose
10. What is the use of web services?
o Web services encompass a set of related standards that can enable two
computers
o The data is passed back and forth using standard protocols such as
HTTP, the same protocol used to transfer ordinary web pages.

157

Visit & Downloaded from : www.LearnEngineering.in


Visit & Downloaded from : www.LearnEngineering.in

o Web services operate using open, text-based standards that enable


components written in different languages and on different platforms to
communicate.
o They are ready to use pieces of software on the Internet. XML,
SOAP, Web Services Description Language (WSDL) and Universal
Description, Discovery and Integration (UDDI) are the standards on which
web services rely.
o UDDI is another XML based format that enables developers and
business to publish and locate Web services on a network.
11. List any four merits for usage of AJAX in web services. (Nov/ Dec 2015)
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.
12. What is the role of callback function in performing a partial page update in an
AJAX application? (May/June 2016)
The AJAX callback function – the function we assign as the onreadystatechange
event handler – is the central part of our AJAX requests. The callback function is
responsible for checking the progress of requests, identifying the result of the request
and handling data returned from the server. Callback functions also serve as
delegators, handing off to other areas of your application code.

Part - B
1. Compare and contrast the traditional web application architecture and AJAX
based web application architecture? (April/May 2016)
OR
Discuss Ajax client server architecture in detail (Nov/Dec 2015)
Introduction
 AJAX is an acronym for Asynchronous JavaScript and XML. It is a group of
inter-related technologies like javascript, dom, xml, html, css etc.
 AJAX allows you to send and receive data asynchronously without reloading
the web page. So it is fast.
 AJAX allows you to send only important information to the server not the
entire page. So only valuable data from the client side is routed to the server
side. It makes your application interactive and faster.
Where it is used?
 There are too many web applications running on the web that are using ajax
technology like gmail, facebook,twitter, google map, youtube etc.
158

Visit & Downloaded from : www.LearnEngineering.in


Visit & Downloaded from : www.LearnEngineering.in

Synchronous (Classic Web-Application Model)


 A synchronous request blocks the client until operation completes i.e. browser
is not unresponsive. In such case, javascript engine of the browser is blocked.

As we can see in the above image, full page is refreshed at request time and user is
blocked until request completes. Let's understand it another way.

Asynchronous (AJAX Web-Application Model)


 An asynchronous request doesn‟t block the client i.e. browser is responsive. At
that time, user can perform another operation also. In such case, javascript
engine of the browser is not blocked.
 Here full page is not refreshed at request time and user gets response from the
ajax engine. Let's try to understand asynchronous communication by the image
given below.

159

Visit & Downloaded from : www.LearnEngineering.in


Visit & Downloaded from : www.LearnEngineering.in

Traditional web application architecture Vs AJAX based web application


architecture

2. How AJAX will work? Explain in detail about XMLHttpRequest and call back?
An object of XMLHttpRequest is used for asynchronous communication between
client and server. It performs following operations:
1. Sends data from the client in the background.
2. Receives the data from the server.
3. Updates the webpage without reloading it.
Properties of XMLHttpRequest object
The common properties of XMLHttpRequest object are as follows:

Property Description

onReadyStateChange It is called whenever readystate attribute changes. It must not be


used with synchronous requests.

ReadyState represents the state of the request. It ranges from 0 to 4.


0 UNOPENED open() is not called.
1 OPENED open is called but send() is not called.
2 HEADERS_RECEIVED send() is called, and headers and status
are available.
3 LOADING Downloading data; responseText holds the data.

160

Visit & Downloaded from : www.LearnEngineering.in


Visit & Downloaded from : www.LearnEngineering.in

4 DONE The operation is completed fully.

ReponseText returns response as text.

ResponseXML returns response as XML

Methods of XMLHttpRequest object


The important methods of XMLHttpRequest object are as follows:

Method Description

void open(method, URL) opens the request specifying get or post


method and url.

void open(method, URL, async) same as above but specifies asynchronous


or not.

void open(method, URL, async, username, same as above but specifies username and
password) password.

void send() sends get request.

void send(string) send post request.

setRequestHeader(header,value) it adds request headers.

How AJAX works?


AJAX communicates with the server using XMLHttpRequest object. Let's try to
understand the flow of ajax or how ajax works by the image displayed below.
1. User sends a request from the UI and a javascript call goes to XMLHttpRequest
object.
2. HTTP Request is sent to the server by XMLHttpRequest object.
3. Server interacts with the database using JSP, PHP, Servlet, ASP.net etc.
4. Data is retrieved.

5. Server sends XML data or JSON data to the XMLHttpRequest callback function.
6. HTML and CSS data is displayed on the browser.

161

Visit & Downloaded from : www.LearnEngineering.in


Visit & Downloaded from : www.LearnEngineering.in

Ajax Example

 To create ajax example, you need to use any server-side language e.g. servlet, jsp,
php, asp.net etc. Here we are using JSP for generating the server-side code.
 In this example, we are simply printing the table of the given number.
Steps to create ajax example with jsp
1. load the org.json.jar file
2. create input page to receive any text or number
3. create server side page to process the request
4. provide entry in web.xml file
1. Load the org.json.jar file
 download the org.json.jar file and save it in inside the WEB-INF/lib directory.
2. Create input page to receive any text or number
 In this example, we have created a form that gets input from the user.
 When user clicks on the showTable button, sendInfo()function is called. We
have written all the ajax code inside this function.
 We have called the getInfo() function whenever ready state changes.
 It writes the returned data in the web page dynamically by the help
of innerHTML property.
table1.html
<html>
<head>
<script>
var request;
function sendInfo()
{
var v=document.vinform.t1.value;
var url="index.jsp?val="+v;
if(window.XMLHttpRequest){
request=new XMLHttpRequest();
}
else if(window.ActiveXObject){
request=new ActiveXObject("Microsoft.XMLHTTP");
}
try
{
request.onreadystatechange=getInfo;
request.open("GET",url,true);
request.send();

162

Visit & Downloaded from : www.LearnEngineering.in


Visit & Downloaded from : www.LearnEngineering.in

}
catch(e)
{
alert("Unable to connect to server");
}
}
function getInfo(){
if(request.readyState==4){
var val=request.responseText;
document.getElementById('amit').innerHTML=val;
}
}
</script>
</head>
<body>
<marquee><h1>This is an example of ajax</h1></marquee>
<form name="vinform">
<input type="text" name="t1">
<input type="button" value="ShowTable" onClick="sendInfo()">
</form>
<span id="amit"> </span>
</body>
</html>
3. Create server side page to process the request
index.jsp
<%
int n=Integer.parseInt(request.getParameter("val"));
for(int i=1;i<=10;i++)
out.print(i*n+"<br>");
%>
4. web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
<session-config>
<session-timeout> 30 </session-timeout>

163

Visit & Downloaded from : www.LearnEngineering.in


Visit & Downloaded from : www.LearnEngineering.in

</session-config>
<welcome-file-list>
<welcome-file>table1.html</welcome-file>
</welcome-file-list>
</web-app>

Output

3. Explain in detail about the basic concepts of web services?


 Web services are open standard (XML, SOAP, HTTP etc.) based Web
applications that interact with other web applications for the purpose of
exchanging data.
 Web Services can convert your existing applications into Web-applications.
Web Services
 A web service is any piece of software that makes itself available over the
internet and uses a standardized XML messaging system. XML is used to encode
all communications to a web service. For example, a client invokes a web service
by sending an XML message, then waits for a corresponding XML response. As
all communication is in XML, web services are not tied to any one operating
system or programming language--Java can talk with Perl; Windows applications
can talk with Unix applications.
 Web services are self-contained, modular, distributed, dynamic applications that
can be described, published, located, or invoked over the network to create
products, processes, and supply chains. These applications can be local,
distributed, or web-based. Web services are built on top of open standards such
as TCP/IP, HTTP, Java, HTML, and XML.
 Web services are XML-based information exchange systems that use the Internet
for direct application-to-application interaction. These systems can include
programs, objects, messages, or documents.

164

Visit & Downloaded from : www.LearnEngineering.in


Visit & Downloaded from : www.LearnEngineering.in

 A web service is a collection of open protocols and standards used for


exchanging data between applications or systems. Software applications written
in various programming languages and running on various platforms can use web
services to exchange data over computer networks like the Internet in a manner
similar to inter-process communication on a single computer. This
interoperability (e.g., between Java and Python, or Windows and Linux
applications) is due to the use of open standards.
To summarize, a complete web service is, therefore, any service that:
 Is available over the Internet or private (intranet) networks
 Uses a standardized XML messaging system
 Is not tied to any one operating system or programming language
 Is self-describing via a common XML grammar
 Is discoverable via a simple find mechanism
Components of Web Services
The basic web services platform is XML + HTTP. All the standard web services
work using the following components
 SOAP (Simple Object Access Protocol)
 UDDI (Universal Description, Discovery and Integration)
 WSDL (Web Services Description Language)
Working of Web Service
A web service enables communication among various applications by using open
standards such as HTML, XML, WSDL, and SOAP. A web service takes the help of:
 XML to tag the data
 SOAP to transfer a message
 WSDL to describe the availability of service.
Example
 Consider a simple account-management and order processing system. The
accounting personnel use a client application built with Visual Basic or JSP to create
new accounts and enter new customer orders.
 The processing logic for this system is written in Java and resides on a Solaris
machine, which also interacts with a database to store information.
The steps to perform this operation are as follows:
 The client program bundles the account registration information into a SOAP
message.
 This SOAP message is sent to the web service as the body of an HTTP POST
request.
 The web service unpacks the SOAP request and converts it into a command that
the application can understand.

165

Visit & Downloaded from : www.LearnEngineering.in


Visit & Downloaded from : www.LearnEngineering.in

 The application processes the information as required and responds with a new
unique account number for that customer.
 Next, the web service packages the response into another SOAP message, which
it sends back to the client program in response to its HTTP request.
 The client program unpacks the SOAP message to obtain the results of the
account registration process.
Web Services - Architecture
There are two ways to view the web service architecture:
 The first is to examine the individual roles of each web service actor.
 The second is to examine the emerging web service protocol stack.
Web Service Roles
There are three major roles within the web service architecture:
1. Service Provider
a. This is the provider of the web service. The service provider implements
the service and makes it available on the Internet.
2. Service Requestor
a. This is any consumer of the web service. The requestor utilizes an existing
web service by opening a network connection and sending an XML
request.
3. Service Registry
a. This is a logically centralized directory of services. The registry provides a
central place where developers can publish new services or find existing
ones. It therefore serves as a centralized clearing house for companies and
their services.
Web Service Protocol Stack
A second option for viewing the web service architecture is to examine the
emerging web service protocol stack. The stack is still evolving, but currently has four
main layers.
1. Service Transport
a. This layer is responsible for transporting messages between applications.
Currently, this layer includes Hyper Text Transport Protocol (HTTP),
Simple Mail Transfer Protocol (SMTP), File Transfer Protocol (FTP), and
newer protocols such as Blocks Extensible Exchange Protocol (BEEP).
2. XML Messaging
a. This layer is responsible for encoding messages in a common XML format
so that messages can be understood at either end. Currently, this layer
includes XML-RPC and SOAP.

166

Visit & Downloaded from : www.LearnEngineering.in


Visit & Downloaded from : www.LearnEngineering.in

3. Service Description
a. This layer is responsible for describing the public interface to a specific
web service. Currently, service description is handled via the Web Service
Description Language (WSDL).
4. Service Discovery
a. This layer is responsible for centralizing services into a common registry
and providing easy publish/find functionality. Currently, service discovery
is handled via Universal Description, Discovery, and Integration (UDDI).
Web Services - Components
XML-RPC
This is the simplest XML-based protocol for exchanging information between
computers.
 XML-RPC is a simple protocol that uses XML messages to perform RPCs.
 Requests are encoded in XML and sent via HTTP POST.
 XML responses are embedded in the body of the HTTP response.
 XML-RPC is platform-independent.
 XML-RPC allows diverse applications to communicate.
 A Java client can speak XML-RPC to a Perl server.
 XML-RPC is the easiest way to get started with web services.
SOAP
SOAP is an XML-based protocol for exchanging information between computers.
 SOAP is a communication protocol.
 SOAP is for communication between applications.
 SOAP is a format for sending messages.
 SOAP is designed to communicate via Internet.
 SOAP is platform independent.
 SOAP is language independent.
WSDL
 WSDL is an XML-based language for describing web services and how to
access them.
 WSDL stands for Web Services Description Language.
 WSDL was developed jointly by Microsoft and IBM.
 WSDL is an XML based protocol for information exchange in decentralized and
distributed environments.
 WSDL is the standard format for describing a web service.
 WSDL definition describes how to access a web service and what operations it
will perform.
 WSDL is a language for describing how to interface with XML-based services.
167

Visit & Downloaded from : www.LearnEngineering.in


Visit & Downloaded from : www.LearnEngineering.in

 WSDL is an integral part of UDDI, an XML-based worldwide business registry.


 WSDL is pronounced as 'wiz-dull' and spelled out as 'W-S-D-L'.
UDDI
UDDI is an XML-based standard for describing, publishing, and finding web
services.
 UDDI stands for Universal Description, Discovery, and Integration.
 UDDI is a specification for a distributed registry of web services.
 UDDI is platform independent, open framework.
 UDDI can communicate via SOAP, CORBA, and Java RMI Protocol.
 UDDI uses WSDL to describe interfaces to web services.
 UDDI is seen with SOAP and WSDL as one of the three foundation standards of
web services.
 UDDI is an open industry initiative enabling businesses to discover each other
and define how they interact over the Internet.
4. Describe the structure of WSDL document, its elements and their purposes with
appropriate examples. (May/June 2016)
 The Web Services Description Language (WSDL) is the most fundamental
technology standard associated with the design of services.
 WSDL definitions are a central part of all aspects of service design.
The structure of a WSDL definition

The definitions element


 The definitions element is the root or parent element of every WSDL
document.
 It defines the name of the web service and specifies the namespaces that used
within WSDL documents are established.
Example

168

Visit & Downloaded from : www.LearnEngineering.in


Visit & Downloaded from : www.LearnEngineering.in

<definitions name="Employee"
targetNamespace="http://www.xmltc.com/tls/employee/wsdl/"
xmlns="http://schemas.xmlsoap.org/wsdl/"
xmlns:act="http://www.xmltc.com/tls/employee/schema/accounting/"
xmlns:hr="http://www.xmltc.com/tls/employee/schema/hr/"
xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/"
xmlns:tns="http://www.xmltc.com/tls/employee/wsdl/"
xmlns:xsd="http://www.w3.org/2001/XMLSchema">
...
</definitions>

Description
 Xmlns - specifies default name space
 Xmlns:tns-Means this namespace i.e namespace used for particular WSDL.
 xmlns:xsd namespace declaration, all elements within the WSDL that belong to
the XML Schema Definition Language.
 xmlns:act and xmlns:hr - also a namespace declarations.
 xmlns:soap - establishes the soap: qualifier used by elements defined in the
bindings.
 targetNameSpace - it lets the WSDL document make references to itself an an
XML schema namespace.
The SOAP message body contains XML content that can represent anything from
simple parameter data to complex business documents. This content can be formally
defined through types provided by the WSDL types area.
Example: A types construct containing an XSD schema construct in which
a complexType is defined.
<types>
<schema
xmlns="http://www.w3.org/2001/XMLSchema"
targetNamespace=
"http://www.xmltc.com/railco/transform/schema/">

169

Visit & Downloaded from : www.LearnEngineering.in


Visit & Downloaded from : www.LearnEngineering.in

<complexType name="ReturnCodeType">
<sequence>
<element name="Code" type="xsd:integer"/>
<element name="Message" type="xsd:string"/>
</sequence>
</complexType>
</schema>
</types>
The message and part elements
Message elements
 Message element assigns the message a name and contains one or more part
child elements that each are assigned a type.
 Message elements are associated to operation elements to establish the input
and output messages of the operation.
Part elements
 Part elements use the type or element attributes to identify the data type of the
message part.
1. Type attribute
 A simple or complex type and generally is used for RPC-style messages.
2. Element attribute
 This can reference an XSD element.
 The name attribute is used to uniquely identify part elements within a
message construct.
Example
Two message constructs likely representing the input and output messages for an
operation.
<message name="getEmployeeWeeklyHoursRequestMessage">
<part name="RequestParameter" element="act:EmployeeHoursRequestType"/>
</message>
<message name="getEmployeeWeeklyHoursResponseMessage">
<part name="ResponseParameter" element="act:EmployeeHoursResponseType/>
</message>
Example
A simple parameter message requiring just a single integer value.
<message name="getID">
<part type="xsd:integer"/>
</message>

170

Visit & Downloaded from : www.LearnEngineering.in


Visit & Downloaded from : www.LearnEngineering.in

The portType, interface, and operation elements


 Service operations are defined within the portType area of the WSDL
definition.
 portType constructs simply represent collections of operations
 Individual operations are defined using the aptly named operation element.
Example
The portType construct hosting two operation constructs.
<portType name="EmployeeInterface">
<operation name="GetWeeklyHoursLimit">
...
</operation>
<operation name="UpdateHistory">
...
</operation>
</portType>
The input and output elements (when used with operation)
 Each operation construct contains input and/or output child elements that
represent the request and response messages the operation is capable of
processing.
Example
operation elements with child input and output elements.
<operation name="GetWeeklyHoursLimit">
<input message="tns:getWeeklyHoursRequestMessage"/>
<output message="tns:getWeeklyHoursResponseMessage"/>
</operation>
<operation name="UpdateHistory">
<input message="tns:updateHistoryRequestMessage"/>
<output message="tns:updateHistoryResponseMessage"/>
</operation>
Example
An operation element with a single child input element.
<operation name="Submit">
<input message="tns:receiveSubmitMessage"/>
</operation>
The binding element
 The binding element begins the concrete portion of the service definition, to
assign a communications protocol that can be used to access and interact with the
171

Visit & Downloaded from : www.LearnEngineering.in


Visit & Downloaded from : www.LearnEngineering.in

WSDL.
 The binding construct contains one or more operation elements.
Example
The binding construct hosting concrete operation definitions.
<binding name="EmployeeBinding" type="tns:EmployeeInterface">
<soap:binding style="document" transport="http://schemas.xmlsoap.org/soap/http"/>
<operation name="GetWeeklyHoursLimit">
<soap:operation soapAction="..."/>
...
</operation>
<operation name="UpdateHistory">
<soap:operation soapAction="..."/>
...
</operation>
</binding>
The style attribute of the soap:binding element defines whether the SOAP messages
used to support an operation are to be formatted as document or RPC-style messages.
The input and output elements (when used with binding)
 Each operation element within a binding construct mirrors the input and
output message child elements defined in the abstract definition.
 The input and output elements do not reference the message elements again.
 It contains protocol details that establish how the messages are going to be
processed and interpreted by the chosen communication technology.
Example
Input and output elements providing message processing information.
<operation name="GetWeeklyHoursLimit">
<soap:operation soapAction="..."/>
<input>
<soap:body use="literal"/>
</input>
<output>
<soap:body use="literal"/>
</output>
</operation>
<operation name="UpdateHistory">
<soap:operation soapAction="..."/>

172

Visit & Downloaded from : www.LearnEngineering.in


Visit & Downloaded from : www.LearnEngineering.in

<input>
<soap:body use="literal"/>
</input>
<output>
<soap:body use="literal"/>
</output>
</operation>
This introduces the soap: body element from the SOAP language that defines the
data type system to be used by SOAP processors, via the use attribute. The use
attribute can be set to "encoding" or "literal".
The service, port, and endpoint elements
 The service element simply provides a physical address at which the service
can be accessed.
 It hosts the port element that contains this location information.
Example
The service and port elements establishing the physical service address.
<service name="EmployeeService">
<port binding="tns:EmployeeBinding" name="EmployeePort">
<soap:address location="http://www.xmltc.com/tls/employee/"/>
</port>
</service>
Because we are binding to the SOAP protocol, the port element contains a child
soap:address element with the physical address information.
The import element
 The import element can be used to import parts of the WSDL definition as
well as XSD schemas.
Example
The import element referencing a schema document.
<import namespace="http://www.xmltc.com/tls/schemas/"
location="http://www.xmltc.com/tls/schemas/employee.xs d"/>
The documentation element
This optional element simply allows u s to add descriptive, human-readable
annotations within a WSDL definition.
Example
The documentation element providing a description of the overall service interface.

<portType name="TransformInterface">
<documentation>

173

Visit & Downloaded from : www.LearnEngineering.in


Visit & Downloaded from : www.LearnEngineering.in

Retrieves an XML document and converts it into the native accounting document
format.
</documentation>
...
</portType>
5. Explain in detail about the structure of SOAP protocol with example?
OR
Draw the structure of a SOAP message (May/June 2016)
 SOAP stands for simple object Access protocol.
 SOAP is an XML-based messaging protocol.
 It defines a set of rules for structuring messages that can be used for simple
one-way messaging but is particularly useful for performing RPC-style (Remote
Procedure call) request-response dialogues.
Figure: The structure of a SOAP message document.

The Envelope element


 The Envelope element represents the root of SOAP message structures.
 It contains a mandatory Body construct and an optional Header construct.
Example
The root Envelope constructs hosting Header and Body constructs.
<Envelope xmlns ="http://schemas.xmlsoap.org/soap/envelope/">
<Header>
...
</Header>
<Body>
...
</Body>
</Envelope>
The Header element
 SOAP header blocks destined to be embedded in the Header construct.
Example

174

Visit & Downloaded from : www.LearnEngineering.in


Visit & Downloaded from : www.LearnEngineering.in

The Header construct hosting a header block.


<Header>
<x:CorrelationID xmlns:x="http://www.xmltc.com/tls/headersample/"
mustUnderstand="1">
0131858580-JDJ903KD
</x:CorrelationID>
</Header>
The Body element
 This is the one required child element of the SOAP Envelope construct.
 SOAP message Body constructs are defined within the WSDL message
constructs.
Figure: SOAP message

A SOAP message body defined within the WSDL message constructs. The
actual processing of the SOAP message via a wire protocol is governed by the
constructs within the concrete definition
Example
The contents of a sample Body construct.

<Body>
<soa:book xmlns:soa="http://www.serviceoriented.ws/">
<soa:ISBN>
0131858580
</soa:ISBN>

175

Visit & Downloaded from : www.LearnEngineering.in


Visit & Downloaded from : www.LearnEngineering.in

<soa:title>
Service-Oriented Architecture
Concepts, Technology, and Design
</soa:title>
</soa:book>
</Body>
The Fault element
 The optional Fault construct provides a ready made error response that is
added inside the Body construct.
 The fault code element contains one of a set of fault conditions predefined by
the SOAP specification.
Example
The Fault constructs residing within the Body construct.

<Body>
<Fault>
<faultcode>
MustUnderstand
</faultcode>
<faultstring>
header was not recognized
</faultstring>
<detail>
<x:appMessage
xmlns:x="http://www.xmltc.com/tls/faults">
The CorrelationID header was not
processed by a recipient that was
required to process it. Now a fault's been
raised and it looks like this recipient is
going to be a problem.
</x:appMessage>
</detail>
</Fault>
</Body>

176

Visit & Downloaded from : www.LearnEngineering.in


Visit & Downloaded from : www.LearnEngineering.in

Industrial/Practical Connectivity of the subject

1. Relate effectively to web development supervisors, coworkers, and clients.


2. Configure and maintain internet services, internet application servers, database
servers, and network services.
3. Construct, modify, implement, query, and maintain effective databases, and
interface with applications.
4. Develop internet services and web application security by applying appropriate
techniques and strategies.
5. Program and debug internet applications using a variety of client-side and
serverside development languages.
6. Develop, deploy, and maintain electronic commerce (e-commerce) applications.
7. Create and maintain functional and dynamic websites by applying graphic and
web design skills and principles.
8. Develop and maintain websites reflective of business objectives and clients` needs
through the application of advertising and marketing principles.
9. Coordinate or participate as a member of a project management team that
develops internet applications.
10. Develop strategies for ongoing personal and professional development that will
lead to enhanced work performance and career opportunities, and keep pace with
industry changes.
11. Identify and apply discipline-specific practices that contribute to the local and
global community through social responsibility, economic commitment and
environmental stewardship.

177

Visit & Downloaded from : www.LearnEngineering.in


Visit & Downloaded from : www.LearnEngineering.in

B.E/ B.Tech. DEGRE EXAMINATION, NOVEMBER/DECEMBER 2015


Fifth Semester
Computer Science and Engineering
CS6501 Internet Programming
(Regulations 2013)
Time: Three hours Maximum: 100 marks
Answer ALL questions
Part- A (10x2=10 marks)
1. Define an abstract class. Give example. [Page.No. 6]
2. Expand DOM, AJAX, AWT, JDBC. [Page.No. 6]
3. List the unique features of java. [Page.No. 9]
4. Differentiate internet and intranet. [Page.No. 47]
5. What are cookies? Give its uses. [Page.No. 89]
6. Define event programming. Name any 2 of its techniques. [Page.No. 88]
7. What is XML parse tree? [Page.No. 123]
8. Name any four built in functions in PHP. [Page.No. 124]
9. What is a web service? Give any four examples. [Page.No. 156]
10. List any four merits for usage of AJAX in web services. [Page.No. 158]
Part B-(5x16=80 marks)
11 (a) (i) Write a Java program to draw smiley using applet.[Page.No.17](10)
(ii) Compare overloading and overriding. [Page.No.17] (6)
Or
(b) Discuss the following:
(i) Multithreading in java [Page.No. 9] (8)
(ii) Exception handling in Java [Page.No. 9] (8)
12.(a) Discuss on
(i) web servers [Page.No. 71] (8)
(ii) XHTML [Page.No. 71] (8)
Or
(b) Elaborate with example the usage of CSS in HTML[Page.No. 68] (16)
13.(a) Using HTML and JSP, design a scientific calculator [Page.No. 90](16)
Or
(b) Explain
(i) DOM model [Page.No. 96] (8)
(ii) Database connectivity [Page.No. 98] (8)
14.(a) Write a PHP program to do string manipulations [Page.No. 127](16)
Or
(b) Explain in detail about
178

Visit & Downloaded from : www.LearnEngineering.in


Visit & Downloaded from : www.LearnEngineering.in

(i) XML schema [Page.No. 129] (8)


(ii) XML parsers and validation [Page.No. 132] (8)
15. (a) Discuss Ajax client server architecture in detail [Page.No. 158] (16)
Or
(b) Write short notes on:
(i) SOAP [Page.No. 164] (8)
(ii) WSDL [Page.No. 164] (8)

179

Visit & Downloaded from : www.LearnEngineering.in


Visit & Downloaded from : www.LearnEngineering.in

B.E/ B.Tech. DEGRE EXAMINATION, APRIL/MAY 2016


Fifth Semester
Computer Science and Engineerring
CS6501 Internet Programming
(Regulations 2013)
Time: Three hours Maximum: 100 marks
Answer ALL questions
Part- A (10x2=10 marks)
1. Give atleast three differences between overriding and overloading of methods
in java. [Page.No. 6]
2. Give an example for a chained exception in java. [Page.No. 209]
3. How does a rich internet application (RIA) differ from traditional web
applications? [Page.No. 48]
4. Write appropriate inline CSS to show a section of the HTML document with
the font size of 20. [Page.No. 207]
5. Write appropriate javascript code to remove an element (current element)
from a DOM. [Page.No. 207]
6. Write the code segment to store current server time in session using java
servlet API. [Page.No. 208]
7. Why is XSLT an important tool in development of work applications?
[Page.No. 123]
8. When should the super global arrays in PHP be used? Which super global
array in PHP would contain a HTML form’s POST data? [Page.No. 123]
9. Draw the structure of a SOAP message. [Page.No. 174]
10. What is the role of callback function in performing a partial page update in an
AJAX application? [Page.No. 158]
Part – B (5x16=80 marks)
11 (a) Consider a scenario where one thread (Producer) is producing integer data
starting from 0 and another thread (consumer) consuming it. In addition, assume
that the producer has to wait until the consumer is finished consuming before it
generates more data. Using java interprocess communication mechanism
implements the above producer and consumer. [Page.No. 183]
OR
(b) Write a java program to find the sum of the digits of the given number. Create a
swing GUI to get an input number and show the sum of its digits. In case the sum
cannot be found due to incorrect input should print “Not able to find the sum. Check
input”. [Page.No. 195]
12(a) Write a brief note on each one of the following RIA technologies [Page.No. 48]
180

Visit & Downloaded from : www.LearnEngineering.in


Visit & Downloaded from : www.LearnEngineering.in

 AJAX
 Flex
 Silverlight
 JavaFx
OR
(b) Write the HTML 5 code for creating a feedback form as shown below. Include
comments in the code to highlight the markup elements and their purpose. The
HTML form should use POST for submitting the form to a program
ProcessContactForm.php [Page.No. 188]
Internet Programming
Contact Form

13(a) Use javascript and HTML to create a page with two panes. The first pane( on
the left) should have a text area where HTML code can be typed by the user. The
pane on the right side should display the preview of the HTML code typed by the
user, as it would be seen on the browser. [Page.No. 197]
OR
(b) Assume that database has a table Employee with two columns. EmployeeID
and Name. Assume that the administrator user id and password to access the
database table are, scott and tiger. Write a JDBC program that can query and print
all the entries in the table Employee. Make the database connection using a type2
driver database.driver and connection string jdbc:db:oci [Page.No. 185]
(16)

14 (a) Create a Webserver based chat applications using PHP. The application
should provide the following functions

181

Visit & Downloaded from : www.LearnEngineering.in


Visit & Downloaded from : www.LearnEngineering.in

 Login
 Send message(to one or more contacts)
 Receive messages ( from one or more contacts)
 Add/ delete/ modify contact list of the user
Discuss the application’s user interface and use comments in PHP to explain
the code clearly.
[Page.No. 199]
OR
(b) (i) List the essential features of XML parsers. [Page.No. 132]
(8)
(ii)List at least five significant differences between DID and XML schema for
defining XML document structures with appropriate examples.
[Page.No. 129] (8)

15(a) Compare and contrast the traditional web application architecture and AJAX
based web application architecture. [Page.No. 158] (16)
OR
(b) Describe the structure of a WSDL document, its elements and their purposes
with appropriate examples [Page.No. 164] (16)

182

Visit & Downloaded from : www.LearnEngineering.in


Visit & Downloaded from : www.LearnEngineering.in

University Programs
1. Consider a scenario where one thread (Producer) is producing integer data
starting from 0 and another thread (consumer) consuming it. In addition,
assume that the producer has to wait until the consumer is finished
consuming before it generates more data. Using java interprocess
communication mechanism implements the above producer and consumer.
(May/June 2016)

public class ProducerConsumerTest {


public static void main(String[] args) {
CubbyHole c = new CubbyHole();
Producer p1 = new Producer(c, 1);
Consumer c1 = new Consumer(c, 1);
p1.start();
c1.start();
}
}
class CubbyHole {
private int contents;
private boolean available = false;
public synchronized int get() {
while (available == false) {
try {
wait();
}
catch (InterruptedException e) {
}
}
available = false;
notifyAll();
return contents;
}
public synchronized void put(int value) {
while (available == true) {
try {
wait();
}
catch (InterruptedException e) {
}

183

Visit & Downloaded from : www.LearnEngineering.in


Visit & Downloaded from : www.LearnEngineering.in

}
contents = value;
available = true;
notifyAll();
}
}
class Consumer extends Thread {
private CubbyHole cubbyhole;
private int number;
public Consumer(CubbyHole c, int number) {
cubbyhole = c;
this.number = number;
}
public void run() {
int value = 0;
for (int i = 0; i < 10; i++) {
value = cubbyhole.get();
System.out.println("Consumer #" + this.number+ " got: " + value);
}
}
}
class Producer extends Thread {
private CubbyHole cubbyhole;
private int number;
public Producer(CubbyHole c, int number) {
cubbyhole = c;
this.number = number;
}
public void run() {
for (int i = 0; i < 10; i++) {
cubbyhole.put(i);
System.out.println("Producer #" + this.number + " put: " + i);
try {
sleep((int)(Math.random() * 100));
} catch (InterruptedException e) { }
}
}
}

184

Visit & Downloaded from : www.LearnEngineering.in


Visit & Downloaded from : www.LearnEngineering.in

Result

The above code sample will produce the following result.

Producer #1 put: 0
Consumer #1 got: 0
Producer #1 put: 1
Consumer #1 got: 1
Producer #1 put: 2
Consumer #1 got: 2
Producer #1 put: 3
Consumer #1 got: 3
Producer #1 put: 4
Consumer #1 got: 4
Producer #1 put: 5
Consumer #1 got: 5
Producer #1 put: 6
Consumer #1 got: 6
Producer #1 put: 7
Consumer #1 got: 7
Producer #1 put: 8
Consumer #1 got: 8
Producer #1 put: 9
Consumer #1 got: 9

2. Assume that database has a table Employee with two columns. EmployeeID
and Name. Assume that the administrator user id and password to access the
database table are, scott and tiger. Write a JDBC program that can query
and print all the entries in the table Employee. Make the database connection
using a type2 driver database.driver and connection string jdbc:db:oci (16)
(May/ June 16)

import java.sql.DriverManager;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.*;
import java.io.*;
import java.net.*;
public class jdbcex {

185

Visit & Downloaded from : www.LearnEngineering.in


Visit & Downloaded from : www.LearnEngineering.in

public static void main(String[] argv) {


System.out.println("-------- MySQL JDBC Connection Testing ------------");
Connection connection = null;
Statement st=null;
try {
Class.forName("com.mysql.jdbc.Driver");
connection =
DriverManager.getConnection("jdbc:mysql://localhost:3306/employ","root",
"tiger");
st = connection.createStatement();
} catch (Exception e) {
System.out.println("Where is your MySQL JDBC Driver?");
System.out.println("Connection Failed! Check output console");
}
System.out.println("MySQL JDBC Driver Registered!");
if (connection != null) {
System.out.println("You made it, take control your database now!");
} else {
System.out.println("Failed to make connection!");
}
try
{
int ch=' ';
System.out.println("\n1.Select Employee\n2.Add Employee\n3Update
Emp \n4.Delete Employee\n5.Exit\n");
while(ch<='5')
{
System.out.println("\nEnter your choice\n");
BufferedReader br=new BufferedReader(new
InputStreamReader(System.in));
ch=Integer.parseInt(br.readLine());
switch (ch)
{
case 1: ResultSet rs = st.executeQuery("select * from emp");
System.out.println("EMPLOYEE TABLE DETAILS");
System.out.println("Emp No \t Emp Name\n");
while(rs.next())
{

186

Visit & Downloaded from : www.LearnEngineering.in


Visit & Downloaded from : www.LearnEngineering.in

String s1= rs.getString("empno");


String s2=rs.getString("empname");
System.out.println(s1+"\t"+s2+"\n");
}
break;
case 2: System.out.println("\nADD DATA TO EMPLOYEE\n");
System.out.println("Enter the empno\n");
//int empno=Integer.parseInt(br.readLine());
String empno=br.readLine();
System.out.println("\nEnter the empname\n");
String empname=br.readLine();
String strsql="INSERT INTO emp(empno,empname) VALUES
('"+empno+"','"+empname+"')";
st.executeUpdate(strsql);
System.out.println(strsql);
System.out.println("\nThe above data is Inserted.\n");
break;
case 3:System.out.println("Enter the empno you want to update\n");
//int empno=Integer.parseInt(br.readLine());
String no=br.readLine();
System.out.println("\nEnter the new empname\n");
String name=br.readLine();
String strql="update emp set empname='"+name+"' where
empno='"+no+"'";
st.executeUpdate(strql);
System.out.println(strql);
System.out.println("\nThe above data is updated.\n");
break;
case 4: System.out.println("Enter the empno you want to delete\n");
//int empno=Integer.parseInt(br.readLine());
no=br.readLine();
//String sql="delete from emp where empno='3'";
String sql="delete from emp where empno='"+ no +"'";
st.executeUpdate(sql);
System.out.println(sql);
System.out.println("\nThe above data is deleted.\n") ;
break;

187

Visit & Downloaded from : www.LearnEngineering.in


Visit & Downloaded from : www.LearnEngineering.in

case 5:
System.exit(0);
break;
default: System.out.println("choice");
break;
}}
connection.close();
}
catch (Exception e) {
System.err.println("Got an exception! ");
System.err.println(e.getMessage());
}
}
}
3.Write the HTML 5 code for creating a feedback form as shown below.
Include comments in the code to highlight the markup elements and their
purpose. The HTML form should use POST for submitting the form to a
program ProcessContactForm.php (May/June 2016)

index.html
<div id="contact-form" class="clearfix">
<h1>Get In Touch!</h1>
<h2>Fill out our super swanky HTML5 contact form below to get in touch
with us! Please provide as much information as possible for us to help you
with your enquiry :)</h2>
<ul id="errors" class="">
<li id="info">There were some problems with your form submission:</li>
</ul>

188

Visit & Downloaded from : www.LearnEngineering.in


Visit & Downloaded from : www.LearnEngineering.in

<p id="success">Thanks for your message! We will get back to you


ASAP!</p>
<form method="post" action="process.php">
<label for="name">Name: <span class="required">*</span></label>
<input type="text" id="name" name="name" value="" placeholder="John
Doe" required="required" autofocus="autofocus" />

<label for="email">Email Address: <span


class="required">*</span></label>
<input type="email" id="email" name="email" value=""
placeholder="[email protected]" required="required" />

<label for="telephone">Telephone: </label>


<input type="tel" id="telephone" name="telephone" value="" />

<label for="enquiry">Enquiry: </label>


<select id="enquiry" name="enquiry">
<option value="general">General</option>
<option value="sales">Sales</option>
<option value="support">Support</option>
</select>

<label for="message">Message: <span class="required">*</span></label>


<textarea id="message" name="message" placeholder="Your message must
be greater than 20 charcters" required="required" data-
minlength="20"></textarea>

<span id="loading"></span>
<input type="submit" value="Holla!" id="submit-button" />
<p id="req-field-desc"><span class="required">*</span> indicates a
required field</p>
</form>
</div>
#contact-form {
background-color:#F2F7F9;
width:465px;
padding:20px;
margin: 50px auto;

189

Visit & Downloaded from : www.LearnEngineering.in


Visit & Downloaded from : www.LearnEngineering.in

border: 6px solid #8FB5C1;


-moz-border-radius:15px;
-webkit-border-radius:15px;
border-radius:15px;
position:relative;
}

#contact-form h1 {
font-size:42px;
}

#contact-form h2 {
margin-bottom:15px;
font-style:italic;
font-weight:normal;
}

#contact-form input,
#contact-form select,
#contact-form textarea,
#contact-form label {
font-size:15px;
margin-bottom:2px;
}

#contact-form input,
#contact-form select,
#contact-form textarea {
width:450px;
border: 1px solid #CEE1E8;
margin-bottom:20px;
padding:4px;
}

#contact-form input:focus,
#contact-form select:focus,
#contact-form textarea:focus {
border: 1px solid #AFCDD8;

190

Visit & Downloaded from : www.LearnEngineering.in


Visit & Downloaded from : www.LearnEngineering.in

background-color: #EBF2F4;
}

#contact-form textarea {
height:150px;
resize: none;
}

#contact-form label {
display:block;
}

#contact-form .required {
font-weight:bold;
color:#F00;
}

#contact-form #submit-button {
width: 100px;
background-color:#333;
color:#FFF;
border:none;
display:block;
float:right;
margin-bottom:0px;
margin-right:6px;
background-color:#8FB5C1;
-moz-border-radius:8px;
}

#contact-form #submit-button:hover {
background-color: #A6CFDD;
}

#contact-form #submit-button:active {
position:relative;
top:1px;
}

191

Visit & Downloaded from : www.LearnEngineering.in


Visit & Downloaded from : www.LearnEngineering.in

#contact-form #loading {
width:32px;
height:32px;
background-image:url(../img/loading.gif);
display:block;
position:absolute;
right:130px;
bottom:16px;
display:none;
}

#errors {
border:solid 1px #E58E8E;
padding:10px;
margin:25px 0px;
display:block;
width:437px;
-webkit-border-radius:8px;
-moz-border-radius:8px;
border-radius:8px;
background:#FFE6E6 url(../img/cancel_48.png) no-repeat 405px center;
display:none;
}

#errors li {
padding:2px;
list-style:none;
}

#errors li:before {
content: ' - ';
}

#errors #info {
font-weight:bold;
}

192

Visit & Downloaded from : www.LearnEngineering.in


Visit & Downloaded from : www.LearnEngineering.in

#errors #info:before {
content: '';
}

#success {
border:solid 1px #83D186;
padding:25px 10px;
margin:25px 0px;
display:block;
width:437px;
-webkit-border-radius:8px;
-moz-border-radius:8px;
border-radius:8px;
background:#D3EDD3 url(../img/accepted_48.png) no-repeat 405px center;
font-weight:bold;
display:none;
}

#errors.visible, #success.visible {
display:block;
}

#req-field-desc {
font-style:italic;
}

/* Remove box shadow firefox, chrome and opera put around required fields. It
looks rubbish. */
input:required, textarea:required {
-moz-box-shadow:none;
-webkit-box-shadow:none;
-o-box-shadow:none;
box-shadow:none;
}
/* Normalize placeholder styles */
/* chrome, safari */
::-webkit-input-placeholder {
color:#CCC;

193

Visit & Downloaded from : www.LearnEngineering.in


Visit & Downloaded from : www.LearnEngineering.in

font-style:italic;
}

/* mozilla */
input:-moz-placeholder, textarea:-moz-placeholder {
color:#CCC;
font-style:italic;
}

/* ie (faux placeholder) */
input.placeholder-text, textarea.placeholder-text {
color:#CCC;
font-style:italic;
}

The CSS is pretty standard

1 #errors li:before {
2 content: ' - ';
3 }

This will put a dash next to our error validation messages. It's basically replacing
the bullet point in the list, I just think this looks better.

1 #contact-form #submit-button:active {
2 position:relative;
3 top:1px;
4 }

Process.php

<?php
if( isset($_POST) ){
//form validation vars
$formok = true;
$errors = array();
//sumbission data
$ipaddress = $_SERVER['REMOTE_ADDR'];
$date = date('d/m/Y');
$time = date('H:i:s');

194

Visit & Downloaded from : www.LearnEngineering.in


Visit & Downloaded from : www.LearnEngineering.in

//form data
$name = $_POST['name'];
$email = $_POST['email'];
$telephone = $_POST['telephone'];
$enquiry = $_POST['enquiry'];
$message = $_POST['message'];
//form validation to go here....
}
//validate name is not empty
if(empty($name)){
$formok = false;
$errors[] = "You have not entered a name";
}
//validate email address is not empty
if(empty($email)){
$formok = false;
$errors[] = "You have not entered an email address";
//validate email address is valid
}elseif(!filter_var($email, FILTER_VALIDATE_EMAIL)){
$formok = false;
$errors[] = "You have not entered a valid email address";
}
//validate message is not empty
if(empty($message)){
$formok = false;
$errors[] = "You have not entered a message";
}
//validate message is greater than 20 charcters
elseif(strlen($message) < 20){
$formok = false;
$errors[] = "Your message must be greater than 20 characters";
}
3. Write a java program to find the sum of the digits of the given number.
Create a swing GUI to get an input number and show the sum of its digits. In
case the sum cannot be found due to incorrect input should print “Not able to
find the sum. Check input”. (May/June 2016)

import javax.swing.JOptionPane;
public class Oppgave2{

195

Visit & Downloaded from : www.LearnEngineering.in


Visit & Downloaded from : www.LearnEngineering.in

public static void main(String[] args){


int x;
int y;
String i, j;
i = JOptionPane.showInputDialog("Write begining number:");
x = Integer.parseInt(i);
j = JOptionPane.showInputDialog("Write end number:");
y = Integer.parseInt(j);
if ( x > y || x == y){
i = JOptionPane.showInputDialog("Wrong!
Begining number is bigger or same as end number!
\nTry again! Write begining number:");
x = Integer.parseInt(i);
j = JOptionPane.showInputDialog("Write end number:");
y = Integer.parseInt(j);
}
int number;
number = x;
int sum = 0;
while(number <= y){
sum = sum + number;
number++;
}
// Here or in while it should write OptionPane.showMessageDialog(null,
"1+2+3+4+5 " + sum);
JOptionPane.showMessageDialog(null, "the sum is: " + sum);

}
}
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
public class Calculate extends JTextField {
public static void main(String[] args) {
JFrame f = new JFrame("Calculate");
f.getContentPane().setLayout(new BoxLayout(f.getContentPane(),
BoxLayout.Y_AXIS));

196

Visit & Downloaded from : www.LearnEngineering.in


Visit & Downloaded from : www.LearnEngineering.in

final JTextField text1 = new JTextField(20);


final JTextField text2 = new JTextField(20);
JPanel panel = new JPanel();
JButton button = new JButton("Calculate");
panel.add(button);
f.getContentPane().add(text1);
f.getContentPane().add(panel);
f.getContentPane().add(text2);
ActionListener l = new ActionListener() {
public void actionPerformed(ActionEvent evt) {
System.out.println("Action event from a text field");
}
};
text1.addActionListener(l);
text2.addActionListener(l);
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
int a=Integer.parseInt(text1.getText());
int sum = 0;
int count=1;
while(count<=a)
{
sum+=count;
count++;
}
text2.setText(String.valueOf(sum));
}
});
f.pack();
f.setVisible(true);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}

4. Use javascript and HTML to create a page with two panes. The first pane( on
the left) should have a text area where HTML code can be typed by the user.
The pane on the right side should display the preview of the HTML code
typed by the user, as it would be seen on the browser (May/June 2016)

197

Visit & Downloaded from : www.LearnEngineering.in


Visit & Downloaded from : www.LearnEngineering.in

HTML file

<html>
<textarea id="core_input">
<script type="text/javascript"> var foo = "test"; </script>
</textarea>
<button id="process">process</button>
<div id="iframe-body"></div>
</html>
Javascript file
document.addEventListener("DOMContentLoaded", function() {
document.getElementById("process").addEventListener("click", function () {
var $iframe = document.getElementById("iframe-render"),
iframe, iframeDoc;
if ( !$iframe ) {
iframe = document.createElement("iframe");
iframe.id = "iframe-render";
document.getElementById("iframe-body").appendChild( iframe );
} else {
iframe = $iframe;
}
iframeDoc = iframe.contentWindow ?
iframe.contentWindow :
iframe.contentDocument.document ?
iframe.contentDocument.document :
iframe.contentDocument;
iframeDoc.document.open();
iframeDoc.document.write(
document.getElementById("core_input").value
);
iframeDoc.document.close();

}, false);
}, false);

CSS File

textarea {display:block;width:100%;height:100px;}

iframe {width:100%;height:300px;}

198

Visit & Downloaded from : www.LearnEngineering.in


Visit & Downloaded from : www.LearnEngineering.in

5. Create a Webserver based chat applications using PHP. The application


should provide the following functions (16)
 Login
 Send message(to one or more contacts)
 Receive messages ( from one or more contacts)
 Add/ delete/ modify contact list of the user
Discuss the application’s user interface and use comments in PHP to
explain the code clearly. (May/ june 16)
Step 1. HTML
As usual, we start with the HTML.
This main chat window.
index.html
<frameset rows="65%,35%" framespacing="1" frameborder="yes" border="1"
bordercolor="#FF0000">
<frame src="messages.php" name="main_frame">

<frame src="main.php" name="login_frame" scrolling="no" noresize


target="middle">
</frameset>

This is login form code.

login_form.html

<link type="text/css" rel="stylesheet" href="styles.css" />

<form class="login_form" method="post" action="main.php">


<div>Username: <input type="text" name="username" /></div>

<div>Password: <input type="password" name="password" /></div>


<div><input type="submit" value="Login" name="Login" /></div>

</form>
<div>You can use username "User1" or "User2" or "User3" and password
"qwerty" to login in system</div>

Here are new 3 template files to chat (2 to messages box and 1 to send message
form):

chat_begin.html

<link type="text/css" rel="stylesheet" href="styles.css" />

<div class="chat_main">

199

Visit & Downloaded from : www.LearnEngineering.in


Visit & Downloaded from : www.LearnEngineering.in

<h3>Chat</h3>

chat_end.html

</div>

chat_input.html

<link type="text/css" rel="stylesheet" href="styles.css" />

<form class="submit_form" method="post" action="main.php">


<div><input type="text" name="s_message" /><input type="submit"
value="Say" name="s_say" /></div>

</form>
<div>You can type anything in chat</div>
Step 2. CSS
Here are used CSS styles.
styles.css
.login_form {
border: 1px solid #AAA;

padding:10px;
}

h3 {margin-top:3px;}

.chat_main {

border:1px solid #AAA;


-moz-box-shadow:0 0 10px #ccc;

-webkit-box-shadow: 0 0 10px #ccc;


width:350px;

padding:10px;
background:#f3f3f3;

.message {
border:1px solid #AAA;

margin:4px;

padding:5px;

-moz-border-radius:7px;

200

Visit & Downloaded from : www.LearnEngineering.in


Visit & Downloaded from : www.LearnEngineering.in

-webkit-border-radius:7px;

background:#ffffff;
}

.textf {

-moz-box-shadow:0 0 10px #CCCCCC;


-webkit-box-shadow:0 0 10px #CCCCCC;

border:1px solid #CCCCCC;


height:40px;

.submit {
-moz-border-radius:7px;

-webkit-border-radius:7px;
background:#F3F3F3;

border:1px solid #CCCCCC;


font-size:16px;

font-weight:bold;
height:35px;

margin-left:10px;
padding:5px;

}
.message span {

font-size:10px;
color:#888;

margin-left:10px;
}

.submit_form {

margin:10px 0px;
}

Step 3. SQL
We will need to execute next SQL in our database.

CREATE TABLE `s_chat_messages` (`id` INT(11) NOT NULL

AUTO_INCREMENT , `user` VARCHAR(255) NOT NULL ,

201

Visit & Downloaded from : www.LearnEngineering.in


Visit & Downloaded from : www.LearnEngineering.in

`message` VARCHAR(255) NOT NULL , `when` INT(11) NOT NULL ,

PRIMARY KEY (`id`)) ENGINE=MyISAM DEFAULT CHARSET=utf8;

STEP 4
As we remember – we had ready easy authentication system. I moved it to external
library file (inc/login.inc.php). This will useful for us – now code more structured and it
comfortable to use in different places of code.
After I created new library to work with chat (inc/chat.inc.php). This class have next
functions:
acceptMessages – function accept sent messages and store it in DB table
getMessages – return list of last 15 messages
\After I created 2 last files: messages.php and main.php. First file used to draw list of
messages. It have autoupdate each 5 second (I thing this is enough to our chat). Second
draw login form and input field of chat. Where we due logged able to post text in chat.
Ok, here are all used PHP files:
main.php
<?php

// set error reporting level


if (version_compare(phpversion(), "5.3.0", ">=") == 1)

error_reporting(E_ALL & ~E_NOTICE & ~E_DEPRECATED);


else

error_reporting(E_ALL & ~E_NOTICE);

require_once('inc/login.inc.php');
require_once('inc/chat.inc.php');

// initialization of login system and generation code

$oSimpleLoginSystem = new
SimpleLoginSystem();

$oSimpleChat = new SimpleChat();

// draw login box


echo $oSimpleLoginSystem->getLoginBox();

// draw chat application

$sChatResult = 'Need login before using';


if ($_COOKIE['member_name'] && $_COOKIE['member_pass']) {

if ($oSimpleLoginSystem->check_login($_COOKIE['member_name'],

202

Visit & Downloaded from : www.LearnEngineering.in


Visit & Downloaded from : www.LearnEngineering.in

$_COOKIE['member_pass'])) {
$sChatResult = $oSimpleChat->acceptMessages();

}
}

echo $sChatResult;

?>

messages.php

<meta http-equiv="refresh" content="5">


<?php

require_once('inc/chat.inc.php');

$oSimpleChat = new SimpleChat();


echo $oSimpleChat->getMessages();

?>

inc/chat.inc.php

<?php

// simple chat class


class SimpleChat
{

// DB variables

var $sDbName;
var $sDbUser;

var $sDbPass;

// constructor
function SimpleChat() {

//mysql_connect("localhost","username","password");
$this->sDbName = 'database_name';

$this->sDbUser = 'username';
$this->sDbPass = 'password';

// adding to DB table posted message


function acceptMessages() {

if ($_COOKIE['member_name']) {

203

Visit & Downloaded from : www.LearnEngineering.in


Visit & Downloaded from : www.LearnEngineering.in

if(isset($_POST['s_say']) && $_POST['s_message']) {

$sUsername = $_COOKIE['member_name'];

//the host, name, and password for your mysql


$vLink = mysql_connect("localhost", $this->sDbUser, $this-
>sDbPass);

//select the database

mysql_select_db($this->sDbName);

$sMessage = mysql_real_escape_string($_POST['s_message']);
if ($sMessage != '') {

mysql_query("INSERT INTO `s_chat_messages` SET


`user`='{$sUsername}', `message`='{$sMessage}',
`when`=UNIX_TIMESTAMP()");
}

mysql_close($vLink);

}
}

ob_start();

require_once('chat_input.html');

$sShoutboxForm = ob_get_clean();

return $sShoutboxForm;

function getMessages() {
$vLink = mysql_connect("localhost", $this->sDbUser, $this->sDbPass);

//select the database

mysql_select_db($this->sDbName);

//returning the last 15 messages


$vRes = mysql_query("SELECT * FROM `s_chat_messages` ORDER BY
`id` ASC LIMIT 15");

$sMessages = '';

// collecting list of messages

if ($vRes) {
while($aMessages = mysql_fetch_array($vRes)) {

204

Visit & Downloaded from : www.LearnEngineering.in


Visit & Downloaded from : www.LearnEngineering.in

$sWhen = date("H:i:s", $aMessages['when']);

$sMessages .= '<div class="message">' . $aMessages['user'] . ': '


. $aMessages['message'] . '<span>(' . $sWhen . ')</span></div>';

}
} else {

$sMessages = 'DB error, create SQL table before';


}

mysql_close($vLink);

ob_start();

require_once('chat_begin.html');
echo $sMessages;

require_once('chat_end.html');
return ob_get_clean();

}
}

?>

inc/login.inc.php

<?

// class SimpleLoginSystem
class SimpleLoginSystem
{

// variables

var $aExistedMembers; // Existed members array

// constructor
function SimpleLoginSystem() {

$this->aExistedMembers = array(
'User1' => 'd8578edf8458ce06fbc5bb76a58c5ca4',

'User2' => 'd8578edf8458ce06fbc5bb76a58c5ca4',


'User3' => 'd8578edf8458ce06fbc5bb76a58c5ca4'

);
}

function getLoginBox() {

205

Visit & Downloaded from : www.LearnEngineering.in


Visit & Downloaded from : www.LearnEngineering.in

ob_start();
require_once('login_form.html');

$sLoginForm = ob_get_clean();

$sLogoutForm = '<a href="'.$_SERVER['PHP_SELF'].'?logout=1">


logout</a>';

if ((int)$_REQUEST['logout'] == 1) {
if (isset($_COOKIE['member_name']) &&
isset($_COOKIE['member_pass']))

$this->simple_logout();
}

if ($_REQUEST['username'] && $_REQUEST['password']) {

if ($this->check_login($_REQUEST['username'],
MD5($_REQUEST['password']))) {
$this->simple_login($_REQUEST['username'],
$_REQUEST['password']);

return 'Hello ' . $_REQUEST['username'] . '! ' . $sLogoutForm;


} else {

return 'Username or Password is incorrect' . $sLoginForm;


}

} else {
if ($_COOKIE['member_name'] && $_COOKIE['member_pass']) {

if ($this->check_login($_COOKIE['member_name'],
$_COOKIE['member_pass'])) {
return 'Hello ' . $_COOKIE['member_name'] . '! ' . $sLogoutForm;

}
}

return $sLoginForm;
}

function simple_login($sName, $sPass) {


$this->simple_logout();

$sMd5Password = MD5($sPass);

$iCookieTime = time() + 24*60*60*30;

206

Visit & Downloaded from : www.LearnEngineering.in


Visit & Downloaded from : www.LearnEngineering.in

setcookie("member_name", $sName, $iCookieTime, '/');


$_COOKIE['member_name'] = $sName;

setcookie("member_pass", $sMd5Password, $iCookieTime, '/');


$_COOKIE['member_pass'] = $sMd5Password;

function simple_logout() {
setcookie('member_name', '', time() - 96 * 3600, '/');

setcookie('member_pass', '', time() - 96 * 3600, '/');

unset($_COOKIE['member_name']);
unset($_COOKIE['member_pass']);

function check_login($sName, $sPass) {


return ($this->aExistedMembers[$sName] == $sPass);

}
}

?>
6. Write appropriate inline CSS to show a section of the HTML document
with the font size of 20. (May/June 2016)

<html>
<h1 style="color:blue;margin-left:30px;" font-size:20px>This is a heading.</h1>
</html>
CSS file
h1 {
font-size: 40px;
}
h2 {
font-size: 30px;
}
p{
font-size: 14px;
}
7. Write appropriate javascript code to remove an element (current
element) from a DOM. [May / June 2016]

<html>

207

Visit & Downloaded from : www.LearnEngineering.in


Visit & Downloaded from : www.LearnEngineering.in

<div id="div1">
<p id="p1">This is a paragraph.</p>
<p id="p2">This is another paragraph.</p>
</div>
<script>
var para = document.createElement("p");
var node = document.createTextNode("This is new.");
para.appendChild(node);
var element = document.getElementById("div1");
var child = document.getElementById("p1");
element.insertBefore(para,child);
</script>
</html>
8. Write the code segment to store current server time in session using
java servlet API. [May / June 2016]

import java.io.*;

import javax.servlet.*;

import javax.servlet.http.*;

import java.util.Date;

public class Time extends HttpServlet {

public void doGet(HttpServletRequest req, HttpServletResponse rsp)

throws ServletException, IOException {

rsp.setContentType("text/html");

PrintWriter out = rsp.getWriter();

Date now = new Date(); // The current Date/time

out.println("<html>");

out.println("<head><title> Time Check </title></head>");

out.println("<body>");

out.println("<p>The time is: " + now + "</p>");

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

208

Visit & Downloaded from : www.LearnEngineering.in


Visit & Downloaded from : www.LearnEngineering.in

9. Give an example for a chained exception in java (May/June 2016)


public class Main{
public static void main (String args[])throws Exception {
int n=20,result=0;
try{
result=n/0;
System.out.println("The result is"+result);
}
catch(ArithmeticException ex){
System.out.println ("Arithmetic exception occoured: "+ex);
try {
throw new NumberFormatException();
}
catch(NumberFormatException ex1) {
System.out.println ("Chained exception thrown manually : "+ex1);
}
}
}
}
Result
The above code sample will produce the following result.
Arithmetic exception occoured :
java.lang.ArithmeticException: / by zero
Chained exception thrown manually :
java.lang.NumberFormatException

209

Visit & Downloaded from : www.LearnEngineering.in

You might also like