Web Technology
Web Technology
QUANTUM SERIES
For
B.Tech Students of Third Year
of All Engineering Colleges Affiliated to
Dr. A.P.J. Abdul Kalam Technical University,
Uttar Pradesh, Lucknow
(Formerly Uttar Pradesh Technical University)
Web Technology
By
Aditya Kumar
TM
CONTENTS
KIT-501 / KCS-602 : WEB TECHNOLOGY
1
UNIT
Introduction and
Core Java
CONTENTS
Part-1 : Introduction : Introduction ................. 1–2D to 1–4D
and Web Development
Strategies, History of Web
and Internet
PART-1
Introduction : Introduction and Web Development Strategies,
History of Web and Internet.
Questions-Answers
Answer
Web development strategy includes following :
1. Identify target user : Identify the user of the website by doing market
research.
2. Make our design portable : To be successful, website design should
be portable and accessible across different browsers, operating systems,
and computer platforms.
3. Design for low bandwidth : Web pages in website should be accessible
at any connection speeds. If page downloaded slowly then users will
leave the website before they see the content.
4. Plan for clear presentation and easy access to information :
Presentation of the information on the website must be clear and easily
accessible to the user.
5. Create smooth transitions : Plan to create a unified look among the
sections and pages of site. Reinforce the identifying elements of the site
and create smooth transitions from one page to another.
Answer
1. In the history of the World Wide Web, there are two lines to be traced :
the development of hypertext, and the development of the internet
protocols.
2. In 1972, DARPA starts research leading to the internet.
3. Its main characteristic is the automatic routing of information packets
and circumventing the problem of network vulnerability.
4. In 1979, Charles Goldfarb invents SGML which separates content
structure from presentation.
5. In 1975, Alan Kay produces the first personal computer.
Web Technology 1–3 D (IT-5/CS-6)
Answer
It is essential to identify objects in web development strategies because it will
help the developer to understand the elements that play a vital role in business
applications.
Web development process :
The process of website development can be divided into following different
life cycle steps :
1. Analysis
7. Maintenance 2. Specification
and Updation Building
3. Design and
Development
4. Content
6. Testing
Writing
5. Coding
2. Specification building :
a. In this phase, Software Requirement Specifications (SRS) document
is prepared.
b. In this document each and every element of the requirement is
presented in detailed form.
3. Design and development :
a. In design phase, the layouts and navigation will be designed as a
prototype.
b. Test plans and procedures are developed for quality assurance.
c. In development phase, team will develop the database with all the
data structures and sample data according to the requirements.
4. Content writing : There are professional content developers who
write industry specific and relevant content for the site. The grammatical
and spelling check should be done in this phase.
5. Coding :
a. In coding stage programmers add the code without disturbing the
design.
b. Coding team generate necessary testing plans as well as technical
documentation.
6. Testing :
a. Both automated testing and manual testing should be done without
fail.
b. After doing all the testing, a live testing is necessary for websites
and web based applications. After uploading the site there should
be a complete testing.
7. Maintenance and updation : Once the website is operational, ongoing
promotion, technical maintenance, content management and staff
training is needed on a regular basis.
PART-2
Protocol Governing Web, Writing Web Projects.
Questions-Answers
Answer
Growth of web technology : Refer Q. 1.1, Page 1–2D, Unit-1.
Protocols governing web :
1. HTTP (Hypertext Transfer Protocol) :
a. Hypertext Transfer Protocol (HTTP) is a method used to transfer
or convey information on the World Wide Web.
b. HTTP is a request/response protocol between clients and servers.
c. The originating client, such as a web browser is referred as the
user agent.
d. The destination server, which stores or creates resources such as
HTML files and images, is called server.
2. ICMP (Internet Control Message Protocol) :
a. ICMP is primarily used by networked computers operating systems
to send error messages.
b. The purpose of these control messages is to provide feedback
about problems in the communication environment.
3. RIP (Routing Information Protocol) :
a. RIP is a dynamic routing protocol based on the Bellman-Ford
algorithm.
b. Routing is the method by which the host or gateway decides where
to send the datagram.
c. The goal of RIP is to supply the information that is needed to do
routing.
4. OSPF (Open Shortest Path First) :
a. OSPF is classified as an Interior Gateway Protocol (IGP).
b. It distributes routing information between routers belonging to a
single Autonomous System (AS).
c. OSPF also provides the authentication of routing updates and
utilizes IP multicast.
5. TCP/IP :
a. TCP/IP stands for Transmission Control Protocol / Internet
Protocol.
b. It is the communication protocol for communication between
computers on the internet.
c. TCP is connection oriented protocol.
d. TCP allows the transmission of arbitrary amount of data by
breaking it into stream of separate IP packets.
Introduction and Core Java 1–6 D (IT-5/CS-6)
6. UDP :
a. User Datagram Protocol (UDP) is a connectionless protocol without
any error detection facility.
b. It is also used for transmission of data.
c. This protocol provides a procedure for application programs to
send messages to other programs with a minimum of protocol
mechanism.
Que 1.5. Explain the HTTP protocol. Mention three basic features
of HTTP that make HTTP a simple but powerful protocol. Give its
architecture. AKTU 2018-19, Marks 07
Answer
1. The Hypertext Transfer Protocol (HTTP) is an application-level protocol
for distributed, hypermedia information systems. This is the foundation
for data communication for the World Wide Web (i.e. internet).
2. HTTP is a generic and stateless protocol which can be used for other
purposes as well using extensions of its request methods, error codes,
and headers.
3. HTTP is a TCP/IP based communication protocol, that is used to deliver
data (HTML files, image files, query results, etc.) on the WWW.
4. The default port is TCP 80, but other ports can be used as well.
Features of HTTP protocol :
1. HTTP is connectionless : The HTTP client, i.e., a browser initiates an
HTTP request and after a request is made, the client disconnects from
the server and waits for a response.
2. HTTP is media independent : It means, any type of data can be sent
by HTTP by specifying appropriate MIME type.
3. HTTP is stateless : As HTTP is connectionless and it is a direct result
of HTTP being a stateless protocol. The server and client are aware of
each other only during a current request.
Architecture :
Get
HTTP HTTP
Client Server
Response
HTTP Protocol
Fig. 1.5.1.
OR
What are the stages and strategies required to develop a web
project ?
Answer
1. A web project is the process of developing and creating a website, activities
in a network which are aimed at a pre-defined goal.
2. The network can be both accessible for everyone, as in the internet, or
only for certain people, as an internet.
Following are the various stages and strategies required in order
to develop a web project :
Phase-I : Strategy :
1. Goals and objectives
2. Team building
3. Research and review
4. Project proposal
Phase-II : Design and specification :
1. Developing concepts
2. Content planning
3. Rough design
4. Final design
5. Build prototype
6. Prototype testing
Phase-III : Production or development :
1. Coding
Phase-IV : Testing and maintenance :
1. Automation testing
2. Manual testing
Phase-V : Register with ISP :
1. Buy domain name
2. Hoisting
Phase-VI : Launch
Introduction and Core Java 1–8 D (IT-5/CS-6)
Testing and
Maintenance
Register with
ISP
Launch
Fig. 1.6.1.
Answer
Web technologies are the technologies which are used to develop website for
the World Wide Web or an internet.
Following are various web technologies used in web design :
1. Client-side technologies :
a. XHTML :
i. XHTML is a markup language designed to structure information
for presentation as web pages.
ii. All XHTML programs are written to ensure that it is clean,
valid and of the highest standard.
b. Cascading style sheets : Cascading style sheets control how web
pages are displayed in the browser, and allow the separation of
presentation from structure and content.
c. JavaScript : JavaScript is a lightweight scripting technology which
is used alongside XHTML documents to make websites more
interactive.
2. Server-side technologies :
a. PHP : PHP is a fast, server-side scripting language that is used to
create interactive, dynamic websites.
b. CGI/Perl : Perl is a programming language that can handle input
and output from a web server, usually through the Common
Gateway Interface.
Web Technology 1–9 D (IT-5/CS-6)
c. XML/XSL :
i. XML is a software and hardware independent markup language
designed for describing and transmitting information.
ii. XSL is a language for defining, transforming and formatting
XML documents.
d. MySQL :
i. MySQL is a fast, open-source relational database management
system that uses the popular Structured Query Language
(SQL).
ii. MySQL is perfect for most websites that need database
functionality.
e. Linux/Apache : Linux is a popular open-source operating system,
and Apache is the most widely used web server on the internet.
Steps to develop a multi-department and large scale website :
1. Gathering information : It includes purpose, main goals, and target
audience.
2. Planning : It includes sitemap and wireframe creation.
3. Design : It includes page layouts and review,
4. Content writing and assembly
5. Coding
6. Testing, review, and launch
7. Maintenance : It includes monitoring and regular updating.
Role of scripting language in web design :
1. Scripting language reflects the object orientation of web pages.
2. Scripting language was designed to add interactivity to HTML pages.
Answer
Protocols governing web : Refer Q. 1.4, Page 1–4D, Unit-1.
Web team :
1. Web team is a group of various technical experts in a developing site
from coding the page to maintain the web server.
2. The ideal web team consists of two sub-teams :
a. The client-side specialists, who create an attractive, clear front-end.
b. The server-side specialists, who create a smoothly operating
back-end.
Introduction and Core Java 1–10 D (IT-5/CS-6)
Answer
Objectives of any websites :
1. Providing quality content on our website regularly, adding new
information, establishing trust, marketing our site on other websites
and social media to become an authoritative resource.
2. E-mail marketing lists, online support (live chat), webinars is provided
to improve interaction with existing and potential customers.
3. Provide active social media program, promotions, reputation
management to our regular customers to build our brand.
Essentials skills required being member of web project team are :
1. HTML/CSS : As a web developer, one should need to understand the
basics of coding and markup language such as HTML and CSS.
2. JavaScript : After learning HTML and CSS, one should have the
knowledge of JavaScript as it makes websites more interactive and
functional.
3. Photoshop : For editing, designing, and stylizing websites one should
have the knowledge of Photoshop to design a handful of banners and
logos for clients.
4. PHP language : Other than HTML/CSS, one should have the skill of
writing code in PHP language which is the core part of WordPress.
Answer
Basic elements of a good website design are as follows :
1. Original content : The most important element is the content shown
on the first page of website. The first page should clearly focus on the
information about the business.
2. Well-organized and easy to read : The most important information
on any page should be property organized and easy to read.
3. More click, less scroll : Website should be designed in such a way that
it has more clickable element and less scrollable.
4. Share your knowledge : Every business has knowledge that their
viewers might find useful. Use our website to showcase that valuable
asset.
Web Technology 1–11 D (IT-5/CS-6)
Answer
1. A successful website is a result of successful planning.
2. Hence, before creating and uploading website, it is important to take the
time to plan exactly what is needed in the website.
3. Thoroughly considering the audience or target market, as well as defining
the purpose and deciding what content will be developed, are extremely
important.
4. This will save time, energy and expense in long run. Early planning also
helps to maintain our focus. Therefore, planning is must before
developing a website.
Advantages of early planning : The main advantage of early planning is
that planning helps in deciding the following questions :
1. Why are we building the website ?
2. What do we envision as the goal of the site ?
3. What do we hope to gain from creating and maintaining a website ?
4. How will we judge the success of the site ?
5. Who is the target audience ?
6. What are the limiting technical factors affecting our site ?
PART-3
Connecting to Internet, Introduction to Internet Services and
Tools, Introduction to Client-Server Computing.
Questions-Answers
OR
What is internet ?
Answer
1. Internet is a global system of interconnected computer networks that
use the standard Internet Protocols suite (TCP/IP) to serve billions of
users worldwide.
2. Internet is a network of networks that consists of millions of private and
public, academic, business, and government networks of local to global
scope that are linked by a broad array of electronic, wireless and optical
networking technologies.
3. The internet carries a vast array of information resources and services,
to support electronic mail.
4. Most traditional communications media, such as telephone and television
services, are reshaped or redefined using the technologies of the internet,
giving rise to services such as Voice over Internet Protocol (VoIP).
5. Newspaper, book and other print publishing has been reshaped into
web sites, blogging, and web feeds.
6. The internet has enabled or accelerated the creation of new forms of
human interactions through instant messaging, internet forums, and
social networking sites.
Answer
1. Internet service provides a way for data to be transferred from internet
servers to our computer.
2. Internet service allows us to access huge amount of information such
as text, graphics, sound and software over the internet.
Four different categories of internet services are as follows :
1. Communication services : There are various communication services
available that offer exchange of information with individuals or groups
which are as follows :
a. Electronic mail
b. Telnet
c. Mailing lists
d. Internet telephony (VoIP)
2. Information retrieval services : There exist several information
retrieval services offering easy access to information present on the
internet which are as follows :
a. File Transfer Protocol (FTP)
Web Technology 1–13 D (IT-5/CS-6)
b. Gopher
3. Web services :
a. Web services allow exchange of information between applications
on the web.
b. Using web services, applications can easily interact with each other.
4. World Wide Web (WWW) :
a. WWW offers a way to access documents spread over the several
servers over the internet.
b. These documents may contain texts, graphics, audio, video,
hyperlinks.
c. The hyperlinks allow the users to navigate between the documents.
Answer
1. A client-server system is a networked computing model that distributes
processes between client and servers.
2. A client-server process usually manages the user-interface portion of
the application; validate data entered by the user, dispatch requests to
server programs.
3. Client process also manages the local resources that the user interacts
with such as the monitor, keyboard, workstation, CPU and other
peripherals.
Network
Fig. 1.14.1.
PART-4
Core Java : Introduction, Operator, Data Type, Variable Arrays.
Questions-Answers
Answer
The basic features of Java are as follows :
1. Simple : Java is easy to learn.
2. Object-oriented : All the functions are defined inside the classes.
3. Platform independent : It is platform independent programming
language because it compiles to byte-code. This byte code is interpreted
by the Virtual Machine (JVM) on any platform.
4. Robust : Java is graceful in the presence of software or hardware
errors. Java has very good exception handlers.
5. Secure : Java has no pointers. All pointer-related security problems are
gone. So it is more secure.
6. Portable : Java is portable because it facilitates us to carry the Java
bytecode to any platform. It does not require any implementation.
7. Multithreaded : Java programs are capable for easy to set up multiple
threads of execution and coordinate parallel processes.
8. Dynamic : Java is a dynamic language. It supports dynamic loading of
classes. It means classes are loaded on demand. It also supports functions
from its native languages, i.e., C and C++.
9. Garbage collection : Java has an automatic garbage collector which
releases the objects which are not in use from long time.
Que 1.16. Discuss data type in Java.
Web Technology 1–15 D (IT-5/CS-6)
Answer
Data type is a classification of data which tells the compiler or interpreter
how the programmer intends to use the data.
Types of data type are :
a. Primitive data types :
1. Primitive data types are built-in data types.
2. Java initializes all primitive data types to default values.
3. Primitive data types are byte, short, int, long, float, double, boolean
and char.
b. Reference data types :
1. Reference data types are made by the logical grouping of primitive
data types.
2. These are called reference data types because they contain the
address of a value rather than the value itself.
3. Reference data types are arrays, objects, interfaces, enum etc.
Answer
An operator is a symbol that usually represents an action or process. These
symbols were adapted from mathematics and logic.
Following are the operators used in Java :
1. Unary operator :
a. The Java unary operators require only one operand.
b. Unary operators are used to perform various operations such as :
i. Incrementing/decrementing a value by one (++,--)
ii. Negating an expression (~)
iii. Inverting the value of a Boolean (!)
2. Arithmetic operator : Java arithmetic operators are used to perform
addition, subtraction, multiplication, and division. They act as basic
mathematical operations.
3. Shift operator :
a. Left shift operator : The left shift operator << is used to shift all
of the bits in a value to the left side of a specified number of times.
b. Right shift operator : The right shift operator >> is used to move
left operands value to right by the number of bits specified by the
right operand.
Introduction and Core Java 1–16 D (IT-5/CS-6)
Answer
1. A variable is a container which holds the value while the Java program
is executed.
2. A variable is assigned with a data type.
3. Variable is a name of memory location.
There are three types of variables in java :
1. Local variable :
a. A variable declared inside the body of the method is called local
variable. We can use this variable only within that method and but
not in the other methods.
b. A local variable cannot be defined with “static” keyword.
2. Instance variable :
a. A variable declared inside the class but outside the body of the
method, is called instance variable.
b. It is called instance variable because its value is instance specific
and is not shared among instances.
3. Static variable :
a. A variable which is declared as static is called static variable. It
cannot be local.
b. We can create a single copy of static variable and share among all
the instances of the class.
c. Memory allocation for static variable happens only once when the
class is loaded in the memory.
Web Technology 1–17 D (IT-5/CS-6)
Answer
1. Java array is an object which contains elements of a similar data type.
2. The elements of an array are stored in a contiguous memory location. It
is a data structure where we store similar elements.
3. We can store only a fixed set of elements in a Java array.
4. The length of an array is established when the array is created.
First index Element
(at index 8)
0 1 3 4 5 6 7 8 9 Indices
Array length is 10
Fig. 1.19.1.
PART-5
Methods and Classes, Inheritance, Packages and Interfaces.
Questions-Answers
Answer
1. A class is a blueprint from which objects are created.
2. A class is a group of objects which have common properties.
3. A class can be declared private or protected.
4. The general syntax of the class construct is :
class user_defined_name {
private :
data type members ;
implementation operations ;
list of friend functions ;
public :
data type members ;
implementation operations ;
protected :
data type members ;
implementation operations ;
};
Example :
class Box {
public:
double length; // Length of a box
double breadth; // Breadth of a box
double height; // Height of a box
};
Answer
Objects :
1. An object is an instance of a class template.
2. Objects are the basic runtime entities in an object-oriented system.
3. An object has three characteristics :
i. State : It represents data (value) of an object.
ii. Behaviour : It represents the behaviour (functionality) of an
object.
iii. Identity : It is a unique ID which is used internally by JVM to
identify each object.
4. General syntax to declare object is :
className ObjectName;
Web Technology 1–19 D (IT-5/CS-6)
Methods :
1. Methods are the set of executable statements.
2. Methods (also called as function) are also the interface to the data
variables of the class.
3. Methods provide a structured approach to programming. A program can
be divided into several methods.
For example :
public class Test
{
int x = 5;
public static void welcome ()
{
system.out.println (“ ------------------”);
}
public static void main(string args [ ])
{
welcome ();
system.out.println(“Hi !!! This is my first program”);
Test my obj = new Test ();
System.out.println (“myobj. x”);
}
}
Answer
1. Inheritance is the mechanism that allows us to extend the definition of
a class without making any physical changes to the existing class.
2. Inheritance creates new classes from existing class. Any new class that
we create from an existing class is called derived class; existing class is
called base class.
Base
Derived1
Derived2 Derived3
Fig. 1.22.1.
3. The inheritance relationship enables a derived class to inherit features
from its base class. Derived class can add new features of its own.
Introduction and Core Java 1–20 D (IT-5/CS-6)
A A B A
B
C B C D
(a) Single inheritance (b) Multiple inheritance (c) Hierarchical inheritance
A A
B
B C
C
D
(d) Multilevel inheritance (e) Hybrid inheritance
Fig.1.22.2.
Answer
Following are the features supported by object-oriented programming
languages :
1. Objects : Refer Q. 1.21, Page 1–18D, Unit-1.
2. Class : Refer Q. 1.20, Page 1–18D, Unit-1.
3. Inheritance : Refer Q. 1.22, Page 1–19D, Unit-1.
4. Polymorphism :
a. Polymorphism is the ability to use an operator or function in different
ways.
Web Technology 1–21 D (IT-5/CS-6)
Answer
1. Package is a mechanism to encapsulate a group of classes, interfaces
and subpackages.
2. Packages are the way to organize files into different directories according
to their functionality, usability as well as category.
3. Packages provide a way to hide classes thus preventing other programs
or packages from accessing classes that are meant for inter use only.
4. Packages also provide a way for separating “design” from “coding”.
5. There are two types of packages in Java :
i. User-defined package : The package we create is called user
defined package.
ii. Built-in package : The already defined package like java.io.*,
java.lang.* etc are known as built-in packages.
To create user-defined package :
User-defined package is created with the help of “package” keyword, and to
use a package we use the import keyword.
Introduction and Core Java 1–22 D (IT-5/CS-6)
Example :
Demo.java :
package abhi;
public class Demo
{
public void sum(int num1,int num2)
{
int result;
result=num1+num2;
System.out.println(“the sum of two numbers is:”+result);
}
}
Tester.java :
import abhi.Demo;
class Tester extends Demo
{
public static void main(String args[ ])
{
Tester obj=new Tester();
obj.sum(10,20);
}
}
Answer
1. An interface defines a set of methods but does not implement them.
2. A class that implements the interface agrees to implement all of the
methods defined in the interface.
3. An interface is a collection of method declarations (without definitions).
An interface can also include constant declarations.
Defining an interface :
1. An interface definition has two components :
a. Interface declaration : The interface declaration declares various
attributes about the interface such as its name and whether it
extends another interface.
b. Interface body : The interface body contains the constant and
method declarations within interface body as shown in Fig 1.25.1.
Web Technology 1–23 D (IT-5/CS-6)
Interface
public interface sleeper
Declaration
{
Method
public void wakeup( );
Declaration
Interface
Body public long ONE_SECOND = 1000; Constant
public long ONE_MINUTE = 60000; Declarations
Fig. 1.25.1.
For example :
// simple interface
interface Calc
{
void sum(int a, int b);
void sub(int a, int b);
}
// class implements with Interface
class MyCalc implements Calc
{
public void sum(int a, int b) // method of Calc
{
System.out.println(“Sum is = ”+ (a + b));
}
public void sub(int a, int b) // method of Calc
{
System.out.println(“Sub is = ”+ (a – b));
}
public static void main(String args[ ])
{
MyCalc cal = new MyCalc( );
cal.sum(100, 20);
cal.sub(100, 20);
}
}
Output :
Sum is = 120
Sub is = 80
Answer
Comparison :
S. No. Object-Oriented Object-Based
Programming Programming
1. It supports all the features of It supports the usage of object and
OOPS. encapsulation.
2. It also supports inheritance It does not support inheritance
and polymorphism. or, polymorphism or, both.
3. It supports built-in objects. It does not supports built-in
objects.
4. C#, Java, VB.Net are the JavaScript, VB are the examples
examples of object-oriented of object-based languages.
languages.
PART-6
Exception Handling, Multithread Programming, I/O.
Questions-Answers
Que 1.27. What are exceptions and how they are handled in java ?
Explain the keywords try, catch, throw, and finally with example.
AKTU 2017-18, Marks 10
OR
Explain exception handling in Java.
OR
What are exceptions and how they are handled ? Explain with an
example. How we define a try and catch block ? Is it essential to
catch all types of exceptions ? AKTU 2018-19, Marks 07
Answer
An exception is an unwanted or unexpected event, which occurs during the
execution of a program i.e., at runtime, that disrupts the normal flow of the
program’s instruction.
Exception handling :
1. Exception handling provides a type-safe, integrated approach for
handling unusual problems that arise while executing a program.
2. To handle the exceptions, exception handling mechanism is designed.
3. The mechanism suggests a separate error handling code that performs
the following tasks :
a. Find the problem (Hit the exception)
b. Inform that an error has occurred (Throw the exception)
c. Receive the error information (Catch the exception)
d. Take corrective actions (Handle the exception)
Introduction and Core Java 1–26 D (IT-5/CS-6)
} }
finally catch (....)
{ {
.............. ..............
} }
catch (....)
{
..............
}
..
.
finally
{
..............
..............
}
4. Throw :
a. Java supports “throw keyword” which is used if we want to throw
our own exceptions.
b. We can do this by using the keyword throw as follows :
throw new Throwable_subclass;
No, it is not essential to catch all type of exceptions.
For example :
throw new ArithmeticException ( ) ;
throw new NumberFormatException ( ) ;
class TestFinallyBlock
{
public static void main(String args[ ])
{
try
{
int data=25/0;
System.out.println(data);
}
catch(ArithmeticException e)
{
System.out.println(“Caught: ”+e);
}
finally
{
System.out.println(“finally block is always executed”);
}
System.out.println(“rest of the code...”);
}
}
Introduction and Core Java 1–28 D (IT-5/CS-6)
Output :
Caught: java.lang.ArithmeticException: / by zero
finally block is always executed
rest of the code...
Answer
Thread : A thread is a light weighted process which runs concurrently with
other threads. All threads of program define a separate path of execution.
Create a thread in Java :
public class Thread Test
{
public static void main (string [ ] args)
{
System.out.println (“Constructing the thread....”);
BytePrinter bp = new BytePrinter ( );
System.out.println (“Starting the thread....”);
bp start ( );
System.out.println (“The thread has been started”);
System.out.println (“The main ( ) method is finishing”);
return;
}
}
Program :
1. In the first step, we will implement the Runnable interface to define the
logic of both threads. In the run method, we check if the number is even
or odd.
2. If the number is even, we call the printEven method of the Printer class,
else we call the printOdd method :
class TaskEvenOdd implements Runnable {
private int max;
private Printer print;
private boolean isEvenNumber;
// standard constructors
@Override
Web Technology 1–29 D (IT-5/CS-6)
Answer
1. A multithreaded program contains two or more parts that can run
concurrently.
2. Each part of such a program is called a thread, and each thread defines
a separate path of execution.
3. Each thread runs parallel to each other.
4. A multithreading is a specialized form of multitasking.
5. In multithread program, each thread has its own life cycle. The life cycle
of thread is shown in Fig. 1.29.1.
New
Program
starts thread
Runnable
Unlock signal Thread completes
signal all await interval task
sleep expires
await
lock
Waiting Timed waiting Terminated
Fig. 1.29.1.
Web Technology 1–31 D (IT-5/CS-6)
Answer
1. Java programs perform I/O through streams.
2. A stream is linked to a physical device by the Java I/O system to make
input and output operation in Java.
3. Streams are clean way to deal with I/O without understanding every
part of our code and the difference between a keyboard and a network.
4. Java defines two types of streams :
a. Byte streams :
i. It provides a convenient means for handling input and output
of bytes.
ii. Byte streams are used for reading or writing binary data.
iii. FileInputStream and FileOutputStream are the most
frequently used classes in byte stream.
b. Character streams :
i. It provides a convenient means for handling input and output
of characters.
ii. They use unicode and therefore, can be internationalized.
Introduction and Core Java 1–32 D (IT-5/CS-6)
PART-7
Java Applet.
Questions-Answers
Answer
Que 1.32. Explain Applet with its life cycle. Write a program to
demonstrate simple java applet to display any image. Compare
Applets over HTML. AKTU 2019-20, Marks 07
Answer
Applet with its life cycle : Refer Q. 1.31, Page 1–32D, Unit-1.
Program :
import java.awt.*;
import java.applet.*;
public class DisplayImage extends Applet {
Image picture;
public void init() {
picture = getImage(getDocumentBase(),“sonoo.jpg”);
}
public void paint(Graphics g) {
g.drawImage(picture, 30,30, this);
}
}
Comparison :
Answer
Difference :
S. No. Applets Application
1. An applet is a java program An application is a java program
which is embedded in web page that runs independently on
to generate dynamic content. clie nt/serve r without we b
browser.
2. The execution of the program The execution of the program
does not start from main( ) starts from the main( ) method.
method.
3. Applet cannot run program from Applicatio n can run the
local machine. program from local machine.
4. It is used to perform small tasks. It is used to perform large tasks.
5. It can only acce ss browser It can access all kind of services
specific services. available on the system.
1. Java is strongly associated with the internet because the first application
program written in Java was HotJava, a browser to run the applet on
internet.
2. So, the internet users use the java to create the applet programs and
run them locally using a java-enabled browser’s like HotJava.
3. The users can use the java-enabled browsers to download the applet
located on the computer system anywhere in the internet and run it on
their computer.
Flowchart to s how various Java tools us ed in application
development :
Start
Install JDK
Input
IDE
Net Beans
Process Maven
Visual VM
Output
Testing tools
Error Testing JUnit
occur Clover
No Gradle
error
occur
Stop
Fig. 1.33.1.
Web Technology 1–35 D (IT-5/CS-6)
Que 1.34. What are the advantages and drawback of applet ? Write
a Java program to create an applet for calculator and also perform
event handling on each button. AKTU 2018-19, Marks 07
Answer
Advantages of applets :
1. Applets are platform independent.
2. Applets are quite secure and safe to use.
3. Applets cache quickly.
4. Applet increase interactivity for users.
5. Database integration is another important advantage of applets.
Drawbacks of applets :
1. Applets do not access client-side resources, like such as file, operating
system.
2. Applet cannot work with native methods.
3. Applet can only extract information about client-machine i.e., its name,
Java version, OS, version etc.
4. Mobile browsers which are running on IOS or Android do not support
applets.
Program :
import java.applet.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.TextEvent;
import java.awt.event.TextListener;;
public class calculator extends Applet implements ActionListener,
TextListener {
String s,s1,s2,s3,s4;
Button b1,b2,b3,b4,b5,b6,b7,b8,b9,b0;
Button add,sub,eq,cl,mul,div;
TextField t1;
int a,b,c;
public void init() {
Introduction and Core Java 1–36 D (IT-5/CS-6)
t1=new TextField(10);
b1=new Button(“1”); b2=new Button(“2”); b3=new Button(“3”);
b4=new Button(“4”); b5=new Button(“5”); b6=new Button(“6”);
b7=new Button(“7”); b8=new Button(“8”); b9=new Button(“9”);
b0=new Button(“0”);
add=new Button(“+”); sub=new Button(“–”);
mul=new Button(“*”); div=new Button(“/”);
eq=new Button(“=”); cl=new Button(“Clear”);
GridLayout gb=new GridLayout(4,5);
setLayout(gb);
add(t1);add(b1);add(b2); add(b3);add(b4);add(b5);
add(b6); add(b7);add(b8); add(b9);add(b0);add(add);
add(sub);add(mul);add(div); add(eq);add(cl);
b1.addActionListener(this); b2.addActionListener(this);
b3.addActionListener(this); b4.addActionListener(this);
b5.addActionListener(this); b6.addActionListener(this);
b7.addActionListener(this); b8.addActionListener(this);
b9.addActionListener(this); b0.addActionListener(this);
add.addActionListener(this); sub.addActionListener(this);
mul.addActionListener(this); div.addActionListener(this);
eq.addActionListener(this); cl.addActionListener(this);
paint();
//t1.addTextListener(this); }
public void paint() {
setBackground(Color.green); }
public void actionPerformed(ActionEvent e) {
s=e.getActionCommand();
if(s.equals(“0”)||s.equals(“1”)||s.equals(“2”)||
s.equals(“3”) || s.equals(“4”) || s.equals(“5”) || s.equals(“6”) ||
s.equals(“7”) || s.equals(“8”) ||
s.equals(“9”)||s.equals(“0”)) {
s1=t1.getText()+s;
t1.setText(s1); }
Web Technology 1–37 D (IT-5/CS-6)
if(s.equals(“+”)) {
s2=t1.getText();
t1.setText(“”);
s3=“+”; }
if(s.equals(“–”)) {
s2=t1.getText();
t1.setText(“”);
s3=“–”; }
if(s.equals(“*”)) {
s2=t1.getText();
t1.setText(“”);
s3=“*”; }
if(s.equals(“–”)) {
s2=t1.getText();
t1.setText(“”);
s3=“–”; }
if(s.equals(“=”)) {
s4=t1.getText();
a=Integer.parseInt(s2);
b=Integer.parseInt(s4);
if(s3.equals(“+”))
c=a+b;
if(s3.equals(“–”))
c=a–b;
t1.setText(String.valueOf(c)); }
if(s.equals(“Clear”)) {
t1.setText(“”); } }
public void textValueChanged(TextEvent e) { }}
PART-8
String Handling, Event Handling.
Introduction and Core Java 1–38 D (IT-5/CS-6)
Questions-Answers
Answer
1. String handling is a process of performing different operation such as
concatenation, comparison on the string.
2. Following are the method used in string handling :
a. Java string length() : The Java string length() method returns
the length of the string. It returns count of total number of
characters present in the string.
b. Java string compareTo() : The Java string compareTo() method
compares the given string with current string. It returns positive
number, negative number or zero.
c. Java string concat() : The Java string concat() method combines
a specific string at the end of another string and returns a combined
string.
d. Java string replace() : The Java string replace() method returns
a string, replacing all the old characters to new characters.
e. Java string equals() : The Java string equals() method compares
the two given strings on the basis of content of the string. If all the
characters are matched, it returns true else it will return false.
f. Java string contains() : The Java string contains() method
searches the sequence of characters in the string. If the sequences
of characters are found, then it returns true otherwise returns
false.
For example :
public class Example{
public static void main(String args[]{
String s1=“Hello”;
String s2=“Aditya”;
s3=s1.concat(“how are you?”);
System.out.println(“Length of string s1 is: ”+s1.length());
System.out.println(s1.compareTo(s2));
Web Technology 1–39 D (IT-5/CS-6)
System.out.println(s3);
System.out.println(s3.contains(“you”));
System.out.println(s1.replace(‘H’, “T”));
}}
Output :
Length of string s1 is: 5
False
Hello how are you?
True
Tello
Answer
Event :
1. An event happens when something changes within a graphical user
interface.
2. We can say that events are objects in Java. It comes under some classes
stored in java.util.EvenObject.
3. The Abstract Window Toolkit (AWT) uses event driven programming to
do processing of user actions, one that underlies all modern window
systems programming.
4. An event describes as a particular user action.
5. The Java run time notifies the program when an interesting event
occurs.
6. For example, events occur when a user clicks on a button, clicks on a
combobox, or types characters into a text field, such as in the following:
a. For a button, the event that is fired is the ActionListener.
b. For a text field, it is the KeyEvent.
The following is required to perform event handling :
1. Implement the Listener interface and override its methods
2. Register the component with the listener
Following are the public methods used for various components :
1. Button : void addActionListener( ActionListener a)
2. List :
void addActionListener(ActionListener a)
Introduction and Core Java 1–40 D (IT-5/CS-6)
void addItemListener(ItemListener a)
3. Choice :
void addItemListener(ItemListener x)
4. MenuItem :
void addActionListener(ActionListener x)
5. TextField :
void addActiontListener(ActionListener x)
void addTextListener(TextListener x)
6. TextArea :
void addTextListener(TextListener x)
PART-9
Introduction to AWT, AWT Controls, Layout Managers.
Questions-Answers
Answer
1. The AWT stands for Abstract Window Toolkit.
2. AWT is a library of class which provides GUI tools to develop GUI
application and applet.
3. It provides many classes for programmers to use. It is the connection
between our application and the native GUI.
4. It is a Java package and can be used in any Java program by importing
java.awt.* via the import keyword.
5. It contains three kinds of classes :
a. Containers class : Frame, Dialog, Panel, Applet etc.
b. Components class : TextField, Button, Checkbox, Scrollbar, Label,
List etc.
c. Custom graphics class : Colour, Font, Dimensions etc.
Web Technology 1–41 D (IT-5/CS-6)
Que 1.38. Mention various AWT controls. Explain any four of them.
Answer
AWT controls : AWT controls are components that allow a user to interact
with our application.
Various AWT controls are as follows : Refer Q. 1.37, Page 1–40D,
Unit-1.
1. Canvas : A canvas is a graphical component representing a region
where we can draw things such as rectangles, circles, and text strings.
2. Checkbox :
a. A Checkbox is a label with a small push button.
b. The state of Checkbox is either true (button is checked) or false
(button not checked).
c. The default initial state is false.
3. CheckboxGroup :
a. A CheckboxGroup is used to control the behaviour of a group of
Checkbox objects (each of which has a true or false state).
b. Exactly one of the Checkbox objects is allowed to be true at one
time.
c. Checkbox objects controlled with a CheckboxGroup are usually
referred to as “radio buttons”.
4. TextArea :
a. A TextArea is a multi-row text field that displays a single string of
characters, where newline (‘\n’ or ‘n\n\r’ or ‘\r’, depending on
platform) ends each row.
Introduction and Core Java 1–42 D (IT-5/CS-6)
b. The width and height of the field is set at construction, but the text
can be scrolled up/down and left/right.
Answer
LayoutManager :
1. LayoutManager is abstract class, we cannot use it directly.
2. LayoutManager class describes how components are “laid out” within a
container.
3. We must subclass it and provide our own functionality or use a derived
class of LayoutManager already created for us.
4. To use a layout we must call setLayout( ) for the container with an
instance of a LayoutManager.
Types of LayoutManager :
a. BorderLayout : This scheme lays out the component in five ways :
i. North-Northern part of the container
ii. South-Southern part of the container
iii. East-Eastern part of the container
iv. West-Western part of the container
v. Center-centered in the container
b. CardLayout : Allows for what Windows programmers have called
“tabbed dialogs” or dynamic dialogs.
c. GridLayout : Allows for the layout of components in a grid-like fashion
rather than “North” or “Center”.
d. FlowLayout : Allows for component to be laid out in a row (or flow)
and aligned (left, right, center).
e. None : No layout, the container will not attempt to reposition the
components during an update.
Que 1.40. Explain AWT and its controls. How the layout manager
manage the AWT controls ? Write a program to demonstrate
graphics (i.e. line, circle, rectangle etc.) using Frame, Panel, and
layout manager. AKTU 2019-20, Marks 07
Web Technology 1–43 D (IT-5/CS-6)
Answer
AWT : Refer Q. 1.37, Page 1–40D, Unit-1.
AWT controls : Refer Q. 1.38, Page 1–41D, Unit-1.
Layout manager : Refer Q. 1.39, Page 1–42D, Unit-1.
Program :
package com.mkyong;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Rectangle;
import java.awt.Shape;
import java.awt.geom.Ellipse2D;
import java.awt.geom.Line2D;
import java.awt.geom.RoundRectangle2D;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
public class DrawShapes extends JFrame {
private static final long serialVersionUID = 1L;
public DrawShapes() {
setSize(new Dimension(320, 320));
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
JPanel p = new JPanel() {
@Override
public void paintComponent(Graphics g) {
Graphics2D g2 = (Graphics2D) g;
Shape line = new Line2D.Double(3, 3, 303, 303);
Shape rect = new Rectangle(3, 3, 303, 303);
Shape circle = new Ellipse2D.Double(100, 100, 100, 100);
Shape roundRect = new RoundRectangle2D.Double(20, 20, 250, 250,
5, 25);
g2.draw(line);
g2.draw(rect);
Introduction and Core Java 1–44 D (IT-5/CS-6)
g2.draw(circle);
g2.draw(roundRect);
}
};
setTitle(“My Shapes”);
this.getContentPane().add(p);
}
public static void main(String arg[ ]) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
// TODO Auto-generated method stub
new DrawShapes();
}
});
}
}
Output :
Que 1.41. What are the uses of layout managers ? Give the name
of classes that represents the layout managers. Explain any five
layout managers. AKTU 2018-19, Marks 07
Answer
Layout manager is used to place the component such as buttons, text boxes
on the application.
Classes that represent the layout managers are :
1. BorderLayout 2. FlowLayout
3. GridLayout 4. CardLayout
5. GridBagLayout 6. BoxLayout
7. NoLayout 8. ScrollPaneLayout
9. SpringLayout
Five layout managers : Refer Q. 1.39, Page 1–42D, Unit-1.
Web Technology 1–45 D (IT-5/CS-6)
Q. 11. Explain AWT and its controls. How the layout manager
manage the AWT controls ? Write a program to
demonstrate graphics (i.e. line, circle, rectangle etc.) using
Frame, Panel, and layout manager.
Ans. Refer Q. 1.40.
Web Technology 2–1 D (IT-5/CS-6)
2
UNIT
Web Page Designing
CONTENTS
Part-1 : Web Page Designing : ........................ 2–2D to 2–11D
HTML : List, Tables, Images
PART-1
Web Page Designing : HTML : List, Tables, Images.
Questions-Answers
Answer
1. HTML is the language interpreted by a browser. Web pages are also
called HTML documents.
2. HTML is a set of special codes that can be embedded in text to add
formatting and linking information.
Structure of a HTML program :
1. Every HTML program has a rigid structure.
2. The entire web page is enclosed within <HTML>- - -</HTML> tags.
3. Within these tags two distinct sections are created using the
<HEAD>- - -</HEAD> tags and the <BODY>- - -</BODY> tags.
4. An HTML document is divided in two parts :
a. Document head using HEAD tags :
i. This HTML tag is used for the identification of the heading or
title of HTML document.
ii. All the information placed within the <HEAD>- - -</HEAD>
tags is not displayed in browser.
iii. The HTML tags used in the head section are :
a. Title tag
b. Style tag
b. Document body using BODY tags :
i. This tag is used for indicating the actual content of the HTML
documents layout and structure.
ii. The tags used to indicate the start and end of the main body of
text information are :
<BODY>
:
</BODY>
iii. The attributes that the <BODY> tag takes are : BGCOLOUR,
BACKGROUND, TEXT etc.
Web Technology 2–3 D (IT-5/CS-6)
Que 2.2. Define HTML tags. Also, explain different tags used for
text formatting in HTML with example.
Answer
HTML tags :
1. Tags are instructions that are embedded directly into the text of the
document.
2. HTML is specified as tags in an HTML document i.e., the web page.
HTML tags are of two types :
1. Paired tags :
a. Paired tag is a combination of two tags, opening tag (<B>) and
closing tag (</B>).
b. The opening tag activates the effect and the closing tag turns the
effect off.
For example : <HTML>- - -</HTML> tags.
2. Singular tags :
a. Singular tag is a standalone tag.
b. It does not have a closing tag.
For example : <BR> tag is used for single line break.
Some of the tags used for text formatting in HTML are :
1. Title :
a. An HTML document has a title that describes what the page is
about. This can be achieved by using TITLE tag.
b. Text included between the <TITLE> - - - - </TITLE> tags are shows
up in the title bar of the browser window.
For example :
<TITLE> Quantum Page </TITLE>
2. Footer :
a. Certain information is needed to be placed at the foot of the HTML
document like copyright information, contact details etc. This can
be achieved by using <ADDRESS> - - - - </ADDRESS> tags.
b. This tag should ideally be placed immediately after the last line of
the textual material of the web page.
For example :
<ADDRESS> Copyright © QUAN TUM PAGE PVT. LTD.
</ADDRESS>
3. Paragraph breaks :
a. <P> tag is used to break paragraph or skip one line between the
previous line and new line.
Web Page Designing 2–4 D (IT-5/CS-6)
Que 2.3. Describe tags used for styling in HTML with example.
Answer
Tags used for styling in HTML are :
1. Heading styles :
a. HTML supports six different levels of headings.
b. The highest level header format is <H1> and the lowest level is
<H6>.
Example : <BODY>
<H1> This is first level heading. </H1>
<H2> This is second level heading. </H2>
<H3> This is third level heading. </H3>
<H4> This is fourth level heading. </H4>
<H5> This is fifth level heading. </H5>
<H6> This is sixth level heading. </H6>
Web Technology 2–5 D (IT-5/CS-6)
</BODY>
Output :
Que 2.4. What is list in HTML ? What are the different types of
lists in HTML ? Give an example of each type.
Answer
Lists are used to present the list of information in well formed and semantic
way.
Types of list are :
1. Unordered list :
i. An unordered list starts with the tag <UL> and ends with </UL>.
ii. Each list item starts with the tag <LI>.
iii. The attributes that can be specified with <LI> : TYPE with three
values as FILLROUND, CIRCLE, SQUARE. The value of attribute
changes the style of the bullet.
iv. It is not necessary to use </LI> tag for ending the list.
Example : Quantum Series is also available for :
<UL TYPE = “FILLROUND”>
<LI> Computer Science
<LI> Information Technology
<LI> MCA
<LI> Electronics
<LI> Mechanical
<LI> Civil
</UL>
Output : Quantum Series is also available for :
Web Technology 2–7 D (IT-5/CS-6)
• Computer Science
• Information Technology
• MCA
• Electronics
•Mechanical
• Civil
2. Ordered list :
i. An ordered list starts with the tag <OL> and ends with </OL>.
ii. Each list items start with the tag <LI>.
iii. The attributes that can be specified with <OL> are :
a. TYPE : It can have five values which are 1, A, a, I, i.
b. START : It can be set of any numerical value.
c. VALUE : It is used for changing the numbering sequence in
the middle of ordered list.
Example : Quantum series for Information technology include :
<OL TYPE = “A” START = “3”>
<LI> Software Engineering
<LI> Web Technology
<LI> DBMS
<LI> Computer Organization
</OL>
Output : Quantum series for Information technology include :
3. Software Engineering
4. Web Technology
5. DBMS
6. Computer Organization
3. Definition list :
i. A definition list is a list of terms and corresponding definitions.
ii. Definition list values appear within <DL> and </DL> tags.
iii. Definition lists consist of two parts :
a. Definition Term <DT>
b. Definition Description <DD>
Example : <DL>
<DT> DBMS
<DD> Database Management System
<DT> CO
<DD> Computer Organization
Web Page Designing 2–8 D (IT-5/CS-6)
</DL>
Output : DBMS
Database Management System
CO
Computer Organization
Que 2.5. Explain the table tag with its attributes in detail.
Answer
All table related tags are included between the <TABLE> - - - - -
</TABLE> tags.
1. Table row : Rows of a table is described between the <TR> - - </TR>
tags. Table rows are of two types :
a. Header rows : A table header row is defined using <TH> - - </TH>
tags. Header row in a table is that which spans across columns of
table and give the information stored in it.
b. Data rows : Data cells placed in the horizontal plane creates a data
row. There could be single or multiple data cells. Data cells are the
columns in a table.
2. Table data : Table data tags used for displaying data in table data cells
using <TD> - - - - - </TD> tags. These tags must be needed inside the
<TR> - - - - - </TR> tags.
3. Table caption :
a. The title of a table in the HTML document is done using table
caption.
b. Table headings are called captions. Captions are given to the table
by using the <CAPTION> - - - - - </CAPTION> tags.
c. This tag has attribute ALIGN with two values TOP and BOTTOM.
4. The attributes that can be included in the <TABLE> tag are :
a. ALIGN : Horizontal alignment is controlled by the ALIGN attribute.
It can be set to LEFT, CENTER or RIGHT.
b. BORDER : Controls the border to be placed around the table. The
border thickness is specified in pixels.
c. CELL PADDING : Controls the distance between the data in a cell
and the boundaries of the cell.
d. CELL SPACING : Controls the spacing between adjacent cells.
e. COLSPAN : Width of the cell in terms of number of columns is
used when a cell occupies more than one column.
f. ROWSPAN : Height of the cell in terms of rows is used when a cell
occupies more than one row.
Web Technology 2–9 D (IT-5/CS-6)
Answer
1. HTML accepts many picture file formats such as .png, .gif and .jpg (.jpeg)
etc.
2. To add an image to web page we used the <IMG> tag, which takes the
name of the image file as an attribute, also control the height, width,
border etc.
3. The <IMG> tag takes the following attributes :
a. ALT : Indicates the text to be displayed in case the browser is
unable to display the image specified in the SRC attribute.
b. SRC : Specifies the location and name of the image file.
c. WIDTH : Specifies the width of the image in pixels.
d. HEIGHT : Specifies the height of the image in pixels.
e. ALIGN : The ALIGN attribute allows us to position an image relative
to the line of text. All graphical web browsers recognize these values
TOP, MIDDLE and BOTTOM.
f. BORDER : Specifies the size of the border to place around the
image.
Creating an image link :
We can also make a clickable link (image displayed with border) indicating
that it is a hyperlink.
Example : <A HREF = “QUANTUM.HTML”>
<IMG SRC = “QUANTUM.GIF” BORDER = “10”> </A>
This tells the web browser that the image file “QUANTUM.GIF” is clickable,
and any click on the image should be directed to the home page i.e.,
QUANTUM.HTML.
Answer
hyperlink.html :
<html><body>
Web Page Designing 2–10 D (IT-5/CS-6)
<th>Thursday</th>
<td>IT302</td><td>IT0304</td>
<td COLSPAN=2><center>PD0302</td>
<td COLSPAN=3 bgcolor=“cyan”><center>IT0320/IT0322</td>
</tr>
<tr>
<th>Friday</th>
<td>IT0308</td><td>IT0306</td>
<td>IT0308</td><td>IT0302</td>
<td COLSPAN=2 bgcolor=“red”><center>ELECTIVE - I</td>
<td></td>
</tr></tbody></table></body>
PART-2
Frames.
Questions-Answers
Answer
1. The HTML frame is a powerful feature that enables a web page to be
broken into different unique sections, that although related and operate
independent of each other.
2. Each ‘frame’ can be loaded with a different document and hence, allow
multiple HTML documents to be seen concurrently.
Following two tags are used in HTML for frame :
a. <FRAMESET> tag :
1. The splitting of a browser screen into frames is accomplished with the
<FRAMESET> and </FRAMESET> tags embedded into the HTML
document.
2. The <FRAMESET> ... </FRAMESET> tags require one of the following
two attributes depending on whether the screen has to be divided into
rows or columns.
a. Rows :
i. This attribute is used to divide the screen into multiple rows.
ii. It can be set equal to a list of values, depending on the required
size of each row.
Web Page Designing 2–12 D (IT-5/CS-6)
Que 2.9. Write HTML code to develop a web page having two
frames that divide the page into two equal rows and divides the first
row into equal columns. Fill each with the different background
colour.
Answer
<html>
<FRAME ROWS = “50%, 50%”>
<FRAMESET COLS =“50%, 50%”>
<FRAME SRC=“File 1.html”> </FRAME>
<FRAME SRC=“File 2.html”> </FRAME>
</FRAMESET>
<FRAME SRC =“File 3.html”> </FRAME>
</FRAMESET>
</html>
For background colour :
For File 1.html :
<html>
<body BGCOLOR = “RED”>
</body>
</html>
Web Page Designing 2–14 D (IT-5/CS-6)
Answer
Role of frames in advertising on web :
1. A frame is a part of a web page or browser window which displays
content independent of its container, with the ability to load content
independently.
2. Frames play a big role in advertising on web by allowing the following
advantages :
a. Content can be loaded and navigated independently.
b. Simple maintenance of content shared across all or most pages.
c. Reducing the amount of bandwidth needed.
d. Allowing several pieces of information to be viewed side by side.
3. All the above advantages helps in reducing the advertising budget and
the audience can view the intended information easily.
Roles of form in making web page dynamic :
1. In hidden frame technique we could hide or minimise the size of frame.
2. The hidden frame is loaded with a web page that contains a form, and
JavaScript is used to dynamically fill out the form making the web page
dynamic.
Header.html
Menu.html Output.html
Also host it as a web page on any server.
Answer
Frameset.html :
<!DOCTYPE html>
<html>
<frameset rows=“25%,*”>
<frame src=“Header.htm”>
<frameset cols=“50%,50%”>
<frame src=“Menu.htm”>
<frame src=“Output.htm”>
</frameset>
</frameset>
</html>
Node.js :
var http = require(‘http’);
var url = require(‘url’);
var fs = require(‘fs’);
var server = http.createServer(function(request, response) {
var path = url.parse(request.url).pathname;
switch (path) {
case ‘/’:
response.writeHead(200, {
‘Content-Type’: ‘text/plain’
});
response.write(“This is Test Message.”);
response.end();
break;
case ‘/frameset.html’:
fs.readFile(__dirname + path, function(error, data) {
if (error) {
response.writeHead(404);
response.write(error);
response.end();
} else {
response.writeHead(200, {
‘Content-Type’: ‘text/html’
});
response.write(data);
response.end();
}
});
break;
Web Page Designing 2–16 D (IT-5/CS-6)
default:
response.writeHead(404);
response.write(“opps this does not exist - 404”);
response.end();
break;
}
});
server.listen(8082);
PART-3
Forms.
Questions-Answers
Answer
1. All the input elements should be enclosed within the opening <FORM>
and closing </FORM> tags like this :
<FORM> The input elements go here </FORM>
2. The following are the important attributes for the form tag :
a. ACTION : This attribute is used to specify where the form data is to
be sent to the server after submission of the form.
b. METHOD :
i. This attribute specifies how to send form data.
ii. The form data can be sent as URL variables (with method =
“GET”) or as HTTP post transaction (with method = “POST”).
Various input items in HTML forms are :
1. Text input :
a. Text input is used to collect single line of text from the user like
name, e-mail address etc.
b. A text input item can be defined like this :
<INPUT TYPE=“text” NAME=“FirstName”>
Web Technology 2–17 D (IT-5/CS-6)
2. Submit button :
a. After entering the data, the user presses the submit button which
triggers the browser to send the data to the server.
b. We can add a submit button to the form using the ‘submit’ input
type.
c. We can add a submit button to our HTML form using the following
code :
<INPUT TYPE=“submit” NAME=“name” VALUE=“Submit”>
3. Checkbox :
a. Checkbox is used to select or deselect the multiple option from a set
of options.
b. If we specify CHECKED, the checkbox will be checked by default.
4. Radio button :
a. Radio buttons are used for selecting one item from multiple available
choices.
b. When the user selects a button in the set, all other buttons in the
set are deselected.
c. The individual button in a set is created using input type “radio”.
5. Dropdown list :
a. <SELECT> tag is used to create a dropdown list.
b. We can create a list using the <SELECT> </SELECT> tag and the
items in the list using the <OPTION> tag.
6. Password input :
a. Login screens usually have a password field where the user enters
his password. We can create a password field by using the input
type PASSWORD.
b. A password field can be created using the following code :
<INPUT TYPE=“PASSWORD” NAME=“pwd”>
7. Uploading a file :
a. Some HTML form allows the user to upload a file.
b. The input type FILE lets the user to upload a file to the server.
c. Here is the syntax of FILE input type :
<INPUT TYPE=“FILE” NAME=“name” VALUE=“filename”>
8. Reset the form :
a. The input type RESET can be used to reset the form.
b. When the user presses the reset button, all the elements in the
form are reset to their default values.
Web Page Designing 2–18 D (IT-5/CS-6)
Answer
<html>
<head>
<script type = “text/JavaScript” src = “validate.js”></script>
</head>
<body>
<form action = “#” name = “RailwayReservationSystem”
onsubmit = “return(validate( ) ) ;”>
<table cellpadding = “2” width = “20%” bgcolor = “99FFFF”
align = “center” cellspacing = “2”>
<tr>
<td colspan = “2”>
<center><font size = “4”><b>Railway Reservation System</b></font>
< /center>
</td>
</tr>
<tr>
<td>From</td>
<td><input type = “text” name = “from” id = “from”
size = “30”></td>
</tr>
<tr>
<td>To</td>
<td><input type = “text” name = “to” id = “to” size = “30”></td>
</tr>
<tr>
<td>Train No/Name</td>
<td><input type = “text” name = “trainno”
id = “trainno” size = “30”></td>
</tr>
<tr>
<td>Class</td>
<td><select name = “Class”>
<option value = “– 1” selected>Select</option>
<option value = “SL”>SL</option>
<option value = “3A”>3A</option>
<option value = “2A”>2A</option>
<option value = “1A”>1A</option>
</select></td>
Web Technology 2–19 D (IT-5/CS-6)
</tr>
<tr>
<td>No. of seats</td>
<td><Select name =“No. of seats”>
<option value = “– 1”selected>Select</option>
<option value = “1”>1</option>
<option value = “2”>2</option>
<option value = “3”>3</option>
</select></td>
</tr>
<tr><td>Passenger</td>
<tr><td>Age</td></tr>
<tr><td>Gender</td></tr>
</tr>
<td><input type = “text” name = “P1”size = “30”></td>
<td><input type = “text” name = “age”size = “2”></td>
<td><Select name =“gender”>
<option value = “M”>M</option>
<option value = “F”>F</option></select>
</td></tr>
<tr>
<td><input type = “text” name = “P2”size = “30”></td>
<td><input type = “text” name = “age”size = “2”></td>
<td><Select name =“gender”>
<option value = “M”>M</option>
<option value = “F”>F</option></select>
</td></tr>
<tr>
<td><input type = “text” name = “P3”size = “30”></td>
<td><input type = “text” name = “age”size = “2”></td>
<td><Select name =“gender”>
<option value = “M”>M</option>
<option value = “F”>F</option></select>
</td></tr>
<tr>
<td>Address</td>
<td><input type = “text” name = “address” id = “address”
size = “50”></td>
</tr>
<tr>
<td>Payment Mode</td>
<td><input type = “radio” name = “Paymentmode” value = “Credit/Debit
Card”>Credit/Debit Card
Web Page Designing 2–20 D (IT-5/CS-6)
Address
PART-4
CSS.
Questions-Answers
Answer
1. Cascading Style Sheet or CSS enables us to separate the content of
HTML documents from the presentation.
2. A single file or a small group of files could define the presentation
format for the entire website. Thus, any format or presentation changes
across the website would be controlled through these CSS files.
3. To define styles, we use the <style> element.
4. To define properties for the documents, we specify the attributes for the
document tags within the <style>.
5. When defining the style for a template HTML file, the style element is
placed within the document <head> and not in the <body>.
Advantages of CSS :
1. To make the web page attractive.
2. Faster download of web page.
3. Increase visual appearance of web page.
Answer
Various features of CSS are :
1. Cascading :
a. This is the capability provided by CSS to allow style information
from several sources to be blended together.
b. The cascade defines an ordered sequence of style sheets where
rules in later sheets have greater precedence than earlier ones.
c. By storing these separately, style sheets can be reused.
Web Page Designing 2–22 D (IT-5/CS-6)
Que 2.16. What is CSS ? What are different ways to create them ?
Answer
CSS : Refer Q. 2.14, Page 2–21D, Unit-2.
Different types of CSS :
1. Inline CSS :
a. An inline CSS is used to apply a unique style to a single HTML
element.
b. An inline CSS uses the style attribute of an HTML element.
For example : Following example sets the text color of the <h1>
element to blue :
<h1 style=“color:blue;”>This is a Blue Heading</h1>
2. Internal CSS :
a. An internal CSS is used to define a style for a single HTML page.
b. An internal CSS is defined in the <head> section of an HTML page,
within a <style>element.
For example :
<!DOCTYPE html>
<html>
<head>
<style>
body {background-color : powderblue;}
h1 {color : blue;}
p {color : red;}
</style>
</head>
Web Technology 2–23 D (IT-5/CS-6)
<body>
<h1>This is a heading</h1>
<p>This is a paragraph.</p>
</body>
</html>
3. External CSS :
a. An external style sheet is used to define the style for many HTML
pages.
b. An external style sheet is used to change the look of an entire
website.
c. To use an external style sheet we add a link in the <head> section
of the HTML page.
For 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>
Que 2.17. What do you mean by CSS ? Write a CSS rule that makes
all the text 2.5 times larger than the base font of the system.
Mention how can you integrate CSS on a web page ?
AKTU 2018-19, Marks 07
Answer
CSS and its integration on a web page : Refer Q. 2.16, Page 2–22D,
Unit-2.
Program :
<HTML><HEAD><STYLE>
H1 {colour: red; font-family: arial; font-size: 2.50 em}
</STYLE></HEAD><BODY>
<H1> This is the H1 element </H1>
</BODY></HTML>
Web Page Designing 2–24 D (IT-5/CS-6)
Answer
Role of CSS :
1. It allows us to develop the overall look of our website.
2. It allows us to position and reposition the components of a web page
with relative ease.
3. It allows us to alter and control the every aspect of layout in a web page.
Importance of CSS :
1. It helps in quick loading of web pages.
2. It helps in saving bandwidth.
2. It helps in customization of web pages.
3. It provides complete consistency to the web pages.
Difference :
Que 2.19. Explain CSS. What are the CSS frameworks? Explain in
brief. What are the different ways of using the stylesheet? Write a
CSS rule that makes all the text 2.5 times larger than the base font
of the system. AKTU 2019-20, Marks 07
Answer
CSS : Refer Q. 2.14, Page 2–21D, Unit-2.
CSS frameworks :
A CSS framework is a library allowing web design for easier, more standards-
compliant using the Cascading Style Sheets language. Bootstrap, Foundation,
Bulma, UIkit, Semantic UI are some of the CSS frameworks.
Web Technology 2–25 D (IT-5/CS-6)
Answer
Properties of CSS are :
1. Font properties :
a. Font-family : Denotes font of the text.
b. Font-size : Denotes the size of the text.
c. Font-style : Denotes the style of the text i.e., normal, bold, italic
etc.
d. Font-weight : Denotes the weight or darkness of the font.
2. Text properties :
a. Word-spacing : Denotes the space between words.
b. Vertical-align : Denotes the vertical positioning of the text and
images, with respect to the baseline.
c. Text-align : Specifies the alignment of the text. The possible values
are center, justify etc.
d. Text-transform : Denotes the transformation of text. The possible
values are capitalize uppercase, lowercase etc.
e. Text-decorate : Denotes the text decoration. The standard values
for this property include blink, line-through, overline, underline
etc.
3. Colour and background properties :
a. Colour : Used to set the colour of the text.
b. Background-colour : This property set an element background
colour.
c. Background-image : Associates a background image with an
element.
d. Background-position : Specifies how a background image is
positioned.
4. Box properties :
a. Margin-properties : The individual margins for a block element
can be set using margin-top, margin-rigid, margin-bottom, or
margin-left.
b. Border properties :
i. Border-style
ii. Border-width
iii. Border-colour
Web Page Designing 2–26 D (IT-5/CS-6)
Uses of CSS :
1. CSS is used in the Web document for presentation purpose.
2. It is used to separate the Web content from the Web presentation.
3. It is used to enhance the features of Web pages like formatting styles.
4. CSS helps in faster downloading of the pages.
PART-5
Document Type Definition, XML : DTD.
Questions-Answers
Answer
1. A Document Type Definition (DTD) defines the basic building blocks of
an XML document.
2. It defines the document structure with a list of various elements and
attributes.
3. A DTD can be declared inline inside an XML document, or as an external
reference.
Types of DTD :
1. Internal DTD declaration : If the DTD is declared inside the XML
file, it should be wrapped in a DOCTYPE definition with the following
syntax :
<!DOCTYPE root-element [element-declarations]>
2. External DTD declaration : If the DTD is declared in an external file,
it should be wrapped in a DOCTYPE definition with the following syntax :
<!DOCTYPE root-element SYSTEM “filename”>
External DTD is preferable because :
They can be used in more than one document. So, it is easy to change in
one external DTD rather than changing in all internal DTD file.
Que 2.22. What is DTD ? What are the differences between external
and internal DTD ? Use suitable example.
AKTU 2015-16, Marks 10
Web Technology 2–27 D (IT-5/CS-6)
Answer
DTD : Refer Q. 2.21, Page 2–26D, Unit-2.
Difference :
<name>Prabha Patil</name>
<company>Quantum</company>
<phone>(011) 123-4567</phone>
</address>
The content of the DTD file address.dtd are as shown :
<!ELEMENT address (name,company,phone)>
<!ELEMENT name (#PCDATA)>
<!ELEMENT company (#PCDATA)>
<!ELEMENT phone (#PCDATA)>
Que 2.23. Explain the role of DTD in XML and also describe its
Answer
Role of DTD :
1. The role of a DTD is to define the legal building blocks of an XML
document.
2. It defines the document structure with a list of legal elements.
3. A DTD can be declared inline in our XML document, or as an external
reference.
Types of DTD : Refer Q. 2.21, Page 2–26D, Unit-2.
Answer
1. XML is a markup language for documents containing structured
information which contains both content and some indication of the role
of content.
2. Extensible Markup Language, abbreviated as XML, describes a class of
data objects called XML documents and partially describes the behaviour
of computer programs which process them.
3. XML documents are made up of storage units called entities, which
contain either parsed or unparsed data.
Significance of XML :
1. XML can store and organize just about any kind of information in a form
according to our needs.
Web Technology 2–29 D (IT-5/CS-6)
2. With its clear, simple syntax and unambiguous structure, XML is easy to
read and parse.
3. XML is easily combined with stylesheets to create formatted documents
in any style.
Difference between XML and HTML :
Root element
<bookstore>
Parent Child
Fig. 2.24.1.
Answer
XML : Refer Q. 2.24, Page 2–28D, Unit-2.
DTD : Refer Q. 2.21, Page 2–26D, Unit-2.
Program :
XML document :
Student.XML
<?xml version = “1.0”?>
<!DOCTYPE STUDENTS SYSTEM “E:\XML1\STUDENT.dtd”>
<STUDENTS><STUDENT><STUDENTDATA>
<Roll_No> 001</Roll_No>
<NAME> RAM</NAME>
<Marks>
<Marks 1> 70 </Marks 1>
<Marks 2> 80 </Marks 2>
<Marks 3> 50 </Marks 3>
<Marks 4> 60 </Marks 4>
<Marks 5> 70 </Marks 5>
<Total> 330 </Total>
<Percentage> 66.0 </Percentage>
</Marks>
</STUDENTDATA></STUDENT></STUDENTS>
NOTE : Write the above code (bold part only) nine times again to
enter the details of rest of the nine students.
Student.dtd
<?xml version “1.0”?>
<!ELEMENT STUDENTS (STUDENT*)>
<!ELEMENT STUDENT (STUDENTDATA*)>
<!ELEMENT STUDENTDATA (Roll_No, Name, Marks, Total, Percentage)>
<!ELEMENT Roll_No (#PCDATA)>
<!ELEMENT NAME (#PCDATA)>
<!ELEMENT Marks (#PCDATA)>
<!ELEMENT Total (#PCDATA)>
<!ELEMENT Percentage (#PCDATA)>
Student.html
<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Transitional//EN”
“E:\XML 1\STUDENT.dtd””>
<html>
Web Page Designing 2–32 D (IT-5/CS-6)
Que 2.26. What are XML parsers ? Explain the types of parsers
with their advantages and disadvantages.
AKTU 2018-19, Marks 07
Answer
XML parser :
1. An XML parser is a software library or package that provides interfaces
for client applications to work with an XML document.
2. The XML Parser is designed to read the XML and create a way for
programs to use XML.
3. XML parser validates the document and check that the document is well
formatted.
There are two types of XML Parsers :
1. DOM :
a. The Document Object Model (DOM) is a platform-independent and
language-independent standard object model for representing
HTML or XML and related formats.
b. The DOM defines a standard for accessing documents like XML
and HTML.
Advantages :
i. It supports both read and write operations and the API is very simple to
use.
ii. It is preferred when random access to widely separated parts of a
document is required.
Disadvantages :
i. It is memory inefficient.
ii. It is comparatively slower than other parsers.
2. SAX :
a. SAX stands for Simple API for XML and works directly with an
XML.
b. SAX is an event-driven API that allows us to interpret a web file
that uses XML.
c. SAX takes the control of event specifies by the programmer and
handles the situation.
Advantages :
i. It is simple and memory efficient.
ii. It is very fast and works for huge documents.
Web Page Designing 2–34 D (IT-5/CS-6)
Disadvantages :
i. It is event based so its API is less intuitive.
ii. Clients never know the full information because the data is broken into
pieces.
Answer
“Document Type Definition (DTD) in XML is necessary” :
1. The main purpose of Document Type Definition is to define the structure
of an XML document.
2. It contains a list of legal elements and defines the structure with the
help of them.
3. DTD provides less control on XML structure.
4. With DTD, independent groups of people can agree to use a common
DTD for interchanging data.
Example : Refer Q. 2.22, Page 2–26D, Unit-2.
External DTD is preferable in following conditions :
1. If we want to use same DTD in more than one XML file.
2. When we define DTD for particular kind of data and then use it in
different XML file.
Internal DTD is preferable only when we want to use the DTD for a particular
XML file only.
PART-6
XML Schemas, Object Model, Presenting and using XML using XML
Processors : DOM, and SAX, Dynamic HTML.
Questions-Answers
Que 2.28. What is XML schema ? Compare XML schema and XML
DTD.
OR
What is DTD ? Also explain its differences with XML schema.
AKTU 2017-18, Marks 10
Web Technology 2–35 D (IT-5/CS-6)
Answer
1. XML schema is an XML based alternative to Document Type Definition
(DTD).
2. The goal or purpose of XML schema is to define the building blocks of an
XML document.
3. XML schema syntax is well-formed XML, making it possible to use XML
tools to edit it.
4. The XML schema language is called as XML Schema Definition (XSD)
language.
5. XML schema defines elements, attributes, child elements, order of child
elements, number of child elements and whether an element is empty
or can include text.
6. It also defines default values, fixed values and data types for elements
and attributes.
DTD : Refer Q. 2.21, Page 2–26D, Unit-2.
Comparison of XML schema and XML DTD :
Answer
1. The Document Object Model (DOM) is a platform-independent and
language-independent standard object model for representing HTML or
XML and related formats.
2. The DOM is a W3C (World Wide Web consortium) standard.
3. The DOM defines a standard for accessing documents like XML and
HTML.
4. It allows programs and scripts to dynamically access and update the
content, structure, and style of document.
Example :
<? xml version = “1.0”?>
<book-order>
<customer> Karamveer </customer>
<shop> Bookmart </shop>
<goods>
<book>
<name > “Web application development with XML and Java”
</name>
</book>
</goods>
</book-order>
DOM
book-order
name
Answer
COM :
1. The Component Object Model (COM) is a software architecture that
allows applications to be built from binary software components.
2. COM is the underlying architecture that forms the foundation for higher-
level software services.
3. It is used to enable inter-process communication and dynamic object
creation in a large range of programming languages.
4. In a component based system, components interact with each other by
calling methods and passing data.
5. COM ensures that there is a standard method of interaction between
the components.
6. All the COM objects need to follow these standards when providing the
functionality.
DCOM :
1. DCOM (Distributed Component Object Model) is a set of Microsoft
concepts and program interfaces in which client program objects can
request services from server program objects on other computers in a
network.
2. DCOM is based on the Component Object Model (COM), which provides
a set of interfaces allowing clients and servers to communicate within
the same computer.
3. DCOM is a model as COM but it is specially designed for distributed
application.
4. DCOM, which originally was called “Network OLE” extends Microsoft’s
COM, and provides the communication substrate under Microsoft’s
COM+ application server infrastructure.
5. DCOM was a major competitor to CORBA.
Answer
1. An XML processor is a software module that is used to read XML
documents and provide application programs with access to their content
and structure.
2. XML processors are written in Java. Some are validating processors,
while others are non-validating.
3. When reading an XML document, a validating processor checks the
validity constraints and the well-formed constraints defined in XML 1.0
recommendation.
4. A validating XML processor is one of the most robust and faithful
implementation of XML processor.
5. The validating processor XML for Java is a Java class library.
Web Page Designing 2–38 D (IT-5/CS-6)
Answer
1. SAX stands for Simple API for XML and works directly with an XML.
2. SAX is an event-driven API that allows us to interpret a web file that
uses XML.
3. SAX takes the control of event specifies by the programmer and
handles the situation.
4. SAX is a simpler interface than DOM and is appropriate where many
or very large files are to be processed.
5. It also helps in manipulating the data content.
6. SAX is faster and uses less memory than DOM.
Example :
<? xml version = “1.0”?>
<book-order>
<customer> Karamveer </customer>
<shop> Bookmart </shop>
<goods>
<book>
<name> Web application development
with XML and Java </name>
</book>
</goods>
</book-order>
(DOM) (SAX)
book-order
start Element : book-order end Element :
start Element : customer book
customer characters : Karamveer end Element :
shop goods
end Element : customer goods
start Element : shop
characters : Bookmart end Element :
"Karamveer" "Bookmart" "book"
end Element : shop book-order
start Element : goods
name start Element : book
start Element : name
character : Web application development
with XML and Java
"Web application
end Element : name
development with
XML and Java"
Fig. 2.32.1.
Web Technology 2–39 D (IT-5/CS-6)
Answer
1. SAX (Simple API for XML) is a serial access parser API for XML.
2. SAX provides a mechanism for reading data from an XML document.
3. A parser which implements SAX (i.e. a SAX parser) functions as a
stream parser with an event-driven API.
4. The user defines a number of callback methods that will be called when
events occur during parsing.
5. The SAX events include :
a. XML text nodes
b. XML element nodes
c. XML processing instructions
d. XML comments
6. Events are triggered when each of these XML features are encountered
and again when the end of them is encountered.
7. XML attributes are provided as part of the data passed to element events.
8. SAX parsing is unidirectional i.e., previously parsed data cannot be
re-read without starting the parsing operation again.
Answer
1. DHTML stands for Dynamic Hyper Text Markup Language.
2. DHTML is a combination of technologies used to create dynamic web
pages.
3. DHTML means a combination of HTML, CSS, DOM and JavaScript.
4. DHTML is designed to enhance the user experience on web.
5. DHTML includes the following features :
a. Dynamic content, which allows the user to dynamically change
web page content.
b. Dynamic positioning of web page elements.
c. Dynamic style, which allows the user to change the web page’s
colour, font, size or content.
Web Page Designing 2–40 D (IT-5/CS-6)
Difference :
Q. 8. Explain the role of DTD in XML and also describe its types
with an example.
Ans. Refer Q. 2.23.
Q. 10. What are XML parsers ? Explain the types of parsers with
their advantages and disadvantages.
Ans. Refer Q. 2.26.
Web Technology 3–1 D (IT-5/CS-6)
3
UNIT
Scripting and
Networking
CONTENTS
Part-1 : Scripting : Javascript : ...................... 3–2D to 3–10D
Introduction,
Documents, Forms
PART-1
Scripting : JavaScript : Introduction, Documents, Forms.
Questions-Answers
Answer
1. JavaScript is a scripting language which enables web authors to design
interactive sites.
2. JavaScript can interact with HTML source code, enabling web authors
to build their sites with dynamic content.
3. JavaScript is an open source language that anyone can use without
purchasing a license.
Working of JavaScript :
1. When the browser loads a web page, the HTML parser creates the DOM.
2. Whenever parser encounters JavaScript directive, it is handed over the
JavaScript engine and loads the external and inline code.
3. After HTML and CSS parsing is completed, JavaScript is executed in
order they were found in web page and DOM is updated and rendered
by the browser.
JavaScript has several features :
1. Programming tool : JavaScript is a scripting language with very simple
syntax.
2. Can produce dynamic text into an HTML page : For instance, the
JavaScript statement - document.write (“<h1>”+name+ “</h1>”); results
into the HTML output <h1> Atul </h1>, if the variable name contains
the text Atul.
3. Reaching to events : JavaScript code executes when something
happens such as when page has finished loading, when a user clicks on
an HTML element.
4. Reading and writing HTML elements : JavaScript can read and
change the content of an HTML element.
5. Validate data : JavaScript can be used to validate form data before it is
submitted to a server, and thus saves the server from extra processing.
Web Technology 3–3 D (IT-5/CS-6)
Answer
Difference between Java and JavaScript :
S. No. Java JavaScript
1. Java is an obje ct-o riente d JavaScript is an object based
programming language. scripting language.
2. Java is strongly typed language JavaScript is very flexible in
and type checking. data type.
3. Objects in Java are static. Objects in JavaScript are
dynamic.
4. It can be use d to cre ate It cannot be used to create
standalone application. standalone application.
5. Variables in Java are declared Variables in JavaScript are
as : int num. declared as : var myname.
Strengths/Advantages of JavaScript :
1. An interpreted language : JavaScript is an interpreted language,
which requires no compilation steps.
2. Quick development : JavaScript does not require time consuming
compilations, scripts can be developed in a short period of time.
3. Performance :
a. JavaScript can be written such that the HTML files are fairly compact
and quite small.
b. It minimizes storage requirements on the web server and download
time for the client.
4. Easy debugging and testing : Being an interpreted language, scripts
in JavaScript are tested line by line and the errors are also listed as they
are encountered.
Weakness/Disadvantages of JavaScript :
1. There are issues of incompatibility of several scripting that result in
website overloading.
2. Different layout engines may render JavaScript differently resulting in
inconsistency in terms of functionality and interface.
3. JavaScript is also a common tool for the web hackers; they use scripts
injection to hack a site.
Scripting and Networking 3–4 D (IT-5/CS-6)
4. JavaScript is light, somehow too much of JavaScript can slow down the
page loading of a website.
Answer
1. A document object represents the HTML document that is displayed
in the window.
2. DOM is an object oriented representation of an HTML document and
acts as an interface between JavaScript and the document itself and
allows the creation of dynamic web pages.
3. The hierarchical structure of object is applied for the organization of
objects in a web document which include following object :
a. Window object : It is the top most element of the object hierarchy.
b. Document object : Each HTML document that gets loaded into
a window becomes a document object which contains the contents
of the page.
c. Form object : Everything enclosed in the <form>...</form> tags
sets the form object. The form object contains all the elements
defined for that object such as text fields, buttons, radio buttons,
and checkboxes.
4. When a web page is loaded, the browser creates a Document Object
Model of the page.
5. DOM supports navigation in any direction (i.e., parent and previous
sibling) and allows for arbitrary modifications.
Answer
Difference between Java and JavaScript : Refer Q. 3.2, Page 3–3D,
Unit-3.
JavaScript function for e-mail address validation :
<script type = “text/javascript”>
function validateEmail()
{
var i;
var str=document.my_form.Email_txt.value;
Web Technology 3–5 D (IT-5/CS-6)
var index_at=str.indexOf(‘‘@’’);
var len=str.length;
var index_dot=str.indexOf(‘‘.’’);
var emailID=document.my_form.Email_txt;
if((emailID.value==null)||(emailID.value ==‘‘ ’’));
{
alert(‘‘Please Enter your Email ID’’);
emailID.focus();
return false;
}
if (str.indexOf(‘‘.’’) == –1|| str.indexOf(‘‘.’’) == 0||
str.indexOf(‘‘@’’) ==–1||str.indexOf(‘‘.’’) == index_at
||str.indexOf(‘‘@’’,(index_at+1))!= –1)||
||str.indexOf(‘‘ ’’))!= –1||
{
alert(‘‘Invalid Email ID’’);
return false;
}
return true;
}
</script>
Answer
Following are the steps used to perform client-side validation using
JavaScript :
1. First the user will enter the value in the form field.
2. Then, browser will ensure that the value provided by user is correct and
is valid so that successful validation can be done.
3. JavaScript used in the web page uniquely defines all the special
functionalities in the client browser.
4. By default, if there is a validation error then an error or pop-up message
is shown by the browser.
5. If there is no error then the validation on client-side will be successfully
performed.
Scripting and Networking 3–6 D (IT-5/CS-6)
For example :
If a form field (fname) is empty, validateform function alerts a message,
and returns false, to prevent the form from being submitted:
function validateForm() {
var x = document.forms[“myForm”][“fname”].value;
if (x == “ ”) {
alert(“Name must be filled out”);
return false;
}
}
The JavaScript function is called when the form is submitted :
<form name=“myForm” action=“/action_page.php” onsubmit=“return
validateForm()” method=“post”>
Name: <input type=“text” name=“fname”>
<input type=“submit” value=“Submit”>
</form>
Answer
Scripting language :
1. A scripting language is a programming language designed for integrating
and communicating with other programming languages.
2. Some of the most widely used scripting languages are JavaScript,
VBScript, PHP, Perl, Python, Ruby, ASP.
JavaScript is used because :
a. It is executed on client side.
b. It saves bandwidth on web server.
c. It is written into an HTML page.
JavaScript function for validating form data :
<script type=“text/javascript”>
function validateform()
{
var name = document.myform.name.value;
var password = document.myform.password.value;
var confirmpassword = document.myform.password2.value;
Web Technology 3–7 D (IT-5/CS-6)
Answer
Comparison : Refer Q. 3.2, Page 3–3D, Unit-3.
Program to sort value using JavaScript :
<!DOCTYPE html>
<html><body>
<h2>JavaScript Array Sort</h2>
<p>The sort() method sorts an array alphabetically.</p>
<button onclick=“myFunction()”>Try it</button>
<p id=“demo”></p>
<script>
var fruits = [“Banana“, “Orange”, “Apple”, “Mango”];
document.getElementById(“demo”).innerHTML = fruits;
function myFunction() {
fruits.sort();
document.getElementById(“demo”).innerHTML = fruits;
}
</script></body></html>
Answer
<html><body>
<script type=“text/javascript”>
var str1=“W3Schools is great!”
document.write(str1.substr(2,6))
document.write(“<br><br>”)
document.write(str1.substring(2,6))
// string length
var str2=“Web Enabling Tools is Cool!”
document.write(“<p>” + str2 + “</p>”)
document.write(“str.length”)
// Square root of a number
var property_value = Math.SQRT1_2
document.write(“Property Value is : ” + property_value);
var value = Math.exp(1);
document.write(“First Test Value : ” + value );
var value = Math.exp(30);
document.write(“<br />Second Test Value : ” + value );
var value = Math.exp(– 1);
document.write(“<br />Third Test Value : ” + value );
// Find maximum of a number
var value = Math.max(10, 20, – 1, 100);
document.write(“First Test Value : ” + value );
var value = Math.max(– 1, – 3, – 40);
document.write(“<br />Second Test Value : ” + value );
</script>
Answer
Role of JavaScript :
1. It makes our website dynamic.
2. It makes our webpage interactive which means that it can respond to
mouse clicks, double clicks, hover and many other actions (called events).
Scripting and Networking 3–10 D (IT-5/CS-6)
3. It can also be used for modifying our html, content and styles, form
validation.
4. JavaScript can interact with the website server to send and receive
information to update UI in real-time.
JavaScript function to check whether a textbox is either empty or
not :
<html>
<script>
function required(inputtx)
{
if (inputtext1.value.length == 0)
{
alert(“Textbox is empty”);
return false;
}
return true;
}
</script>
<body>
<form>
<input type = “text” name=“text1”>
</form>
</body></html>
PART-2
Statements, Functions, Objects.
Questions-Answers
Answer
There are following conditional statement used in JavaScript :
1. If statement : If statement is used if we want to execute some code
only if a specified condition is true.
Web Technology 3–11 D (IT-5/CS-6)
Syntax :
if (condition)
{
code to be executed if condition is true
}
For example :
<script type = “text/javascript”>
var d = new Date();
var time = d.getHours();
if (time<10)
{
document.write (“<b>Good morning to all</b>”);
}
</script>
2. If...else statement : If...else statement is used when we do not confirm
about the condition that is true or not.
Syntax :
if (condition)
{
code to be executed if condition is true
}
else
{
code to be executed if condition is not true
}
For example :
<script type = “text/javascript”>
//If the time is less than 10, print “Good Day” Otherwise “Good Night”
var d = new Date ();
var time = d.getHours ();
if (time < 10)
{
document.write (“Good Day”);
}
else
{
document.write (“Good Night”);
}
Scripting and Networking 3–12 D (IT-5/CS-6)
</script>
3. If...else if...else statement : We can use the if...else if...else statement
if we want to select one from many sets of lines with different condition.
Syntax :
if (condition1)
{
code to be executed if condition1 is true
}
else if (condition2)
{
code to be executed if condition2 is true
}
else
{
code to be executed if condition1 and condition2 are not true
}
For example :
<script type = “text/javascript”>
var d = new Date();
var time = d.getHours();
if (time<10)
{
document.write(“<b>Good morning</b>”);
}
else if (time>10 && time<16)
{
document.write(“<b>Good afternoon</b>”);
}
else
{
document.write (“<b>Good night</b>”);
}
</script>
Web Technology 3–13 D (IT-5/CS-6)
Answer
Data types in JavaScript : JavaScript provides different data types to hold
different types of values.
There are two types of data types in JavaScript :
1. Primitive data type : There are five types of primitive data types in
JavaScript. They are as follows :
Function in JavaScript :
1. Functions can be defined both in the <head> and in the <body> section
of a document.
2. However, to assure that the function is read/loaded by the browser
before it is called, it is needed to be defined in the <head> section.
3. Syntax :
function function_name (var1, var2, . . . , varX)
{
some code
}
var1, var2, etc., are variables or values passed into the function.
4. A function with no parameters must include the parentheses () after
the function name :
function function_name ()
{
Web Technology 3–15 D (IT-5/CS-6)
some code
}
Answer
Comparison : Refer Q. 3.2, Page 3–3D, Unit-3.
Different object in JavaScript :
1. Built-in objects : These objects are used quite extensively for data
processing in JavaScript. Following are some built-in object :
a. String object :
i. The string object enables programs to work with and manipulate
string.
ii. It provide methods such as : big(), blink(), bold(), italics(),
charAt(), touppercase(), tolowercase() and substring().
b. Math object :
i. The math object provides some commonly used methods such
as : sqrt(num), abs(num), sin(num), cos(num), tan(num),
exp(num), min(a, b), max(a, b), log(num), pow(a, b), floor(num),
ceil(num) etc.
c. Date object :
i. The date object enables JavaScript programmers to create an
object that contains information about a particular date and
provides a set of methods to work with that information.
ii. Syntax :
var mydate = new Date(<parameters>);
iii. If the parameter left empty, it indicates current date and time.
iv. The date object provides some methods which are : getDate(),
setDate(), getHours(), setHours(), getTime(), setTime(),
getDay(), setDay(), getMinutes(), setMinutes(), getSecond(),
setSecond().
d. Array object :
i. The array object stores multiple values in a single variable.
ii. Syntax :
var fruits = new Array( “apple”, “orange”, “mango” );
2. User-defined objects :
a. A user-defined object is also associated with properties and methods,
which belong to it.
Scripting and Networking 3–16 D (IT-5/CS-6)
b. The user-defined object would also require methods that will allow
the storage of name, age and salary of the employee object.
function Employee(name, age, salary)
{
this.name = name;
this.age = age;
this.salary = salary;
}
c. In the given example, object Employee has three properties : name,
age and salary. Here, this keyword refers to the current object in
focus. In given example, this.name will refer to the name of the
current object.
For example :
<html>
<head>
<title>JavaScript Object </title>
</head>
<body>
<script type=“text/javascript”>
var value = Math.acos(-1);
document.write(“ACOS Test Value : ” + value +“<br>”);
// Math object
var d = new Date();
document.write(“<b>Locale String:</b> ” +
d.toLocaleString()+“<br>”);
// Date Object
var str = “CareerRide Info”; //String Object
var s = str.split();
document.write(“<b>Char At:</b> ” + str.charAt(1)+“<br>”);
document.write(“<b>CharCode At:</b> ” + str.charCodeAt(2)+“<br>”);
document.write(“<b>Index of:</b> ” + str.indexOf(“ide”)+“<br>”);
</script>
</body>
</html>
Output:
ACOS Test Value : 3.141592653589793
Locale String: 22/02/2020 11:14:06 AM
Char At: a
Web Technology 3–17 D (IT-5/CS-6)
Answer
1. In JavaScript we can associate functions with objects by creating objects
and assigning properties.
2. Every object in JavaScript has different property.
3. Property of an object is defined in a variable which is attached to an object.
4. Object properties are mostly the same as simple JavaScript variables.
5. JavaScript has a number of predefined objects. So, we can create our
own objects and embed the function directly in the object.
For example :
var myCar = new Object();
myCar.make = “Nissan”;
myCar.model = “N-54”;
myCar.year = 1972;
<script type=“text/javascript”>
function user(name, email) {
this.name = name;
this.email = email;
//Custom method for object
this.toString = function userToString() {
return(“Name: ”+this.name+“ Email: ”+this.email);
}
}
var obj = new user(“Aditya”,“[email protected]”);
document.write(obj.toString());
</script>
Que 3.14. How do we handle event in JavaScript ? What is
DHTML ?
Answer
Event handling in JavaScript :
1. JavaScript allows us to change the default action associated with events.
For example, event processing where a user clicks a hyperlink on a
page. Fig. 3.14.1 depicts how events occur and are handled in JavaScript.
Scripting and Networking 3–18 D (IT-5/CS-6)
PART-3
Introduction to AJAX.
Questions-Answers
Answer
1. AJAX (Asynchronous JavaScript and XML) is a set of web development
techniques for creating better, faster and more interactive web
applications with the help of XML, HTML, CSS and JavaScript.
2. Traditional web applications tend to follow the pattern shown in
Fig. 3.15.1.
3. First a page is loaded. Next, the user performs some action such as
filling out a form or clicking a link.
Web Technology 3–19 D (IT-5/CS-6)
Data transmitting
Data trans mitting
Data transmitting
Data trans mittin
Client-side
Waiting Waiting
Time
vent
vent
UI Update
UI Update
UI Update
UI Update
Change
Indicator
Activity
AJAX
Data
User E
User E
User E
communication
layer
Time
Server-side Server-side
Server-side Processing Processing
Fig. 3.15.2. AJAX style communication flow.
Scripting and Networking 3–20 D (IT-5/CS-6)
Que 3.16. What is AJAX ? Explain its advantage and its working.
Answer
AJAX : Refer Q. 3.15, Page 3–18D, Unit-3.
Advantages of AJAX :
1. Reduces the server traffic and increases the speed.
2. Ajax is responsive and time for data transfer is also less.
3. Form validation
4. Bandwidth usage can be reduced.
5. Asynchronous calls can be made which reduces the time for data arrival.
Working of AJAX : XMLHttpRequest object plays an important role as
AJAX communicates with the server using XMLHttpRequest object.
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.
2 HTTP request
XMLHttpRequest Business logic
implementation
Fig. 3.16.1.
Web Technology 3–21 D (IT-5/CS-6)
For example :
<!DOCTYPE html>
<html>
<body>
<div id=“demo”>
<h2>The XMLHttpRequest Object</h2>
<button type=“button” onclick=“loadDoc()”>Change Content</button>
</div>
<script>
function loadDoc() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById(“demo”).innerHTML = this.responseText;
}
};
xhttp.open(“GET”, “ajax_info.txt”, true);
xhttp.send();
}
</script>
</body>
</html>
Answer
AJAX : Refer Q. 3.15, Page 3–18D, Unit-3.
Applications of AJAX are :
1. AJAX is used to change the text without reloading the web page.
2. AJAX is a technique used for creating fast and dynamic web pages.
3. AJAX contains div section which is used to display information returned
from a server.
Scripting and Networking 3–22 D (IT-5/CS-6)
4. Major application of AJAX is in login forms where user can enter their
login details directly on the original page.
For example :
<!DOCTYPE html>
<html>
<style>
table,th,td {
border : 1px solid black;
border-collapse: collapse;
}
th,td {
padding: 5px;
}
</style>
<body>
<h1>The XMLHttpRequest Object</h1>
<form action=“”>
<select name=“customers” onchange=“showCustomer(this.value)”>
<option value=“”>Select a customer:</option>
<option value=“name1”>Aakash Pandey</option>
<option value=“name2”>Mohan</option>
<option value=“name3”>Harshit Kumar</option>
</select>
</form>
<br>
<div id=“txtHint”>Customer info will be listed here...</div>
<script>
function showCustomer(str) {
var xhttp;
if (str == “”) {
document.getElementById(“txtHint”).innerHTML = “”;
return;
}
xhttp = new XMLHttpRequest();
Web Technology 3–23 D (IT-5/CS-6)
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById(“txtHint”).innerHTML = this.responseText;
} };
xhttp.open(“GET”, “getcustomer.asp?q=”+str, true);
xhttp.send();
}
</script>
</body>
</html>
PART-4
Networking : Internet Addressing, InetAddress, Factory Methods,
Instance Methods.
Questions-Answers
Answer
1. The IP address is a network layer address that uniquely identifies each
computer on network.
2. Each TCP/IP host is identified by a logical IP address.
3. The IP address identifies a system’s location on the network. An IP
address must be globally unique and have a uniform format.
4. Each IP address includes a network ID and a host ID.
i. The network ID (also known as a network address) identifies the
systems that are located on the same physical network ID. The
network ID must be unique to the internetwork.
ii. The host ID (also known as a host address) identifies a workstation,
server, router, or other TCP/IP host within a network. The address
for each host must be unique to the network ID.
5. The use of the term network ID refers to any IP network ID, whether
it is class-based, a subnet, or a supernet.
Scripting and Networking 3–24 D (IT-5/CS-6)
Class
type Netid Hostid
Fig. 3.18.1.
6. An IP address is 32 bits long. It is a common practice to segment the 32
bits of the IP address into four 8-bit fields called octets.
7. Each octet is converted to a decimal number (the base 10 numbering
system) in the range 0-255 and separated by a period (a dot). This
formal is called dotted decimal notation.
Answer
IP address is classified as :
1. Class A :
i. Class A addresses are assigned to networks with a very large
number of hosts.
ii. The high-order bit in a class A address is always set to zero.
iii. The next seven bits (completing the first octet) complete network
ID. The remaining 24 bits (the last three octets) represent the
host ID.
iv. This allows for 126 networks and 16,777,214 i.e., 224 hosts per
network.
2. Class B :
i. Class B addresses are assigned to medium-sized to large-sized
networks.
ii. The two high-order bit in a class B address are always set to binary
10.
iii. The next 14 bits (completing the first two octets) complete the
network ID. The remaining 16 bits (last two octets) represent the
host ID.
iv. This allows for 16,384 networks and 65,534 hosts per network.
Web Technology 3–25 D (IT-5/CS-6)
Fig. 3.19.1.
3. Class C :
i. Class C addresses are used for small networks.
ii. The three high-order bits in a class C address are always set to
binary 110.
iii. The next 21 bits (completing the first three octets) complete the
network ID. The remaining 8 bits (last octet) represent the host
ID.
iv. This allows for 2,097, 152 networks and 254 hosts per network.
From To
Class A 0.0.0.0 127 . 255 . 255 . 255
Netid Hostid Netid Hostid
Class B 128 . 0 . 0 . 0 191 . 255 . 255 . 255
Netid Hostid Netid Hostid
Class C 192 . 0 . 0 . 0 223 . 255 . 255 . 255
Netid Hostid Netid Hostid
Class D 224 . 0 . 0 . 0 239 . 255 . 255 . 255
Group address Netid Hostid
Class E 240 . 0 . 0 . 0 255 . 255 . 255 . 255
Undefined Undefined
Fig. 3.19.2.
4. Class D :
i. Class D addresses are reserved for IP multicast addresses.
ii. The four high-order bits in a class D address are always set to
binary 1110.
iii. The remaining bits are for the address that interested hosts will
recognize.
iv. Microsoft supports class D addresses for applications to multicast
data to multicast-capable hosts on an internetwork.
5. Class E : Class E addresses are experimental addresses reserved for
future use. The high-order bits in a class E address are set to 1111.
Scripting and Networking 3–26 D (IT-5/CS-6)
Answer
InetAddress class :
1. The InetAddress class is used to encapsulate both the numerical IP
address and the domain name for that address.
2. The InetAddress class hides the number inside.
3. InetAddress can handle both IPv4 and IPv6 addresses.
4. The InetAddress class has no visible constructors.
Factory methods :
1. Factory methods are used to create an IntAddress object.
2. Factory method is a static method in a class and return an instance of
that class.
3. Three commonly used InetAddress factory methods are as follows :
a. The getLocalHost() : This method simply returns the InetAddress
object that represents the local host.
b. The getByName() : This method returns an InetAddress for a
host name passed to it. If this method is unable to resolve the
host name then, they throw an UnknownHostException.
c. The getAllByName() : This method returns an array of
InetAddresses that represent all of the addresses that a particular
name resolves to. It will also throw an UnknownHostException
if it cannot resolve the name to at least one address.
Answer
1. Instance method is a method defined in a class and only accessible
through the object of the class.
2. The InetAddress class has several instance methods, which can be
used on the objects.
3. Following are the object returned by the methods which are as follows :
a. Boolean equals(Object other) : It returns true if this object
has the same Internet address as other. Otherwise, it returns
false.
b. Byte[ ] getAddress() : It returns a byte array that represents
the object’s Internet address in network byte order.
c. String getHostAddress() : It returns a string that represents
the host address associated with the InetAddress object.
Web Technology 3–27 D (IT-5/CS-6)
PART-5
TCP/IP Client Sockets, URL, URL Connection,
TCP/IP Server Socket, Datagram.
Questions-Answers
Que 3.22. Explain TCP/IP client socket. Also, write the constructor
and methods used to create a client socket.
Answer
1. TCP/IP client sockets are used to implement bi-directional, point-to-
point, stream-based connections between hosts on the Internet.
2. A socket can be used to connect Java I/O system to other programs
that may reside either on the local machine or on any other machine
on the Internet.
3. The creation of a Socket object implicitly establishes a connection
between the client and server.
4. Following are the two constructors used to create client socket :
a. Socket(String hostName, int port) : Creates a socket connecting
the local host to the named host, port and can throw an Unknown
HostException or an IOException.
b. Socket(InetAddress ipAddress, int port) : Creates a socket
using a pre-existing InetAddress object, a port and can throw an
IOException.
5. Following methods are used by TCP/IP client socket :
a. InetAddress getInetAddress() : Returns the InetAddress
associated with the Socket object.
b. Int getPort() : Returns the remote port to which the Socket
object is connected.
c. Int getLocalPort() : Returns the local port to which the Socket
object is connected.
Scripting and Networking 3–28 D (IT-5/CS-6)
Answer
1. URL is an acronym for Uniform Resource Locator.
2. It points to a resource on the World Wide Web (WWW).
3. A URL contains many information like protocol name, server name,
port number and file name.
4. The URL is represented by an URL class.
5. Consider the following URL :
http://www.quantumpage.com/aktu-paper.html
a. Protocol : In this case, http is the protocol.
b. Server name or IP address : In this case, www.quantumpage.com
is the server name.
c. Port number : It is an optional attribute. If we write http//
www.quantumpage.com:80/aktu-papers.html/, 80 is the port
number. If port number is not mentioned in the URL, it returns
– 1.
d. File name or directory name : In this case, aktu-papers.html
is the file name.
Following are the method provided by java.net.URL class :
S. No. Method Description
URLConnection class :
1. The Java URLConnection class represents a communication link between
the URL and the application.
2. This class can be used to read and write data to the specified resource
referred by the URL.
Web Technology 3–29 D (IT-5/CS-6)
Answer
1. The TCP/IP ServerSocket is used to create servers that listen for
either local or remote client programs to connect them on published
ports.
2. TCP/IP ServerSockets are quite different from normal sockets.
3. When we create a TCP/IP Server Socket, it will register itself with the
systems that have client connections.
4. The constructors for TCP/IP ServerSocket reflect the port number
that we wish to accept connections on and, how long we want the port
to be in the queue.
5. The queue length tells the system how many client connections it can
leave pending before it should simply refuse connections.
6. It has constructors that create new TCP/IP ServerSocket objects,
methods that listen for connections on a specified port, methods that
configure the various TCP/IP server socket options, and the usual
miscellaneous methods such as toString().
Answer
i. Socket programming :
1. Java socket programming is used for communication between the
applications running on different JRE.
2. Java socket programming can be connection-oriented or connection-
less.
3. Socket and ServerSocket classes are used for connection-oriented socket
programming and DatagramSocket and DatagramPacket classes are
used for connection-less socket programming.
Scripting and Networking 3–30 D (IT-5/CS-6)
Answer
1. Datagram is a unit of transfer associated with networking.
2. Datagram is typically structured in header and payload section.
3. It provides a connectionless communication service across a
packet-switched network.
Characteristics of datagram :
1. It is transmitted from source to destination without guarantee of delivery.
2. It provides a connectionless communication service.
Datagram socket :
1. It is a communication link used to send datagram between applications.
2. Datagram so cket is a type of network so cket which pro vide
connectionless point for sending and receiving packets.
3. Every packet sent from a datagram socket is individually routed and
delivered.
4. Java DatagramSocket and DatagramPacket classes are used for
connectionless socket programming.
5. A DatagramPacket is a message that can be sent or received through
DatagramSocket.
6. Commonly used constructors of DatagramSocket class are as follows :
a. DatagramSocket() throws SocketException : It creates a
datagram socket and binds it with the available port number on
the localhost machine.
b. DatagramSocket(int port) throws SocketException : It creates
a datagram socket and binds it with the port number.
c. DatagramSocket(int port, InetAddress address) throws
SocketException : It creates a datagram socket and binds it
with the specified port number and host address.
Web Technology 3–31 D (IT-5/CS-6)
Que 3.27. Discuss socket and server socket in Java with its
package. Write a program in Java to demonstrate, how the
communication is establish between client and server ?
AKTU 2019-20, Marks 07
Answer
Socket : Refer Q. 3.22, Page 3–27D, Unit-3.
Server socket : Refer Q. 3.24, Page 3–29D, Unit-3.
For example :
// A Java program for a Client
import java.net.*;
import java.io.*;
public class Client
{
// initialize socket and input output streams
private Socket socket = null;
private DataInputStream input = null;
private DataOutputStream out = null;
// constructor to put ip address and port
public Client(String address, int port)
{
// establish a connection
try
{
socket = new Socket(address, port);
System.out.println(“Connected”);
// takes input from terminal
input = new DataInputStream(System.in);
// sends output to the socket
out = new DataOutputStream(socket.getOutputStream());
}
catch(UnknownHostException u)
Scripting and Networking 3–32 D (IT-5/CS-6)
{
System.out.println(u);
}
catch(IOException i)
{
System.out.println(i);
}
// string to read message from input
String line = “”;
// keep reading until “Over” is input
while (!line.equals(“Over”))
{
try
{
line = input.readLine();
out.writeUTF(line);
}
catch(IOException i)
{
System.out.println(i);
}
}
// close the connection
try
{
input.close();
out.close();
socket.close();
}
catch(IOException i)
{
System.out.println(i);
}
}
public static void main(String args[ ])
{
Client client = new Client(“127.0.0.1”, 5000);
}
}
Web Technology 3–33 D (IT-5/CS-6)
Web Technology 4–1 D (IT-5/CS-6)
4
UNIT
Enterprise Java Beans
and JDBC
CONTENTS
Part-1 : Enterprise Java Bean : ............................. 4–2D to 4–8D
Preparing a Class to be a
Java Beans, Creating a
Java Beans, Java Beans Properties
PART-1
Enterprise Java Bean : Preparing a Class to be a Java Beans,
Creating a Java Beans, Java Beans Properties.
Questions-Answers
Answer
1. An Enterprise Java Bean is a server-side component which encapsulates
business logic.
2. EJB (Enterprise Java Bean) is used to develop scalable, robust and
secured enterprise applications in Java.
3. Middleware services such as security, transaction management etc. are
provided by EJB container to all EJB applications.
4. To run EJB application, we need an application server (EJB Container)
such as Jboss, Glassfish, Weblogic, Websphere etc.
5. EJB application is deployed on the server, so it is also called server-side
component.
Advantages of EJB :
1. It can run in multithreaded environment.
2. It contains only business logic.
3. EJB provides distributed transaction support.
4. It provides portable and scalable solutions of the problem.
5. It provides a mechanism to store and retrieve data in a persistent way.
Disadvantages of EJB :
1. It requires application server.
2. It requires only Java client. For other language client, we need to go for
web service.
3. It is complex to understand and develop EJB applications.
Que 4.2. Discuss EJB. Explain EJB architecture. What are its
OR
Write short note on EJB architecture. AKTU 2016-17, Marks 05
Answer
EJB : Refer Q. 4.1, Page 4–2D, Unit-4.
EJB architecture :
JSP/servlet
Client-side Server
HTTP
Web browser
request JDBC
EJB Database
driver
connection
J2EE Server
Que 4.3. What is Java Bean exactly ? Write down the steps to
create Java Bean. What is the role of introspection in Java Bean ?
OR
Enterprise Java Beans & JDBC 4–4 D (IT-5/CS-6)
Answer
EJB architecture and its types : Refer Q. 4.2, Page 4–2D, Unit-4.
Java Beans :
1. Java Beans are classes which encapsulate several objects into a single
object.
2. It helps in accessing the objects from multiple places.
3. It is a portable, platform independent model written in Java.
Steps used to create Java Bean :
Step 1 : Put source code into a file named “SimpleBean.java” :
import java.awt. * ;
import java.io.Serializable;
public class SimpleBean extends Canvas
implements Serializable {
// Constructor sets inherited properties
public SimpleBean ( ) {
setSize (60, 40);
setBackground (Color.red);
}
}
Step 2 : Compile the file :
javac SimpleBean.java
Step 3 : Create a manifest file, named “manifest.tmp” :
Name : SimpleBean.class
Java-Bean : True
Step 4 : Create the JAR file, named “SimpleBean.jar” :
jar cfm SimpleBean.jar manifest.tmp SimpleBean.class
Then, verify that the content is correct by the command “jar tf
SimpleBean.jar”.
Step 5 :
1. Start and run the Bean Box.
2. Load JAR file into Bean Box by selecting “Loadjar...” under the File
menu.
Web Technology 4–5 D (IT-5/CS-6)
Step 6 :
1. After the file selection dialog box is closed. Then “SimpleBean” appear
at the bottom of the toolbox window.
2. Select SimpleBean.jar.
3. Cursor will change to a plus. In the middle BeanBox window, we can
now click to drop in what will appear to be a coloured rectangle.
Step 7 : Try changing the red box colour with the Properties windows.
Step 8 : Choose “Events” under the “Edit” menu in the middle window to see
what events SimpleBean can send. These events are inherited from
java.awt.Canvas.
Role of introspection in Java Bean :
1. Introspection in Java is used in the context of Java Beans which defines
the component model of Java.
2. Introspection feature enables a Java Bean to get the properties, methods
and events of other beans at runtime.
3. This helps the developers to design and develop their beans without
knowing the details of other beans.
Steps to build application using BDK :
Step 1 : Create a directory for the new bean.
Step 2 : Create the Java source file(s).
Step 3 : Compile the source file(s).
Step 4 : Create a manifest file.
Step 5 : Generate a JAR file.
Step 6 : Start the BDK.
Step 7 : Test the newly created Java Bean.
Que 4.4. Explain JavaBeans. Why they are used ? Discuss setter
Answer
Java Beans : Refer Q. 4.3, Page 4–3D, Unit-4.
Java Beans are used because :
1. It encapsulates many objects into a single object.
2. It allows us to use properties of getter and setter methods.
3. It has Java object which has constructor with no argument.
4. It can be manipulated visually in a builder tools.
Getter and setter method :
1. In Java, getter and setter are two conventional methods that are used
for retrieving and updating value of a variable.
Enterprise Java Beans & JDBC 4–6 D (IT-5/CS-6)
For example :
The following code is an example of simple class with a private variable
and a couple of getter/setter methods :
public class SimpleGetterAndSetter {
private int number;
public int getNumber() {
return this.number;
}
public void setNumber(int num) {
this.number = num;
}
}
2. The class declares a private variable, number. Since “number” is private,
code from outside this class cannot access the variable directly,
SimpleGetterAndSetter obj = new SimpleGetterAndSetter();
obj.number = 10;
int num = obj.number;
3. Inside the main class invoke the getter i.e., getNumber() and the setter
i.e., setNumber() in order to read or update the variable,
For example :
public static void main (String args[ ])
{
SimpleGetterAndSetter obj = new SimpleGetterAndSetter();
obj.setNumber(10);
System.out.println (obj.getNumber ( ));
}
4. Getter and setter are also known as accessor and mutator in Java.
Answer
Java Beans is a Java class that should have following conventions:
1. It must implement serializable interface.
2. It should have a public constructor without argument.
3. All properties in Java Bean must be private with public getter and setter
methods.
Example of Java Bean class :
//Employee.java
Web Technology 4–7 D (IT-5/CS-6)
package mypack;
public class Employee implements java.io.Serializable{
private int id;
private String name;
public Employee(){}
public void setId(int id){this.id=id;}
public int getId(){return id;}
public void setName(String name){this.name=name;}
public String getName(){return name;}
}
To access the Java Bean class, we should use getter and setter methods :
package mypack;
public class Test{
public static void main(String args[]){
Employee e=new Employee(); //object is created
e.setName(“Arjun”); //setting value to the object
System.out.println(e.getName()); // getting value to the object
}}
Answer
Java Bean class contains three types of properties :
1. Simple properties :
a. A simple property has a single value.
b. It can be identified by the following design patterns, where N is the
name of the property and T is its type.
public T getN();
public void setN(T parameter)
c. If the property has both read and write permission then both the
get and set methods can access the values. Otherwise, only one
method can access the values.
d. If the property has only read permission then only get method can
access the values, similarly if the property has only write permission
then only set method can access the values.
2. Boolean properties :
a. A boolean property has a value of true or false.
b. It can be identified by the following design patterns, where N is the
name of the property.
Enterprise Java Beans & JDBC 4–8 D (IT-5/CS-6)
PART-2
Types of Beans, Stateful Session Bean, Stateless Session Bean,
Enlity Bean.
Questions-Answers
Answer
Session bean :
1. Session bean encapsulates business logic only, it can be invoked by local,
remote and web service client.
2. It can be used for managing activities like database access, calculation
etc.
3. The life cycle of session bean is maintained by the application server
(EJB container).
4. Session bean is created by a customer and its duration is only for the
signal client server session.
Types of session bean :
1. Stateless session bean :
a. Stateless session bean is a business object that represents business
logic only. It does not have state (data).
Web Technology 4–9 D (IT-5/CS-6)
b. The stateless bean objects are pooled by the EJB container to service
the request on demand.
c. It can be accessed by one client at a time.
d. The stateless session bean is distributed object which has no
connection with informal state; only allow parallel access to beans.
e. Annotations used in stateless session bean are :
i. @Stateless
ii. @PostConstruct
iii. @PreDestroy
2. Stateful session bean :
a. Stateful session bean is a business object that represents business
logic like stateless session bean. But, it maintains state (data).
b. Conversational state between multiple method calls is maintained
by the container in stateful session bean.
c. There are five important annotations used in stateful session bean :
i. @Stateful
ii. @PostConstruct
iii. @PreDestroy
iv. @PrePassivate
v. @PostActivate
3. Singleton session beans :
a. A singleton session bean is instantiated once per application and
exists for the lifecycle of the application.
b. Singleton session beans are designed for circumstances in which a
single enterprise bean instance is shared across and concurrently
accessed by clients.
c. It has only one singleton session bean per application.
d. It can implement web service endpoints.
e. Singleton session beans maintain their state between client
invocations but are not required to maintain their state across
server crashes or shutdowns.
Answer
1. Entity beans are objects that represent a persistence storage
mechanism.
2. Each entity beans has underlying table in a relational database and each
row in the table represents the instance of the bean.
Enterprise Java Beans & JDBC 4–10 D (IT-5/CS-6)
Que 4.9. What do you mean by session bean ? Explain its types
using suitable example.
Answer
Session bean and its types : Refer Q. 4.7, Page 4–8D, Unit-4.
Example : An example of stateless session bean is a stock quote component
that returns the current price of a given stock symbol. Such a bean could
look up the stock price from a database that is updated by a real-time feed.
An example of a stateful session bean is a shopping cart that represents the
collection of products selected by a particular customer for purchase during
a session. The shopping cart should not be shared because it represents a
particular interaction with a particular customer and is alive only for the
customer’s session.
PART-3
Java Database Connectivity (JDBC) : Merging Data from Multiple
Tables : Joining.
Questions-Answers
Answer
1. JDBC (Java Database Connectivity) is a Java API that manages
connection to database, issuing queries and commands and handling
result sets obtained from the database.
2. JDBC is useful for both application developers and JDBC driver vendors.
3. JDBC is specially used for having connectivity with the RDBMS packages
using corresponding JDBC driver.
Working of JDBC :
1. All Java application establishes connection with the data source and
invokes classes and interfaces from JDBC driver for sending queries to
the data source.
2. The JDBC driver connects to corresponding database and retrieves the
result.
3. These results are based on SQL statements, which are then returned to
Java applications.
4. Java application then uses the retrieved information for further
processing.
Java
application
Send SQL
Result
JDBC
Drivers
Connects
Result
Database
Fig. 4.10.1.
Answer
Components of JDBC :
1. Driver manager :
a. When Java applications need connection to the database it invokes
the DriverManager class.
Enterprise Java Beans & JDBC 4–12 D (IT-5/CS-6)
b. This class then loads JDBC drivers in the memory. The driver
manager also attempts to open a connection with the desired
database.
2. Connection :
a. This is an interface which represents connectivity with the data
source.
b. The connection is used for creating the statement instance.
3. Statement :
a. This interface is used for representing the SQL statements.
b. Some SQL statements are :
SELECT *FROM students _ table;
UPDATE students _table set name = ‘Nitin’ WHERE roll _ no = ‘1’;
c. There are two specialised statement types : PreparedStatement
and callableStatement.
4. ResultSet :
a. This interface is used to represent the database resultSet.
b. After using SELECT SQL statement, the information obtained from
the database can be displayed using ResultSet.
5. SQL exception : For handling SQL exceptions, this interface is used.
Answer
JDBC architecture :
Java Application
JDBC API
Driver Manager
Driver
Database
Fig. 4.12.1.
Web Technology 4–13 D (IT-5/CS-6)
Answer
Types of JDBC drivers are :
1. JDBC-ODBC bridge driver (Type 1 driver) :
a. These drivers are the bridge drivers such as JDBC-ODBC bridge.
b. These drivers rely on an intermediary such as ODBC to transfer
the SQL calls to the database.
c. Bridge drivers often rely on native code, although the JDBC-ODBC
library native code is part of the Java-2 virtual machine.
Application
JDBC-Driver Manager
ODBC-Driver Manager
Application
JDBC
DBMS vendor
client-side Socket
connection DBMS
libraries based
server
on C language
Application
JDBC
Socket connection
JAVA based (DBMS specific
DBMS
socket driver protocol)
Server
Que 4.14. What is JDBC ? Explain the drivers used in JDBC. Write
a JDBC program for insert and display the record of employees
using prepared statement. AKTU 2018-19, Marks 07
Web Technology 4–15 D (IT-5/CS-6)
Answer
JDBC : Refer Q. 4.10, Page 4–10D, Unit-4.
Drivers in JDBC : Refer Q. 4.13, Page 4–13D, Unit-4.
Program :
import java.sql.*; import java.io.*;
public class PreparedStatementDemo1 {
Connection con;
PreparedStatement ps;
public PreparedStatementDemo1() {
try {
Class.forName(“com.mysql.jdbc.Driver”);
con = DriverManager.getConnection(“jdbc:mysql://localhost/
test?user=root&password=root”);
} catch (Exception e) { e.printStackTrace(); } }
// add customer detail
public String addCustomer(String custid, String name, String address,
String contact) {
String status = “”;
try {
ps = con.prepareStatement(“insert into Customer values(?,?,?,?)”);
ps.setString(1, custid); ps.setString(2, name);
ps.setString(3, address); ps.setString(4, contact);
int i = ps.executeUpdate();
if (i != 0) {
status = “Inserted”;
} else {
status = “Not Inserted”; }
} catch (Exception e) { e.printStackTrace(); }
return status; }
// customer record
public void searchCustomer(String custid) {
String sql = “”;
if (custid.trim().length() == 0) {
sql = “select * from Customer”;
} else {
sql = “select * from Customer where custid=” + custid + “”; }
try {
ps = con.prepareStatement(sql);
ResultSet res = ps.executeQuery();
while (res.next()) {
System.out.print(res.getString(1));
System.out.print(res.getString(2));
System.out.print(res.getString(3));
System.out.println(res.getString(4)); }
} catch (SQLException e) {e.printStackTrace(); } }
Enterprise Java Beans & JDBC 4–16 D (IT-5/CS-6)
PART-4
Manipulating, Databases with JDBC, Prepared Statements
Transaction Processing, Stored Procedures.
Questions-Answers
Answer
import java.sql.*;
public class jdbcConn
{
public static void main(String[] args) throws Exception
{
Class.forName(“org.apache.derby.jdbc.ClientDriver”);
Connection con = DriverManager.getConnection (
“jdbc:derby://localhost:1527/testDb”,“username”, “password”);
Statement stmt = con.createStatement();
String query =“SELECT fname,lname,isbn FROM author INNER JOIN
books ON author.AUTHORID = books.AUTHORID”;
ResultSet rs = stmt.executeQuery(query);
System.out.println(“Fname Lname ISBN”);
while (rs.next())
{
String fname = rs.getString(“fname”);
String lname = rs.getString(“lname”);
int isbn = rs.getInt(“isbn”);
System.out.println(fname + “ ” + lname+“ ”+isbn);
}
System.out.println();
System.out.println();
}
}
Enterprise Java Beans & JDBC 4–18 D (IT-5/CS-6)
Output :
Fname Lname ISBN
Jatin Garg 123
Pankaj Sharma 113
Pankaj Sharma 112
Pankaj Sharma 122
Answer
JDBC application architecture : Refer Q. 4.12, Page 4–12D, Unit-4.
Types of JDBC driver : Refer Q. 4.13, Page 4–13D, Unit-4.
Steps to connect database with web application using JDBC :
Step 1 : Create a database using some suitable database management package.
Step 2 : Initiate object for JDBC driver using following statement :
Class.forName (“com.mysql.jdbc.Driver”). newInstance ( );
Step 3 : Using DriverManager class and getConnection method we get
connected to the database.
To get connected with MySQL database we use following statement :
DriverManager.getConnection (“jdbc:mysql://localhost; 3306/students”, “root”,
“system”);
Answer
1. Prepared statement interface is a subinterface of statement.
2. It is used to execute parameterized query.
3. The PreparedStatement interfaces define the methods and properties
that enable us to send SQL or PL/SQL commands and receive data from
our database.
4. This statement gives us the flexibility for supplying arguments
dynamically.
5. Syntax to create PreparedStatement object :
PreparedStatement pstmt = null;
try {
String SQL = “Update Employees SET age = ? WHERE id = ?”;
pstmt = conn.prepareStatement(SQL);
...
Web Technology 4–19 D (IT-5/CS-6)
}
catch (SQLException e) {
...
}
finally {
pstmt.close();
}
6. All parameters in JDBC are represented by the ? symbol, which is
known as the parameter marker. We must supply values for every
parameter before executing the SQL statement.
7. To close the PreparedStatement object a simple call to the close() method
is made. If we close the connection object first, it will close the
PreparedStatement object as well.
Answer
Steps to connect a Java application with database :
1. Register the driver :
Class.forName() is used to load the driver class explicitly.
Example :
Class.forName(“sun.jdbc.odbc.JdbcOdbcDriver”);
2. Create a connection :
a. getConnection() method of DriverManager class is used to create a
connection.
b. Syntax :
getConnection(String url)
getConnection(String url, String username, String password)
getConnection(String url, Properties info)
Example : Establishing connection with Oracle Driver
Connection con = DriverManager.getConnection
(“jdbc:oracle:thin:@localhost:1521:XE”,“username”,“password”);
3. Create SQL statement :
a. createStatement() method is invoked on current connection object
to create a SQL Statement.
b. Syntax :
public Statement createStatement() throws SQLException
Example :
Statement s=con.createStatement();
Enterprise Java Beans & JDBC 4–20 D (IT-5/CS-6)
Answer
1. A database driver is a computer program that implements a protocol
(ODBC or JDBC) for a database connection.
2. The driver works like an adaptor which connects a generic interface to
a specific database vendor implementation.
Types of database drivers : Refer Q. 4.13, Page 4–13D, Unit-4.
Steps to get any value into database : Refer Q. 4.14, Page 4–14D,
Unit-4.
Answer
1. A program which contains n number of SQL statements and residing a
database environment is known as stored procedure.
2. Stored procedures are divided into two types :
a. Procedure :
i. A procedure is one which contains block of statements which
will return either zero or more than one value.
Web Technology 4–21 D (IT-5/CS-6)
Answer
Differences :
Answer
1. A transaction is a group of operation used to perform single task.
2. If all operations in the group are successful then the task is finished and
the transaction is successfully completed.
3. If any one operation in the group is failed then the task is failed and the
transaction is failed.
Transaction sucessful
commit
Transaction
Transaction failed
Fig. 4.22.1.
Types of transaction :
1. Local transaction : A local transaction means that all operations in a
transaction are executed against one database.
For example : If we transfer money from first account to second account
and both accounts belongs to same bank then transaction is local transaction.
2. Global transaction : A global transaction means that all operations in
a transaction are executed against multiple databases.
For example : If we transfer money from first account to second account
belongs to different banks then the transaction is a global transaction.
Answer
In JDBC, Connection interface provides different methods to manage
transaction.
Method Description
void setAutoCommit(boolean transaction is committed by default.
status)
void commit() commits the transaction.
void rollback() cancels the transaction.
Web Technology 4–23 D (IT-5/CS-6)
For Example :
import java.sql.*;
class TrxaExample
{
public static void main(String[ ] args)throws Exception
{
Class.forName(“oracle.jdbc.OracleDriver”);
Connection con=DriverManager.getConnection(“jdbc:oracle:thin:@quantum-
pc:1521:xe”,“system”,“system”);
System.out.println(“driver is loaded”);
Statement stmt=con.createStatement();
con.setAutoCommit(false);
try
{
int i1=stmt.executeUpdate(“insert into student values(110,‘quantum’,685)”);
int i2=stmt.executeUpdate(“update customer set custadd=‘Ghaziabad’where
custid=111”);
int i3=stmt.executeUpdate(“delete from student where sid=101”);
con.commit();
System.out.println(“Transaction is successful”);
} //end of try
catch (Exception e)
{
try
{
con.rollback();
System.out.println(“Transaction is failed”);
}
catch (Exception ex)
{
System.out.println(ex);
}
} //end of catch
stmt.close();
con.close();
System.out.println(“connection is closed”);
} //end of main
} //end of class
Enterprise Java Beans & JDBC 4–24 D (IT-5/CS-6)
Web Technology 5–1 D (IT-5/CS-6)
5
UNIT
Servlets and Java
Server Pages (JSP)
CONTENTS
Part-1 : Servlets : Servlet Overview ..................... 5–2D to 5–9D
and Architecture, Interface
Servlet and the Servlet Life Cycle
PART-1
Servlets : Servlet Overview and Architecture, Interface Servlet
and the Servlet Life Cycle.
Questions-Answers
Que 5.1. What is servlet ? Explain its life cycle. Give its
characteristics.
Answer
Servlet :
1. Servlets are simple Java programs that run on the servers.
2. Servlets are most commonly used with HTTP. So, servlets are also
called as HTTP servlet.
3. Servlet can process and store the data submitted by an HTML form.
4. Servlets are useful for providing the dynamic contents.
Life cycle of Servlet :
Loading and
Start instantiation
init()
destroy()
End
of life End
cycle
Fig. 5.1.1.
Web Technology 5–3 D (IT-5/CS-6)
Que 5.2. Explain the life cycle of servlet. Also write a servlet for
Answer
Life cycle of servlet : Refer Q. 5.1, Page 5–2D, Unit-5.
Servlet for displaying “HELLO WORLD” :
// Import required java libraries
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
// Extend HttpServlet class
public class HelloWorld extends HttpServlet {
private String message;
public void init() throws ServletException {
// Do required initialization
message = “HELLO WORLD”;
}
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException
{
// Set response content type
response.setContentType(“text/html”);
// Actual logic goes here.
PrintWriter out = response.getWriter();
out.println(“<h1>” + message + “</h1>”);
}
public void destroy() {
// do nothing.
}
}
Answer
1. CGI is an acronym for the Common Gateway Interface which is a
standard protocol for running programs within a web server.
Web Technology 5–5 D (IT-5/CS-6)
Que 5.4. What is servlet ? Explain its life cycle. Illustrate some
characteristics of servlet. How does servlet score over CGI ?
AKTU 2015-16, Marks 10
Answer
Servlet, its lifecycle and characteristics of servlet : Refer Q. 5.1,
Page 5–2D, Unit-5.
Java servlets have following advantage over CGI and other API’s :
i. Platform independence : Java servlets are pure Java program, so it is
platform independent. It can run on any servlet enabled web server.
ii. Performance : In case of servlets, initialization takes place very first
time it receives a request and remains in memory till times out or server
shut downs. This helps us to develop high speed data driven websites.
iii. Extensibility : Java servlets are developed in Java which is robust,
well-designed and object-oriented language which can be extended into
new objects.
iv. Safety : Java servlet provides a very good safety features like memory
management, exception handling features and emerged as a very
powerful web server extension.
Servlets & Java Server Page (JSP) 5–6 D (IT-5/CS-6)
Answer
Servlet architecture includes :
Servlet interface
Generic servlet
HttpServlet
MyServlet
1. Servlet interface :
a. To write a servlet we need to implement Servlet interface.
b. Servlet interface can be implemented directly or indirectly by
extending GenericServlet or HttpServlet class.
2. GenericServlet :
a. GenericServlet provides simple versions of the lifecycle methods
init( ) and destroy( ).
b. It also implements the log method which is declared in the
ServletContext interface.
3. HttpServlet :
a. HttpServlet is an abstract class present in javax.servlet.http package
and has no abstract methods.
b. It extends GenericServlet class.
c. When the servlet container uses HTTP protocol to send request,
then it creates HttpServletRequest and HttpServletResponse
objects.
4. MyServlet : MyServlet is the combination of servlet interface,
genericServlet and HttpServlet.
Que 5.6. Write short notes on servlet interface.
Answer
1. Servlet interface provides common behaviour to all the servlets.
2. Servlet interface needs to be implemented for creating any servlet (either
directly or indirectly).
3. Servlet interface defines methods that are implemented by all servlets.
4. Following are five methods defined in servlet interface :
Web Technology 5–7 D (IT-5/CS-6)
Answer
1. When the web server starts, the servlet container deploys and loads all
the servlets.
2. Servlet container creates ServletContext object which act as an interface
and defines the set of methods that a servlet can use to communicate
with the servlet container.
2. Once the servlet is loaded, the servlet container creates the instance of
servlet class. For each instantiated servlet, its init() method is invoked.
3. Client (user browser) sends an Http request to web server on a certain
port.
4. Then, the servlet container create s HttpServletRequest and
HttpServletResponse objects.
5. The HttpServletRequest object provides the access to the request
information and the HttpServletResponse object allows us to change
the http response before sending it to the client.
6. The servlet container produce a new thread that calls service() method
for each client request.
7. The service() method dispatches the request to the correct handler
method based on the type of request.
Servlets & Java Server Page (JSP) 5–8 D (IT-5/CS-6)
Http servlet
Client Server
Get request
doGet()
Get response
Post request Service ()
doPost()
Post response
Fig. 5.7.1.
8. When servlet container shuts down, it unloads all the servlets and calls
destroy() method for each initialized servlets.
Que 5.8. Explain servlets with its life cycle. How its life cycle is
different from the life cycle of JSP ? Explain with an example.
AKTU 2019-20, Marks 07
Answer
Servlets with its life cycle : Refer Q. 5.1, Page 5–2D, Unit-5.
Difference :
1. In servlet life cycle, the servlet object is created first.
2. The init() method is invoked by the servlet container and the servlet is
initialized by its arguments.
3. Servlet’s service() method is invoked next. At the end, the destroy()
method is invoked.
4. In case of a Java Server Page life cycle, the .jsp is converted into .class
file which is a servlet and then follows the process of the servlet. In
other words, the .jsp is translated into servlet and the functionality is
same as that of the servlet.
JSP lifecycle example :
Demo.jsp :
<html>
<head>
<title>Demo JSP</title>
</head>
<%
int demvar=0;%>
<body>
Count is :
<% Out.println(demovar++); %>
<body>
</html>
Web Technology 5–9 D (IT-5/CS-6)
PART-2
Handling HTTP Get Requests, Handling Post Requests,
Redirecting Requests to Other Resources.
Questions-Answers
Que 5.9. Explain handling in HTTP get and post request in servlet
with example.
Answer
1. To handle HTTP requests in a servlet, extend the HttpServlet class and
override the servlet methods that handle the HTTP requests that our
servlet supports.
2. The methods that handle these requests are doGet() and doPost().
Handling Get requests :
1. Handling Get requests involves overriding the doGet() method.
For example :
public class BookDetailServlet extends HttpServlet {
public void doGet (HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException
{
...
// set content-type header before accessing the Writer
response.setContentType(“text/html”);
PrintWriter out = response.getWriter();
// then write the response
out.println(“<html>” +
“<head><title>Book Description</title></head>” +
...);
//Get the identifier of the book to display
String bookId = request.getParameter(“bookId”);
if (bookId != null) {
// and the information about the book and print it
...
}
out.println(“</body></html>”);
out.close();
}
...
}
2. The servlet extends the HttpServlet class and overrides the doGet()
method.
3. Within the doGet() method, the getParameter () method gets the servlet’s
expected argument.
Web Technology 5–11 D (IT-5/CS-6)
Answer
1. The RequestDispatcher is a interface which provides the facility of
dispatching the request to another resource such as HTML, servlet or
JSP.
2. This interface can also be used to include the content of another resource
also.
3. It is one of the ways of servlet collaboration.
Methods of RequestDispatcher interface :
1. Public void forward(ServletRequest request, ServletResponse
response)throws ServletException, java.io.IOException : It
forwards a request from a servlet to another resource (servlet, JSP file,
or HTML file) on the server.
2. Public void include(ServletRequest request, ServletResponse
response)throws ServletException, java.io.IOException : It
includes the content of a resource (servlet, JSP page, or HTML file) in
the response.
There are three ways to get RequestDispatcher object in the servlet :
1. By calling the getRequestDispatcher(String path) method on
ServletRequest : It returns a RequestDispatcher object that wraps the
resource located at the given path. This method will return null if the
ServletContext cannot return a RequestDispatcher.
2. By getR equestDispatcher(String path) method on
ServletContext : It returns a RequestDispatcher object that wraps the
named servlet or JSP page. Names can be defined for servlets and JSP
pages in the web application. If the ServletContext cannot return a
RequestDispatcher, this method will return null.
3. By calling getNamedDispatcher(servlet logical name) on
ServletContext object : It returns a RequestDispatcher object that
acts as a wrapper for the resource located at the specified context-
relative path.
PART-3
Session Tracking, Cookies, Session Tracking with HTTP Session.
Questions-Answers
Answer
1. Session tracking is a way to maintain state (data) of a user. It is also
known as session management in servlet.
2. It is used to recognize the particular user.
3. Each time user requests to the server, server treats the request as the
new request and maintain the state of a user using session tracking
techniques to recognize a particular user.
4. HTTP is stateless that means each request is considered as the new
request. It is shown in the Fig. 5.11.1.
3. second request (new)
1. request(new)
2. response
Client
Fig. 5.11.1. Server
Answer
1. Cookie is a key value pair of information sent by the server to the
browser which is saved in the client computer.
2. A cookie is a small piece of information that is persisted between the
multiple client requests.
3. 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.
Working of cookie :
1. Client sends a request to the server.
2. Cookie is added with request from the servlet and stored in the cache of
the browser.
3. After that if response is sent by the server, cookie is added with it by
default.
4. Server can identify the client using the cookie.
Servlets & Java Server Page (JSP) 5–14 D (IT-5/CS-6)
3. Request + Cookie
1. Request
2. Response + cookie
Browser
Server
Fig. 5.12.1.
There are two types of cookies in servlet :
1. Non-persistent cookie : It is valid for single session only. It is removed
each time when user closes the browser.
2. Persistent cookie : It is valid for multiple sessions. It is not removed
each time when user closes the browser. It is removed only if user
logout or sign out.
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.
Que 5.13. Write short notes on session tracking with HttpSession.
Answer
1. The HttpSession object is used for session tracking.
2. A session contains information specific to a particular user across the
whole application.
3. When a user enters into a website (or an online application) for the first
time HttpSession is obtained via request.getSession(), the user is given
a unique ID to identify his session. This unique ID can be stored into a
cookie or in a request parameter.
session id
Fig. 5.13.1.
Web Technology 5–15 D (IT-5/CS-6)
Answer
Program :
Index.html :
<!DOCTYPE html><html><head>
Servlets & Java Server Page (JSP) 5–16 D (IT-5/CS-6)
<meta charset=“ISO-8859-1”>
<title>Servlet Login Example</title>
</head><body>
<h1>Welcome to Login App by Cookie</h1>
<a href=“login.html”>Login</a>|
<a href=“LogoutServlet”>Logout</a>|
<a href=“ProfileServlet”>Profile</a></body></html>
link.html :
<a href=“login.html”>Login</a> |
<a href=“LogoutServlet”>Logout</a> |
<a href=“ProfileServlet”>Profile</a>
<hr>
login.html :
<form action=“LoginServlet” method=“post”>
Name:<input type=“text” name=“name”><br>
Password:<input type=“password” name=“password”><br>
<input type=“submit” value=“login”></form>
LoginServlet.java :
package com.javatpoint;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class LoginServlet extends HttpServlet {
protected void doPost(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
response.setContentType(“text/html”);
PrintWriter out=response.getWriter();
request.getRequestDispatcher(“link.html”).include(request, response);
String name=request.getParameter(“name”);
String password=request.getParameter(“password”);
if(password.equals(“admin123”)){
Web Technology 5–17 D (IT-5/CS-6)
Answer
Let us assume a table “account_detail” which contains the details about the
Account number.
create table account_detail
(
ac_no number,
name VARCHAR2(40),
address VARCHAR2(40),
balance number,
CONSTRAINT “account_detail_pk” PRIMARY KEY (“ac_no”) ENABLE
)
Index.html :
This page get the account number from the user and forwards this data to
servlet which is responsible to show the records based on the given account
number.
<html>
<body>
<form action=“servlet/Search”>
Enter A/c No.:<input type=“text” name=“ac”/></br>
<input type=“submit” value=“search”/>
</form>
</body>
</html>
Search.java :
This is the servlet file which gets the input from the user and maps this data
with the database and prints the record for the matched data. In this page,
we are displaying the column name of the database along with data. So, we
are using ResultSetMetaData interface.
import java.io.*;
import java.sql.*;
import javax.servlet.ServletException;
import javax.servlet.http.*;
public class Search extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse
response)
throws ServletException, IOException {
response.setContentType(“text/html”);
Web Technology 5–19 D (IT-5/CS-6)
<url-pattern>/servlet/Search</url-pattern>
</servlet-mapping>
</web-app>
PART-4
Java Server Page (JSP) : Introduction, Java Server Page Overview,
A First Java Server Page Example.
Questions-Answers
Answer
1. Java Server Pages (JSP) is a technology that helps software developers
to create dynamically generated web pages based on HTML, XML or
other document types.
2. JSP supports both scripting and element based dynamic content, and
allows developers to create their own tag libraries.
3. JSP pages are compiled for efficient server processing.
4. JSP is platform independent. So, it can be easily upgraded or switched
without affecting JSP based applications.
JSP architecture :
1. Java Server Pages are part of a 3-tier architecture.
2. A server (application or web server) supports the Java Server Pages.
3. This server will act as a mediator between the client browser and a
database.
4. The following diagram shows the JSP architecture :
JSP request
Client Request sent to web
server
Web
Client Internet
server
(Browser) Database
HTML
HTML sent (servlet
to client output)
Fig. 5.16.1. JSP architecture.
Web Technology 5–21 D (IT-5/CS-6)
a. The user goes to a JSP page and makes the request via internet in
web browser.
b. The JSP request is sent to the web server.
c. Web server accepts the requested .jsp file and passes the JSP file to
the JSP Servlet Engine.
d. If the JSP file has been called the first time then the JSP file is
parsed otherwise servlet is instantiated. The next step is to generate
a servlet from the JSP file. The generated servlet output is sent via
the Internet from web server to user's web browser.
d. Now in last step, HTML results are displayed on the user's web
browser.
JSP provides better performance : JSP allows to embed the Java code
directly in the HTML file and generates the contents dynamically. This helps
to enhance the performance of JSP.
Que 5.17. What is JSP ? What are the advantages of JSP over
various server-side programs ?
Answer
JSP : Refer Q. 5.16, Page 5–20D, Unit-5.
Advantages of JSP over other server-side programs are :
1. JSP is platform independent whereas other server-side programs are
not.
2. JSP code is portable but other server-side programs are not.
3. JSP can be used for large application but other server-side programs are
used for small application.
4. JSP uses static type checking while other uses dynamic type checking.
Answer
1. In JSP processing, the JSP engine compiles the servlets upto an
executable class and forwards the original request to the servlet engine
and execute it on the web server.
2. JSP pages can be processed using JSP container only.
3. Following are the steps that need to be followed while processing the
request for JSP page :
a. Client makes a request for required JSP page to the server.
b. The server must have JSP container so that JSP request can be
processed.
Servlets & Java Server Page (JSP) 5–22 D (IT-5/CS-6)
Answer
1. Tomcat is a web server and servlet container that is used to deploy and
serve Java web application.
2. Tomcat server is a Java-capable HTTP server, which could execute
special Java programs known as “Java servlet” and “Java Server Pages”.
3. Tomcat can operate as a standalone web server.
4. It can operate as an out-of-process servlet container for some web servers,
such as Apache.
5. For other web servers, such as IIS (Internet Information Services), it
can operate as an in-process servlet container.
6. Tomcat server runs on a specific TCP post from a specific IP address.
7. The default TCP port number for HTTP protocol is 80, which is used for
the production HTTP server.
8. To test HTTP server, we can choose any unused port number between
1024 and 65535.
9. There are two important environment variables to set before running
Tomcat :
a. Set CATALINA_HOME to the root of Tomcat directory.
b. Set JAVA_HOME to the root directory of Java JDK or JRE.
Que 5.20. What are the steps for running JSP program in Tomcat
server ?
Answer
Steps for running JSP program in Tomcat server are :
1. Create a JSP code and save it using the filename extension.jsp.
2. Copy this JSP file to the directory named webapps. This directory is
present within the Tomcat directory.
3. Start the Tomcat server by typing the command startup.
Web Technology 5–23 D (IT-5/CS-6)
4. Open some suitable web browser type the path for JSP code with the
prefix http://localhost. Localhost is the default DNS for Tomcat web
server.
Que 5.21. Write a simple JSP page for displaying the message :
“This is my first JSP page !!!”.
Answer
<%@ page language = “java” contentType = “test/html” %>
<%@ page import = “java.util.*”>
<html>
<!-- This is basic JSP page -->
<title> JSP Demo </title>
<body>
<%--Displaying the message on the browser --%>
<% out.println(“This my first JSP page!!!”); %>
</body>
</html>
Que 5.22. Compare JSP and Servlet. Explain the life cycle of a
JSP page with a suitable diagram. Also list any five action tags
used in JSP. AKTU 2018-19, Marks 07
Answer
JSP file
Translation phase
Servlet file
Compilation phase
Servlet class
1. Translation of JSP page to Servlet : This is the first step of JSP life
cycle. This translation phase deals with syntactic correctness of JSP.
Here test.jsp file is translated to test.java.
2. Compilation of JSP page : Here the generated java servlet file
(test.java) is compiled to a class file (test.class).
3. Class loading : Servlet class which has been loaded from JSP source
is now loaded into container.
4. Instantiation : Here instance of the class is generated. The container
manages one or more instance by providing response to requests.
5. Initialization : jspInit() method is called only once during the life
cycle immediately after the generation of servlet instance from JSP.
6. Request processing : jspService() method is used to serve the raised
requests by JSP. It takes request and response object as parameters.
This method cannot be overridden.
7. JSP cleanup : In order to remove the JSP from use by the container
or to destroy method for servlets jspDestroy() method is used. This
method is called once, if we need to perform any cleanup task like
closing open files, releasing database connections jspDestroy() can be
overridden.
Five action tags used in JSP are :
1. <JSP : use Bean>
2. <JSP : set Property>
3. <JSP : include>
4. <JSP : attribute>
5. <JSP : body>
Que 5.23. How we deploy the Servlets on Tomcat Web Container ?
Also explain how we change the default number of Tomcat
Container ?
Web Technology 5–25 D (IT-5/CS-6)
Answer
To create a Servlet applications do the following steps :
1. Create directory structure for our application.
2. Create a Servlet.
3. Compile the Servlet.
4. Create deployement descriptor for our application.
5. Start the server and deploy the application.
Following steps are required to change the default port of Tomcat
container :
1. Stop Tomcat server if it is already running.
2. Open <Tomcat_Home>/conf/server.xml file for editing.
3. Look for port *8080* in the xml file and replace with any available port.
4. If there is other Tomcat running on the same server, we have to change
SHUTDOWN port as well.
5. Start Tomcat server.
Answer
JSP is an extension of servlet not replacement. This statement can be justified
by following advantages of JSP :
1. JSP is not a replacement of Servlets but extension of Servlets, as coding
decreases more than half.
2. In JSP, static code and dynamic code are separated.
3. JSP needs no compilation by the programmer.
4. In JSP, presentation layer and business logic layer can be separated
with the usage of Java Beans.
Problem of Servlet technology solved by JSP are :
1. Difficult to code.
2. Do not allow parsing and decoding HTML headers.
3. It cannot be integrated with other backend services.
4. It does not manage cookies.
5. Do not allow reading and sending HTML headers.
PART-5
Implicit Objects, Scripting, Standard Actions, Directives,
Custom Tag Libraries.
Servlets & Java Server Page (JSP) 5–26 D (IT-5/CS-6)
Questions-Answers
Answer
Different types of implicit objects in JSP are :
1. Application object : The application object has an application scope
and contains a reference to the instance of a class that implements the
javax.servlet.ServletContext interface that represents the application.
2. Config object :
a. The config object has a page scope. This object implements the
javax.servlet.ServletConfig interface.
b. The config object gives access to configuration data for initializing
the JSP.
3. Session object :
a. HttpSession class represents the current session of the JSP page.
b. It represents the scope of this session, and it is useful in order to
keep attributes and values and providing them in different JSP
pages of same application.
4. Out object :
a. The out object also has a page scope. Out object is an instance of
javax.servlet.jsp.JspWriter class.
b. By using this object the text is added to the response message body.
5. Page object :
a. Page object is an instance of java.lang.Object class.
b. The page object is a reference to the current instance of the JSP.
Example :
<%@ page language=“java” contentType=“text/html; charset=US-ASCII”
pageEncoding=“US-ASCII”%>
<%@ page import=“java.util.Date” %>
<!DOCTYPE html PUBLIC “-//W3C//DTD HTML 4.01 Transitional//EN”
“http://www.w3.org/TR/html4/loose.dtd”>
<html>
<head>
<meta http-equiv=“Content-Type” content=“text/html; charset=US-
ASCII”>
Web Technology 5–27 D (IT-5/CS-6)
Que 5.26. What are Java Beans ? Why they are used ? Write a JSP
page and use an existing Java Beans in JSP page by using the
standard action. Write the program with describing the output ?
AKTU 2017-18, Marks 10
OR
What are standard actions in JSP ? Illustrate with example.
AKTU 2017-18, Marks 10
Answer
Java Beans and why they are used : Refer Q. 4.4, Page 4–5D, Unit-4.
Different types of standard action tags used in JSP are :
1. <jsp:useBean> :
a. This action associates an instance of a Java Bean defined with a
given scope and ID, through a newly declared scripting variable of
the same ID.
b. The <jsp:useBean> action is very flexible.
c. Its exact semantics depends on the values of the given attributes.
d. The attributes for the <jsp:useBean> are : id, scope, class,
beanName, type.
2. <jsp:setProperty> :
a. This action helps to integrate Java Beans into JSPs.
b. It sets the value of a Beans property.
c. This action has the attributes name, property, param, value.
Servlets & Java Server Page (JSP) 5–28 D (IT-5/CS-6)
3. <jsp:getProperty> :
a. This action gets a property value from a Java Beans component
and adds it to the response.
b. Attribute of this action are : name, property.
4. <jsp:include> :
a. This action provides a mechanism for including additional static
and dynamic resources in the current JSP page.
b. The attributes for this action are : page, flush.
5. <jsp:attribute> : This action is used to set the value of an action attribute
based on the body of this element.
6. <jsp:body> :
a. This action is used to set the action element body based on the body
of this statement.
b. It is required when the action element body contains <jsp:attribute>
action element.
7. <jsp:element> : It dynamically generates an XML element, optionally
with attributes and a body defined by nested <jsp:attribute> and
<jsp:body> actions.
8. <jsp:text> : This action is used to encapsulate template text that should
be used in JSP pages written as XML documents.
Example of <jsp:include> Action :
<html>
<head>
<title>The include Action Example</title>
</head>
<body>
<center>
<h2>The include action Example</h2>
<jsp:include page = “date.jsp” flush = “true” />
</center>
</body>
</html>
Output :
The include action Example
Today’s date: 12-june-2018 14:54:22
Example of <jsp:useBean>, <jsp:setProperty>,
<jsp:getProperty> actions :
Let us define a test bean that will further be used :
/* File: TestBean.java */
package action;
public class TestBean {
private String message = “No message specified”;
public String getMessage() {
return(message);
}
public void setMessage(String message) {
Web Technology 5–29 D (IT-5/CS-6)
this.message = message;
}
}
Now use the following code in main.jsp file. This loads the bean and sets/
gets a simple String parameter.
<html>
<head>
<title>Using JavaBeans in JSP</title>
</head>
<body>
<center>
<h2>Using JavaBeans in JSP</h2>
<jsp:useBean id = “test” class = “action.TestBean” />
<jsp:setProperty name = “test” property = “message”
value = “Hello JSP...”/>
<p>Got message....</p>
<jsp:getProperty name = “test” property = “message”/>
</center>
</body>
</html>
Output :
Using JavaBeans in JSP
Got message....
Hello JSP...
Example of <jsp:element>, <jsp:attribute> and <jsp:body>
actions :
<%@page language = “java” contentType = “text/html”%>
<html xmlns = “http://www.w3.org/1999/xhtml”
xmlns:jsp = “http://java.sun.com/JSP/Page”>
<head><title>Generate XML Element</title></head>
<body>
<jsp:element name = “xmlElement”>
<jsp:attribute name = “xmlElementAttr”>
Value for the attribute
</jsp:attribute>
<jsp:body>
Body for XML element
</jsp:body>
</jsp:element>
</body>
</html>
Example of <jsp:text> action :
<jsp:text><![CDATA[<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML
1.0 Strict//EN”
“DTD/xhtml1-strict.dtd”>]]></jsp:text>
<head><title>jsp:text action</title></head>
<body>
Servlets & Java Server Page (JSP) 5–30 D (IT-5/CS-6)
<books><book><jsp:text>
Welcome to JSP Programming
</jsp:text></book></books>
</body>
</html>
Que 5.27. What do you mean by JSP processing ? How JSP pages
are handled ? Explain various JSP directives with suitable examples.
AKTU 2015-16, Marks 10
OR
What are JSP directives ? Explain various types of directives with
example. AKTU 2017-18, Marks 10
Answer
JSP processing : Refer Q. 5.18, Page 5–21D, Unit-5.
JSP page handling :
Error handling at page level :
1. A JSP page can specify its own default error JSP page from an exception
that is occurring within it, through the JSP error tag.
2. This enables a JSP page to specify its own handling of an error.
3. A JSP page that does not contain a JSP error tag has an error fall
through to the application-level error JSP page.
For example :
i. Create a single error JSP page that handles the errors that occur
across all the other JSP pages in the application. To specify a JSP
page as an errorHandler page, use this JSP page directive :
<%@ page isErrorPage=“true” %>
In the erro rHandler JSP page, use ErrorDataBe an o r
StoreErrorDataBean to retrieve more information about the
exception and display messages.
ii. Include the errorHandler JSP page in other JSP pages, by using
this JSP directive to specify that if exceptions occur on the current
page, forward the request to errorHandler.jsp :
<%@ page errorPage=“/errorHandler.jsp” %>
JSP directives :
1. Directives are JSP elements that provide global information about an
entire JSP page.
2. All directives have scope of the entire JSP file.
3. The directive elements specify information about the page that remains
the same between requests.
There are three possible directives currently defined by the JSP specification :
Web Technology 5–31 D (IT-5/CS-6)
a. Page directive :
1. The page directive defines information that is globally available for
JSP.
2. The page directive is a JSP tag that is used in almost every JSP file
and defines a number of attributes that can affect the whole page.
3. The syntax is as follows :
<%@ page attribute%>
Example :
<%@ page language=“java” contentType=“text/html; charset=ISO-
8859-1” pageEncoding=“ISO-8859-1”%>
<%@page
import=“com.javacode.examples.jspdirectivesexample.Pizza” %>
<%@ page import=“java.util.*”%>
In the first line of e xample , language, contentType and
pageEncoding page directive attributes are in the same directive
statement.
b. Include directive :
1. The include directive is used to insert text and code at JSP translation
time.
2. It includes a static file in a JSP file.
3. It has the following syntax :
<%@ include file = “relativeURL”%>
Example :
In the example “header.html” page is inserted into the Pizza form :
...
<head>
<meta charset=“UTF-8”>
<title>Jsp Directives Example</title>
<link rel=“stylesheet” href=“./static/css/pizzaorder.css”>
</head>
<body>
<%@ include file=“header.html” %>
<form action=“orderResult.jsp” method=“POST”>
<h3>Pizza Types</h3>
<div>
...
header.html:
<h4>Java Code Examples<h4>
c. Taglib directive :
1. The taglib directive declares that the page uses custom user defined
tags, it also defines the tags library.
2. The term custom tag refers to both tags and elements.
3. A tag is simply a short piece of a markup that is a part of JSP
element.
4. The syntax is as follows :
<%@ taglib uri = “tagLibraryURI” prefix = “tagPrefix”%>
Servlets & Java Server Page (JSP) 5–32 D (IT-5/CS-6)
Example :
Following example shows a declaration sample in a JSP page :
<%@ taglib prefix=“jgc” uri=“WEB-INF/custom.tld”%>
...
<jgc:HelloWorld/>
...
Answer
1. JSP scripting elements allows us to insert Java code into Java Servlet
generated from JSP page.
2. Following are the four scripting elements :
a. JSP comment :
i. JSP comment is to document the code.
ii. JSP comment is used to note some parts of JSP page to make
it clearer and easier to maintain.
iii. The syntax of JSP comment is as follows :
<%-- This is a JSP comment --%>
b. Expression :
i. The expression is one of the most basic scripting elements in
JSP.
ii. The expression is used to insert value directly to the output.
iii. The syntax of an expression is as follows :
<%= expression%>
iv. It is noticed that there is no space between <% and =.
c. Scriptlet tag :
i. Scriptlet is similar to expression except for the equal sign “=”.
ii. We can insert any plain Java code inside a scriptlet.
iii. The syntax of scriptlet tag is as follows :
<% // any java source code here %>
d. Declaration tag :
i. We can declare static member, instance variable and methods
inside declaration tag.
ii. Syntax of declaration tag :
<%! declaration %>
Example :
<html>
<head>
Web Technology 5–33 D (IT-5/CS-6)
Answer
Que 5.30. What are Java Beans ? Why they are used ? Write a JSP
page and use an existing Java Beans in JSP page by using the
standard action. Write the program with describing the output ?
AKTU 2017-18, Marks 10
Servlets & Java Server Page (JSP) 5–34 D (IT-5/CS-6)
Answer
Java Beans and Java Beans are used because : Refer Q. 4.4,
Page 4–5D, Unit-4.
JSP page :
Login.jsp :
<body>
<h2>Using Java Beans with JSP</h2>
<form method =“get” action = “http://localhost:7001/examplesWebApp/
Receive.jsp”>
Enter User Name <input type=“text” name=“user”> <br>
Enter Password <input type=“password” name=“pass”> <br>
<input type=“submit”>
</form>
</body>
Receive.jsp :
<body>
<jsp:useBean id=“snr” class=“pack.ValidateBean” />
<jsp:setProperty name=“snr” property=“user” />
<jsp:setProperty name=“snr” property=“pass” />
You entered user name as <jsp:getProperty name=“snr” property=“user” />
<br>
You entered user password as <jsp:getProperty name=“snr” property=“pass”
/> <br>
<br>
You are a <%= snr.validate(“Rao”, “java”) %> user. <br>
<b>Thank You</b>
</body>
ValidateBean.jsp :
package pack;
public class ValidateBean
{
String user;
String pass;
public ValidateBean( ) { }
public void setUser(String user)
{
this.user = user;
}
public String getUser( )
{
Web Technology 5–35 D (IT-5/CS-6)
return user;
}
public void setPass(String pass)
{
this.pass = pass;
}
public String getPass( )
{
return pass;
}
public String validate(String s1,String s2)
{
if(s1.equals(user) && s2.equals(pass))
return “VALID”;
else
return “INVALID”;
}
}
Output :
Using Java Beans with JSP
Submit
You entered user name as Rao
You entered user password as java
You are a VALID user.
Thank You
Explanation of Output :
1. The getProperty action calls get method and gets the value of the
property.
2. The first statement calls getUser() method and retrieves the value of
the variable user (set earlier with set method) and directly puts in the
output stream of client.
<%= snr.validate(“Rao”, “java”) %>
3. The statement calls validate() method of ValidateBean and checks the
user name and password entered by the user with Rao and java. The
result of validation is returned to JSP expression which sends to client.
Answer
1. A custom tag library is a collection of the Tag Library Descriptor (TLD)
and all files for a related set of custom actions.
Servlets & Java Server Page (JSP) 5–36 D (IT-5/CS-6)
Answer
1. JSP application consists of more than a single page, and multiple pages
often need access to the same information and server-side resources.
2. We need a way to pass data from one page to another when same
request is processed by multiple pages.
Sharing session data :
1. When a user need same data over the multiple request in a session.
2. This type of sharing is for different requests of same user.
3. This type of sharing of data is called sharing of session data.
Web Technology 5–37 D (IT-5/CS-6)
Server
Client 2 Session 2
Session ID2
Fig. 5.32.1. Session scope.
Sharing application data :
1. When the different users make same request through multiple pages to
an application.
2. In this case, the information is saved in the application by one page and
later it can be accessed by another page, even if the two pages were
requested by different users.
3. This type of sharing of data is called sharing of application data.
Client 1
Server Application
Client 2
Web Technology SQ–1 D (IT-5/CS-6)
1 Introduction and
Core Java
(2 Marks Questions)
Network
Fig. 1.3.1.
1.10. What is the difference between JDK, JRE, JIT and JVM ?
AKTU 2015-16, Marks 02
Ans.
1. Java Development Kit (JDK) is a bundle of software components
that is used to develop Java based applications.
2. Java Runtime Environment (JRE) is an implementation of the
JVM which actually executes Java programs.
3. Just In Time compiler (JIT) compiler is a component of JRE which
improves the performance of Java applications by compiling byte
code to native machine code at runtime.
4. Java Virtual Machine (JVM) is an abstract computing machine.
1.14. What are the two major protocols for accessing e-mail from
servers ? AKTU 2018-19, Marks 02
Ans. Post Office Protocol version 3 (POP3), Simple Mail Transfer Protocol
(SMTP) are the two majo r pro to co ls used fo r accessing
e-mail from servers.
1.17. Define Path in JDK. How path is different from class path ?
AKTU 2019-20, Marks 02
Ans. Path variable is set for providing path for all Java tools like Java,
Javac, Javap, Javah, jar, Appletviewer which are used in Java
programming. All these tools are available in bin folders so we set
path upto bin folders.
S. No. Path Class path
1. Path variable is se t fo r Class path variable is set for
providing path for all java tools providing path of all Java classes
like Java, Javac, Javap, Javah, which is used in our application.
jar, Appletviewer
2. It contains a path to the Java It contains a path of the classes
tools. provided by JDK.
3. Java tools include Java, Javac, All the classes are available in
Javap, Javah. “rt.jar” file.
4. Command to check path : Command to check class path :
>>echo %path%. >>echo %classpath%
2 Marks Questions SQ–6 D (IT-5/CS-6)
Web Technology SQ–7 D (IT-5/CS-6)
2.1. Explain the HTML tags : Table, frame and forms with the
help of suitable examples. AKTU 2015-16, Marks 02
Ans. Table :
A table is a two dimensional matrix, consisting of rows and columns.
Example :
<table><tr>
<td> row 1</td>
<td> row 1</td>
</tr>
</table>
Frame :
The HTML frame is a powerful feature that enables a web page to
be broken into different unique sections, that although related and
operate independent of each other.
Example :
<framset cols = “50%, 50%”>
<frame src = “File 1.html”>
<frame src = “File 2.html”>
</framset>
Forms :
All the input elements should be enclosed within the opening and
closing tags like this :
<FORM> The input elements go here </FORM>
Example :
<form>
Login :
<input type = “text” name = “login” size = ” 30”>
Password :
<input type = “password” name = “password” >
<input type = “submit” value = “Submit”>
</form>
Ans. CSS is a language that describes the style of the HTML document.
Different ways of creating stylesheets are :
1. Inline stylesheets
2. Embedded stylesheets
3. External stylesheets
2.6. What are forms and how they are created in HTML ?
AKTU 2017-18, Marks 02
Ans. An HTML form is a section of document containing normal content,
markup, special elements called controls (checkboxes, radio buttons,
menus etc.) and labels on those controls.
The HTML <form> tag is used to create an HTML form and it has
following syntax :
<form action = “script URL” method = “GET|POST”>
Form elements like input, text area etc.
</form>
Example :
<!DOCTYPE html>
<html lang=“en-US”>
<head>
<title>Welcome to Quantum Page </title>
</head>
<body>
<h1 onclick=“this.style.color=‘red’”>Hi Everyone!</h1>
</body>
</html>
Width
2. It is basically one website design that will look good at any size from
a large desktop LCD monitor to the smaller screens we use on
smart phones and tablets.
3. Facebook, Youtube are the example of responsive webpage.
Web Technology SQ–13 D (IT-5/CS-6)
3 Scripting and
Networking
(2 Marks Questions)
Web Technology SQ–15 D (IT-5/CS-6)
Ans.
S. No. Java Bean EJB
1. The Java Bean components The EJB components are
can be visible or invisible to always invisible to the user.
the user.
4.7. What are JAR files ? Explain its advantage. Write the
command for creating JAR file. AKTU 2017-18, Marks 02
Ans. A JAR (Java ARchive) file is a file that contains compressed version
of class files, audio files, image files or directories.
Advantages of JAR file :
a. Security
b. Decreased download time
c. Compression
To create a JAR file, we can use following command :
jar cf jarfilename inputfiles
4.11. Compare JDBC and ODBC. List the different types of JDBC
drivers. AKTU 2019-20, Marks 02
Ans. Comparison :
S. No. JDBC ODBC
2 Marks Questions SQ–18 D (IT-5/CS-6)
5.1. What do you mean by servlets ? What are the methods used
in life cycle of servlets ?
Ans. Servlets are server-side components that provide a powerful
mechanism for developing server-side of web application.
The life cycle of a servlet uses following three methods :
a. Init() method
b. Service() method
c. Destroy() method
Ans. Java Server Pages (JSPs) are simple and powerful technology used
to generate dynamic HTML documents on the server-side.
5.10. Discuss about Tomcat server. How to set the Class path
for servlet in Tomcat server ? AKTU 2019-20, Marks 02
Ans. Tomcat server : Refer Q. 5.7, Page SQ–19D, Unit-5, Two Marks
Questions.
To set class path for servlet in Tomcat server :
1. Copy servlet-api.jar file location and set the class path in environment
variable.
2 Marks Questions SQ–20 D (IT-5/CS-6)
2. If our class path is already set for core java programming, we need
to edit class path variable. For edit classpath just put ‘;’ at end of
previous variable and paste new copied location (without deleting
previous classpath variable).
Web Technology SP–1 D (IT-5/CS-6)
B. Tech.
(SEM. V) ODD SEMESTER THEORY
EXAMINATION, 2015-16
WEB TECHNOLOGY
SECTION-A
d. Explain the HTML tags : Table, frame and forms with the
help of suitable examples.
SECTION – B
Note : Attempt any five questions from this section. (10 × 5 = 50)
2. What is XML ? Discuss the significance of XML. How is XML
different from HTML ? Explain the process of XML parsing.
How are they useful ?
Solved Paper (2015-16) SP–2 D (IT-5/CS-6)
9. Describe the PHP life cycle and how does PHP score over
ASP and JSP ?
SECTION – C
Web Technology SP–3 D (IT-5/CS-6)
SECTION-A
Network
Fig. 1.
Solved Paper (2015-16) SP–4 D (IT-5/CS-6)
d. Explain the HTML tags : Table, frame and forms with the
help of suitable examples.
Ans. Table :
A table is a two dimensional matrix, consisting of rows and columns.
Example :
<table><tr>
<td> row 1</td>
<td> row 1</td>
</tr>
</table>
Frame :
The HTML frame is a powerful feature that enables a web page to
be broken into different unique sections, that although related and
operate independent of each other.
Example :
<framset cols = “50%, 50%”>
<frame src = “File 1.html”>
<frame src = “File 2.html”>
</framset>
Forms :
All the input elements should be enclosed within the opening and
closing tags like this :
<FORM> The input elements go here </FORM>
Example :
<form>
Login :
<input type = “text” name = “login” size = ” 30”>
Password :
<input type = “password” name = “password” >
<input type = “submit” value = “Submit”>
</form>
4. destroy( )
5. paint( )
Ans.
1. XML is a markup language for documents containing structured
information which contains both content and some indication of
the role of content.
2. Extensible Markup Language, abbreviated as XML, describes a
class of data objects called XML documents and partially describes
the behaviour of computer programs which process them.
3. XML documents are made up of storage units called entities, which
contain either parsed or unparsed data.
Significance of XML :
1. XML can store and organize just about any kind of information in a
form according to our needs.
2. With its clear, simple syntax and unambiguous structure, XML is
easy to read and parse.
3. XML is easily combined with stylesheets to create formatted
documents in any style.
Difference between XML and HTML :
S. No. XML HTML
1. XML is designed to describe HTML is designed to display data
data and to focus on what data and to focus on how data looks
is about. like.
2. XML is about describing HTML is abo ut displaying
information. information.
3. XML tags are not predefined. HTML tags are predefined.
4. In XML, data is stored in In HTML, data is stored inside the
separate XML file. HTML tags.
<author>Erik T. Ray</author>
<year>2013</year>
<price>39.95</price>
</book>
</bookstore>
Root element
<bookstone>
Parent Child
Fig. 2.
XML parser is useful in :
1. Loading the elements of XML document.
2. Accessing the elements of XML document.
3. Deleting the elements of XML document.
4. Changing the elements of XML document.
Difference :
S. No. External DTD Internal DTD
1. In external DTD, elements are In internal DTD, elements are
declared outside the XML files. declared within the XML files.
2. The syntax for external DTD The syntax for internal DTD is :
is :
<!DOCTYPE roo t-e le me nt <!DOCTYPE roo t-element
SYSTEM “file-name”> [element-declarations]>
where file-name is the file with where root-element is the name
.dtd extension. of root element and element-
declarations is where we declare
the elements.
3. To reference it as external To reference it as internal DTD,
DTD, standalone attribute in standalone attribute in XML
the XML declaration must be declaration must be set to yes.
set as no . This means, This means the declaration
declaration include s works independent of external
information from the external source.
source.
Example of internal DTD :
<?xml version=“1.0” encoding=“UTF-8” standalone=“yes” ?>
<!DOCTYPE address [
<!ELEMENT address (name,company,phone)>
<!ELEMENT name (#PCDATA)>
<!ELEMENT company (#PCDATA)>
<!ELEMENT phone (#PCDATA)> ]>
<address>
<name>Pratibha </name>
<company>Quantum</company>
<phone>(011) 123-4567</phone>
</address>
Example of external DTD :
<?xml version=“1.0” encoding="UTF-8" standalone=“no” ?>
<!DOCTYPE address SYSTEM “address.dtd”>
<address>
<name>Prabha Patil</name>
<company>Quantum</company>
<phone>(011) 123-4567</phone>
</address>
The content of the DTD file address.dtd are as shown :
<!ELEMENT address (name,company,phone)>
<!ELEMENT name (#PCDATA)>
<!ELEMENT company (#PCDATA)>
<!ELEMENT phone (#PCDATA)>
Solved Paper (2015-16) SP–10 D (IT-5/CS-6)
Da ta tra nsmitting
Data trans mitting
Data transmitting
Da ta tra nsmittin
Client-side
Waiting Waiting
Time
vent
vent
vent
UI Update
UI Update
UI Update
UI Update
Change
Indicator
Activity
AJAX
Data
User E
User E
User E
communication
layer
Time
Server-side Server-side
Server-side Processing Processing
Fig. 4. AJAX style communication flow.
Applications of AJAX are :
1. AJAX is used to change the text without reloading the web page.
2. AJAX is a technique used for creating fast and dynamic web pages.
3. AJAX contains div section which is used to display information
returned from a server.
4. Major application of AJAX is in login forms where user can enter
their login details directly on the original page.
For example :
<!DOCTYPE html>
<html>
<style>
table,th,td {
border : 1px solid black;
border-collapse: collapse;
}
th,td {
padding: 5px;
}
</style>
<body>
<h1>The XMLHttpRequest Object</h1>
<form action=“”>
<select name=“customers” onchange=“showCustomer(this.value)”>
<option value=“”>Select a customer:</option>
<option value=“name1”>Aakash Pandey</option>
<option value=“name2”>Mohan</option>
<option value=“name3”>Harshit Kumar</option>
</select>
</form>
<br>
Web Technology SP–13 D (IT-5/CS-6)
destroy()
End
of life End
cycle
Fig. 5.
Solved Paper (2015-16) SP–14 D (IT-5/CS-6)
For example :
i. Create a single error JSP page that handles the errors that occur
across all the other JSP pages in the application. To specify a JSP
page as an errorHandler page, use this JSP page directive :
<%@ page isErrorPage=“true” %>
In the erro rHandler JSP page, use ErrorDataBe an o r
StoreErrorDataBean to retrieve more information about the
exception and display messages.
ii. Include the errorHandler JSP page in other JSP pages, by using
this JSP directive to specify that if exceptions occur on the current
page, forward the request to errorHandler.jsp :
<%@ page errorPage=“/errorHandler.jsp” %>
JSP directives :
Various JSP directives are :
a. Page directive :
1. The page directive defines information that is globally available
for JSP.
2. The page directive is a JSP tag that is used in almost every JSP
file and defines a number of attributes that can affect the
whole page.
3. The syntax is as follows :
<%@ page attribute%>
Example :
<%@ page language =“java” co ntentType =“te xt/html;
charset=ISO-8859-1” pageEncoding=“ISO-8859-1”%>
<%@page
import=“com.javacode.examples.jspdirectivesexample.Pizza”
%>
<%@ page import=“java.util.*”%>
In the first line of example, language, contentType and
pageEncoding page directive attributes are in the same directive
statement.
b. Include directive :
1. The include directive is used to insert text and code at JSP
translation time.
2. It includes a static file in a JSP file.
3. It has the following syntax :
<%@ include file = “relativeURL”%>
Example :
In the example “header.html” page is inserted into the Pizza
form :
...
<head>
<meta charset=“UTF-8”>
<title>Jsp Directives Example</title>
<link rel=“stylesheet” href=“./static/css/pizzaorder.css”>
</head>
Web Technology SP–17 D (IT-5/CS-6)
<body>
<%@ include file=“header.html” %>
<form action=“orderResult.jsp” method=“POST”>
<h3>Pizza Types</h3>
<div>
...
header.html:
<h4>Java Code Examples<h4>
c. Taglib directive :
1. The taglib directive declares that the page uses custom user
defined tags, it also defines the tags library.
2. The term custom tag refers to both tags and elements.
3. A tag is simply a short piece of a markup that is a part of JSP
element.
4. The syntax is as follows :
<%@ taglib uri = “tagLibraryURI” prefix = “tagPrefix”%>
Example :
Following example shows a declaration sample in a JSP page :
<%@ taglib prefix=“jgc” uri=“WEB-INF/custom.tld”%>
...
<jgc:HelloWorld/>
...
JSP/servlet
Client-side Server
HTTP
Web browser
request JDBC
EJB Database
driver
connection
J2EE Server
Fig. 6. Architecture.
The EJB architecture is an extension of web architecture.
Working of EJB architecture :
1. The client is working on a web browser.
2. There is a database server that hosts a database, like MySQL /
Oracle.
3. The J2EE server machine is running on an application server.
4. The client interface is provided with JSP / Servlet.
Solved Paper (2015-16) SP–18 D (IT-5/CS-6)
9. Describe the PHP life cycle and how does PHP score over
ASP and JSP ?
Ans. PHP life cycle :
$ PHP-f test PHP
Terminate PHP
Fig. 7.
Explanation :
1. When we start Apache server, it starts the PHP interpreter.
2. PHP calls MINIT (Module Initialization) method of each extension.
Each MINIT method initializes and defines a set of functions and
classes.
3. Now, PHP layer set up an environment to execute the requested
PHP page. It creates a symbol table which stores various variables
used for executing this page.
4. PHP then calls RNIT (Request Initialization) method for
each module. It is pre-appended to every PHP script before
execution.
5. PHP execution is completed by reaching the end of the script.
6. Now, PHP starts the cleanup process. RSHUTDOWN method of
every extension is called to destroy the symbol table.
7. Finally, when all requests have been made PHP calls the
MSHUTDOWN method of every extension and free all persistent
memory allocated during the MINIT cycle and PHP is terminated.
Solved Paper (2015-16) SP–20 D (IT-5/CS-6)
SECTION – C
Java Application
JDBC API
Driver Manager
Driver
Database
Fig. 8.
1. Java application : It is a standalone Java program which uses the
JDBC API to get connected and perform operations on the database
data.
Web Technology SP–21 D (IT-5/CS-6)
Web server
Dynamic
Obtaining data page
ODBC
API
PHP User
Database
quest
.php file Page re
b. Tomcat server
Ans.
1. Tomcat is a web server and servlet container that is used to deploy
and serve Java web application.
2. Tomcat server is a Java-capable HTTP server, which could execute
special Java programs known as “Java servlet” and “Java Server
Pages”.
3. Tomcat can operate as a standalone web server.
4. It can operate as an out-of-process servlet container for some web
servers, such as Apache.
5. For other web servers, such as IIS (Internet Information Services),
it can operate as an in-process servlet container.
6. Tomcat server runs on a specific TCP post from a specific IP address.
7. The default TCP port number for HTTP protocol is 80, which is used
for the production HTTP server.
8. To test HTTP server, we can choose any unused port number
between 1024 and 65535.
9. There are two important environment variables to set before
running Tomcat :
a. Set CATALINA_HOME to the root of Tomcat directory.
b. Set JAVA_HOME to the root directory of Java JDK or JRE.
c. CORBA
Ans.
1. CORBA stands for Common Object Request Broker Architecture.
It is a standard defined by Object Management Group (OMG). It
allows a communication between the systems that are present on
the different platforms.
2. It is an architecture and specification for creating, distributing and
managing distributed program objects in a network.
3. Part of the CORBA standard is the Interface Definition Language
(IDL), which is an implementation-independent language for
describing the interfaces of remote objects.
Web Technology SP–1 D (IT-5/CS-6)
B. Tech.
(SEM. V) ODD SEMESTER THEORY
EXAMINATION, 2016-17
WEB TECHNOLOGY
Section-A
1. Answer all parts. All parts carry equal marks. Write answer of each
part in short. (2 × 10 = 20)
c. What is HTML ?
j. Define ODBC.
Section-B
g. Describe the PHP life cycle and how does PHP score over
ASP and JSP ?
Section-C
Note : Attempt any two questions from this section. (15 × 2 = 30)
Web Technology SP–3 D (IT-5/CS-6)
Section-A
1. Answer all parts. All parts carry equal marks. Write answer of each
part in short. (2 × 10 = 20)
c. What is HTML ?
Ans. HTML (Hypertext Markup Language) is a set of special codes that
can be embedded in text to add formatting and linking information.
Ans.
S. No. Dynamic web page Static web page
1. Dynamic web page s are Static web pages will remain
behavioral and have the same for the time until and unless
capacity to produce someone changes it manually.
distinctive co ntent fo r
different visitors.
2. Dynamic pages are complex Static web pages are simple to
to construct. construct.
j. Define ODBC.
Ans. Open Database Connectivity (ODBC) is an open standard API for
accessing a database. By using ODBC statements in a program, we
can access files in a number of different databases, including MS
Access, DB2, Excel, and Text.
Section-B
Ans.
1. Internet is a global system of interconnected computer networks
that use the standard Internet Protocols suite (TCP/IP) to serve
billions of users worldwide.
2. Internet is a network of networks that consists of millions of private
and public, academic, business, and government networks of local
to global scope that are linked by a broad array of electronic, wireless
and optical networking technologies.
3. The internet carries a vast array of information resources and
services, to support electronic mail.
4. Most traditional communications media, such as telephone and
television services, are reshaped or redefined using the technologies
of the internet, giving rise to services such as Voice over Internet
Protocol (VoIP).
5. Newspaper, book and other print publishing has been reshaped
into web sites, blogging, and web feeds.
6. The internet has enabled or accelerated the creation of new forms
of human interactions through instant messaging, internet forums,
and social networking sites.
<tr>
<td colspan = “2”>
<center><font size = “4”><b>Railway Reservation System</b></
font>< /center>
</td>
</tr>
<tr>
<td>From</td>
<td><input type = “text” name = “from” id = “from”
size = “30”></td>
</tr>
<tr>
<td>To</td>
<td><input type = “text” name = “to” id = “to” size = “30”></td>
</tr>
<tr>
<td>Train No/Name</td>
<td><input type = “text” name = “trainno”
id = “trainno” size = “30”></td>
</tr>
<tr>
<td>Class</td>
<td><select name = “Class”>
<option value = “– 1” selected>Select</option>
<option value = “SL”>SL</option>
<option value = “3A”>3A</option>
<option value = “2A”>2A</option>
<option value = “1A”>1A</option>
</select></td>
</tr>
<tr>
<td>No. of seats</td>
<td><Select name =“No. of seats”>
<option value = “– 1”selected>Select</option>
<option value = “1”>1</option>
<option value = “2”>2</option>
<option value = “3”>3</option>
</select></td>
</tr>
<tr><td>Passenger</td>
<tr><td>Age</td></tr>
<tr><td>Gender</td></tr>
</tr>
<td><input type = “text” name = “P1”size = “30”></td>
<td><input type = “text” name = “age”size = “2”></td>
<td><Select name =“gender”>
<option value = “M”>M</option>
Web Technology SP–7 D (IT-5/CS-6)
</body>
</html>
Output :
Railway Reservation System
From
To
Train No./Name
Class Select
No. of seats Select
Passenger name Age Gender
Address
Ans.
1. ASP is a technology used for developing dynamic websites by letting
a page author include logic, such as VBScript and JavaScript code,
in regular web pages to generate the dynamic parts.
2. ASP uses server-side scripting to dynamically produce web pages that
are not affected by the type of browser, the website visitor is using.
3. When an ASP page is requested, the code in the page is executed by
the server.
4. The result is inserted into the page, and the combination of the
static and dynamic content is sent to the browser.
5. ASP pages have the extension (.asp).
Advantages of ASP :
1. It provides three-tier architecture.
2. Provide easy way to deploy the new applications and maintenance.
3. Consistent programming model.
4. Direct support for security.
5. Easy to learn and install.
Disadvantages of ASP :
1. Interpreted and loosely-typed code.
2. Mix layout (HTML) and logic (scripting code).
3. Limited development and debugging tools.
4. No real state management.
5. Update files only when server is down.
6. Obscure configuration settings.
g. Describe the PHP life cycle and how does PHP score over
ASP and JSP ?
Ans. PHP life cycle :
$ PHP-f test PHP
Terminate PHP
Fig. 1.
Explanation :
1. When we start Apache server, it starts the PHP interpreter.
2. PHP calls MINIT (Module Initialization) method of each extension.
Each MINIT method initializes and defines a set of functions and
classes.
3. Now, PHP layer set up an environment to execute the requested
PHP page. It creates a symbol table which stores various variables
used for executing this page.
4. PHP then calls RNIT (Request Initialization) method for
each module. It is pre-appended to every PHP script before
execution.
5. PHP execution is completed by reaching the end of the script.
6. Now, PHP starts the cleanup process. RSHUTDOWN method of
every extension is called to destroy the symbol table.
7. Finally, when all requests have been made PHP calls the
MSHUTDOWN method of every extension and free all persistent
memory allocated during the MINIT cycle and PHP is terminated.
PHP over ASP and JSP :
1. PHP uses a blend of interpretation and compilation in order to
provide the best mix of performance and flexibility to programmers.
Web Technology SP–11 D (IT-5/CS-6)
Root element
<bookstone>
Parent Child
Fig. 2.
XML parser is useful in :
1. Loading the elements of XML document.
2. Accessing the elements of XML document.
3. Deleting the elements of XML document.
4. Changing the elements of XML document.
Da ta tra nsmitting
Data trans mitting
Data transmitting
Da ta tra nsmittin
Client-side
Waiting Waiting
Time
vent
vent
UI Update
UI Update
UI Update
UI Update
Change
Indicator
Activity
AJAX
Data
User E
User E
User E
communication
layer
Time
Server-side Server-side
Server-side Processing Processing
b. EJB architecture :
JSP/servlet
Client-side Server
HTTP
Web browser
request JDBC
EJB Database
driver
connection
J2EE Server
Fig. 5. Architecture.
The EJB architecture is an extension of web architecture.
Working of EJB architecture :
1. The client is working on a web browser.
2. There is a database server that hosts a database, like
MySQL / Oracle.
3. The J2EE server machine is running on an application server.
4. The client interface is provided with JSP / Servlet.
5. The application server manages the relationships between the
client and database.
c. AWT :
1. The AWT stands for Abstract Window Toolkit.
2. AWT is a library of class which provides GUI tools to develop
GUI application and applet.
3. It provides many classes for programmers to use. It is the
connection between our application and the native GUI.
4. It is a Java package and can be used in any Java program by
importing java.awt.* via the import keyword.
5. It contains three kinds of classes :
a. Containers class : Frame, Dialog, Panel, Applet etc.
b. Components class : TextField, Button, Checkbox,
Scrollbar, Label, List etc.
c. Custom graphics class : Colour, Font, Dimensions etc.
Web Technology SP–1 D (IT-5/CS-6)
B. Tech.
(SEM. V) ODD SEMESTER THEORY
EXAMINATION, 2017-18
WEB TECHNOLOGY
Note : 1. Attempt all questions. If require any missing data; then choose
suitably.
2. Illustrate with program and comments if required.
Section-A
Section B
Section-C
c. Explain the role of DTD in XML and also describe its types
with an example.
b. What are Java Beans ? Why they are used ? Write a JSP
page and use an existing Java Beans in JSP page by using
the standard action. Write the program with describing
the output ?
Solved Paper (2017-18) SP–4 D (IT-5/CS-6)
Note : 1. Attempt all questions. If require any missing data; then choose
suitably.
2. Illustrate with program and comments if required.
Section-A
c. Compression
To create a JAR file, we can use following command :
jar cf jarfilename inputfiles
Section B
<p>This is a paragraph.</p>
</body>
</html>
3. External CSS :
a. An external style sheet is used to define the style for many
HTML pages.
b. An external style sheet is used to change the look of an entire
website.
c. To use an external style sheet we add a link in the <head>
section of the HTML page.
For 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>
4. Throw :
a. Java supports “throw keyword” which is used if we want to
throw our own exceptions.
b. We can do this by using the keyword throw as follows :
throw new Throwable_subclass;
No, it is not essential to catch all type of exceptions.
For example :
throw new ArithmeticException ( ) ;
throw new NumberFormatException ( ) ;
class TestFinallyBlock
{
public static void main(String args[ ])
{
try
{
int data=25/0;
System.out.println(data);
}
catch(ArithmeticException e)
{
System.out.println(“Caught: ”+e);
}
finally
{
System.out.println(“finally block is always executed”);
}
System.out.println(“rest of the code...”);
}
}
Output :
Caught: java.lang.ArithmeticException: / by zero
finally block is always executed
rest of the code...
Da ta tra nsmitting
Data trans mitting
Data transmitting
Da ta tra nsmittin
Client-side
Waiting Waiting
Time
vent
vent
UI Update
UI Update
UI Update
UI Update
Change
Indicator
Activity
AJAX
Data
User E
User E
User E
communication
layer
Time
Server-side Server-side
Server-side Processing Processing
Fig. 2. AJAX style communication flow.
Solved Paper (2017-18) SP–12 D (IT-5/CS-6)
Advantages of AJAX :
1. Reduces the server traffic and increases the speed.
2. Ajax is responsive and time for data transfer is also less.
3. Form validation
4. Bandwidth usage can be reduced.
5. Asynchronous calls can be made which reduces the time for data
arrival.
Working of AJAX : XMLHttpRequest object plays an important
role as AJAX communicates with the server using XMLHttpRequest
object.
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.
2 HTTP request
XMLHttpRequest Business logic
implementation
Fig. 3.
For example :
<!DOCTYPE html>
<html>
<body>
<div id=“demo”>
<h2>The XMLHttpRequest Object</h2>
<button type=“button” onclick=“loadDoc()”>Change Content</
button>
Web Technology SP–13 D (IT-5/CS-6)
</div>
<script>
function loadDoc() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById(“demo”).innerHTML=
this.responseText;
}
};
xhttp.open(“GET”, “ajax_info.txt”, true);
xhttp.send();
}
</script>
</body>
</html>
6. Example : Example :
<XS : element name = <!DOCTYPE not
‘‘note’’> [
<XS : Complextype> <!ELEMENT not (to , from,
<XS: sequence > heading, body)>
<XS: element name ‘‘to’’ <!Element to (# PCDATA) >
type=‘‘XS: String’’/> <!Element from (# PCDATA)>
<XS: element name ‘‘from’’ <! Element heading (?)>
type=‘‘XS : string’’/> <!Element body (#PCDATA)]>
<XS:element
name=‘‘heading’’
type= ‘‘XS:string’’/>
Section-C
3. Attempt any one part of the following : (10 × 1 = 10)
a. What are JSP directives ? Explain various types of directives
with example.
Ans. JSP directives :
1. Directives are JSP elements that provide global information about
an entire JSP page.
2. All directives have scope of the entire JSP file.
3. The directive elements specify information about the page that
remains the same between requests.
There are three possible directives currently defined by the JSP
specification :
a. Page directive :
1. The page directive defines information that is globally available for
JSP.
2. The page directive is a JSP tag that is used in almost every JSP file
and defines a number of attributes that can affect the whole page.
3. The syntax is as follows :
<%@ page attribute%>
Example :
<%@ page language=“java” contentType=“text/html; charset=ISO-
8859-1” pageEncoding=“ISO-8859-1”%>
<%@page
import=“com.javacode.examples.jspdirectivesexample.Pizza” %>
<%@ page import=“java.util.*”%>
In the first line of e xample , language, contentType and
pageEncoding page directive attributes are in the same directive
statement.
b. Include directive :
1. The include directive is used to insert text and code at JSP translation
time.
Web Technology SP–15 D (IT-5/CS-6)
3. Session object :
a. HttpSession class represents the current session of the JSP
page.
b. It represents the scope of this session, and it is useful in order
to keep attributes and values and providing them in different
JSP pages of same application.
4. Out object :
a. The out object also has a page scope. Out object is an instance
of javax.servlet.jsp.JspWriter class.
b. By using this object the text is added to the response message
body.
5. Page object :
a. Page object is an instance of java.lang.Object class.
b. The page object is a reference to the current instance of the
JSP.
Example :
<%@ page language=“java” contentType=“text/html; charset=US-
ASCII” pageEncoding=“US-ASCII”%>
<%@ page import=“java.util.Date” %>
<!DOCTYPE html PUBLIC “-//W3C//DTD HTML 4.01 Transitional/
/EN” “http://www.w3.org/TR/html4/loose.dtd”>
<html>
<head>
<meta http-equiv=“Content-Type” content=“text/html; charset=US-
ASCII”>
<title>Index JSP Page</title>
</head>
<body>
<%-- out object example --%>
<h4>Hi There</h4>
<strong>Current Time is</strong>: <% out.print(new Date());
%><br><br>
<%-- config object example --%>
<strong>User init param value
</strong>:<%=config.getInitParameter(“User”) %><br><br>
<%-- application object example --%>
<strong>User context param value</strong>:
<%=application.getInitParameter(“User”) %><br><br>
<%-- session object example --%>
<strong>User Session ID</strong>:<%=se ssio n.ge tId()
%><br><br>
<%-- page object example --%>
<strong>Generated Servlet Name</strong>:
<%=page.getClass().getName() %>
</body>
</html>
Web Technology SP–17 D (IT-5/CS-6)
</html>
Output :
The include action Example
Today’s date: 12-june-2018 14:54:22
Example of <jsp:useBean>, <jsp:setProperty>,
<jsp:getProperty> actions :
Let us define a test bean that will further be used :
/* File: TestBean.java */
package action;
public class TestBean {
private String message = “No message specified”;
public String getMessage() {
return(message);
}
public void setMessage(String message) {
this.message = message;
}
}
Now use the following code in main.jsp file. This loads the bean and
sets/gets a simple String parameter.
<html>
<head>
<title>Using JavaBeans in JSP</title>
</head>
<body>
<center>
<h2>Using JavaBeans in JSP</h2>
<jsp:useBean id = “test” class = “action.TestBean” />
<jsp:setProperty name = “test” property = “message”
value = “Hello JSP...”/>
<p>Got message....</p>
<jsp:getProperty name = “test” property = “message”/>
</center>
</body>
</html>
Output :
Using JavaBeans in JSP
Got message....
Hello JSP...
Example of <jsp:element>, <jsp:attribute> and <jsp:body>
actions :
<%@page language = “java” contentType = “text/html”%>
<html xmlns = “http://www.w3.org/1999/xhtml”
xmlns:jsp = “http://java.sun.com/JSP/Page”>
<head><title>Generate XML Element</title></head>
<body>
Web Technology SP–19 D (IT-5/CS-6)
Loading and
Start instantiation
init()
destroy()
End
of life End
cycle
Fig. 4.
Servlet for displaying “HELLO WORLD” :
// Import required java libraries
import java.io.*;
Solved Paper (2017-18) SP–20 D (IT-5/CS-6)
import javax.servlet.*;
import javax.servlet.http.*;
// Extend HttpServlet class
public class HelloWorld extends HttpServlet {
private String message;
public void init() throws ServletException {
// Do required initialization
message = “HELLO WORLD”;
}
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException
{
// Set response content type
response.setContentType(“text/html”);
// Actual logic goes here.
PrintWriter out = response.getWriter();
out.println(“<h1>” + message + “</h1>”);
}
public void destroy() {
// do nothing.
}
}
Ans.
1. The Document Object Model (DOM) is a platform-independent and
language-independent standard object model for representing
HTML or XML and related formats.
2. The DOM is a W3C (World Wide Web consortium) standard.
3. The DOM defines a standard for accessing documents like XML
and HTML.
4. It allows programs and scripts to dynamically access and update the
content, structure, and style of document.
Example :
<? xml version = “1.0”?>
<book-order>
<customer> Karamveer </customer>
<shop> Bookmart </shop>
<goods>
<book>
<name> “Web application development with XML and Java”
</name>
</book>
</goods>
</book-order>
DOM
book-order
name
Fig. 5.
Web server
Dynamic
Obtaining data page
ODBC
API
PHP User
Database
quest
.php file Page re
c. Explain the role of DTD in XML and also describe its types
with an example.
Ans. Role of DTD :
1. The role of a DTD is to define the legal building blocks of an XML
document.
2. It defines the document structure with a list of legal elements.
3. A DTD can be declared inline in our XML document, or as an
external reference.
Types of DTD :
1. Internal DTD declaration : If the DTD is declared inside the
XML file, it should be wrapped in a DOCTYPE definition with the
following syntax :
<!DOCTYPE root-element [element-declarations]>
2. External DTD declaration : If the DTD is declared in an external
file, it should be wrapped in a DOCTYPE definition with the following
syntax :
<!DOCTYPE root-element SYSTEM “filename”>
Example of internal DTD :
<?xml version=“1.0” encoding=“UTF-8” standalone=“yes” ?>
<!DOCTYPE address [
<!ELEMENT address (name,company,phone)>
<!ELEMENT name (#PCDATA)>
<!ELEMENT company (#PCDATA)>
<!ELEMENT phone (#PCDATA)> ]>
<address>
<name>Pratibha </name>
<company>Quantum</company>
<phone>(011) 123-4567</phone>
</address>
Example of external DTD :
<?xml version=“1.0” encoding="UTF-8" standalone=“no” ?>
<!DOCTYPE address SYSTEM “address.dtd”>
<address>
<name>Prabha Patil</name>
Web Technology SP–27 D (IT-5/CS-6)
<company>Quantum</company>
<phone>(011) 123-4567</phone>
</address>
The content of the DTD file address.dtd are as shown :
<!ELEMENT address (name,company,phone)>
<!ELEMENT name (#PCDATA)>
<!ELEMENT company (#PCDATA)>
<!ELEMENT phone (#PCDATA)>
import javax.servlet.ServletException;
import javax.servlet.http.*;
public class Search extends HttpServlet {
public void do Ge t(HttpSe rvle tReque st reque st,
HttpServletResponse response)
throws ServletException, IOException {
response.setContentType(“text/html”);
PrintWriter out = response.getWriter();
String rollno=request.getParameter(“ac”);
int ac=Integer.valueOf(ac_no);
try{
Class.forName(“oracle.jdbc.driver.OracleDriver”);
Connection con=DriverManager.getConnection(
“jdbc:o racle :thin:@lo calhost:1521:xe ”,“syste m”,“oracle ”);
PreparedStatement ps=con.prepareStatement(“select * from result
where ac_no =?”);
ps.setInt(1,ac);
out.print(“<table width=50% border=1>”);
out.print(“<caption>Result:</caption>”);
ResultSet rs=ps.executeQuery();
/* Printing column names */
ResultSetMetaData rsmd=rs.getMetaData();
int total=rsmd.getColumnCount();
out.print(“<tr>”);
for(int i=1;i<=total;i++)
{
out.print(“<th>”+rsmd.getColumnName(i)+“</th>”);
}
ut.print(“</tr>”);
/* Printing result */
while(rs.next())
{
out.print(“<tr><td>”+rs.getInt(1)+“</td><td>”+rs.getString(2)+
“</td><td>”+rs.getString(3)+“</td><td>”+rs.getString(4)+
“</td></tr>”);
}
out.print(“</table>”);
}catch (Exception e2) {e2.printStackTrace();}
finally{out.close();}
}
}
web.xml file :
This is the configuration file which provides information of the
servlet to the container.
<web-app>
<servlet>
<servlet-name>Search</servlet-name>
Web Technology SP–29 D (IT-5/CS-6)
<servlet-class>Search</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Search</servlet-name>
<url-pattern>/servlet/Search</url-pattern>
</servlet-mapping>
</web-app>
b. What are Java Beans ? Why they are used ? Write a JSP
page and use an existing Java Beans in JSP page by using
the standard action. Write the program with describing
the output ?
Ans. Java Beans :
1. Java Beans are classes which encapsulate several objects into a
single object.
2. It helps in accessing the objects from multiple places.
3. It is a portable, platform independent model written in Java.
Java Beans are used because :
1. It encapsulates many objects into a single object.
2. It allows us to use properties of getter and setter methods.
3. It has Java object which has constructor with no argument.
4. It can be manipulated visually in a builder tools.
Different types of standard action tags used in JSP are :
1. <jsp:useBean> :
a. This action associates an instance of a Java Bean defined with
a given scope and ID, through a newly declared scripting
variable of the same ID.
b. The <jsp:useBean> action is very flexible.
c. Its exact semantics depends on the values of the given
attributes.
d. The attributes for the <jsp:useBean> are : id, scope, class,
beanName, type.
2. <jsp:setProperty> :
a. This action helps to integrate Java Beans into JSPs.
b. It sets the value of a Beans property.
c. This action has the attributes name, property, param, value.
3. <jsp:getProperty> :
a. This action gets a property value from a Java Beans component
and adds it to the response.
b. Attribute of this action are : name, property.
4. <jsp:text> : This action is used to encapsulate template text that
should be used in JSP pages written as XML documents.
Example of <jsp:useBean>, <jsp:setProperty>,
<jsp:getProperty> actions :
Let us define a test bean that will further be used :
/* File: TestBean.java */
Solved Paper (2017-18) SP–30 D (IT-5/CS-6)
package action;
public class TestBean {
private String message = “No message specified”;
public String getMessage() {
return(message);
}
public void setMessage(String message) {
this.message = message;
}
}
Now use the following code in main.jsp file. This loads the bean and
sets/gets a simple String parameter.
<html>
<head>
<title>Using JavaBeans in JSP</title>
</head>
<body>
<center>
<h2>Using JavaBeans in JSP</h2>
<jsp:useBean id = “test” class = “action.TestBean” />
<jsp:setProperty name = “test” property = “message”
value = “Hello JSP...”/>
<p>Got message....</p>
<jsp:getProperty name = “test” property = “message”/>
</center>
</body>
</html>
Output :
Using JavaBeans in JSP
Got message....
Hello JSP...
Example of <jsp:text> action :
<jsp:text><![CDATA[<!DOCTYPE html PUBLIC “-//W3C//DTD
XHTML 1.0 Strict//EN”
“DTD/xhtml1-strict.dtd”>]]></jsp:text>
<head><title>jsp:text action</title></head>
<body>
<books><book><jsp:text>
Welcome to JSP Programming
</jsp:text></book></books>
</body>
</html>
Web Technology SP–1 D (IT-5/CS-6)
B. Tech.
(SEM. V) ODD SEMESTER THEORY
EXAMINATION, 2018-19
WEB TECHNOLOGIES
Section-A
b. Define constructor.
f. What are the two major protocols for accessing e-mail from
servers ?
Section-B
Section-C
Solved Paper (2018-19) SP–4 D (IT-5/CS-6)
f. What are the two major protocols for accessing e-mail from
servers ?
Ans. Post Office Protocol version 3 (POP3), Simple Mail Transfer Protocol
(SMTP) are the two majo r pro to co ls used fo r accessing
e-mail from servers.
Section-B
Ans. hyperlink.html :
<html><body>
<a href=“Pagelink.html”>Different Tags</a><br>
<br><a href=“table.html”>Time Table</a><br>
</body></html>
Table.html :
<html><head>
<title>Time Table</title>
</head><body>
<B><center><h3>
AKTU UNIVERSITY,<br>
DEPARTMENT OF INFORMATION TECHNOLOGY<br>
EFFECTIVE FROM : 04.02.19<br></center></b></h3>
<table border=“2” width=“75%” cellspacing=“2” cellpadding=“25”
align=center><h3>
<caption align=left>Sem: III IT\CS
& nbsp; & nbsp; & nbsp; & nbsp; & nbsp; & nbsp; &
nbsp; & nbsp; & nbsp; & nbsp; & nbsp; & nbsp; & nbsp; & nbsp;
& nbsp; & nbsp; & nbsp; & nbsp; & nbsp; & nbsp; & nbsp; </
caption></h3>
<thead><tr>
<th>Periods</th>
<th ROWSPAN=2>1 <br>8.30-9.20</th>
<th ROWSPAN=2>2<br>9.20-10.10</th>
<th ROWSPAN=2>3<br>10.20-11.10</th>
<th ROWSPAN=2>4<br>11.10-12.00</th>
<th ROWSPAN=2>5<br>1.30-2.20</th>
<th ROWSPAN=2>6<br>2.20-3.10</th>
<th ROWSPAN=2>7<br>3.10-4.00</th>
</tr>
<tr><th> Days</th>
</thead>
<tbody><tr>
<th>Monday</th>
<td>IT0302</td><td>IT0306</td><td>IT0304</td>
IT0322 -Web Technology LAB
<td>IT0306</td><td>IT0302</td>
<td COLSPAN=2><center>IT0324</td></tr>
<tr>
<th>Tuesday</th>
<td COLSPAN =4 bgcolor=“cyan”><center>IT0320/IT0322</
td>
<td>IT0310</td>
<td>IT0304</td><td>IT308</td></tr>
<tr>
<th>Wednesday</th>
Solved Paper (2018-19) SP–6 D (IT-5/CS-6)
<script>
var fruits = [“Banana“, “Orange”, “Apple”, “Mango”];
document.getElementById(“demo”).innerHTML = fruits;
function myFunction() {
fruits.sort();
document.getElementById(“demo”).innerHTML = fruits;
}
</script></body></html>
Install JDK
Input
IDE
Net Beans
Process Maven
Visual VM
Output
Testing tools
Error Testing JUnit
occur Clover
No Gradle
error
occur
Stop
Fig. 1.
JSP file
Translation phase
Servlet file
Compilation phase
Servlet class
7. NoLayout 8. ScrollPaneLayout
9. SpringLayout
Five layout managers :
a. BorderLayout : This scheme lays out the component in five ways :
i. North-Northern part of the container
ii. South-Southern part of the container
iii. East-Eastern part of the container
iv. West-Western part of the container
v. Center-centered in the container
b. CardLayout : Allows for what Windows programmers have called
“tabbed dialogs” or dynamic dialogs.
c. GridLayout : Allows for the layout of components in a grid-like
fashion rather than “North” or “Center”.
d. FlowLayout : Allows for component to be laid out in a row (or
flow) and aligned (left, right, center).
e. None : No layout, the container will not attempt to reposition the
components during an update.
Section-C
Architecture :
Get
HTTP HTTP
Client Server
Response
HTTP Protocol
Fig. 2.
Student.dtd
<?xml version “1.0”?>
<!ELEMENT STUDENTS (STUDENT*)>
<!ELEMENT STUDENT (STUDENTDATA*)>
<!ELEMENT STUDENTDATA (Roll_No, Name, Marks, Total,
Percentage)>
<!ELEMENT Roll_No (#PCDATA)>
<!ELEMENT NAME (#PCDATA)>
<!ELEMENT Marks (#PCDATA)>
<!ELEMENT Total (#PCDATA)>
<!ELEMENT Percentage (#PCDATA)>
Student.html
<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Transitional/
/EN”
“E:\XML 1\STUDENT.dtd””>
<html>
<head COLOUR:RED><h1 style = “color : red”>
<MARQUEE DIRECTION = “RIGHT”><CENTER> COLLEGE OF
EN GINEERIN G AN D TECHNOLOGY </CEN TER> </
MARQUEE> </H1>
<title> STUDENT DETAILS DISPLAY <title>
</head>
<body style = “background-colour : PINK”> <H2 STYLE =
“COLOUR : BLUE”> <MARQUEE> <CENTER> DEPARTMENT
OF COMPUTER SCIENCE
</CENTER> </MARQUEE><BR></H2>
<MARQUEE DIRECTION = “DOWN”><H3 STYLE = “COLOR :
GREEN”><CENTER> FINAL CS STUDENTS DETAILS </
CENTER> </MARQUEE><BR><BR></H3><CENTER><TABLE
BORDER = “1”>
<THEAD><TR>
<TH> Roll_No </TH><TH> NAME </TH><TH> Marks 1 </TH>
<TH> Marks 2 </TH><TH> Marks 3 </TH><TH> Marks 4 </TH>
<TH> Marks 5 </TH><TH> Total </TH><TH>Percentage </TH>
</TR>
</THEAD>
<TFOOT><TR>
<TH COLSPAN = “4”> STUDENT CATALOG</TH>
</TFOOT>
<TR>
<TD> 001 </TD><TD> RAM </TD>
<TD> Marks 1 : 70 </TD><TD> Marks 2 : 80 </TD>
<TD> Marks 3 : 50 </TD><TD> Marks 4 : 60 </TD>
<TD> Marks 5 : 70 </TD><TD> 330 </TD><TD> 66.0 </TD>
</TR>
</TABLE></CENTER></body></html>
Web Technology SP–13 D (IT-5/CS-6)
4. Throw :
a. Java supports “throw keyword” which is used if we want to
throw our own exceptions.
b. We can do this by using the keyword throw as follows :
throw new Throwable_subclass;
No, it is not essential to catch all type of exceptions.
For example :
throw new ArithmeticException ( ) ;
throw new NumberFormatException ( ) ;
class TestFinallyBlock
{
public static void main(String args[ ])
{
try
{
int data=25/0;
System.out.println(data);
}
catch(ArithmeticException e)
{
System.out.println(“Caught: ”+e);
}
finally
{
System.out.println(“finally block is always executed”);
}
System.out.println(“rest of the code...”);
}
}
Output :
Caught: java.lang.ArithmeticException: / by zero
finally block is always executed
rest of the code...
Button add,sub,eq,cl,mul,div;
TextField t1;
int a,b,c;
public void init() {
t1=new TextField(10);
b1=new Button(“1”); b2=new Button(“2”); b3=new Button(“3”);
b4=new Button(“4”); b5=new Button(“5”); b6=new Button(“6”);
b7=new Button(“7”); b8=new Button(“8”); b9=new Button(“9”);
b0=new Button(“0”);
add=new Button(“+”); sub=new Button(“–”);
mul=new Button(“*”); div=new Button(“/”);
eq=new Button(“=”); cl=new Button(“Clear”);
GridLayout gb=new GridLayout(4,5);
setLayout(gb);
add(t1);add(b1);add(b2); add(b3);add(b4);add(b5);
add(b6); add(b7);add(b8); add(b9);add(b0);add(add);
add(sub);add(mul);add(div); add(eq);add(cl);
b1.addActionListener(this); b2.addActionListener(this);
b3.addActionListener(this); b4.addActionListener(this);
b5.addActionListener(this); b6.addActionListener(this);
b7.addActionListener(this); b8.addActionListener(this);
b9.addActionListener(this); b0.addActionListener(this);
add.addActionListener(this); sub.addActionListener(this);
mul.addActionListener(this); div.addActionListener(this);
eq.addActionListener(this); cl.addActionListener(this);
paint();
//t1.addTextListener(this); }
public void paint() {
setBackground(Color.green); }
public void actionPerformed(ActionEvent e) {
s=e.getActionCommand();
if(s.equals(“0”)||s.equals(“1”)||s.equals(“2”)||
s.equals(“3”) || s.equals(“4”) || s.equals(“5”) || s.equals(“6”) ||
s.equals(“7”) || s.equals(“8”) ||
s.equals(“9”)||s.equals(“0”)) {
s1=t1.getText()+s;
t1.setText(s1); }
if(s.equals(“+”)) {
s2=t1.getText();
t1.setText(“”);
s3=“+”; }
if(s.equals(“–”)) {
s2=t1.getText();
t1.setText(“”);
s3=“–”; }
if(s.equals(“*”)) {
s2=t1.getText();
Solved Paper (2018-19) SP–18 D (IT-5/CS-6)
t1.setText(“”);
s3=“*”; }
if(s.equals(“–”)) {
s2=t1.getText();
t1.setText(“”);
s3=“–”; }
if(s.equals(“=”)) {
s4=t1.getText();
a=Integer.parseInt(s2);
b=Integer.parseInt(s4);
if(s3.equals(“+”))
c=a+b;
if(s3.equals(“–”))
c=a–b;
t1.setText(String.valueOf(c)); }
if(s.equals(“Clear”)) {
t1.setText(“”); } }
public void textValueChanged(TextEvent e) { }}
For example : Following example sets the text color of the <h1>
element to blue :
<h1 style=“color:blue;”>This is a Blue Heading</h1>
2. Internal CSS :
a. An internal CSS is used to define a style for a single HTML
page.
b. An internal CSS is defined in the <head> section of an HTML
page, within a <style>element.
For example :
<!DOCTYPE html>
<html>
<head>
<style>
body {background-color : powderblue;}
h1 {color : blue;}
p {color : red;}
</style>
</head>
<body>
<h1>This is a heading</h1>
<p>This is a paragraph.</p>
</body>
</html>
3. External CSS :
a. An external style sheet is used to define the style for many
HTML pages.
b. An external style sheet is used to change the look of an entire
website.
c. To use an external style sheet we add a link in the <head>
section of the HTML page.
For 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>
Ans. Difference :
S. No. Session Cookies
1. Sessions are stored in server. Cookies are stored in the user’s
browser.
2. A session is available as long as Cookies can keep information
the browser is opened. User can in the user’s browser until
not disable the session. deleted by user or set as per the
timer.
3. It will be destroyed if we close It will not be destroyed even if
the browser. we close the browser.
4. It can store any object. Cookies can only store string.
5. Session cannot be same for We can save cookies for future
future reference. reference.
Program :
Index.html :
<!DOCTYPE html><html><head>
<meta charset=“ISO-8859-1”>
<title>Servlet Login Example</title>
</head><body>
<h1>Welcome to Login App by Cookie</h1>
<a href=“login.html”>Login</a>|
<a href=“LogoutServlet”>Logout</a>|
<a href=“ProfileServlet”>Profile</a></body></html>
link.html :
<a href=“login.html”>Login</a> |
<a href=“LogoutServlet”>Logout</a> |
<a href=“ProfileServlet”>Profile</a>
<hr>
login.html :
<form action=“LoginServlet” method=“post”>
Name:<input type=“text” name=“name”><br>
Password:<input type=“password” name=“password”><br>
<input type=“submit” value=“login”></form>
LoginServlet.java :
package com.javatpoint;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
Web Technology SP–21 D (IT-5/CS-6)
Ans. JDBC :
1. JDBC (Java Database Connectivity) is a Java API that manages
connection to database, issuing queries and commands and handling
result sets obtained from the database.
2. JDBC is useful for both application developers and JDBC driver
vendors.
3. JDBC is specially used for having connectivity with the RDBMS
packages using corresponding JDBC driver.
Drivers in JDBC :
1. JDBC-ODBC bridge driver (Type 1 driver) :
a. These drivers are the bridge drivers such as JDBC-ODBC
bridge.
b. These drivers rely on an intermediary such as ODBC to transfer
the SQL calls to the database.
c. Bridge drivers often rely on native code, although the JDBC-
ODBC library native code is part of the Java-2 virtual machine.
Application
JDBC-Driver Manager
ODBC-Driver Manager
Application
JDBC
DBMS vendor
client-side Socket
connection DBMS
libraries based
server
on C language
Application
JDBC
Socket connection
JAVA based (DBMS specific
DBMS
socket driver protocol)
Server
status = “Inserted”;
} else {
status = “Not Inserted”; }
} catch (Exception e) { e.printStackTrace(); }
return status; }
// customer record
public void searchCustomer(String custid) {
String sql = “”;
if (custid.trim().length() == 0) {
sql = “select * from Customer”;
} else {
sql = “select * from Customer where custid=” + custid + “”; }
try {
ps = con.prepareStatement(sql);
ResultSet res = ps.executeQuery();
while (res.next()) {
System.out.print(res.getString(1));
System.out.print(res.getString(2));
System.out.print(res.getString(3));
System.out.println(res.getString(4)); }
} catch (SQLException e) {e.printStackTrace(); } }
public String deleteCustomer(String custId) {
String status = “”;
try {
ps = con.prepareStatement(“delete from Customer where
custid=?”);
ps.setString(1, custId);
int i = ps.executeUpdate();
if (i != 0) {
status = “Customer details deleted”;
} else {
status = “Customer details not deleted”; }
} catch (Exception e) {e.printStackTrace(); }
return status; }
public void menuDisplay() {
try {
BufferedReader br = new BufferedReader(new
InputStreamReader(System.in));
int ch = 0;
while (true) {
System.out.println(“== Customer Management System == \n”
+ “1. Add Customer \n” + “2. Display Customer’s record \n”
+ “3. Exit \n” + “Enter Choice \n”);
String str1 = br.readLine().toString();
ch = Integer.parseInt(str1);
switch (ch) {
case 1: {
Web Technology SP–25 D (IT-5/CS-6)
Web Technology SP–1 D (IT-5/CS-6)
B. Tech.
(SEM. V) ODD SEMESTER THEORY
EXAMINATION, 2019-20
WEB TECHNOLOGIES
Note : Attempt all sections. If require any missing data; then choose
suitably.
Section-A
Section-B
Section-C
Solved Paper (2019-20) SP–4 D (IT-5/CS-6)
Note : Attempt all sections. If require any missing data; then choose
suitably.
Section-A
Width
</body>
</html>
Section-B
Ans. Comparison :
S. No. Object-Oriented Object-Based
Programming Programming
1. It supports all the features of It supports the usage of object and
OOPS. encapsulation.
2. It also supports inheritance It does not support inheritance
and polymorphism. or, polymorphism or, both.
3. It supports built-in objects. It does not supports built-in
objects.
4. C#, Java, VB.Net are the JavaScript, VB are the examples
examples of object-oriented of object-based languages.
languages.
Output :
Inside Constructor with String parameter as JBT
Inside Constructor without parameter
}
}
3. We define the Printer class as :
class Printer {
private volatile boolean isOdd;
synchronized void printEven(int number) {
while (!isOdd) {
try {
wait();
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
System.out.println(Thread.currentThread().getName() + “:” +
number);
isOdd = false;
notify();
}
synchronized void printOdd(int number) {
while (isOdd) {
try {
wait();
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
System.out.println(Thread.currentThread().getName() + “:” +
number);
isOdd = true;
notify();
}
}
4. In the main method, we use the defined class to create two threads.
We create an object of the Printer class and pass it as the parameter
to the TaskEvenOdd constructor:
public static void main(String... args) {
Printer print = new Printer();
Thread t1 = new Thread(new TaskEvenOdd(print, 5, false),“Odd”);
Thread t2 = new Thread(new TaskEvenOdd(print, 5, true),“Even”);
t1.start();
t2.start();
}
Ans. XML :
1. XML is a markup language for documents containing structured
information which contains both content and some indication of
the role of content.
2. Extensible Markup Language, abbreviated as XML, describes a
class of data objects called XML documents and partially describes
the behaviour of computer programs which process them.
3. XML documents are made up of storage units called entities, which
contain either parsed or unparsed data.
Program :
XML document :
Student.XML
<?xml version = “1.0”?>
<!DOCTYPE STUDENTS SYSTEM “E:\XML1\STUDENT.dtd”>
<STUDENTS><STUDENT><STUDENTDATA>
<Roll_No> 001</Roll_No>
<NAME> RAM</NAME>
<Marks>
<Marks 1> 70 </Marks 1>
<Marks 2> 80 </Marks 2>
<Marks 3> 50 </Marks 3>
<Marks 4> 60 </Marks 4>
<Marks 5> 70 </Marks 5>
<Total> 330 </Total>
<Percentage> 66.0 </Percentage>
</Marks>
</STUDENTDATA></STUDENT></STUDENTS>
NOTE : Write the above code (bold part only) nine times again to
enter the details of rest of the nine students.
Student.dtd
<?xml version “1.0”?>
<!ELEMENT STUDENTS (STUDENT*)>
<!ELEMENT STUDENT (STUDENTDATA*)>
<!ELEMENT STUDENTDATA (Roll_No, Name, Marks, Total,
Percentage)>
<!ELEMENT Roll_No (#PCDATA)>
<!ELEMENT NAME (#PCDATA)>
<!ELEMENT Marks (#PCDATA)>
<!ELEMENT Total (#PCDATA)>
<!ELEMENT Percentage (#PCDATA)>
Student.html
<!DOCTYPE html PU BLIC “-//W3C//DTD XHTML 1.0
Transitional//EN”
“E:\XML 1\STUDENT.dtd””>
<html>
Web Technology SP–11 D (IT-5/CS-6)
Ans. EJB :
1. An Enterprise Java Bean is a server-side component which
encapsulates business logic.
2. EJB (Enterprise Java Bean) is used to develop scalable, robust
and secured enterprise applications in Java.
3. Middleware services such as security, transaction management
etc. are provided by EJB container to all EJB applications.
4. To run EJB application, we need an application server (EJB
Container) such as Jboss, Glassfish, Weblogic, Websphere etc.
5. EJB application is deployed on the server, so it is also called server-
side component.
EJB architecture :
JSP/servlet
Client-side Server
HTTP
Web browser
request JDBC
EJB Database
driver
connection
J2EE Server
Fig. 1. Architecture.
The EJB architecture is an extension of web architecture.
Working of EJB architecture :
1. The client is working on a web browser.
2. There is a database server that hosts a database, like MySQL /
Oracle.
3. The J2EE server machine is running on an application server.
4. The client interface is provided with JSP / Servlet.
5. The application server manages the relationships between the
client and database.
Types of EJB :
1. Entity bean : Entity beans represent persistent data storage.
Entity beans are used for modeling the business concept.
2. Session bean : Session beans are used for managing processes
or tasks. Hence, session beans are used for managing activities.
3. Message driven bean : Message driven bean is similar to the
session bean but it gets activated only when asynchronous message
arrives. When a message arrives then the EJB container calls the
message driven bean on message method to process the message.
Section-C
import javax.swing.SwingUtilities;
public class DrawShapes extends JFrame {
private static final long serialVersionUID = 1L;
public DrawShapes() {
setSize(new Dimension(320, 320));
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
JPanel p = new JPanel() {
@Override
public void paintComponent(Graphics g) {
Graphics2D g2 = (Graphics2D) g;
Shape line = new Line2D.Double(3, 3, 303, 303);
Shape rect = new Rectangle(3, 3, 303, 303);
Shape circle = new Ellipse2D.Double(100, 100, 100, 100);
Shape roundRect = new RoundRectangle2D.Double(20, 20, 250,
250, 5, 25);
g2.draw(line);
g2.draw(rect);
g2.draw(circle);
g2.draw(roundRect);
}
};
setTitle(“My Shapes”);
this.getContentPane().add(p);
}
public static void main(String arg[ ]) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
// TODO Auto-generated method stub
new DrawShapes();
}
});
}
}
Output :
Program :
XML document :
Student.XML
<?xml version = “1.0”?>
<!DOCTYPE STUDENTS SYSTEM “E:\XML1\STUDENT.dtd”>
<STUDENTS><STUDENT><STUDENTDATA>
<Roll_No> 001</Roll_No>
<NAME> RAM</NAME>
<Marks>
<Marks 1> 70 </Marks 1>
<Marks 2> 80 </Marks 2>
<Marks 3> 50 </Marks 3>
<Marks 4> 60 </Marks 4>
<Marks 5> 70 </Marks 5>
<Total> 330 </Total>
<Percentage> 66.0 </Percentage>
</Marks>
</STUDENTDATA></STUDENT></STUDENTS>
NOTE : Write the above code (bold part only) nine times again
to enter the details of rest of the nine students.
Web Technology SP–19 D (IT-5/CS-6)
Student.dtd
<?xml version “1.0”?>
<!ELEMENT STUDENTS (STUDENT*)>
<!ELEMENT STUDENT (STUDENTDATA*)>
<!ELEMENT STUDENTDATA (Roll_No, Name, Marks, Total,
Percentage)>
<!ELEMENT Roll_No (#PCDATA)>
<!ELEMENT NAME (#PCDATA)>
<!ELEMENT Marks (#PCDATA)>
<!ELEMENT Total (#PCDATA)>
<!ELEMENT Percentage (#PCDATA)>
Student.html
<!DOCTYPE html PU BLIC “-//W3C//DTD XHTML 1.0
Transitional//EN”
“E:\XML 1\STUDENT.dtd””>
<html>
<head COLOUR:RED><h1 style = “color : red”>
<MARQUEE DIRECTION = “RIGHT”><CENTER> COLLEGE
OF ENGINEERING AND TECHNOLOGY </CENTER> </
MARQUEE></H1>
<title>STUDENT DETAILS DISPLAY <title>
</head>
<body style = “background-colour : PINK”> <H2 STYLE =
“COLOUR : BLUE”> <MARQUEE> <CENTER> DEPARTMENT
OF COMPUTER SCIENCE
</CENTER> </MARQUEE><BR></H2>
<MARQUEE DIRECTION = “DOWN”><H3 STYLE = “COLOR :
GREEN”><CENTER> FINAL CS STUDENTS DETAILS </
CENTER> </MARQUEE><BR><BR></H3><CENTER><TABLE
BORDER = “1”>
<THEAD><TR>
<TH> Roll_No </TH><TH> NAME </TH><TH> Marks 1 </TH>
<TH> Marks 2 </TH><TH> Marks 3 </TH><TH> Marks 4 </TH>
<TH> Marks 5 </TH><TH> Total </TH><TH>Percentage </TH>
</TR>
</THEAD>
<TFOOT><TR>
<TH COLSPAN = “4”> STUDENT CATALOG</TH>
</TFOOT>
<TR>
<TD> 001 </TD><TD> RAM </TD>
<TD> Marks 1 : 70 </TD><TD> Marks 2 : 80 </TD>
<TD> Marks 3 : 50 </TD><TD> Marks 4 : 60 </TD>
<TD> Marks 5 : 70 </TD><TD> 330 </TD><TD> 66.0 </TD>
</TR>
</TABLE></CENTER></body></html>
Solved Paper (2019-20) SP–20 D (IT-5/CS-6)
<h1>This is a heading</h1>
<p>This is a paragraph.</p>
</body>
</html>
3. External CSS :
a. An external style sheet is used to define the style for many
HTML pages.
b. An external style sheet is used to change the look of an entire
website.
c. To use an external style sheet we add a link in the <head>
section of the HTML page.
For 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>
Program :
<HTML><HEAD><STYLE>
H1 {colour: red; font-family: arial; font-size: 2.50 em}
</STYLE></HEAD><BODY>
<H1> This is the H1 element </H1>
</BODY></HTML>
Da ta tra nsmitting
Data trans mitting
Data transmitting
Da ta tra nsmittin
Client-side
Waiting Waiting
Time
vent
vent
UI Update
UI Update
UI Update
UI Update
Change
Indicator
Activity
AJAX
Data
User E
User E
User E
communication
layer
Time
Server-side Server-side
Server-side Processing Processing
Fig. 3. AJAX style communication flow.
Applications of AJAX are :
1. AJAX is used to change the text without reloading the web page.
2. AJAX is a technique used for creating fast and dynamic web pages.
3. AJAX contains div section which is used to display information
returned from a server.
4. Major application of AJAX is in login forms where user can enter
their login details directly on the original page.
Web Technology SP–23 D (IT-5/CS-6)
For example :
<!DOCTYPE html>
<html>
<style>
table,th,td {
border : 1px solid black;
border-collapse: collapse;
}
th,td {
padding: 5px;
}
</style>
<body>
<h1>The XMLHttpRequest Object</h1>
<form action=“”>
<se le ct name=“custo me rs”
onchange=“showCustomer(this.value)”>
<option value=“”>Select a customer:</option>
<option value=“name1”>Aakash Pandey</option>
<option value=“name2”>Mohan</option>
<option value=“name3”>Harshit Kumar</option>
</select>
</form>
<br>
<div id=“txtHint”>Customer info will be listed here...</div>
<script>
function showCustomer(str) {
var xhttp;
if (str == “”) {
document.getElementById(“txtHint”).innerHTML = “”;
return;
}
xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
d o c um e nt . g et E l e m e ntB y I d ( “ tx t H i nt ”) . i nne r HTM L=
this.responseText;
} };
xhttp.open(“GET”, “getcustomer.asp?q=”+str, true);
xhttp.send();
}
</script>
</body>
</html>
Ans. Comparison :
S. No. Java JavaScript
1. Java is an obje ct-o riente d JavaScript is an object based
programming language. scripting language.
2. Java is strongly typed language JavaScript is very flexible in
and type checking. data type.
3. Objects in Java are static. Objects in JavaScript are
dynamic.
4. It can be use d to cre ate It cannot be used to create
standalone application. standalone application.
5. Variables in Java are declared Variables in JavaScript are
as : int num. declared as : var myname.
Different object in JavaScript :
1. Built-in objects : These objects are used quite extensively for
data processing in JavaScript. Following are some built-in object :
a. String object :
i. The string object enables programs to work with and
manipulate string.
ii. It provide methods such as : big(), blink(), bold(), italics(),
charAt(), touppercase(), tolowercase() and substring().
b. Math object :
i. The math object provides some commonly used methods
such as : sqrt(num), abs(num), sin(num), cos(num),
tan(num), exp(num), min(a, b), max(a, b), log(num),
pow(a, b), floor(num), ceil(num) etc.
c. Date object :
i. The date object enables JavaScript programmers to
create an object that contains information about a
particular date and provides a set of methods to work
with that information.
ii. Syntax :
var mydate = new Date(<parameters>);
iii. If the parameter left empty, it indicates current date
and time.
iv. The date object provides some methods which are :
getDate(), setDate(), getHours(), setHours(), getTime(),
setTime (), ge tDay(), se tDay(), ge tMinutes(),
setMinutes(), getSecond(), setSecond().
d. Array object :
i. The array object stores multiple values in a single
variable.
ii. Syntax :
var fruits = new Array( “apple”, “orange”, “mango” );
Web Technology SP–25 D (IT-5/CS-6)
2. User-defined objects :
a. A user-defined object is also associated with properties and
methods, which belong to it.
b. The user-defined object would also require methods that will
allow the storage of name, age and salary of the employee
object.
function Employee(name, age, salary)
{
this.name = name;
this.age = age;
this.salary = salary;
}
c. In the given example, object Employee has three properties :
name, age and salary. Here, this keyword refers to the current
object in focus. In given example, this.name will refer to the
name of the current object.
For example :
<html>
<head>
<title>JavaScript Object </title>
</head>
<body>
<script type=“text/javascript”>
var value = Math.acos(-1);
document.write(“ACOS Test Value : ” + value +“<br>”);
// Math object
var d = new Date();
document.write(“<b>Locale String:</b> ” +
d.toLocaleString()+“<br>”);
// Date Object
var str = “CareerRide Info”; //String Object
var s = str.split();
document.write(“<b>Char At:</b> ” + str.charAt(1)+“<br>”);
document.write(“<b>CharCode At:</b> ” +
str.charCodeAt(2)+“<br>”);
document.write(“<b>Index of:</b> ” +
str.indexOf(“ide”)+“<br>”);
</script>
</body>
</html>
Output:
ACOS Test Value : 3.141592653589793
Locale String: 22/02/2020 11:14:06 AM
Char At: a
CharCode At: 114
Index of: 7
Solved Paper (2019-20) SP–26 D (IT-5/CS-6)
Java Application
JDBC API
Driver Manager
Driver
Database
Fig. 4.
1. Java application : It is a standalone Java program which uses
the JDBC API to get connected and perform operations on the
database data.
2. JDBC API : It is a set of classes and interfaces used in a Java
program for database operations. Java.sql and Javax.sql packages
provide the necessary library support.
3. Driver manager : Java program uses DriverManager class to
get the connection with the database.
4. Driver : It is the software that establishes connection with the
database. It is the translation software that translates the JDBC
method calls. This software enables the communication between
Java program and the database.
5. Database : It is a collection of all enterprise data.
Types of JDBC driver :
1. JDBC-ODBC bridge driver (Type 1 driver) :
a. These drivers are the bridge drivers such as JDBC-ODBC
bridge.
b. These drivers rely on an intermediary such as ODBC to
transfer the SQL calls to the database.
Web Technology SP–27 D (IT-5/CS-6)
Application
JDBC-Driver Manager
ODBC-Driver Manager
Application
JDBC
DBMS vendor
client-side Socket
connection DBMS
libraries based
server
on C language
Application
JDBC
Socket connection
JAVA based (DBMS specific
DBMS
socket driver protocol)
Server
System.out.println();
}
}
Output :
Fname Lname ISBN
Jatin Garg 123
Pankaj Sharma 113
Pankaj Sharma 112
Pankaj Sharma 122
For example :
public static void main (String args[ ])
{
SimpleGetterAndSetter obj = new SimpleGetterAndSetter();
obj.setNumber(10);
System.out.println (obj.getNumber ( ));
}
4. Getter and setter are also known as accessor and mutator in Java.
Loading and
Start instantiation
init()
destroy()
End
of life End
cycle
Fig. 8.
Stages of the Servlet life cycle :
1. Loading a Servlet :
a. The first stage of the Servlet lifecycle involves loading and
initializing the Servlet by the Servlet container.
b. The Servlet container performs two operations in this stage :
i. Loading : Loads the Servlet class.
Web Technology SP–31 D (IT-5/CS-6)
</head>
<%
int demvar=0;%>
<body>
Count is :
<% Out.println(demovar++); %>
<body>
</html>
Demo JSP Page is converted into demo_jsp.servlet in the below
code.
Public class demp_jsp extends HttpServlet{
Public void _jspse rvice(HttpSe rvle tReque st reque st,
HttpSe rvle tRespo nse re sponse ) Thro ws IOException,
ServletException
{
PrintWriter out = response.getWriter();
response.setContentType(“text/html”);
out.write (“<html><body>”);
int demovar=0;
out.write(“Count is:”);
out.print(demovar++);
out.write(“</body></html>”);
}
}
5. The web container calls the init() method only once after creating
the servlet instance.
6. The init() method is used to initialize the servlet. It is the life
cycle method of the javax.servlet.Servlet interface.
7. Syntax of the init() method :
public void init(ServletConfig config) throws ServletException
8. A new thread is then gets created, which invokes the_jspService()
method, with a request (HttpServletRequest) and response
(HttpServletResponse) objects as parameters shown below :
[code language=“java”]
void _jspService( HttpServletRequest req, HttpServletResponse
res)
{
//code goes here
}[/code]
9. Invokes the jspDestroy() method to destroy the instance of the
servlet class. code :
[code language=“java”]
public void jspDestory()
{
//code to remove the instances of servlet class
}
Web Technology SP–33 D (IT-5/CS-6)
<meta charset=“UTF-8”>
<title>Jsp Directives Example</title>
<link rel=“stylesheet” href=“./static/css/pizzaorder.css”>
</head>
<body>
<%@ include file=“header.html” %>
<form action=“orderResult.jsp” method=“POST”>
<h3>Pizza Types</h3>
<div>
...
header.html:
<h4>Java Code Examples<h4>
c. Taglib directive :
1. The taglib directive declares that the page uses custom user
defined tags, it also defines the tags library.
2. The term custom tag refers to both tags and elements.
3. A tag is simply a short piece of a markup that is a part of JSP
element.
4. The syntax is as follows :
<%@ taglib uri = “tagLibraryURI” prefix = “tagPrefix”%>
Example :
Following example shows a declaration sample in a JSP page :
<%@ taglib prefix=“jgc” uri=“WEB-INF/custom.tld”%>
...
<jgc:HelloWorld/>
...