Download as pdf or txt
Download as pdf or txt
You are on page 1of 249

MAHARANA PRATAP GROUP OF INSTITUTIONS

KOTHI MANDHANA, KANPUR

(Approved by AICTE, New Delhi and Affiliated to Dr.AKTU, Lucknow)

Digital Notes

[Department of Computer Science & Engineering]

Subject Name : Web Technolgy

Subject Code : KCS-602

Course : B. Tech

Branch : CSE

Semester : IIIrd

Prepared by : Mr. Suneel Awasthi


Contents
Unit- I ............................................................................................................................................................. 9
Introduction and Web Development Strategies ................................................................................................ 9
1.1 World Wide Web: ................................................................................................................................. 9
1.2 History of WWW: ................................................................................................................................. 9
1.3 Protocols Governing Web:..................................................................................................................... 9
1.4 Website ................................................................................................................................................10
1.5 Web Applications .................................................................................................................................11
1.6 Writing web Projects and Target Users .................................................................................................11
1.7 Internet and its services, internet tool ....................................................................................................15
1.8 Client Server Computing ......................................................................................................................17
1.9 Characteristics of The Client And The Server .......................................................................................18
1.10 Java Introduction ................................................................................................................................21
1.11 Operators: ..........................................................................................................................................21
1.12 Data Types in Java .............................................................................................................................22
1.14 Java Variables ....................................................................................................................................24
1.15 Types of Variables..............................................................................................................................25
1.16 Java Arrays ........................................................................................................................................26
1.16.1 Advantages ..................................................................................................................................26
1.16.2 Disadvantages ..............................................................................................................................26
1.16.3 Types of Array in java .................................................................................................................26
1.16.4 Single Dimensional Array in Java ................................................................................................27
1.16.5 Example of Java Array.................................................................................................................27
1.7 Classes and objects ...............................................................................................................................27
1.17.1 What is a class in Java .................................................................................................................28
1.17.2 Syntax to declare a class: .............................................................................................................29
1.18 Instance variable in Java .....................................................................................................................29
1.19 Method in Java ...................................................................................................................................29
1.19.1 new keyword in Java....................................................................................................................29
1.19.2 Object and Class Example: main within the class .........................................................................30
1.19.3 Object and Class Example: main outside the class ........................................................................30
1.20 Inheritence .........................................................................................................................................31
1.20.1 Why use inheritance in java .........................................................................................................31
1.20.2 Terms used in Inheritance ............................................................................................................31
1.20.3 The syntax of Java Inheritance .....................................................................................................32
1.20.4 Java Inheritance Example ............................................................................................................32
1.21 Abstract classes and abstract methods .................................................................................................33
1.22 Interfaces............................................................................................................................................35
1.23 Exception Handling ............................................................................................................................36
1.24 Advantage of Exception Handling ......................................................................................................37
1.25 Hierarchy of Java Exception classes ...................................................................................................37
1.26 Types of Java Exceptions ...................................................................................................................38
1.27 Java Exception Keywords ...................................................................................................................38
1.27 Advantages of Java Multithreading .....................................................................................................40
1.28 Multitasking .......................................................................................................................................40
1.28.1Process-based Multitasking (Multiprocessing) ..............................................................................40
1.28.2 Thread-based Multitasking (Multithreading) ................................................................................40
1.29 Life cycle of a Thread (Thread States) ................................................................................................40
1.29.1 Explanation of Different Thread States ........................................................................................41
1.30 JAVA I/O ...........................................................................................................................................41
1.31 Stream ................................................................................................................................................42
1.32 OutputStream vs InputStream .............................................................................................................42
1.33 Applet ................................................................................................................................................44
1.33.1 Advantage of Applet ....................................................................................................................44
1.33.2 Drawback of Applet .....................................................................................................................45
1.33.3 Hierarchy of Applet .....................................................................................................................45
1.33.4 Lifecycle of Java Applet ..............................................................................................................45
1.34 EVENT HANDLING .........................................................................................................................47
1.34.1 Example of EventHandling in applet: ...........................................................................................47
1.34.2 Event and Listener (Java Event Handling)........................................................................................48
1.34.3 Java Event classes and Listener interfaces ....................................................................................48
1.34.4 Registration Methods ...................................................................................................................49
1.34.5 Java Event Handling Code ...........................................................................................................50
1.34.6 Java event handling by implementing ActionListener ...................................................................50
1.35 AWT ..................................................................................................................................................51
1.35.1 Why AWT is platform independent? ............................................................................................51
1.35.2 Java AWT Hierarchy ...................................................................................................................52
1.36 Components .......................................................................................................................................52
1.36.1 Container .....................................................................................................................................52
1.36.2 Types of containers: .....................................................................................................................53
1.37AWT Example by Inheritance .............................................................................................................54
1.38 Layout Managers ................................................................................................................................55
1.39 Java BorderLayout .............................................................................................................................56
1.39 Java Grid Layout ................................................................................................................................57
1.40 Java FlowLayout ................................................................................................................................59
Unit 2 ............................................................................................................................................................62
2.1 HTML .....................................................................................................................................................62
2.2 What is HTML? ...................................................................................................................................62
2.2.1 A Simple HTML Document ...........................................................................................................63
2.3 List: .....................................................................................................................................................63
2.3.1 Unordered HTML List ...................................................................................................................64
2.3.2 Ordered HTML List.......................................................................................................................65
2.3.3 HTML Description Lists ................................................................................................................66
2.4.1 HTML Tables ................................................................................................................................66
2.5 Define an HTML Table ........................................................................................................................67
2.6 Table Cells ...........................................................................................................................................68
2.7 Table Rows ..........................................................................................................................................68
2.8 Table Headers ......................................................................................................................................69
2.9.1 HTML Images Syntax ...................................................................................................................70
2.9.2 The src Attribute ............................................................................................................................70
2.9.3 The alt Attribute ............................................................................................................................71
2.10 Frames: ..............................................................................................................................................71
2.10.1HTML Iframe Syntax ...................................................................................................................72
2.11Forms: .................................................................................................................................................74
2.11Text Fields ..........................................................................................................................................77
2.12 Radio Buttons .....................................................................................................................................78
2.13 xml .....................................................................................................................................................80
2.13.1 XML Usage...................................................................................................................................80
2.13.2 What is Markup? ..........................................................................................................................80
2.13.3 XML Attributes ...............................................................................................................................83
2.13.4 XML - Declaration ..........................................................................................................................85
2.13.5 XML - Tags.....................................................................................................................................86
2.13.5 XML - Elements ..............................................................................................................................87
2.13.6 XML - Comments ...........................................................................................................................90
2.13.6 XML - Character Entities.................................................................................................................91
2.13.7 XML - CDATA Sections .................................................................................................................92
2.13.7 XML - WhiteSpaces ........................................................................................................................93
2.13.8 XML - Processing ...........................................................................................................................94
2.13.9 XML - DTDs...................................................................................................................................97
2.13.10 XML - DOM ............................................................................................................................... 102
2.13.11 XML - Namespaces ..................................................................................................................... 103
2.13.12 XML - Databases......................................................................................................................... 104
2.13.13 XML - Parsers ............................................................................................................................. 107
2.13.14 XML - Processors ........................................................................................................................ 107
2.14 CSS .................................................................................................................................................. 108
2.14.1 Advantages ofCSS ........................................................................................................................... 108
2.14.2 WhoCreates andMaintainsCSS?........................................................................................................... 109
2.14.3 The ClassSelectors ......................................................................................................................... 110
2.14.4 TheChildSelectors ......................................................................................................................... 111
2.14.5 TheAttributeSelectors............................................................................................................................ 111
2.14.6 Multiple Style Rules............................................................................................................................. 112
2.14.7 Grouping Selectors ........................................................................................................................ 112
2.14.8 EmbeddedCSS-The<style>Element ....................................................................................................... 113
2.14.9 InlineCSS-The style Attribute ................................................................................................................ 114
2.14.10 CSS Rules Overriding .................................................................................................................. 116
2.14.11 HandlingOld Browsers....................................................................................................................... 116
2.14.13 CSS Comments ............................................................................................................................... 117
2.14.14 CSS ─ MEASUREMENT UNITS .................................................................................................. 117
2.14.15 CSS ─ COLORS........................................................................................................................... 118
2.14.16 CSS Colors -Hex Codes ................................................................................................................... 119
2.14.17 CSS Colors -ShortHexCodes ............................................................................................................ 119
Unit 3 .......................................................................................................................................................... 120
Java script .................................................................................................................................................... 120
3.1 JavaScript Can Change HTML Content .............................................................................................. 120
3.2 JavaScript Can Change HTML Attribute Values ................................................................................. 120
3.2.1 The Light Bulb ............................................................................................................................ 120
3.3 JavaScript Statements ......................................................................................................................... 121
3.3.1 JavaScript Programs .................................................................................................................... 121
3.4 JavaScript Statements ......................................................................................................................... 122
3.5 Semicolons ; ....................................................................................................................................... 122
3.6 JavaScript White Space ...................................................................................................................... 123
3.7 JavaScript Line Length and Line Breaks ............................................................................................. 123
3.8 JavaScript Code Blocks ...................................................................................................................... 124
3.9 JavaScript Keywords .......................................................................................................................... 124
3.10 JavaScript Functions ......................................................................................................................... 126
3.11 JavaScript Function Syntax............................................................................................................... 127
3.12 Function Invocation .......................................................................................................................... 127
3.13 Function Return ............................................................................................................................. 128
3.13.1 The () Operator Invokes the Function ......................................................................................... 129
3.13.2 Functions Used as Variable Values ............................................................................................ 129
3.14 Local Variables ................................................................................................................................ 130
3.15 Real Life Objects, Properties, and Methods ...................................................................................... 131
3.16 Object Definition .............................................................................................................................. 132
3.17 Object Properties ........................................................................................................................... 132
3.18 Accessing Object Properties ............................................................................................................. 133
3.19 Object Methods ................................................................................................................................ 134
3.20 AJAX Introduction ........................................................................................................................... 138
3.20.1 AJAX Example.......................................................................................................................... 138
3.20.2 AJAX Example Explained ......................................................................................................... 139
3.20.3 How AJAX Works ..................................................................................................................... 140
3.20.3 The XMLHttpRequest Object .................................................................................................... 141
3.21 Define a Callback Function .............................................................................................................. 142
3.21.1 Send a Request .......................................................................................................................... 142
3.22 Access Across Domains ................................................................................................................... 142
3.22.1 XMLHttpRequest Object Methods ............................................................................................. 143
3.22.2 XMLHttpRequest Object Properties .......................................................................................... 145
3.23 The onload Property ......................................................................................................................... 146
3.24 Multiple Callback Functions ............................................................................................................. 147
3.25 AJAX - XMLHttpRequest ................................................................................................................ 149
3.26 GET or POST ................................................................................................................................... 151
3.27 Synchronous Request ....................................................................................................................... 153
3.28 The XML File .................................................................................................................................. 157
3.29 The PHP File - "gethint.php" ............................................................................................................ 158
3.30 Example Explained - The showCustomer() Function ........................................................................ 160
3.31 The AJAX Server Page..................................................................................................................... 160
3.33 XML Applications ............................................................................................................................ 161
3.34 Display XML Data in an HTML Table ............................................................................................. 162
3.35 Display the First CD in an HTML div Element ................................................................................. 162
3.36 JavaBean .......................................................................................................................................... 163
3.36.1 JavaBean Properties ................................................................................................................... 164
3.36.2 Advantages of JavaBean ............................................................................................................ 165
3.36.3 Disadvantages of JavaBean ........................................................................................................ 165
3.37.......................................................................................................................................................... 165
3.37EJB Tutorial ...................................................................................................................................... 165
3.38 The Java Beans API ......................................................................................................................... 167
Unit 4 .......................................................................................................................................................... 170
4.1 EJB ........................................................................................................................................................ 170
4.2 JavaBean ............................................................................................................................................ 170
4.2.1 Creating a Java Bean ................................................................................................................... 170
4.2.2 Types of Bean: ............................................................................................................................ 171
4.2.3 Difference between RMI and EJB ................................................................................................ 172
4.2.4 EJB and Webservice .................................................................................................................... 172
4.2.5Session Bean: ............................................................................................................................... 173
4.2.6 Types of Session Bean ................................................................................................................. 173
4.2.7 Entity Bean in EJB 3.x ................................................................................................................. 173
4.2.8 Message Driven Bean .................................................................................................................. 173
4.2.9 Message Driven Bean Example.................................................................................................... 174
4.3 JDBC: ................................................................................................................................................ 174
4.3.1 JDBC Drivers: ............................................................................................................................. 175
4.4 Database with JDBC: ......................................................................................................................... 179
4.5 Transaction Management in JDBC ..................................................................................................... 183
4.6Stored Procedures: .............................................................................................................................. 185
4.7 Full example to call the stored procedure using JDBC ........................................................................ 186
UNIT 5 ........................................................................................................................................................ 188
5.1 Servlets | Servlet Tutorial ....................................................................................................................... 188
5.2 What is a Servlet? ............................................................................................................................... 188
5.4 Handling HTTP Request & HTTP Response: .................................................................................... 190
5.5 Create a directory structures ............................................................................................................... 191
5.6 One Time Configuration for Apache Tomcat Server ........................................................................... 195
5.7 Redirecting Request to Other Resource: .............................................................................................. 195
5.8 Methods of RequestDispatcher interface ............................................................................................. 195
5.7 Session Tracking: ............................................................................................................................... 201
5.8 Cookies: ............................................................................................................................................. 202
5.9 Types of Cookie ................................................................................................................................. 202
5.9.1 Advantage of Cookies .................................................................................................................. 203
5.9.2 Disadvantage of Cookies ............................................................................................................. 203
5.9.3 Session Tracking with Http Session: ............................................................................................ 203
5.10 Java Server Pages(JSP): .................................................................................................................... 206
5.10.1 Advantages of JSP over Servlet.................................................................................................. 207
5.10.2 The Lifecycle of a JSP Page ....................................................................................................... 208
5.10.3 The Directory structure of JSP ................................................................................................... 210
5.11 Implicit Objects in JSP: .................................................................................................................... 210
5.12 JSP Directives: ................................................................................................................................. 211
5.12.1 JSP page directive ...................................................................................................................... 212
5.12.2 JSP Standard Actions: ................................................................................................................ 216
5.12.3 Advantage of jsp:include action tag............................................................................................ 218
5.12.4 Difference between jsp include directive and include action ....................................................... 218
5.13 Custom Tag in JSP: .......................................................................................................................... 219
5.14 JSP Custom Tag API ........................................................................................................................ 219
6 Question Bank .......................................................................................................................................... 223
UNIT 1 .................................................................................................................................................... 223
UNIT-II ................................................................................................................................................... 223
UNIT –III ................................................................................................................................................ 224
UNIT-IV .................................................................................................................................................. 225
UNIT-V ................................................................................................................................................... 225
7 Multiple Choice Question.......................................................................................................................... 227
UNIT 1 .................................................................................................................................................... 227
UNIT 2 .................................................................................................................................................... 229
UNIT 3 .................................................................................................................................................... 231
UNIT 4 .................................................................................................................................................... 234
UNIT 5 .................................................................................................................................................... 243
8 Previous Year Question Papers.................................................................................................................. 249
2010 to 2015 ............................................................................................................................................ 249
Unit- I
Introduction and Web Development Strategies

1.1 World Wide Web:


The World Wide Web is a system of interlinked hypertext documents accessed
via the Internet. Web is a huge collection of pages of information linked to each
other around the globe.

1.2 History of WWW:

WWW is created by Sir Tim Berners Lee in 1989 at CERN in Geneva.

In 1990, the first text only browsers were setup and CERN scientist
could access hypertext files and other information at CERN. HTML was
based on a subset of the standard generalized markup language (SGML).
To transfer HTML document to remote sites a new protocol was devised
called HTTP (Hyper Text Transfer Protocol).

In the fall of 1991, conference goes around the world started hearing about
the promise but sparks still were not flying.

In 1993, there are only about 50 websites world wide. A browser that
allowed user to take advantage of the web’s graphical capabilities was
developed at the National center for Super Computing application
(NCSA). NCSA called the browser Mosaic.

1.3 Protocols Governing Web:


Protocol: A protocol is a set of rules that is used to communicate applications to each
other.
OR
A protocol is the interface required for communicating the different applications.

HTTP: HTTP is the primary protocol used to distribute information on the web.
Initial HTTP 0.9 does not allow for content typing and does not have provisions for
supplying meta-information.
Content Typing: To identify the type of data being transferred.
Meta Information: It is supplemental data, such as environment variables that identify
the client’s computer
Current version is HTTP 1.0
TCP/IP: It is a set of rules that an application can use to package its information for
sending across the networks of networks.

FTP: It is used to transfer the files over networks.

E-Mail: It is a method of exchanging digital messages across the Internet or other


computer networks.

Telnet: Telnet lets you remotely log into another system and browse files and
directories on that remote system.

1.4 Website

Website: A website is simply a collection of interlinked web pages.


Classification: A. Corporate Website B. Individual website

A. Corporate Website:
i. In this, there is certain no. of persons, who develop their website for a particular
organization.
ii. The corporate website are formed when group of people have common interest and
objective.
iii. The purpose of this website is to convey the information of organization to all
over the world.

B. Individual website: It is just like profile management system. In this type of


website an individual wants to develop website for h-projection, career growth etc.

Cyber Laws

Cyber Laws: Cyber law is a term used to describe the legal issues related to use of
communication technology, particularly “cyberspace” i.e. Internet. Indian and
International Cyber Law: Cyber Laws are formed by the government to prevent the
internet crime. These crimes could be hacking, threat on internet, denial of services
etc. Cyberspace includes computer, computer networks, internet data, software etc.
i. Data Protection and Privacy Law: This is due to the nature of the internet and
amount of information that may be accessed through it, such legislation is critical
to protect the fundamental rights of privacy of an individual.

ii. Electronic and Digital Signature Law: This is required so that uniform and
standard procedures are established for authentication of electronics records, EDI,
E-Mail.

iii. Computer Crime Law: due to victim of internet threats.

iv. Telecommunication Law: Approve and supervise the application of fees and
rates charged for telecommunication services in accordance with the provision of
the applicable law.

v. Intellectual Property Law: This includes copyright law, trademark law,


semiconductor law and patent law in relation to computer hardware and
software.

IT Act 2000 (INDIA):


E-Governance
Authentication of E-Records
Digital Signatures
Controlled certifying authorities
Penalties for damage of computer and computer system.

1.5 Web Applications

Web Applications:
Simple office software (word processors, online spreadsheets, and presentation
tools).
More advanced applications such as project management, computer-aided design,
video editing and point-of-sale.

1.6 Writing web Projects and Target Users

Writing web Projects and Target Users:


A. Write a project mission statement: Write the specific mission statement that
you want to do.

B. Identify Objectives:
i. Specific
ii. Measurable
iii. Attainable
iv. Realistic
v. Time limited

C. Identify your target users: The matter of a website will be determined by the
users whom you want to visit the site. This is totally depend upon
i. Market research
ii. Focus group
iii. Understanding intranet audiences

D. Determine the scope: By supporting documents and client’s approval.

E. Budget:
i. Assumption for budgets.
ii. Budget categories.
iii. Determine hidden costs and tools.

F. Planning issues:
i. Discuss client’s existing information system.
ii. Project team and developing infrastructure.
iii. Where the website will place.

Comparison between traditional project and web project:


Web Projects Traditional Projects

1. Project managers are not always 1. They are always different.


client. They could be same. 2. It is not applicable in this case
2. Often beta technologies are used for 3. It do exist for traditional projects.
testing, often without tech support. 4. More specialized.
3. Pricing model for web projects does 5. Difficult of traditional projects.
not exist. 6. Standards for web projects exist.
4. Team roles are less specialized. 7. Not true for these projects.
5. Clients are often unwilling to bear the
cost of web development.
6. Standards for web projects do not
exist.
7. Project manager’s responsibilities are
very broad.

Identification of objects:
A. Object identification: All the components which are visible in website are
objects or in other words, we can say that all visible components in the web
browser are defined as objects. Ex. Text box, command button etc.

B. Web development process:


Strategy:
Goals and objectives
Team building
Research and review
Project proposal

Design and Specification:


Developing concept
Content planning
Rough design
Final design

Produced desired Result:


Build prototype
Prototype testing
Original design
Satisfy the clients need

Testing and maintenance:


Test the code
Maintain the web server.

Register with ISP:


Register domain name
Get web space

Launch:
Connect domain name with web server
Finally host the web accordingly.

Web Team

Web Team: Web team is a group of various technical experts in a developing site
from coding the page to maintain the web server.
Types:

A. Server Side: hired by a company to develop a website.

B. Client Side: part of the company putting together the website.

Assessment techniques used to comprise a web team:

a. Deciding roles and responsibilities: The composition of team varies to depend


on the audience, scope and complexity level of the web. There are key roles on
each virtual project. One should always decide for core, extended and special
team members in a web and shares responsibilities accordingly.

b. Common Team Compositions: It is possible to acknowledge specific type of


teams and determine to be based on the kind of project, who is likely to be part of
the team though these are all type of web project. As for example the team
composition might be account manager, creative lead, project manager, designer
etc.

c. Putting together with right team: It meet out the needs with low price, more
effectively in reasonable time. So it is the team that fulfils the website
requirements successfully.

d. Identifying Necessary Skills: The skill set in the base of web team. It must have in
care to plan, design, build and deploy a website.

Core Team member


1. Project Manager:
Specify the work.
Developing the project plan.
Scheduling.
Allocation resources.
Budgeting and managing the team.

2. Technical lead:
Managing programmers.
Chooses specialized team such as security
expert, database programmers.

3. Web Production specialist:


Integrate the site using html or java script.

4. Creative Lead: determines creative concepts for the site and responsible for site
design.

5. Quality Assurance Lead: for testing purpose.

Extended Team Member


1. Account Manager: It interacts with the client, project manager and creative lead.

2. Programmer: develops applications for the web projects.

3. Network Engineer: configuring a web server.

4. Information architects: It understands how to display information visually to users


and how to interact with the website.

5. Content Writer: write contents for the website.

6. Tester: It tests the web project based on the team plan that QA lead writes.

1.7 Internet and its services, internet tool


ARPANET:
In 1969, a project was funded by the Advanced Research Project Agency
(ARPA), an arm of the U.S. Department of Defence. ARPA established a packet-
switching network of computers linked by point-to-point leased lines called
Advanced Research Project agency Network (ARPANET) that provided a basis for
early research into networking.

The conventions developed by ARPA is specify how individual


computers could communicate across that network became TCP/IP.

As networking possibilities grew to include other types of links and


devices, ARPA adapted TCP/IP to the demands of the new technology. As
involvement in TCP/IP grew, the scope of ARPANET expanded until it became the
backbone of an internetwork today referred to as the internet.

ISP
The Internet Service Provider (ISP) gives you the telephone access and software
you need to connect to the internet along with some technical help.

Many ISPs also include an electronic mail account, host customers web pages and
offer services a company that do business on the Internet.

There are aprox. 200 ISPs in India like VSNL, MTNL, ERNET (Education and
Research Community Network) etc.

UDP
The User Datagram Protocol (UDP) is one of the core members of the Internet
Protocol Suite, the set of network protocols used for the Internet. With UDP,
computer applications can send messages, in this case referred to as datagrams, to
other hosts on an Internet Protocol (IP) network without requiring prior
communications to set up special transmission channels or data paths.

Uploading of files
Uploading requires a 6 MHz. bandwidth in a range below 40 MHz. At this
low frequency, home appliances can create a noisy environment that effect
modulation.

The modulation technique that is normally used is QPSK (4bit at a time).


This means that a user can upload information at a rate of 12 Mbps.

Presently the uploading rate is between 500 Kbps and 1 Mbps.

Portal
A web portal, also known as a links page, presents information from diverse
sources in a unified way. Apart from the standard search engine feature, web
portals offer other services such as e-mail, news, stock prices, information,
databases and entertainment. Portals provide a way for enterprises to provide a
consistent look and feel with access control and procedures for multiple
applications and databases, which otherwise would have been different entities
altogether. Examples of public web portals are AOL, iGoogle, MSNBC, Netvibes,
and Yahoo.

1.8 Client Server Computing

Client
A client is a single-user workstation that provides presentation services, database
services and connectivity along with an interface for user interaction to acquire
business needs.

Server
A server is one or more multi-user processors with a higher capacity of shared memory
which provides connectivity and the database services along with interfaces relevant to
the business procedures.

Client/Server computing provides an environment that enhances business procedures


by appropriately synchronizing the application processing between the client and the
server.

The protocol relies on the basis of request serving; request for services by clients;
response of processed results by the server. The communication between the two
aspects is gained through InterProcess communication (IPC) which facilitates the
distributed placement of the client and server procedures.

The Client/Server model is basically platform independent and blends with


“cooperating processing” or “peer-to-peer” model. The platform provides the
opportunity for users to access the business functionality thereby exposing into risky
situations since its transparent to the underlying technology aswell as to the user.

1.9 Characteristics of The Client And The Server

The clients and the servers are the logical entities that work together over a
network to accomplish a task.

· Service: The client/server is basically a relationship between processes running


on distributed devices, server process considered as a supplier of services where the
client process is a consumer of services. Briefly, this methodology provides a
separation of functionalities subject to offered services.

· Resource sharing: A server is eligible of handling clients simultaneously, controlling


the service access for the resources.

· Asymmetrical protocols: Client/server is considered as a many-to-one


relationship which is initiated by clients through request of service while the server
passively awaits. Sometimes a client may pass a reference to a callback object when it
requests a service. This enforces the server call back the client, making the server a
client itself.

· Transparency of location: The server process can reside in a client or any


machine across a network .In such situations Client/Server software is responsible for
implying the server location by redirecting service calls. Therefore a program can be a
client/server/or both.

· Inter- Communication via messages: Interaction between clients and servers is


obtained through a message-passing mechanism mainly to deliver service requests and
responses.

· Encapsulation of services: A server is specialized in satisfying client requests


varyingly and can be upgraded without affecting its external environment (clients,
shared resources) as long as the message broadcasting interface remains the same.
· Scalability: Client/Server systems can be scaled horizontally or vertically. Horizontal
scaling implies the addition or removal of client workstations with a minor impact in
performance. Migration to more efficient servers or dividing the work load over
numerous servers is considered as vertical scaling.

· Integrity: Since the server code and server data is managed centrally,
maintenance cost is less and results in shared data consistency and undependability of
clients.

Advantages

Organizations often seek opportunities to maintain service and quality competition to


sustain its market position with the help of technology where the client/server model
makes an effective impact. Deployment of client/server computing in an organization
will positively increase productivity through the usage of cost-effective user interfaces,
enhanced data storage, vast connectivity and reliable application services.

If properly implemented its capable of improving organizational behavior with the help
of the knowledgeable worker-who can manipulate data and respond to the errors
appropriately.

 Improved Data Sharing


Data is retained by usual business processes and manipulated on a server is available
for designated users (clients) over an authorized access. The use of Structured Query
Language (SQL) supports open access from all client aspects and also transparency in
network services depict that similar data is being shared among users.

 Integration of Services
Every client is given the opportunity to access corporate information via the desktop
interface eliminating the necessity to log into a terminal mode or another processor.
Desktop tools like spreadsheet, power point presentations etc can be used to deal with
corporate data with the help of database and application servers resident on the network
to produce meaningful information.

 Shared Resources amongst Different Platforms


Applications used for client/server model is built regardless of the hardware platform
or technical background of the entitled software (Operating System S/W) providing an
open computing environment, enforcing users to obtain the services of clients and
servers (database, application, communication servers).

 Inter-Operation of Data

All development tools used for client/server applications access the back-end database
server through SQL, an industry-standard data definition and access language, helpful
for consistent management of corporate data. Advanced database products enable
user/application to gain a merged view of corporate data dispersed over several
platforms. Rather than a single target platform this ensures database integrity with the
ability to perform updates on multiple locations enforcing quality recital and recovery.

 Data Processing capability despite the location

We are in an era which undergoes a transformation of machine-centered systems to


user-centered systems. Machine-centered systems like mainframe, mini-micro
applications had unique access platforms and functionality keys, navigation options,
performance and security were all visible. Through client/server users can directly log
into a system despite of the location or technology of the processors.

 Easy maintenance
Since client/server architecture is a distributed model representing dispersed
responsibilities among independent computers integrated across a network, it’s an
advantage in terms of maintenance. It’s easy to replace, repair, upgrade and relocate a
server while clients remain unaffected. This unawareness of change is called as
encapsulation.

 Security
Servers have better control access and resources to ensure that only authorized clients
can access or manipulate data and server-updates are administered effectively.

Disadvantages-compared to peer-peer networks


 Overloaded servers
When there are frequent simultaneous client requests, servers severely get overloaded,
forming traffic congestion. But in a P2P network adding more nodes will increase its
bandwidth since it’s calculated as the sum of bandwidths of each node in the network.

1.10 Java Introduction: java is a programming language and a platform. Java is a high level,
robust, object-oriented and secure programming language.

Java was developed by Sun Microsystems (which is now the subsidiary of Oracle) in the year
1995. James Gosling is known as the father of Java. Before Java, its name was Oak. Since Oak was
already a registered company, so James Gosling and his team changed the name from Oak to Java

1.11 Operators:

Operator in Java is a symbol that is used to perform operations. For example: +, -, *, / etc.

There are many types of operators in Java which are given below:

o Unary Operator,
o Arithmetic Operator,
o Shift Operator,
o Relational Operator,
o Bitwise Operator,
o Logical Operator,
o Ternary Operator and
o Assignment Operator
o Java Operator Precedence

Operator Type Category Precedence

Unary postfix expr++ expr--

prefix ++expr --expr +expr -expr ~ !

Arithmetic multiplicative */%

additive +-
Shift shift << >> >>>

Relational comparison < > <= >= instanceof

equality == !=

Bitwise bitwise AND &

bitwise exclusive OR ^

bitwise inclusive OR |

Logical logical AND &&

logical OR ||

Ternary ternary ?:

Assignment assignment = += -= *= /= %= &= ^= |= <<= >>= >>>=

1.12 Data Types in Java

Data types specify the different sizes and values that can be stored in the variable. There are two types
of data types in Java:

1. Primitive data types: The primitive data types include boolean, char, byte, short, int, long, float and
double.
2. Non-primitive data types: The non-primitive data types include Classes, Interfaces, and Arrays.

Java Primitive Data Types

In Java language, primitive data types are the building blocks of data manipulation. These are the
most basic data types available in Java language

o boolean data type


o byte data type
o char data type
o short data type
o int data type
o long data type
o float data type
o double data type

Data Type Default Value Default size

boolean false 1 bit

char '\u0000' 2 byte

byte 0 1 byte

short 0 2 byte

int 0 4 byte

long 0L 8 byte

float 0.0f 4 byte

double 0.0d 8 byte

Boolean Data Type


The Boolean data type is used to store only two possible values: true and false. This data type is used
for simple flags that track true/false conditions.

The Boolean data type specifies one bit of information, but its "size" can't be defined precisely.

Example:
1. Boolean one = false
Byte Data Type

The byte data type is an example of primitive data type. It isan 8-bit signed two's complement integer.
Its value-range lies between -128 to 127 (inclusive). Its minimum value is -128 and maximum value
is 127. Its default value is 0.

The byte data type is used to save memory in large arrays where the memory savings is most
required. It saves space because a byte is 4 times smaller than an integer. It can also be used in place
of "int" data type.

Example:

1. byte a = 10, byte b = -20

Variable:
1.14 Java Variables

A variable is a container which holds the value while the Java program is executed. A variable is
assigned with a data type.

Variable is a name of memory location. There are three types of variables in java: local, instance and
static.

There are two types of data types in Java: primitive and non-primitive.

Variable

A variable is the name of a reserved area allocated in memory. In other words, it is a name of the
memory location. It is a combination of "vary + able" which means its value can be changed.
1. int data=50;//Here data is variable
1.15 Types of Variables

There are three types of variables in Java:

o local variable
o instance variable
o static variable

1) Local Variable

A variable declared inside the body of the method is called local variable. You can use this variable
only within that method and the other methods in the class aren't even aware that the variable exists.

A local variable cannot be defined with "static" keyword.

2) Instance Variable

A variable declared inside the class but outside the body of the method, is called an instance variable.
It is not declared as static.

It is called an instance variable because its value is instance-specific and is not shared among
instances.

3) Static variable
A variable that is declared as static is called a static variable. It cannot be local. You can create a
single copy of the static variable and share it among all the instances of the class. Memory allocation
for static variables happens only once when the class is loaded in the memory

Arrays:
1.16 Java Arrays

Normally, an array is a collection of similar type of elements which has contiguous memory location.

Java array is an object which contains elements of a similar data type. Additionally, The elements of
an array are stored in a contiguous memory location. It is a data structure where we store similar
elements. We can store only a fixed set of elements in a Java array.

Array in Java is index-based, the first element of the array is stored at the 0th index, 2nd element is
stored on 1st index and so on.

Unlike C/C++, we can get the length of the array using the length member. In C/C++, we need to use
the sizeof operator.

In Java, array is an object of a dynamically generated class. Java array inherits the Object class, and
implements the Serializable as well as Cloneable interfaces. We can store primitive values or objects
in an array in Java. Like C/C++, we can also create single dimentional or multidimentional arrays in
Java.

Moreover, Java provides the feature of anonymous arrays which is not available in C/C++.

1.16.1 Advantages
o Code Optimization: It makes the code optimized, we can retrieve or sort the data efficiently.
o Random access: We can get any data located at an index position.

1.16.2 Disadvantages
o Size Limit: We can store only the fixed size of elements in the array. It doesn't grow its size at
runtime. To solve this problem, collection framework is used in Java which grows automatically.

1.16.3 Types of Array in java


There are two types of array.

o Single Dimensional Array


o Multidimensional Array

1.16.4 Single Dimensional Array in Java

Syntax to Declare an Array in Java

1. dataType[] arr; (or)


2. dataType []arr; (or)
3. dataType arr[];

Instantiation of an Array in Java

1. arrayRefVar=new datatype[size];
1.16.5 Example of Java Array

Let's see the simple example of java array, where we are going to declare, instantiate, initialize and
traverse an array.

1. //Java Program to illustrate how to declare, instantiate, initialize


2. //and traverse the Java array.
3. class Testarray{
4. public static void main(String args[]){
5. int a[]=new int[5];//declaration and instantiation
6. a[0]=10;//initialization
7. a[1]=20;
8. a[2]=70;
9. a[3]=40;
10. a[4]=50;
11. //traversing array
12. for(int i=0;i<a.length;i++)//length is the property of array
13. System.out.println(a[i]);
14. }}

1.7 Classes and objects:


An object is an instance of a class. A class is a template or blueprint from which objects are created.
So, an object is the instance(result) of a class.

Object Definitions:

o An object is a real-world entity.


o An object is a runtime entity.
o The object is an entity which has state and behavior.
o The object is an instance of a class.

1.17.1 What is a class in Java

A class is a group of objects which have common properties. It is a template or blueprint from which
objects are created. It is a logical entity. It can't be physical.

A class in Java can contain:

o Fields
o Methods
o Constructors
o Blocks
o Nested class and interface
1.17.2 Syntax to declare a class:
1. class <class_name>{
2. field;
3. method;
4. }

1.18 Instance variable in Java

A variable which is created inside the class but outside the method is known as an instance variable.
Instance variable doesn't get memory at compile time. It gets memory at runtime when an object or
instance is created. That is why it is known as an instance variable.

1.19 Method in Java

In Java, a method is like a function which is used to expose the behavior of an object.

Advantage of Method
o Code Reusability
o Code Optimization

1.19.1 new keyword in Java


The new keyword is used to allocate memory at runtime. All objects get memory in Heap memory
area.

1.19.2 Object and Class Example: main within the class

In this example, we have created a Student class which has two data members id and name. We are
creating the object of the Student class by new keyword and printing the object's value.

Here, we are creating a main() method inside the class.

File: Student.java

1. //Java Program to illustrate how to define a class and fields


2. //Defining a Student class.
3. class Student{
4. //defining fields
5. int id;//field or data member or instance variable
6. String name;
7. //creating main method inside the Student class
8. public static void main(String args[]){
9. //Creating an object or instance
10. Student s1=new Student();//creating an object of Student
11. //Printing values of the object
12. System.out.println(s1.id);//accessing member through reference variable
13. System.out.println(s1.name);
14. }
15. }
Test it Now

Output:

0
null
1.19.3 Object and Class Example: main outside the class

In real time development, we create classes and use it from another class. It is a better approach than
previous one. Let's see a simple example, where we are having main() method in another class.

We can have multiple classes in different Java files or single Java file. If you define multiple classes
in a single Java source file, it is a good idea to save the file name with the class name which has
main() method.
File: TestStudent1.java

1. //Java Program to demonstrate having the main method in


2. //another class
3. //Creating Student class.
4. class Student{
5. int id;
6. String name;
7. }
8. //Creating another class TestStudent1 which contains the main method
9. class TestStudent1{
10. public static void main(String args[]){
11. Student s1=new Student();
12. System.out.println(s1.id);
13. System.out.println(s1.name);
14. }
15. }

1.20 Inheritence:

Inheritance in Java is a mechanism in which one object acquires all the properties and behaviors of
a parent object. It is an important part of OOPs (Object Oriented programming system).

The idea behind inheritance in Java is that you can create new classes that are built upon existing
classes. When you inherit from an existing class, you can reuse methods and fields of the parent class.
Moreover, you can add new methods and fields in your current class also.

Inheritance represents the IS-A relationship which is also known as a parent-child relationship.

1.20.1 Why use inheritance in java


o For Method Overriding (so runtime polymorphism can be achieved).
o For Code Reusability.

1.20.2 Terms used in Inheritance


o Class: A class is a group of objects which have common properties. It is a template or blueprint from
which objects are created.
o Sub Class/Child Class: Subclass is a class which inherits the other class. It is also called a derived
class, extended class, or child class.
o Super Class/Parent Class: Superclass is the class from where a subclass inherits the features. It is
also called a base class or a parent class.
o Reusability: As the name specifies, reusability is a mechanism which facilitates you to reuse the fields
and methods of the existing class when you create a new class. You can use the same fields and
methods already defined in the previous class.

1.20.3 The syntax of Java Inheritance


1. class Subclass-name extends Superclass-name
2. {
3. //methods and fields
4. }

The extends keyword indicates that you are making a new class that derives from an existing class.
The meaning of "extends" is to increase the functionality.

In the terminology of Java, a class which is inherited is called a parent or superclass, and the new
class is called child or subclass.

1.20.4 Java Inheritance Example

As displayed in the above figure, Programmer is the subclass and Employee is the superclass. The
relationship between the two classes is Programmer IS-A Employee. It means that Programmer is a
type of Employee.

1. class Employee{
2. float salary=40000;
3. }
4. class Programmer extends Employee{
5. int bonus=10000;
6. public static void main(String args[]){
7. Programmer p=new Programmer();
8. System.out.println("Programmer salary is:"+p.salary);
9. System.out.println("Bonus of Programmer is:"+p.bonus);
10. }
11. }

1.21 Abstract classes and abstract methods:


Abstract class in Java
A class which is declared with the abstract keyword is known as an abstract class in Java. It can have
abstract and non-abstract methods (method with the body).

Before learning the Java abstract class, let's understand the abstraction in Java first.

Abstraction in Java

Abstraction is a process of hiding the implementation details and showing only functionality to the
user.

Another way, it shows only essential things to the user and hides the internal details, for example,
sending SMS where you type the text and send the message. You don't know the internal processing
about the message delivery.

Abstraction lets you focus on what the object does instead of how it does it.

Ways to achieve Abstraction

There are two ways to achieve abstraction in java

1. Abstract class (0 to 100%)


2. Interface (100%)

Abstract class in Java


A class which is declared as abstract is known as an abstract class. It can have abstract and non-
abstract methods. It needs to be extended and its method implemented. It cannot be instantiated.

Points to Remember
o An abstract class must be declared with an abstract keyword.
o It can have abstract and non-abstract methods.
o It cannot be instantiated.
o It can have constructors and static methods also.
o It can have final methods which will force the subclass not to change the body of the method.

Example of abstract class

1. abstract class A{}

Abstract Method in Java

A method which is declared as abstract and does not have implementation is known as an abstract
method.

Example of abstract method


1. abstract void printStatus();//no method body and abstract

Example of Abstract class that has an abstract method

In this example, Bike is an abstract class that contains only one abstract method run. Its
implementation is provided by the Honda class.

1. abstract class Bike{


2. abstract void run();
3. }
4. class Honda4 extends Bike{
5. void run(){System.out.println("running safely");}
6. public static void main(String args[]){
7. Bike obj = new Honda4();
8. obj.run();
9. }
10. }

1.22 Interfaces:

An interface in Java is a blueprint of a class. It has static constants and abstract methods.

The interface in Java is a mechanism to achieve abstraction. There can be only abstract methods in
the Java interface, not method body. It is used to achieve abstraction and multiple inheritance in Java.

In other words, you can say that interfaces can have abstract methods and variables. It cannot have a
method body.

Java Interface also represents the IS-A relationship.

Competitive questions on Structures in Hindi


Keep Watching

It cannot be instantiated just like the abstract class.

Since Java 8, we can have default and static methods in an interface.

Since Java 9, we can have private methods in an interface.

Why use Java interface?

There are mainly three reasons to use interface. They are given below.
o It is used to achieve abstraction.
o By interface, we can support the functionality of multiple inheritance.
o It can be used to achieve loose coupling.

How to declare an interface?

An interface is declared by using the interface keyword. It provides total abstraction; means all the
methods in an interface are declared with the empty body, and all the fields are public, static and final
by default. A class that implements an interface must implement all the methods declared in the
interface.

Syntax:
1. interface <interface_name>{
2.
3. // declare constant fields
4. // declare methods that abstract
5. // by default.
6. }

1.23 Exception Handling


The Exception Handling in Java is one of the powerful mechanism to handle the runtime errors so
that the normal flow of the application can be maintained.

What is Exception in Java?

Dictionary Meaning: Exception is an abnormal condition.

In Java, an exception is an event that disrupts the normal flow of the program. It is an object which is
thrown at runtime.

What is Exception Handling?

Exception Handling is a mechanism to handle runtime errors such as ClassNotFoundException,


IOException, SQLException, RemoteException, etc.

1.24 Advantage of Exception Handling

The core advantage of exception handling is to maintain the normal flow of the application. An
exception normally disrupts the normal flow of the application; that is why we need to handle
exceptions. Let's consider a scenario:

1. statement 1;
2. statement 2;
3. statement 3;
4. statement 4;
5. statement 5;//exception occurs
6. statement 6;
7. statement 7;
8. statement 8;
9. statement 9;
10. statement 10;

Suppose there are 10 statements in a Java program and an exception occurs at statement 5; the rest of
the code will not be executed, i.e., statements 6 to 10 will not be executed. However, when we
perform exception handling, the rest of the statements will be executed. That is why we use exception
handling in Java.

1.25 Hierarchy of Java Exception classes

The java.lang.Throwable class is the root class of Java Exception hierarchy inherited by two
subclasses: Exception and Error. The hierarchy of Java Exception classes is given below:
1.26 Types of Java Exceptions

There are mainly two types of exceptions: checked and unchecked. An error is considered as the
unchecked exception. However, according to Oracle, there are three types of exceptions namely:

1. Checked Exception
2. Unchecked Exception
3. Error

1.27 Java Exception Keywords

Java provides five keywords that are used to handle the exception. The following table describes
each.
Keyword Description

try The "try" keyword is used to specify a block where we should place an
exception code. It means we can't use try block alone. The try block
must be followed by either catch or finally.

catch The "catch" block is used to handle the exception. It must be preceded
by try block which means we can't use catch block alone. It can be
followed by finally block later.

finally The "finally" block is used to execute the necessary code of the
program. It is executed whether an exception is handled or not.

throw The "throw" keyword is used to throw an exception.

throws The "throws" keyword is used to declare exceptions. It specifies that


there may occur an exception in the method. It doesn't throw an
exception. It is always used with method signature.
Java Exception Handling Example

Let's see an example of Java Exception Handling in which we are using a try-catch statement to
handle the exception.

JavaExceptionExample.java

1. public class JavaExceptionExample{


2. public static void main(String args[]){
3. try{
4. //code that may raise exception
5. int data=100/0;
6. }catch(ArithmeticException e){System.out.println(e);}
7. //rest code of the program
8. System.out.println("rest of the code...");
9. }
10. }
Multithreading

Multithreading in Java is a process of executing multiple threads simultaneously.

A thread is a lightweight sub-process, the smallest unit of processing. Multiprocessing and


multithreading, both are used to achieve multitasking.
However, we use multithreading than multiprocessing because threads use a shared memory area.
They don't allocate separate memory area so saves memory, and context-switching between the
threads takes less time than process.

Java Multithreading is mostly used in games, animation, etc.

1.27 Advantages of Java Multithreading

1) It doesn't block the user because threads are independent and you can perform multiple
operations at the same time.

2) You can perform many operations together, so it saves time.

3) Threads are independent, so it doesn't affect other threads if an exception occurs in a single
thread.

1.28 Multitasking

Multitasking is a process of executing multiple tasks simultaneously. We use multitasking to utilize


the CPU. Multitasking can be achieved in two ways:

o Process-based Multitasking (Multiprocessing)


o Thread-based Multitasking (Multithreading)

1.28.1Process-based Multitasking (Multiprocessing)


o Each process has an address in memory. In other words, each process allocates a separate memory
area.
o A process is heavyweight.
o Cost of communication between the process is high.
o Switching from one process to another requires some time for saving and loading registers, memory
maps, updating lists, etc.

1.28.2 Thread-based Multitasking (Multithreading)


o Threads share the same address space.
o A thread is lightweight.
o Cost of communication between the thread is low.

1.29 Life cycle of a Thread (Thread States)

In Java, a thread always exists in any one of the following states. These states are:
1. New
2. Active
3. Blocked / Waiting
4. Timed Waiting
5. Terminated

1.29.1 Explanation of Different Thread States

New: Whenever a new thread is created, it is always in the new state. For a thread in the new state,
the code has not been run yet and thus has not begun its execution.

Active: When a thread invokes the start() method, it moves from the new state to the active state. The
active state contains two states within it: one is runnable, and the other is running.

o Runnable: A thread, that is ready to run is then moved to the runnable state. In the runnable state, the
thread may be running or may be ready to run at any given instant of time. It is the duty of the thread
scheduler to provide the thread time to run, i.e., moving the thread the running state.
A program implementing multithreading acquires a fixed slice of time to each individual thread. Each
and every thread runs for a short span of time and when that allocated time slice is over, the thread
voluntarily gives up the CPU to the other thread, so that the other threads can also run for their slice of
time. Whenever such a scenario occurs, all those threads that are willing to run, waiting for their turn
to run, lie in the runnable state. In the runnable state, there is a queue where the threads lie.
o Running: When the thread gets the CPU, it moves from the runnable to the running state. Generally,
the most common change in the state of a thread is from runnable to running and again back to
runnable.

Blocked or Waiting: Whenever a thread is inactive for a span of time (not permanently) then, either
the thread is in the blocked state or is in the waiting state.

1.30 JAVA I/O

ava I/O (Input and Output) is used to process the input and produce the output.

Java uses the concept of a stream to make I/O operation fast. The java.io package contains all the
classes required for input and output operations.

We can perform file handling in Java by Java I/O API.

1.31 Stream

A stream is a sequence of data. In Java, a stream is composed of bytes. It's called a stream because it
is like a stream of water that continues to flow.

In Java, 3 streams are created for us automatically. All these streams are attached with the console.

1) System.out: standard output stream

2) System.in: standard input stream

3) System.err: standard error stream

Let's see the code to print output and an error message to the console.

1. System.out.println("simple message");
2. System.err.println("error message");

Let's see the code to get input from console.

1. int i=System.in.read();//returns ASCII code of 1st character


2. System.out.println((char)i);//will print the character
1.32 OutputStream vs InputStream

The explanation of OutputStream and InputStream classes are given below:

OutputStream

Java application uses an output stream to write data to a destination; it may be a file, an array,
peripheral device or socket.

InputStream

Java application uses an input stream to read data from a source; it may be a file, an array, peripheral
device or socket.

Let's understand the working of Java OutputStream and InputStream by the figure given below.
OutputStream class

OutputStream class is an abstract class. It is the superclass of all classes representing an output stream
of bytes. An output stream accepts output bytes and sends them to some sink.

Useful methods of OutputStream

Method Description

1) public void write(int)throws IOException is used to write a byte to the current output stream.

2) public void write(byte[])throws IOException is used to write an array of byte to the current output
stream.

3) public void flush()throws IOException flushes the current output stream.

4) public void close()throws IOException is used to close the current output stream.

OutputStream Hierarchy
InputStream class

InputStream class is an abstract class. It is the superclass of all classes representing an input stream of
bytes.

Useful methods of InputStream

Method Description

1) public abstract int read()throws reads the next byte of data from the input stream. It
IOException returns -1 at the end of the file.

2) public int available()throws returns an estimate of the number of bytes that can be
IOException read from the current input stream.

3) public void close()throws IOException is used to close the current input stream.

InputStream Hierarchy

1.33 Applet

Applet is a special type of program that is embedded in the webpage to generate the dynamic content.
It runs inside the browser and works at client side.

1.33.1 Advantage of Applet

There are many advantages of applet. They are as follows:

o It works at client side so less response time.


o Secured
o It can be executed by browsers running under many plateforms, including Linux, Windows, Mac Os
etc.

1.33.2 Drawback of Applet


o Plugin is required at client browser to execute applet.

1.33.3 Hierarchy of Applet

As displayed in the above diagram, Applet class extends Panel. Panel class extends Container which is the subclass of
Component.

1.33.4 Lifecycle of Java Applet


1. Applet is initialized.
2. Applet is started.
3. Applet is painted.
4. Applet is stopped.
5. Applet is destroyed.
Lifecycle methods for Applet:

The java.applet.Applet class 4 life cycle methods and java.awt.Component class provides 1 life cycle
methods for an applet.

java.applet.Applet class

For creating any applet java.applet.Applet class must be inherited. It provides 4 life cycle methods of
applet.

1. public void init(): is used to initialized the Applet. It is invoked only once.
2. public void start(): is invoked after the init() method or browser is maximized. It is used to start the
Applet.
3. public void stop(): is used to stop the Applet. It is invoked when Applet is stop or browser is
minimized.
4. public void destroy(): is used to destroy the Applet. It is invoked only once.

java.awt.Component class

The Component class provides 1 life cycle method of applet.


1. public void paint(Graphics g): is used to paint the Applet. It provides Graphics class object that can
be used for drawing oval, rectangle, arc etc.

Who is responsible to manage the life cycle of an applet?

Java Plug-in software.

How to run an Applet?

There are two ways to run an applet

1. By html file.
2. By appletViewer tool (for testing purpose).

Simple example of Applet by html file:

To execute the applet by html file, create an applet and compile it. After that create an html file and
place the applet code in html file. Now click the html file.

1. //First.java
2. import java.applet.Applet;
3. import java.awt.Graphics;
4. public class First extends Applet{
5.
6. public void paint(Graphics g){
7. g.drawString("welcome",150,150);
8. }
9.
10. }

1.34 EVENT HANDLING :


As we perform event handling in AWT or Swing, we can perform it in applet also. Let's see the simple
example of event handling in applet that prints a message by click on the button.

1.34.1 Example of EventHandling in applet:

1. import java.applet.*;
2. import java.awt.*;
3. import java.awt.event.*;
4. public class EventApplet extends Applet implements ActionListener{
5. Button b;
6. TextField tf;
7.
8. public void init(){
9. tf=new TextField();
10. tf.setBounds(30,40,150,20);
11.
12. b=new Button("Click");
13. b.setBounds(80,150,60,50);
14.
15. add(b);add(tf);
16. b.addActionListener(this);
17.
18. setLayout(null);
19. }
20.
21. public void actionPerformed(ActionEvent e){
22. tf.setText("Welcome");
23. }
24. }
In the above example, we have created all the controls in init() method because it is invoked only once.
myapplet.html
1. <html>
2. <body>
3. <applet code="EventApplet.class" width="300" height="300">
4. </applet>
5. </body>
6. </html>
1.34.2 Event and Listener (Java Event Handling)
Changing the state of an object is known as an event. For example, click on button, dragging mouse etc. The java.awt.event
package provides many event classes and Listener interfaces for event handling.
1.34.3 Java Event classes and Listener interfaces
Event Classes Listener Interfaces

ActionEvent ActionListener

MouseEvent MouseListener and MouseMotionListener

MouseWheelEvent MouseWheelListener

KeyEvent KeyListener

ItemEvent ItemListener

TextEvent TextListener

AdjustmentEvent AdjustmentListener

WindowEvent WindowListener

ComponentEvent ComponentListener

ContainerEvent ContainerListener

FocusEvent FocusListener
Steps to perform Event Handling

Following steps are required to perform event handling:

1. Register the component with the Listener

1.34.4 Registration Methods

For registering the component with the Listener, many classes provide the registration methods. For
example:

o Button
o public void addActionListener(ActionListener a){}
o MenuItem
o public void addActionListener(ActionListener a){}

o TextField
o public void addActionListener(ActionListener a){}
o public void addTextListener(TextListener a){}

o TextArea
o public void addTextListener(TextListener a){}

o Checkbox
o public void addItemListener(ItemListener a){}

o Choice
o public void addItemListener(ItemListener a){}
o List
o public void addActionListener(ActionListener a){}
o public void addItemListener(ItemListener a){}

1.34.5 Java Event Handling Code

We can put the event handling code into one of the following places:

1. Within class
2. Other class
3. Anonymous class

1.34.6 Java event handling by implementing ActionListener


1. import java.awt.*;
2. import java.awt.event.*;
3. class AEvent extends Frame implements ActionListener{
4. TextField tf;
5. AEvent(){
6.
7. //create components
8. tf=new TextField();
9. tf.setBounds(60,50,170,20);
10. Button b=new Button("click me");
11. b.setBounds(100,120,80,30);
12.
13. //register listener
14. b.addActionListener(this);//passing current instance
15.
16. //add components and set size, layout and visibility
17. add(b);add(tf);
18. setSize(300,300);
19. setLayout(null);
20. setVisible(true);
21. }
22. public void actionPerformed(ActionEvent e){
23. tf.setText("Welcome");
24. }
25. public static void main(String args[]){
26. new AEvent();
27. }
28. }

public void setBounds(int xaxis, int yaxis, int width, int height); have been used in the above
example that sets the position of the component it may be button, textfield etc.

1.35 AWT:

Java AWT (Abstract Window Toolkit) is an API to develop Graphical User Interface (GUI) or
windows-based applications in Java.

Java AWT components are platform-dependent i.e. components are displayed according to the view
of operating system. AWT is heavy weight i.e. its components are using the resources of underlying
operating system (OS).

The java.awt package provides classes for AWT API such as TextField, Label, ,
RadioButton, CheckBox, Choice, List etc.

The AWT tutorial will help the user to understand Java GUI programming in simple and easy steps.

1.35.1 Why AWT is platform independent?

Java AWT calls the native platform calls the native platform (operating systems) subroutine for
creating API components like TextField, ChechBox, button, etc.

For example, an AWT GUI with components like TextField, label and button will have different look
and feel for the different platforms like Windows, MAC OS, and Unix. The reason for this is the
platforms have different view for their native components and AWT directly calls the native
subroutine that creates those components.

In simple words, an AWT application will look like a windows application in Windows OS whereas it
will look like a Mac application in the MAC OS.

1.35.2 Java AWT Hierarchy

The hierarchy of Java AWT classes are given below.

1.36 Components

All the elements like the button, text fields, scroll bars, etc. are called components. In Java AWT,
there are classes for each component as shown in above diagram. In order to place every component
in a particular position on a screen, we need to add them to a container.

1.36.1 Container
The Container is a component in AWT that can contain another components like buttons, textfields,
labels etc. The classes that extends Container class are known as container such as Frame,
Dialog and Panel.

It is basically a screen where the where the components are placed at their specific locations. Thus it
contains and controls the layout of components.

1.36.2 Types of containers:

There are four types of containers in Java AWT:

1. Window
2. Panel
3. Frame
4. Dialog

1.36.2.1 Window

The window is the container that have no borders and menu bars. You must use frame, dialog or
another window for creating a window. We need to create an instance of Window class to create this
container.

1.36.2.2 Panel

The Panel is the container that doesn't contain title bar, border or menu bar. It is generic container for
holding the components. It can have other components like button, text field etc. An instance of Panel
class creates a container, in which we can add components.

1.36.2.3 Frame

The Frame is the container that contain title bar and border and can have menu bars. It can have other
components like button, text field, scrollbar etc. Frame is most widely used container while
developing an AWT application.

Useful Methods of Component Class

Method Description

public void add(Component c) Inserts a component on this component.

public void setSize(int width,int height) Sets the size (width and height) of the component.

public void setLayout(LayoutManager m) Defines the layout manager for the component.

public void setVisible(boolean status) Changes the visibility of the component, by default
false.
Java AWT Example

To create simple AWT example, you need a frame. There are two ways to create a GUI using Frame
in AWT.

1. By extending Frame class (inheritance)


2. By creating the object of Frame class (association)

1.37AWT Example by Inheritance

Let's see a simple example of AWT where we are inheriting Frame class. Here, we are showing
Button component on the Frame.

AWTExample1.java

1. // importing Java AWT class


2. import java.awt.*;
3.
4. // extending Frame class to our class AWTExample1
5. public class AWTExample1 extends Frame {
6.
7. // initializing using constructor
8. AWTExample1() {
9.
10. // creating a button
11. Button b = new Button("Click Me!!");
12.
13. // setting button position on screen
14. b.setBounds(30,100,80,30);
15.
16. // adding button into frame
17. add(b);
18.
19. // frame size 300 width and 300 height
20. setSize(300,300);
21.
22. // setting the title of Frame
23. setTitle("This is our basic AWT example");
24.
25. // no layout manager
26. setLayout(null);
27.
28. // now frame will be visible, by default it is not visible
29. setVisible(true);
30. }
31.
32. // main method
33. public static void main(String args[]) {
34.
35. // creating instance of Frame class
36. AWTExample1 f = new AWTExample1();
37.
38. }
39.
40. }

1.38 Layout Managers :


BorderLayout (LayoutManagers)
Java LayoutManagers

The LayoutManagers are used to arrange components in a particular manner. The Java
LayoutManagers facilitates us to control the positioning and size of the components in GUI forms.
LayoutManager is an interface that is implemented by all the classes of layout managers. There are
the following classes that represent the layout managers:

1. java.awt.BorderLayout
2. java.awt.FlowLayout
3. java.awt.GridLayout
4. java.awt.CardLayout
5. java.awt.GridBagLayout
6. javax.swing.BoxLayout
7. javax.swing.GroupLayout
8. javax.swing.ScrollPaneLayout
9. javax.swing.SpringLayout etc.

1.39 Java BorderLayout

The BorderLayout is used to arrange the components in five regions: north, south, east, west, and
center. Each region (area) may contain one component only. It is the default layout of a frame or
window. The BorderLayout provides five constants for each region:

1. public static final int NORTH


2. public static final int SOUTH
3. public static final int EAST
4. public static final int WEST
5. public static final int CENTER

Constructors of BorderLayout class:


o BorderLayout(): creates a border layout but with no gaps between the components.
o BorderLayout(int hgap, int vgap): creates a border layout with the given horizontal and vertical gaps
between the components.

Example of BorderLayout class: Using BorderLayout() constructor

FileName: Border.java

1. import java.awt.*;
2. import javax.swing.*;
3.
4. public class Border
5. {
6. JFrame f;
7. Border()
8. {
9. f = new JFrame();
10.
11. // creating buttons
12. JButton b1 = new JButton("NORTH");; // the button will be labeled as NORTH
13. JButton b2 = new JButton("SOUTH");; // the button will be labeled as SOUTH
14. JButton b3 = new JButton("EAST");; // the button will be labeled as EAST
15. JButton b4 = new JButton("WEST");; // the button will be labeled as WEST
16. JButton b5 = new JButton("CENTER");; // the button will be labeled as CENTER
17.
18. f.add(b1, BorderLayout.NORTH); // b1 will be placed in the North Direction
19. f.add(b2, BorderLayout.SOUTH); // b2 will be placed in the South Direction
20. f.add(b3, BorderLayout.EAST); // b2 will be placed in the East Direction
21. f.add(b4, BorderLayout.WEST); // b2 will be placed in the West Direction
22. f.add(b5, BorderLayout.CENTER); // b2 will be placed in the Center
23.
24. f.setSize(300, 300);
25. f.setVisible(true);
26. }
27. public static void main(String[] args) {
28. new Border();
29. }
30. }
1.39 Java Grid Layout

The Java Grid Layout class is used to arrange the components in a rectangular grid. One component is
displayed in each rectangle.

Constructors of Grid Layout class


1. GridLayout(): creates a grid layout with one column per component in a row.
2. GridLayout(int rows, int columns): creates a grid layout with the given rows and columns but no
gaps between the components.
3. GridLayout(int rows, int columns, int hgap, int vgap): creates a grid layout with the given rows and
columns along with given horizontal and vertical gaps.

Example of GridLayout class: Using GridLayout() Constructor

The GridLayout() constructor creates only one row. The following example shows the usage of the
parameterless constructor.

FileName: GridLayoutExample.java
1. // import statements
2. import java.awt.*;
3. import javax.swing.*;
4.
5. public class GridLayoutExample
6. {
7. JFrame frameObj;
8.
9. // constructor
10. GridLayoutExample()
11. {
12. frameObj = new JFrame();
13.
14. // creating 9 buttons
15. JButton btn1 = new JButton("1");
16. JButton btn2 = new JButton("2");
17. JButton btn3 = new JButton("3");
18. JButton btn4 = new JButton("4");
19. JButton btn5 = new JButton("5");
20. JButton btn6 = new JButton("6");
21. JButton btn7 = new JButton("7");
22. JButton btn8 = new JButton("8");
23. JButton btn9 = new JButton("9");
24.
25. // adding buttons to the frame
26. // since, we are using the parameterless constructor, therfore;
27. // the number of columns is equal to the number of buttons we
28. // are adding to the frame. The row count remains one.
29. frameObj.add(btn1); frameObj.add(btn2); frameObj.add(btn3);
30. frameObj.add(btn4); frameObj.add(btn5); frameObj.add(btn6);
31. frameObj.add(btn7); frameObj.add(btn8); frameObj.add(btn9);
32.
33. // setting the grid layout using the parameterless constructor
34. frameObj.setLayout(new GridLayout());
35.
36.
37. frameObj.setSize(300, 300);
38. frameObj.setVisible(true);
39. }
40.
41. // main method
42. public static void main(String argvs[])
43. {
44. new GridLayoutExample();
45. }
46. }
1.40 Java FlowLayout

The Java FlowLayout class is used to arrange the components in a line, one after another (in a flow).
It is the default layout of the applet or panel.

Fields of FlowLayout class


1. public static final int LEFT
2. public static final int RIGHT
3. public static final int CENTER
4. public static final int LEADING
5. public static final int TRAILING

Constructors of FlowLayout class


1. FlowLayout(): creates a flow layout with centered alignment and a default 5 unit horizontal and
vertical gap.
2. FlowLayout(int align): creates a flow layout with the given alignment and a default 5 unit horizontal
and vertical gap.
3. FlowLayout(int align, int hgap, int vgap): creates a flow layout with the given alignment and the
given horizontal and vertical gap.

Example of FlowLayout class: Using FlowLayout() constructor

FileName: FlowLayoutExample.java
1. // import statements
2. import java.awt.*;
3. import javax.swing.*;
4.
5. public class FlowLayoutExample
6. {
7.
8. JFrame frameObj;
9.
10. // constructor
11. FlowLayoutExample()
12. {
13. // creating a frame object
14. frameObj = new JFrame();
15.
16. // creating the buttons
17. JButton b1 = new JButton("1");
18. JButton b2 = new JButton("2");
19. JButton b3 = new JButton("3");
20. JButton b4 = new JButton("4");
21. JButton b5 = new JButton("5");
22. JButton b6 = new JButton("6");
23. JButton b7 = new JButton("7");
24. JButton b8 = new JButton("8");
25. JButton b9 = new JButton("9");
26. JButton b10 = new JButton("10");
27.
28.
29. // adding the buttons to frame
30. frameObj.add(b1); frameObj.add(b2); frameObj.add(b3); frameObj.add(b4);
31. frameObj.add(b5); frameObj.add(b6); frameObj.add(b7); frameObj.add(b8);
32. frameObj.add(b9); frameObj.add(b10);
33.
34. // parameter less constructor is used
35. // therefore, alignment is center
36. // horizontal as well as the vertical gap is 5 units.
37. frameObj.setLayout(new FlowLayout());
38.
39. frameObj.setSize(300, 300);
40. frameObj.setVisible(true);
41. }
42.
43. // main method
44. public static void main(String argvs[])
45. {
46. new FlowLayoutExample();
47. }
48. }
Unit 2
2.1 HTML
HTML is the standard markup language for creating Web pages.

2.2 What is HTML?

 HTML stands for Hyper Text Markup Language


 HTML is the standard markup language for creating Web pages
 HTML describes the structure of a Web page
 HTML consists of a series of elements
 HTML elements tell the browser how to display the content
 HTML elements label pieces of content such as "this is a heading", "this is a
paragraph", "this is a link", etc.
2.2.1 A Simple HTML Document
Example
<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
</head>
<body>

<h1>My First Heading</h1>


<p>My first paragraph.</p>

</body>
</html>

2.3 List:

HTML lists allow web developers to group a set of related items in lists.

Example

An unordered HTML list:

 Item
 Item
 Item
 Item
An ordered HTML list:

1. First item
2. Second item
3. Third item
4. Fourth item

Try it Yourself »

2.3.1 Unordered HTML List

An unordered list starts with the <ul> tag. Each list item starts with the <li> tag.

The list items will be marked with bullets (small black circles) by default:

Example
<ul>
<li>Coffee</li>
<li>Tea</li>
<li>Milk</li>
</ul>

Try it Yourself »
2.3.2 Ordered HTML List

An ordered list starts with the <ol> tag. Each list item starts with the <li> tag.

The list items will be marked with numbers by default:

Example
<ol>
<li>Coffee</li>
<li>Tea</li>
<li>Milk</li>
</ol>
Try it Yourself »
2.3.3 HTML Description Lists

HTML also supports description lists.

A description list is a list of terms, with a description of each term.

The <dl> tag defines the description list, the <dt> tag defines the term (name), and
the <dd> tag describes each term:

Example
<dl>
<dt>Coffee</dt>
<dd>- black hot drink</dd>
<dt>Milk</dt>
<dd>- white cold drink</dd>
</dl>

2.4Table:Try it Yourself »

2.4.1 HTML Tables

HTML tables allow web developers to arrange data into rows and columns.

Example
Company Contact Country

Alfreds Futterkiste Maria Anders Germany

Centro comercial Moctezuma Francisco Chang Mexico

Ernst Handel Roland Mendel Austria

Island Trading Helen Bennett UK

Laughing Bacchus Winecellars Yoshi Tannamuri Canada

Magazzini Alimentari Riuniti Giovanni Rovelli Italy

2.5 Define an HTML Table


A table in HTML consists of table cells inside rows and columns

Example

A simple HTML table:

<table>
<tr>
<th>Company</th>
<th>Contact</th>
<th>Country</th>
</tr>
<tr>
<td>Alfreds Futterkiste</td>
<td>Maria Anders</td>
<td>Germany</td>
</tr>
<tr>
<td>Centro comercial Moctezuma</td>
<td>Francisco Chang</td>
<td>Mexico</td>
</tr>
</table>

2.6 Table Cells

Each table cell is defined by a <td> and a </td> tag.

td stands for table data.

Everything between <td> and </td> are the content of the table cell.

Example
<table>
<tr>
<td>Emil</td>
<td>Tobias</td>
<td>Linus</td>
</tr>
</table>

2.7 Table Rows


Each table row starts with a <tr> and end with a </tr> tag.

tr stands for table row.

Example
<table>
<tr>
<td>Emil</td>
<td>Tobias</td>
<td>Linus</td>
</tr>
<tr>
<td>16</td>
<td>14</td>
<td>10</td>
</tr>
</table>

You can have as many rows as you like in a table, just make sure that the number
of cells are the same in each row.

2.8 Table Headers

Sometimes you want your cells to be headers, in those cases use the <th> tag
instead of the <td> tag:

Example

Let the first row be table headers:

<table>
<tr>
<th>Person 1</th>
<th>Person 2</th>
<th>Person 3</th>
</tr>
<tr>
<td>Emil</td>
<td>Tobias</td>
<td>Linus</td>
</tr>
<tr>
<td>16</td>
<td>14</td>
<td>10</td>
</tr>
</table>

2.9 Images:
2.9.1 HTML Images Syntax

The HTML <img> tag is used to embed an image in a web page.

Images are not technically inserted into a web page; images are linked to web
pages. The <img> tag creates a holding space for the referenced image.

The <img> tag is empty, it contains attributes only, and does not have a closing tag.

The <img> tag has two required attributes:

 src - Specifies the path to the image


 alt - Specifies an alternate text for the image

Syntax
<img src="url" alt="alternatetext">

2.9.2 The src Attribute

The required src attribute specifies the path (URL) to the image.

Note: When a web page loads, it is the browser, at that moment, that gets the
image from a web server and inserts it into the page. Therefore, make sure that the
image actually stays in the same spot in relation to the web page, otherwise your
visitors will get a broken link icon. The broken link icon and the alt text are shown if
the browser cannot find the image.

Example
<img src="img_chania.jpg" alt="Flowers in Chania">

2.9.3 The alt Attribute

The required alt attribute provides an alternate text for an image, if the user for
some reason cannot view it (because of slow connection, an error in the src
attribute, or if the user uses a screen reader).

The value of the alt attribute should describe the image:

Example
<img src="img_chania.jpg" alt="Flowers in Chania">

Image Size - Width and Height

You can use the style attribute to specify the width and height of an image.

Example
<img src="img_girl.jpg" alt="Girl in a
jacket" style="width:500px;height:600px;">
2.10 Frames:

An HTML iframe is used to display a web page within a web page.


2.10.1HTML Iframe Syntax

The HTML <iframe> tag specifies an inline frame.

An inline frame is used to embed another document within the current HTML
document.

Syntax
<iframe src="url" title="description"></iframe>

Tip: It is a good practice to always include a title attribute for the <iframe>. This is
used by screen readers to read out what the content of the iframe is.
Iframe - Set Height and Width

Use the height and width attributes to specify the size of the iframe.

The height and width are specified in pixels by default:

Example
<iframe src="demo_iframe.htm" height="200" width="300" title="Iframe
Example"></iframe>

Or you can add the style attribute and use the CSS height and width properties:

Example
<iframe src="demo_iframe.htm" style="height:200px;width:300px;" title="Iframe
Example"></iframe>

Iframe - Remove the Border

By default, an iframe has a border around it.

To remove the border, add the style attribute and use the CSS border property:

Example
<iframe src="demo_iframe.htm" style="border:none;" title="Iframe
Example"></iframe>

With CSS, you can also change the size, style and color of the iframe's border:

Example
<iframe src="demo_iframe.htm" style="border:2px solid red;" title="Iframe
Example"></iframe>
Iframe - Target for a Link

An iframe can be used as the target frame for a link.

The target attribute of the link must refer to the name attribute of the iframe:

Example
<iframe src="demo_iframe.htm" name="iframe_a" title="Iframe
Example"></iframe>

<p><a href="https://www.w3schools.com" target="iframe_a">W3Schools.com</a></p


>

2.11Forms:

An HTML form is used to collect user input. The user input is most often sent to
a server for processing.

Example
First name:
John

Last name:
Doe

Submit
Try it Yourself »

The <form> Element

The HTML <form> element is used to create an HTML form for user input:

<form>
.
form elements
.
</form>

The <form> element is a container for different types of input elements, such as: text
fields, checkboxes, radio buttons, submit buttons, etc.
The <input> Element

The HTML <input> element is the most used form element.

An <input> element can be displayed in many ways, depending on the type attribute.

Here are some examples:

Type Description

<input type="text"> Displays a single-line text input field

<input type="radio"> Displays a radio button (for selecting one of


many choices)

<input type="checkbox"> Displays a checkbox (for selecting zero or


more of many choices)

<input type="submit"> Displays a submit button (for submitting


the form)

<input type="button"> Displays a clickable button


2.11Text Fields

The <input type="text"> defines a single-line input field for text input.

Example
A form with input fields for text:

<form>
<label for="fname">First name:</label><br>
<input type="text" id="fname" name="fname"><br>
<label for="lname">Last name:</label><br>
<input type="text" id="lname" name="lname">
</form>Try it Yourself »

This is how the HTML code above will be displayed in a browser:

First name:

Last name:

The <label> Element

Notice the use of the <label> element in the example above.

The <label> tag defines a label for many form elements.


The <label> element is useful for screen-reader users, because the screen-reader
will read out loud the label when the user focus on the input element.

The <label> element also help users who have difficulty clicking on very small
regions (such as radio buttons or checkboxes) - because when the user clicks the
text within the <label> element, it toggles the radio button/checkbox.

The for attribute of the <label> tag should be equal to the id attribute of
the <input> element to bind them together.

2.12 Radio Buttons

The <input type="radio"> defines a radio button.

Radio buttons let a user select ONE of a limited number of choices.

Example

A form with radio buttons:

<p>Choose your favorite Web language:</p>

<form>
<input type="radio" id="html" name="fav_language" value="HTML">
<label for="html">HTML</label><br>
<input type="radio" id="css" name="fav_language" value="CSS">
<label for="css">CSS</label><br>
<input type="radio" id="javascript" name="fav_language" value="JavaScript">
<label for="javascript">JavaScript</label>
</form>
This is how the HTML code above will be displayed in a browser:

Choose your favorite Web language:

HTML
CSS
JavaScript

Checkboxes

The <input type="checkbox"> defines a checkbox.

Checkboxes let a user select ZERO or MORE options of a limited number of choices.

Example

A form with checkboxes:

<form>
<input type="checkbox" id="vehicle1" name="vehicle1" value="Bike">
<label for="vehicle1"> I have a bike</label><br>
<input type="checkbox" id="vehicle2" name="vehicle2" value="Car">
<label for="vehicle2"> I have a car</label><br>
<input type="checkbox" id="vehicle3" name="vehicle3" value="Boat">
<label for="vehicle3"> I have a boat</label>
</form>
2.13 xml
XML stands for Extensible Markup Language. It is a text-based markup language derived from
Standard Generalized Markup Language (SGML).
XML tags identify the data and are used to store and organize the data, rather than specifying how
to display it like HTML tags, which are used to display the data. XML is not going to replace HTML
in the near future, but it introduces new possibilities by adopting many successful features of HTML.
There are three important characteristics of XML that make it useful in a variety of systems and
solutions −
 XML is extensible − XML allows you to create your own self-descriptive tags, or language,
that suits your application.
 XML carries the data, does not present it − XML allows you to store the data irrespective
of how it will be presented.
 XML is a public standard − XML was developed by an organization called the World Wide
Web Consortium (W3C) and is available as an open standard.

2.13.1 XML Usage


A short list of XML usage says it all −
 XML can work behind the scene to simplify the creation of HTML documents for large web
sites.
 XML can be used to exchange the information between organizations and systems.
 XML can be used for offloading and reloading of databases.
 XML can be used to store and arrange the data, which can customize your data handling
needs.
 XML can easily be merged with style sheets to create almost any desired output.
 Virtually, any type of data can be expressed as an XML document.

2.13.2 What is Markup?


XML is a markup language that defines set of rules for encoding documents in a format that is both
human-readable and machine-readable. So what exactly is a markup language? Markup is
information added to a document that enhances its meaning in certain ways, in that it identifies the
parts and how they relate to each other. More specifically, a markup language is a set of symbols
that can be placed in the text of a document to demarcate and label the parts of that document.
Following example shows how XML markup looks, when embedded in a piece of text −
<message>
<text>Hello, world!</text>
</message>

This snippet includes the markup symbols, or the tags such as <message>...</message> and
<text>... </text>. The tags <message> and </message> mark the start and the end of the XML code
fragment. The tags <text> and </text> surround the text Hello, world!.
Is XML a Programming Language?
A programming language consists of grammar rules and its own vocabulary which is used to create
computer programs. These programs instruct the computer to perform specific tasks. XML does not
qualify to be a programming language as it does not perform any computation or algorithms. It is
usually stored in a simple text file and is processed by special software that is capable of
interpreting XML.
XML - Syntax
In this chapter, we will discuss the simple syntax rules to write an XML document. Following is a
complete XML document −
<?xml version = "1.0"?>
<contact-info>
<name>Tanmay Patil</name>
<company>TutorialsPoint</company>
<phone>(011) 123-4567</phone>
</contact-info>

You can notice there are two kinds of information in the above example −
 Markup, like <contact-info>
 The text, or the character data, Tutorials Point and (040) 123-4567.
The following diagram depicts the syntax rules to write different types of markup and text in an XML
document.

Let us see each component of the above diagram in detail.


XML Declaration
The XML document can optionally have an XML declaration. It is written as follows −
<?xml version = "1.0" encoding = "UTF-8"?>

Where version is the XML version and encoding specifies the character encoding used in the
document.
Syntax Rules for XML Declaration
 The XML declaration is case sensitive and must begin with "<?xml>" where "xml" is written
in lower-case.
 If document contains XML declaration, then it strictly needs to be the first statement of the
XML document.
 The XML declaration strictly needs be the first statement in the XML document.
 An HTTP protocol can override the value of encoding that you put in the XML declaration.
Tags and Elements
An XML file is structured by several XML-elements, also called XML-nodes or XML-tags. The
names of XML-elements are enclosed in triangular brackets < > as shown below −
<element>
Syntax Rules for Tags and Elements
Element Syntax − Each XML-element needs to be closed either with start or with end elements as
shown below −
<element>....</element>

or in simple-cases, just this way −


<element/>

Nesting of Elements − An XML-element can contain multiple XML-elements as its children, but the
children elements must not overlap. i.e., an end tag of an element must have the same name as
that of the most recent unmatched start tag.
The Following example shows incorrect nested tags −
<?xml version = "1.0"?>
<contact-info>
<company>TutorialsPoint
</contact-info>
</company>

The Following example shows correct nested tags −


<?xml version = "1.0"?>
<contact-info>
<company>TutorialsPoint</company>
<contact-info>

Root Element − An XML document can have only one root element. For example, following is not a
correct XML document, because both the x and y elements occur at the top level without a root
element −
<x>...</x>
<y>...</y>

The Following example shows a correctly formed XML document −


<root>
<x>...</x>
<y>...</y>
</root>

Case Sensitivity − The names of XML-elements are case-sensitive. That means the name of the
start and the end elements need to be exactly in the same case.
For example, <contact-info> is different from <Contact-Info>
2.13.3 XML Attributes
An attribute specifies a single property for the element, using a name/value pair. An XML-element
can have one or more attributes. For example −
<a href = "http://www.tutorialspoint.com/">Tutorialspoint!</a>
Here href is the attribute name and http://www.tutorialspoint.com/ is attribute value.
Syntax Rules for XML Attributes
 Attribute names in XML (unlike HTML) are case sensitive. That is, HREF and href are
considered two different XML attributes.
 Same attribute cannot have two values in a syntax. The following example shows incorrect
syntax because the attribute b is specified twice


<a b = "x" c = "y" b = "z">....</a>

 Attribute names are defined without quotation marks, whereas attribute values must always
appear in quotation marks. Following example demonstrates incorrect xml syntax


<a b = x>....</a>

In the above syntax, the attribute value is not defined in quotation marks.
XML References
References usually allow you to add or include additional text or markup in an XML document.
References always begin with the symbol "&" which is a reserved character and end with the
symbol ";". XML has two types of references −
 Entity References − An entity reference contains a name between the start and the end
delimiters. For example &amp; where amp is name. The name refers to a predefined string
of text and/or markup.
 Character References − These contain references, such as &#65;, contains a hash mark
(“#”) followed by a number. The number always refers to the Unicode code of a character. In
this case, 65 refers to alphabet "A".
XML Text
The names of XML-elements and XML-attributes are case-sensitive, which means the name of start
and end elements need to be written in the same case. To avoid character encoding problems, all
XML files should be saved as Unicode UTF-8 or UTF-16 files.
Whitespace characters like blanks, tabs and line-breaks between XML-elements and between the
XML-attributes will be ignored.
Some characters are reserved by the XML syntax itself. Hence, they cannot be used directly. To
use them, some replacement-entities are used, which are listed below −

Not Allowed Character Replacement Entity Character Description

< &lt; less than

> &gt; greater than

& &amp; ampersand

' &apos; apostrophe

" &quot; quotation mark

XML - Documents
An XML document is a basic unit of XML information composed of elements and other markup in an
orderly package. An XML document can contains wide variety of data. For example, database of
numbers, numbers representing molecular structure or a mathematical equation.
XML Document Example
A simple document is shown in the following example −
<?xml version = "1.0"?>
<contact-info>
<name>Tanmay Patil</name>
<company>TutorialsPoint</company>
<phone>(011) 123-4567</phone>
</contact-info>

The following image depicts the parts of XML document.

Document Prolog Section


Document Prolog comes at the top of the document, before the root element. This section
contains −

 XML declaration
 Document type declaration
You can learn more about XML declaration in this chapter − XML Declaration
Document Elements Section
Document Elements are the building blocks of XML. These divide the document into a hierarchy of
sections, each serving a specific purpose. You can separate a document into multiple sections so
that they can be rendered differently, or used by a search engine. The elements can be containers,
with a combination of text and other elements.
You can learn more about XML elements in this chapter − XML Elements

2.13.4 XML - Declaration


This chapter covers XML declaration in detail. XML declaration contains details that prepare an
XML processor to parse the XML document. It is optional, but when used, it must appear in the first
line of the XML document.
Syntax
Following syntax shows XML declaration −
<?xml
version = "version_number"
encoding = "encoding_declaration"
standalone = "standalone_status"
?>

Each parameter consists of a parameter name, an equals sign (=), and parameter value inside a
quote. Following table shows the above syntax in detail −

Parameter Parameter_value Parameter_description

Version 1.0 Specifies the version of the XML standard


used.

Encoding UTF-8, UTF-16, ISO- It defines the character encoding used in the
10646-UCS-2, ISO- document. UTF-8 is the default encoding
10646-UCS-4, ISO-8859- used.
1 to ISO-8859-9, ISO-
2022-JP, Shift_JIS, EUC-
JP

Standalone yes or no It informs the parser whether the document


relies on the information from an external
source, such as external document type
definition (DTD), for its content. The default
value is set to no. Setting it to yes tells the
processor there are no external declarations
required for parsing the document.

Rules
An XML declaration should abide with the following rules −
 If the XML declaration is present in the XML, it must be placed as the first line in the XML
document.
 If the XML declaration is included, it must contain version number attribute.
 The Parameter names and values are case-sensitive.
 The names are always in lower case.
 The order of placing the parameters is important. The correct order is: version, encoding and
standalone.
 Either single or double quotes may be used.
 The XML declaration has no closing tag i.e. </?xml>
XML Declaration Examples
Following are few examples of XML declarations −
XML declaration with no parameters −
<?xml >
XML declaration with version definition −
<?xml version = "1.0">
XML declaration with all parameters defined −
<?xml version = "1.0" encoding = "UTF-8" standalone = "no" ?>
XML declaration with all parameters defined in single quotes −
<?xml version = '1.0' encoding = 'iso-8859-1' standalone = 'no' ?>
2.13.5 XML - Tags
Let us learn about one of the most important part of XML, the XML tags. XML tags form the
foundation of XML. They define the scope of an element in XML. They can also be used to insert
comments, declare settings required for parsing the environment, and to insert special instructions.
We can broadly categorize XML tags as follows −
Start Tag
The beginning of every non-empty XML element is marked by a start-tag. Following is an example
of start-tag −
<address>
End Tag
Every element that has a start tag should end with an end-tag. Following is an example of end-tag −
</address>
Note, that the end tags include a solidus ("/") before the name of an element.
Empty Tag
The text that appears between start-tag and end-tag is called content. An element which has no
content is termed as empty. An empty element can be represented in two ways as follows −
A start-tag immediately followed by an end-tag as shown below −
<hr></hr>

A complete empty-element tag is as shown below −


<hr />

Empty-element tags may be used for any element which has no content.
XML Tags Rules
Following are the rules that need to be followed to use XML tags −
Rule 1
XML tags are case-sensitive. Following line of code is an example of wrong syntax </Address>,
because of the case difference in two tags, which is treated as erroneous syntax in XML.
<address>This is wrong syntax</Address>

Following code shows a correct way, where we use the same case to name the start and the end
tag.
<address>This is correct syntax</address>
Rule 2
XML tags must be closed in an appropriate order, i.e., an XML tag opened inside another element
must be closed before the outer element is closed. For example −
<outer_element>
<internal_element>
This tag is closed before the outer_element
</internal_element>
</outer_element>
2.13.5 XML - Elements
XML elements can be defined as building blocks of an XML. Elements can behave as containers to
hold text, elements, attributes, media objects or all of these.
Each XML document contains one or more elements, the scope of which are either delimited by
start and end tags, or for empty elements, by an empty-element tag.
Syntax
Following is the syntax to write an XML element −
<element-name attribute1 attribute2>
....content
</element-name>

where,
 element-name is the name of the element. The name its case in the start and end tags must
match.
 attribute1, attribute2 are attributes of the element separated by white spaces. An attribute
defines a property of the element. It associates a name with a value, which is a string of
characters. An attribute is written as −
name = "value"
name is followed by an = sign and a string value inside double(" ") or single(' ') quotes.
Empty Element
An empty element (element with no content) has following syntax −
<name attribute1 attribute2.../>

Following is an example of an XML document using various XML element −


<?xml version = "1.0"?>
<contact-info>
<address category = "residence">
<name>Tanmay Patil</name>
<company>TutorialsPoint</company>
<phone>(011) 123-4567</phone>
</address>
</contact-info>
XML Elements Rules
Following rules are required to be followed for XML elements −
 An element name can contain any alphanumeric characters. The only punctuation mark
allowed in names are the hyphen (-), under-score (_) and period (.).
 Names are case sensitive. For example, Address, address, and ADDRESS are different
names.
 Start and end tags of an element must be identical.
 An element, which is a container, can contain text or elements as seen in the above
example.
XML - Attributes
This chapter describes the XML attributes. Attributes are part of XML elements. An element can
have multiple unique attributes. Attribute gives more information about XML elements. To be more
precise, they define properties of elements. An XML attribute is always a name-value pair.
Syntax
An XML attribute has the following syntax −
<element-name attribute1 attribute2 >
....content..
< /element-name>

where attribute1 and attribute2 has the following form −


name = "value"
value has to be in double (" ") or single (' ') quotes. Here, attribute1 and attribute2 are unique
attribute labels.
Attributes are used to add a unique label to an element, place the label in a category, add a
Boolean flag, or otherwise associate it with some string of data. Following example demonstrates
the use of attributes −
<?xml version = "1.0" encoding = "UTF-8"?>
<!DOCTYPE garden [
<!ELEMENT garden (plants)*>
<!ELEMENT plants (#PCDATA)>
<!ATTLIST plants category CDATA #REQUIRED>
]>

<garden>
<plants category = "flowers" />
<plants category = "shrubs">
</plants>
</garden>

Attributes are used to distinguish among elements of the same name, when you do not want to
create a new element for every situation. Hence, the use of an attribute can add a little more detail
in differentiating two or more similar elements.
In the above example, we have categorized the plants by including attribute category and assigning
different values to each of the elements. Hence, we have two categories of plants, one flowers and
other shrubs. Thus, we have two plant elements with different attributes.
You can also observe that we have declared this attribute at the beginning of XML.
Attribute Types
Following table lists the type of attributes −

Attribute Type Description

StringType It takes any literal string as a value. CDATA is a StringType. CDATA is


character data. This means, any string of non-markup characters is a
legal part of the attribute.

This is a more constrained type. The validity constraints noted in the


grammar are applied after the attribute value is normalized. The
TokenizedType attributes are given as −
 ID − It is used to specify the element as unique.
 IDREF − It is used to reference an ID that has been named for
TokenizedType another element.
 IDREFS − It is used to reference all IDs of an element.
 ENTITY − It indicates that the attribute will represent an
external entity in the document.
 ENTITIES − It indicates that the attribute will represent
external entities in the document.
 NMTOKEN − It is similar to CDATA with restrictions on what
data can be part of the attribute.
 NMTOKENS − It is similar to CDATA with restrictions on what
data can be part of the attribute.

This has a list of predefined values in its declaration. out of which, it


must assign one value. There are two types of enumerated attribute

 NotationType − It declares that an element will be referenced
EnumeratedType
to a NOTATION declared somewhere else in the XML
document.
 Enumeration − Enumeration allows you to define a specific
list of values that the attribute value must match.

Element Attribute Rules


Following are the rules that need to be followed for attributes −
 An attribute name must not appear more than once in the same start-tag or empty-element
tag.
 An attribute must be declared in the Document Type Definition (DTD) using an Attribute-List
Declaration.
 Attribute values must not contain direct or indirect entity references to external entities.
 The replacement text of any entity referred to directly or indirectly in an attribute value must
not contain a less than sign (<)

2.13.6 XML - Comments


This chapter explains how comments work in XML documents. XML comments are similar to
HTML comments. The comments are added as notes or lines for understanding the purpose of an
XML code.
Comments can be used to include related links, information, and terms. They are visible only in the
source code; not in the XML code. Comments may appear anywhere in XML code.
Syntax
XML comment has the following syntax −
<!--Your comment-->

A comment starts with <!-- and ends with -->. You can add textual notes as comments between the
characters. You must not nest one comment inside the other.
Example
Following example demonstrates the use of comments in XML document −
<?xml version = "1.0" encoding = "UTF-8" ?>
<!--Students grades are uploaded by months-->
<class_list>
<student>
<name>Tanmay</name>
<grade>A</grade>
</student>
</class_list>

Any text between <!-- and --> characters is considered as a comment.


XML Comments Rules
Following rules should be followed for XML comments −

 Comments cannot appear before XML declaration.


 Comments may appear anywhere in a document.
 Comments must not appear within attribute values.
 Comments cannot be nested inside the other comments.
2.13.6 XML - Character Entities
This chapter describes the XML Character Entities. Before we understand the Character Entities,
let us first understand what an XML entity is.
As put by W3 Consortium the definition of an entity is as follows −
"The document entity serves as the root of the entity tree and a starting-point for an XML processor".
This means, entities are the placeholders in XML. These can be declared in the document prolog or
in a DTD. There are different types of entities and in this chapter we will discuss Character Entity.
Both, HTML and XML, have some symbols reserved for their use, which cannot be used as content
in XML code. For example, < and > signs are used for opening and closing XML tags. To display
these special characters, the character entities are used.
There are few special characters or symbols which are not available to be typed directly from the
keyboard. Character Entities can also be used to display those symbols/special characters.
Types of Character Entities
There are three types of character entities −

 Predefined Character Entities


 Numbered Character Entities
 Named Character Entities
Predefined Character Entities
They are introduced to avoid the ambiguity while using some symbols. For example, an ambiguity is
observed when less than ( < ) or greater than ( > ) symbol is used with the angle tag (<>). Character
entities are basically used to delimit tags in XML. Following is a list of pre-defined character entities
from XML specification. These can be used to express characters without ambiguity.
 Ampersand − &amp;
 Single quote − &apos;
 Greater than − &gt;
 Less than − &lt;
 Double quote − &quot;
Numeric Character Entities
The numeric reference is used to refer to a character entity. Numeric reference can either be in
decimal or hexadecimal format. As there are thousands of numeric references available, these are
a bit hard to remember. Numeric reference refers to the character by its number in the Unicode
character set.
General syntax for decimal numeric reference is −
&# decimal number ;
General syntax for hexadecimal numeric reference is −
&#x Hexadecimal number ;
The following table lists some predefined character entities with their numeric values −

Entity name Character Decimal reference Hexadecimal reference

quot " &#34; &#x22;

amp & &#38; &#x26;

apos ' &#39; &#x27;

lt < &#60; &#x3C;

gt > &#62; &#x3E;

Named Character Entity


As it is hard to remember the numeric characters, the most preferred type of character entity is the
named character entity. Here, each entity is identified with a name.
For example −

 'Aacute' represents capital character with acute accent.

 'ugrave' represents the small with grave accent.

2.13.7 XML - CDATA Sections


In this chapter, we will discuss XML CDATA section. The term CDATA means, Character Data.
CDATA is defined as blocks of text that are not parsed by the parser, but are otherwise recognized
as markup.
The predefined entities such as &lt;, &gt;, and &amp; require typing and are generally difficult to
read in the markup. In such cases, CDATA section can be used. By using CDATA section, you are
commanding the parser that the particular section of the document contains no markup and should
be treated as regular text.
Syntax
Following is the syntax for CDATA section −
<![CDATA[
characters with markup
]]>

The above syntax is composed of three sections −


 CDATA Start section − CDATA begins with the nine-character delimiter <![CDATA[
 CDATA End section − CDATA section ends with ]]> delimiter.
 CData section − Characters between these two enclosures are interpreted as characters,
and not as markup. This section may contain markup characters (<, >, and &), but they are
ignored by the XML processor.
Example
The following markup code shows an example of CDATA. Here, each character written inside the
CDATA section is ignored by the parser.
<script>
<![CDATA[
<message> Welcome to TutorialsPoint </message>
]] >
</script >

In the above syntax, everything between <message> and </message> is treated as character data
and not as markup.
CDATA Rules
The given rules are required to be followed for XML CDATA −

 CDATA cannot contain the string "]]>" anywhere in the XML document.
 Nesting is not allowed in CDATA section.
2.13.7 XML - WhiteSpaces
In this chapter, we will discuss whitespace handling in XML documents. Whitespace is a collection
of spaces, tabs, and newlines. They are generally used to make a document more readable.
XML document contains two types of whitespaces - Significant Whitespace and Insignificant
Whitespace. Both are explained below with examples.
Significant Whitespace
A significant Whitespace occurs within the element which contains text and markup present
together. For example −
<name>TanmayPatil</name>

and
<name>Tanmay Patil</name>

The above two elements are different because of the space between Tanmay and Patil. Any
program reading this element in an XML file is obliged to maintain the distinction.
Insignificant Whitespace
Insignificant whitespace means the space where only element content is allowed. For example −
<address.category = "residence">
or
<address....category = "..residence">

The above examples are same. Here, the space is represented by dots (.). In the above example,
the space between address and category is insignificant.
A special attribute named xml:space may be attached to an element. This indicates that
whitespace should not be removed for that element by the application. You can set this attribute
to default or preserve as shown in the following example −
<!ATTLIST address xml:space (default|preserve) 'preserve'>
Where,
 The value default signals that the default whitespace processing modes of an application
are acceptable for this element.
 The value preserve indicates the application to preserve all the whitespaces.

2.13.8 XML - Processing


This chapter describes the Processing Instructions (PIs). As defined by the XML 1.0
Recommendation,
"Processing instructions (PIs) allow documents to contain instructions for applications. PIs are not
part of the character data of the document, but MUST be passed through to the application.
Processing instructions (PIs) can be used to pass information to applications. PIs can appear
anywhere in the document outside the markup. They can appear in the prolog, including the
document type definition (DTD), in textual content, or after the document.
Syntax
Following is the syntax of PI −
<?target instructions?>
Where
 target − Identifies the application to which the instruction is directed.
 instruction − A character that describes the information for the application to process.
A PI starts with a special tag <? and ends with ?>. Processing of the contents ends immediately
after the string ?> is encountered.
Example
PIs are rarely used. They are mostly used to link XML document to a style sheet. Following is an
example −
<?xml-stylesheet href = "tutorialspointstyle.css" type = "text/css"?>
Here, the target is xml-
stylesheet. href="tutorialspointstyle.css" and type="text/css" are data or instructions the target
application will use at the time of processing the given XML document.
In this case, a browser recognizes the target by indicating that the XML should be transformed
before being shown; the first attribute states that the type of the transform is XSL and the second
attribute points to its location.
Processing Instructions Rules
A PI can contain any data except the combination ?>, which is interpreted as the closing delimiter.
Here are two examples of valid PIs −
<?welcome to pg = 10 of tutorials point?>

<?welcome?>
XML - Encoding
Encoding is the process of converting unicode characters into their equivalent binary
representation. When the XML processor reads an XML document, it encodes the document
depending on the type of encoding. Hence, we need to specify the type of encoding in the XML
declaration.
Encoding Types
There are mainly two types of encoding −

 UTF-8
 UTF-16
UTF stands for UCS Transformation Format, and UCS itself means Universal Character Set. The
number 8 or 16 refers to the number of bits used to represent a character. They are either 8(1 to 4
bytes) or 16(2 or 4 bytes). For the documents without encoding information, UTF-8 is set by default.
Syntax
Encoding type is included in the prolog section of the XML document. The syntax for UTF-8
encoding is as follows −
<?xml version = "1.0" encoding = "UTF-8" standalone = "no" ?>
The syntax for UTF-16 encoding is as follows −
<?xml version = "1.0" encoding = "UTF-16" standalone = "no" ?>
Example
Following example shows the declaration of encoding −
<?xml version = "1.0" encoding = "UTF-8" standalone = "no" ?>
<contact-info>
<name>Tanmay Patil</name>
<company>TutorialsPoint</company>
<phone>(011) 123-4567</phone>
</contact-info>

In the above example encoding="UTF-8", specifies that 8-bits are used to represent the
characters. To represent 16-bit characters, UTF-16 encoding can be used.
The XML files encoded with UTF-8 tend to be smaller in size than those encoded with UTF-16
format.
XML - Validation
Validation is a process by which an XML document is validated. An XML document is said to be
valid if its contents match with the elements, attributes and associated document type
declaration(DTD), and if the document complies with the constraints expressed in it. Validation is
dealt in two ways by the XML parser. They are −

 Well-formed XML document


 Valid XML document
Well-formed XML Document
An XML document is said to be well-formed if it adheres to the following rules −
 Non DTD XML files must use the predefined character entities for amp(&), apos(single
quote), gt(>), lt(<), quot(double quote).
 It must follow the ordering of the tag. i.e., the inner tag must be closed before closing the
outer tag.
 Each of its opening tags must have a closing tag or it must be a self ending
tag.(<title>....</title> or <title/>).
 It must have only one attribute in a start tag, which needs to be quoted.
 amp(&), apos(single quote), gt(>), lt(<), quot(double quote) entities other than these must
be declared.
Example
Following is an example of a well-formed XML document −
<?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>Tanmay Patil</name>
<company>TutorialsPoint</company>
<phone>(011) 123-4567</phone>
</address>

The above example is said to be well-formed as −


 It defines the type of document. Here, the document type is element type.
 It includes a root element named as address.
 Each of the child elements among name, company and phone is enclosed in its self
explanatory tag.
 Order of the tags is maintained.
Valid XML Document
If an XML document is well-formed and has an associated Document Type Declaration (DTD), then
it is said to be a valid XML document. We will study more about DTD in the chapter XML - DTDs.
2.13.9 XML - DTDs
The XML Document Type Declaration, commonly known as DTD, is a way to describe XML
language precisely. DTDs check vocabulary and validity of the structure of XML documents against
grammatical rules of appropriate XML language.
An XML DTD can be either specified inside the document, or it can be kept in a separate document
and then liked separately.
Syntax
Basic syntax of a DTD is as follows −
<!DOCTYPE element DTD identifier
[
declaration1
declaration2
........
]>

In the above syntax,


 The DTD starts with <!DOCTYPE delimiter.
 An element tells the parser to parse the document from the specified root element.
 DTD identifier is an identifier for the document type definition, which may be the path to a
file on the system or URL to a file on the internet. If the DTD is pointing to external path, it is
called External Subset.
 The square brackets [ ] enclose an optional list of entity declarations called Internal Subset.
Internal DTD
A DTD is referred to as an internal DTD if elements are declared within the XML files. To refer it as
internal DTD, standalone attribute in XML declaration must be set to yes. This means, the
declaration works independent of an external source.
Syntax
Following is the syntax of internal DTD −
<!DOCTYPE root-element [element-declarations]>
where root-element is the name of root element and element-declarations is where you declare the
elements.
Example
Following is a simple 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>Tanmay Patil</name>
<company>TutorialsPoint</company>
<phone>(011) 123-4567</phone>
</address>

Let us go through the above code −


Start Declaration − Begin the XML declaration with the following statement.
<?xml version = "1.0" encoding = "UTF-8" standalone = "yes" ?>
DTD − Immediately after the XML header, the document type declaration follows, commonly
referred to as the DOCTYPE −
<!DOCTYPE address [
The DOCTYPE declaration has an exclamation mark (!) at the start of the element name. The
DOCTYPE informs the parser that a DTD is associated with this XML document.
DTD Body − The DOCTYPE declaration is followed by body of the DTD, where you declare
elements, attributes, entities, and notations.
<!ELEMENT address (name,company,phone)>
<!ELEMENT name (#PCDATA)>
<!ELEMENT company (#PCDATA)>
<!ELEMENT phone_no (#PCDATA)>

Several elements are declared here that make up the vocabulary of the <name> document.
<!ELEMENT name (#PCDATA)> defines the element name to be of type "#PCDATA". Here
#PCDATA means parse-able text data.
End Declaration − Finally, the declaration section of the DTD is closed using a closing bracket and
a closing angle bracket (]>). This effectively ends the definition, and thereafter, the XML document
follows immediately.
Rules
 The document type declaration must appear at the start of the document (preceded only by
the XML header) − it is not permitted anywhere else within the document.
 Similar to the DOCTYPE declaration, the element declarations must start with an
exclamation mark.
 The Name in the document type declaration must match the element type of the root
element.
External DTD
In external DTD elements are declared outside the XML file. They are accessed by specifying the
system attributes which may be either the legal .dtd file or a valid URL. To refer it as external
DTD, standalone attribute in the XML declaration must be set as no. This means, declaration
includes information from the external source.
Syntax
Following is the syntax for external DTD −
<!DOCTYPE root-element SYSTEM "file-name">
where file-name is the file with .dtd extension.
Example
The following example shows external DTD usage −
<?xml version = "1.0" encoding = "UTF-8" standalone = "no" ?>
<!DOCTYPE address SYSTEM "address.dtd">
<address>
<name>Tanmay Patil</name>
<company>TutorialsPoint</company>
<phone>(011) 123-4567</phone>
</address>

The content of the DTD file address.dtd is as shown −


<!ELEMENT address (name,company,phone)>
<!ELEMENT name (#PCDATA)>
<!ELEMENT company (#PCDATA)>
<!ELEMENT phone (#PCDATA)>
Types
You can refer to an external DTD by using either system identifiers or public identifiers.
System Identifiers
A system identifier enables you to specify the location of an external file containing DTD
declarations. Syntax is as follows −
<!DOCTYPE name SYSTEM "address.dtd" [...]>
As you can see, it contains keyword SYSTEM and a URI reference pointing to the location of the
document.
Public Identifiers
Public identifiers provide a mechanism to locate DTD resources and is written as follows −
<!DOCTYPE name PUBLIC "-//Beginning XML//DTD Address Example//EN">
As you can see, it begins with keyword PUBLIC, followed by a specialized identifier. Public
identifiers are used to identify an entry in a catalog. Public identifiers can follow any format,
however, a commonly used format is called Formal Public Identifiers, or FPIs.
XML - Schemas
XML Schema is commonly known as XML Schema Definition (XSD). It is used to describe and
validate the structure and the content of XML data. XML schema defines the elements, attributes
and data types. Schema element supports Namespaces. It is similar to a database schema that
describes the data in a database.
Syntax
You need to declare a schema in your XML document as follows −
Example
The following example shows how to use schema −
<?xml version = "1.0" encoding = "UTF-8"?>
<xs:schema xmlns:xs = "http://www.w3.org/2001/XMLSchema">
<xs:element name = "contact">
<xs:complexType>
<xs:sequence>
<xs:element name = "name" type = "xs:string" />
<xs:element name = "company" type = "xs:string" />
<xs:element name = "phone" type = "xs:int" />
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:schema>

The basic idea behind XML Schemas is that they describe the legitimate format that an XML
document can take.
Elements
As we saw in the XML - Elements chapter, elements are the building blocks of XML document. An
element can be defined within an XSD as follows −
<xs:element name = "x" type = "y"/>
Definition Types
You can define XML schema elements in the following ways −
Simple Type
Simple type element is used only in the context of the text. Some of the predefined simple types
are: xs:integer, xs:boolean, xs:string, xs:date. For example −
<xs:element name = "phone_number" type = "xs:int" />
Complex Type
A complex type is a container for other element definitions. This allows you to specify which child
elements an element can contain and to provide some structure within your XML documents. For
example −
<xs:element name = "Address">
<xs:complexType>
<xs:sequence>
<xs:element name = "name" type = "xs:string" />
<xs:element name = "company" type = "xs:string" />
<xs:element name = "phone" type = "xs:int" />
</xs:sequence>
</xs:complexType>
</xs:element>

In the above example, Address element consists of child elements. This is a container for
other <xs:element> definitions, that allows to build a simple hierarchy of elements in the XML
document.
Global Types
With the global type, you can define a single type in your document, which can be used by all other
references. For example, suppose you want to generalize the person and company for different
addresses of the company. In such case, you can define a general type as follows −
<xs:element name = "AddressType">
<xs:complexType>
<xs:sequence>
<xs:element name = "name" type = "xs:string" />
<xs:element name = "company" type = "xs:string" />
</xs:sequence>
</xs:complexType>
</xs:element>
Now let us use this type in our example as follows −
<xs:element name = "Address1">
<xs:complexType>
<xs:sequence>
<xs:element name = "address" type = "AddressType" />
<xs:element name = "phone1" type = "xs:int" />
</xs:sequence>
</xs:complexType>
</xs:element>

<xs:element name = "Address2">


<xs:complexType>
<xs:sequence>
<xs:element name = "address" type = "AddressType" />
<xs:element name = "phone2" type = "xs:int" />
</xs:sequence>
</xs:complexType>
</xs:element>

Instead of having to define the name and the company twice (once for Address1 and once
for Address2), we now have a single definition. This makes maintenance simpler, i.e., if you decide
to add "Postcode" elements to the address, you need to add them at just one place.
Attributes
Attributes in XSD provide extra information within an element. Attributes
have name and type property as shown below −
<xs:attribute name = "x" type = "y"/>
XML - Tree Structure
An XML document is always descriptive. The tree structure is often referred to as XML Tree and
plays an important role to describe any XML document easily.
The tree structure contains root (parent) elements, child elements and so on. By using tree
structure, you can get to know all succeeding branches and sub-branches starting from the root.
The parsing starts at the root, then moves down the first branch to an element, take the first branch
from there, and so on to the leaf nodes.
Example
Following example demonstrates simple XML tree structure −
<?xml version = "1.0"?>
<Company>
<Employee>
<FirstName>Tanmay</FirstName>
<LastName>Patil</LastName>
<ContactNo>1234567890</ContactNo>
<Email>tanmaypatil@xyz.com</Email>
<Address>
<City>Bangalore</City>
<State>Karnataka</State>
<Zip>560212</Zip>
</Address>
</Employee>
</Company>
Following tree structure represents the above XML document −

In the above diagram, there is a root element named as <company>. Inside that, there is one more
element <Employee>. Inside the employee element, there are five branches named <FirstName>,
<LastName>, <ContactNo>, <Email>, and <Address>. Inside the <Address> element, there are
three sub-branches, named <City> <State> and <Zip>.

2.13.10 XML - DOM


The Document Object Model (DOM) is the foundation of XML. XML documents have a hierarchy
of informational units called nodes; DOM is a way of describing those nodes and the relationships
between them.
A DOM document is a collection of nodes or pieces of information organized in a hierarchy. This
hierarchy allows a developer to navigate through the tree looking for specific information. Because it
is based on a hierarchy of information, the DOM is said to be tree based.
The XML DOM, on the other hand, also provides an API that allows a developer to add, edit, move,
or remove nodes in the tree at any point in order to create an application.
Example
The following example (sample.htm) parses an XML document ("address.xml") into an XML DOM
object and then extracts some information from it with JavaScript −
<!DOCTYPE html>
<html>
<body>
<h1>TutorialsPoint DOM example </h1>
<div>
<b>Name:</b> <span id = "name"></span><br>
<b>Company:</b> <span id = "company"></span><br>
<b>Phone:</b> <span id = "phone"></span>
</div>
<script>
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.open("GET","/xml/address.xml",false);
xmlhttp.send();
xmlDoc = xmlhttp.responseXML;

document.getElementById("name").innerHTML=
xmlDoc.getElementsByTagName("name")[0].childNodes[0].nodeValue;
document.getElementById("company").innerHTML=
xmlDoc.getElementsByTagName("company")[0].childNodes[0].nodeValue;
document.getElementById("phone").innerHTML=
xmlDoc.getElementsByTagName("phone")[0].childNodes[0].nodeValue;
</script>
</body>
</html>

Contents of address.xml are as follows −


<?xml version = "1.0"?>
<contact-info>
<name>Tanmay Patil</name>
<company>TutorialsPoint</company>
<phone>(011) 123-4567</phone>
</contact-info>

Now let us keep these two files sample.htm and address.xml in the same directory /xml and
execute the sample.htm file by opening it in any browser. This should produce the following output.

Here, you can see how each of the child nodes is extracted to display their values.

2.13.11 XML - Namespaces


A Namespace is a set of unique names. Namespace is a mechanisms by which element and
attribute name can be assigned to a group. The Namespace is identified by URI(Uniform Resource
Identifiers).
Namespace Declaration
A Namespace is declared using reserved attributes. Such an attribute name must either
be xmlns or begin with xmlns: shown as below −
<element xmlns:name = "URL">
Syntax
 The Namespace starts with the keyword xmlns.
 The word name is the Namespace prefix.
 The URL is the Namespace identifier.
Example
Namespace affects only a limited area in the document. An element containing the declaration and
all of its descendants are in the scope of the Namespace. Following is a simple example of XML
Namespace −
<?xml version = "1.0" encoding = "UTF-8"?>
<cont:contact xmlns:cont = "www.tutorialspoint.com/profile">
<cont:name>Tanmay Patil</cont:name>
<cont:company>TutorialsPoint</cont:company>
<cont:phone>(011) 123-4567</cont:phone>
</cont:contact>

Here, the Namespace prefix is cont, and the Namespace identifier (URI)
as www.tutorialspoint.com/profile. This means, the element names and attribute names with
the cont prefix (including the contact element), all belong to
the www.tutorialspoint.com/profile namespace.

2.13.12 XML - Databases


XML Database is used to store huge amount of information in the XML format. As the use of XML
is increasing in every field, it is required to have a secured place to store the XML documents. The
data stored in the database can be queried using XQuery, serialized, and exported into a desired
format.
XML Database Types
There are two major types of XML databases −

 XML- enabled
 Native XML (NXD)
XML - Enabled Database
XML enabled database is nothing but the extension provided for the conversion of XML document.
This is a relational database, where data is stored in tables consisting of rows and columns. The
tables contain set of records, which in turn consist of fields.
Native XML Database
Native XML database is based on the container rather than table format. It can store large amount
of XML document and data. Native XML database is queried by the XPath-expressions.
Native XML database has an advantage over the XML-enabled database. It is highly capable to
store, query and maintain the XML document than XML-enabled database.
Example
Following example demonstrates XML database −
<?xml version = "1.0"?>
<contact-info>
<contact1>
<name>Tanmay Patil</name>
<company>TutorialsPoint</company>
<phone>(011) 123-4567</phone>
</contact1>

<contact2>
<name>Manisha Patil</name>
<company>TutorialsPoint</company>
<phone>(011) 789-4567</phone>
</contact2>
</contact-info>
Here, a table of contacts is created that holds the records of contacts (contact1 and contact2),
which in turn consists of three entities − name, company and phone.
XML - Viewers
This chapter describes THE various methods to view an XML document. An XML document can
be viewed using a simple text editor or any browser. Most of the major browsers supports XML.
XML files can be opened in the browser by just double-clicking the XML document (if it is a local
file) or by typing the URL path in the address bar (if the file is located on the server), in the same
way as we open other files in the browser. XML files are saved with a ".xml" extension.
Let us explore various methods by which we can view an XML file. Following example (sample.xml)
is used to view all the sections of this chapter.
<?xml version = "1.0"?>
<contact-info>
<name>Tanmay Patil</name>
<company>TutorialsPoint</company>
<phone>(011) 123-4567</phone>
</contact-info>
Text Editors
Any simple text editor such as Notepad, TextPad, or TextEdit can be used to create or view an XML
document as shown below −

Firefox Browser
Open the above XML code in Chrome by double-clicking the file. The XML code displays coding
with color, which makes the code readable. It shows plus(+) or minus (-) sign at the left side in the
XML element. When we click the minus sign (-), the code hides. When we click the plus (+) sign,
the code lines get expanded. The output in Firefox is as shown below −
Chrome Browser
Open the above XML code in Chrome browser. The code gets displayed as shown below −

Errors in XML Document


If your XML code has some tags missing, then a message is displayed in the browser. Let us try to
open the following XML file in Chrome −
<?xml version = "1.0"?>
<contact-info>
<name>Tanmay Patil</name>
<company>TutorialsPoint</company>
<phone>(011) 123-4567</phone>
</contact-info>

In the above code, the start and end tags are not matching (refer the contact_info tag), hence an
error message is displayed by the browser as shown below −

XML - Editors
XML Editor is a markup language editor. The XML documents can be edited or created using
existing editors such as Notepad, WordPad, or any similar text editor. You can also find a
professional XML editor online or for downloading, which has more powerful editing features such
as −

 It automatically closes the tags that are left open.


 It strictly checks syntax.
 It highlights XML syntax with colour for increased readability.
 It helps you write a valid XML code.
 It provides automatic verification of XML documents against DTDs and Schemas.
Open Source XML Editors
Following are some open source XML editors −
 Online XML Editor − This is a light weight XML editor which you can use online.
 Xerlin − Xerlin is an open source XML editor for Java 2 platform released under an Apache
license. It is a Java based XML modelling application, for creating and editing XML files
easily.
 CAM - Content Assembly Mechanism − CAM XML Editor tool comes with XML+JSON+SQL
Open-XDX sponsored by Oracle.

2.13.13 XML - Parsers


XML parser is a software library or a package that provides interface for client applications to work
with XML documents. It checks for proper format of the XML document and may also validate the
XML documents. Modern day browsers have built-in XML parsers.
Following diagram shows how XML parser interacts with XML document −

The goal of a parser is to transform XML into a readable code.


To ease the process of parsing, some commercial products are available that facilitate the
breakdown of XML document and yield more reliable results.
Some commonly used parsers are listed below −
 MSXML (Microsoft Core XML Services) − This is a standard set of XML tools from
Microsoft that includes a parser.
 System.Xml.XmlDocument − This class is part of .NET library, which contains a number of
different classes related to working with XML.
 Java built-in parser − The Java library has its own parser. The library is designed such that
you can replace the built-in parser with an external implementation such as Xerces from
Apache or Saxon.
 Saxon − Saxon offers tools for parsing, transforming, and querying XML.
 Xerces − Xerces is implemented in Java and is developed by the famous open source
Apache Software Foundation.

2.13.14 XML - Processors


When a software program reads an XML document and takes actions accordingly, this is
called processing the XML. Any program that can read and process XML documents is known as
an XML processor. An XML processor reads the XML file and turns it into in-memory structures that
the rest of the program can access.
The most fundamental XML processor reads an XML document and converts it into an internal
representation for other programs or subroutines to use. This is called a parser, and it is an
important component of every XML processing program.
Processor involves processing the instructions, that can be studied in the chapter Processing
Instruction.
Types
XML processors are classified as validating or non-validating types, depending on whether or not
they check XML documents for validity. A processor that discovers a validity error must be able to
report it, but may continue with normal processing.
A few validating parsers are − xml4c (IBM, in C++), xml4j (IBM, in Java), MSXML (Microsoft, in
Java), TclXML (TCL), xmlproc (Python), XML::Parser (Perl), Java Project X (Sun, in Java).
A few non-validating parsers are − OpenXML (Java), Lark (Java), xp (Java), AElfred (Java),
expat (C), XParse (JavaScript), xmllib (Python).

2.14 CSS

Cascading Style Sheets, fondly referred to as CSS, is a simple design language intended to simplify the
process of making web pages presentable.
CSS handles the look and feel part of a web page. Using CSS, you can control the color of thetext, the style of
fonts, the spacing between paragraphs, how columns are sized and laid out,what background images or colors
are used, as well as a variety of other effects.
CSS is easy to learn and understand but it provides a powerful control over the presentation of an HTML
document. Most commonly, CSS is combined with the markup languages HTML or XHTML.

2.14.1 Advantages of CSS

CSS saves time - You can write CSS once and then reuse the same sheet in multipleHTML pages. You can
define a style for each HTML element and apply it to as many web pages as you want.
Pages load faster - If you are using CSS, you do not need to write HTML tag attributes every time. Just write
one CSS rule of a tag and apply it to all the occurrences of that tag. So, less code means faster download times.
Easy maintenance - To make a global change, simply change the style, and all the elements in all the web
pages will be updated automatically.
Superior styles to HTML - CSS has a much wider array of attributes than HTML, soyou can give a far better
look to your HTML page in comparison to HTML attributes.
Multiple Device Compatibility - Style sheets allow content to be optimized for morethan one type of device.
By using the same HTML document, different versions of a website can be presented for handheld devices
such as PDAs and cellphones or for printing.
Global web standards – Now HTML attributes are being deprecated and it is being recommended to use CSS.
So it’s a good idea to start using CSS in all the HTML pagesto make them compatible with future browsers.
2.14.2 Who Creates andMaintains CSS?
CSS is created and maintained through a group of people within the W3C called the CSS Working Group. The
CSS Working Group creates documents called specifications. When a specification has been discussed and
officially ratified by the W3C members, it becomes a recommendation.
These ratified specifications are called recommendations because the W3C has no control overthe actual
implementation of the language. Independent companies and organizations createthat software.
NOTE: The World Wide Web Consortium or W3C is a group that makes recommendations about how the
Internet works and how it should evolve.

CSSVersions
Cascading Style Sheets level 1 (CSS1) came out of W3C as a recommendation in December 1996. This
version describes the CSS language as well as a simple visual formatting model for all the HTML tags.
CSS2 became a W3C recommendation in May 1998 and builds on CSS1. This version adds support for media-
specific style sheets e.g. printers and aural devices, downloadable fonts, element positioning and tables.
A CSS comprises of style rules that are interpreted by the browser and then applied to thecorresponding
elements in your document. A style rule is made of three parts:
Selector: A selector is an HTML tag at which a style will be applied. This could be anytag like <h1> or <table> etc.
Property: A property is a type of attribute of HTML tag. Put simply, all the HTMLattributes are converted into CSS
properties. They could be color, border, etc.
Value: Values are assigned to properties. For example, color property can have thevalue either red or #F1F1F1 etc.
You can put CSS Style Rule Syntax as follows:

selector { property: value }


Example: You can define a table border as follows:

table{ border :1px solid #C00; }

Here table is a selector and border is a property and the given value 1px solid #C00 is thevalue of that
property.
You can define selectors in various simple ways based on your comfort. Let me put theseselectors one by
one.

TheTypeSelectors
This is the same selector we have seen above. Again, one more example to give a color to alllevel 1 headings:

h1 {
color: #36CFFF;
}

The Universal Selectors


Rather than selecting elements of a specific type, the universal selector quite simply matchesthe name of any
element type:

This rule renders the content of every element in our document in black.

TheDescendant Selectors
Suppose you want to apply a style rule to a particular element only when it lies inside a particular element. As
given in the following example, the style rule will apply to <em> element only when it lies inside the <ul> tag.

ul em {
color: #000000;
}

2.14.3 The Class Selectors


You can define style rules based on the class attribute of the elements. All the elements havingthat class will be
formatted according to the defined rule.

.black {
color: #000000;

}
This rule renders the content in black for every element with class attribute set to black in ourdocument. You can
make it a bit more particular. For example:

h1.black {
color: #000000;
}
This rule renders the content in black for only <h1> elements with class attribute set to black.
You can apply more than one class selectors to a given element. Consider the followingexample:

<p class="center bold">


This para will be styled by the classes center and bold.

</p>

TheIDSelectors
You can define style rules based on the id attribute of the elements. All the elements havingthat id will be
formatted according to the defined rule.

#black {
color: #000000;
}

This rule renders the content in black for every element with id attribute set to black in ourdocument. You
can make it a bit more particular. For example:
h1#black {
color: #000000;
}

This rule renders the content in black for only <h1> elements with id attribute set to black.
The true power of id selectors is when they are used as the foundation for descendantselectors. For
example:

#black h2 {
color: #000000;
}

In this example, all level 2 headings will be displayed in black color when those headings willlie within tags
having id attribute set to black.

2.14.4 The Child Selectors


You have seen the descendant selectors. There is one more type of selector, which is verysimilar to
descendants but have different functionality. Consider the following example:

body > p {
color: #000000;
}

This rule will render all the paragraphs in black if they are a direct child of the <body> element. Other
paragraphs put inside other elements like <div> or <td> would not have anyeffect of this rule.

2.14.5 TheAttribute Selectors


You can also apply styles to HTML elements with particular attributes. The style rule below will match all the
input elements having a type attribute with a value of text:

input[type="text"]{
color: #000000;
}

The advantage to this method is that the <input type="submit" /> element is unaffected, andthe color applied
only to the desired text fields.
There are following rules applied to attribute selector.
p[lang] - Selects all paragraph elements with a lang attribute.
p[lang="fr"] - Selects all paragraph elements whose lang attribute has a value ofexactly "fr".
p[lang~="fr"] - Selects all paragraph elements whose lang attribute contains theword "fr".
p[lang|="en"] - Selects all paragraph elements whose lang attribute contains valuesthat are exactly "en", or begin with "en-
".
2.14.6 Multiple Style Rules
You may need to define multiple style rules for a single element. You can define these rules to combine
multiple properties and corresponding values into a single block as defined in thefollowing example:

h1 {
color: #36C;
font-weight:
normal; letter-
spacing: .4em;
margin-bottom: 1em;
text-transform: lowercase;
}

Here all the property and value pairs are separated by a semicolon (;). You can keep themin a
single line or multiple lines. For better readability, we keep them in separate lines.
For a while, don't bother about the properties mentioned in the above block. These propertieswill be explained in
the coming chapters and you can find the complete detail about propertiesin CSS References.

2.14.7 Grouping Selectors


You can apply a style to many selectors if you like. Just separate the selectors with a comma,as given in the
following example:

h1, h2, h3
{ color:
#36C;
font-weight:
normal; letter-
spacing: .4em;
margin-bottom: 1em;
text-transform: lowercase;
}

This define style rule will be applicable to h1, h2 and h3 element as well. The order of the listis irrelevant. All
the elements in the selector will have the corresponding declarations appliedto them.
You can combine the various class selectors together as shown below:
#content, #footer, #supplement {
position:
absolute; left:
510px; width:
200px;
}

There are four ways to associate styles with your HTML document. Most commonly used methods are inline
CSS and External CSS.

2.14.8 Embedded CSS -The <style> Element


You can put your CSS rules into an HTML document using the <style> element. This tag is placed inside the
<head>...</head> tags. Rules defined using this syntax will be applied to all the elements available in the
document. Here is the generic syntax:

<head>
<style type="text/css"
media="..."> Style Rules
............
</style>
</head>

Attributes

Attributes associated with <style> elements are:


Attribute Value Description

type text/css Specifies the style sheet language as a content-type(MIME type).


This is a required attribute.

media screentty Specifies the device, the document will be displayedon. Default
tv projection handheld value is all. This is an optional attribute.
print braille
aural all

Example
Following is an example of embed CSS based on the above syntax:

<head>
<style type="text/css"
media="all"> h1{
color: #36C;
}
</style>
</head>

2.14.9 Inline CSS - The style Attribute


You can use style attribute of any HTML element to define style rules. These rules will beapplied to that
element only. Here is the generic syntax:

<element style="...style rules ">

Attributes

Attribute Value Description

style stylerules The value of style attribute is a combination of style


declarationsseparated by semicolon (;).

Example
Following is the example of inline CSS based on the above syntax:

<h1 style ="color:#36C;"> This is inline CSS </h1>


It will produce the following result:

This is inline CSS


ExternalCSS- The<link>Element

The <link> element can be used to include an external stylesheet file in your HTML document.
An external style sheet is a separate text file with .css extension. You define all the Style rules within this text
file and then you can include this file in any HTML document using <link>element.
Here is the generic syntax of including external CSS file:

<head>
<link type="text/css" href="..." media="..." />
</head>

Attributes
Attributes associated with <style> elements are:
Attribute Value Description

type text/css Specifies the style sheet language as a content-type (MIMEtype).


This attribute is required.

href URL Specifies the style sheet file having Style rules. This attributeis a
required.

media screentty Specifies the device the document will be displayed on. Defaultvalue is
tv projection all. This is an optional attribute.
handheld
print braille

auralall

Example
Consider a simple style sheet file with a name mystyle.css having the following rules:

h1, h2, h3
{ color:
#36C;
font-weight:
normal; letter-
spacing: .4em;
margin-bottom: 1em;
text-transform: lowercase;
}
<head>
Now you can include this file mystyle.css in any HTML document as follows:

<head>
<link type="text/css" href="mystyle.css" media="all" />
</head>

ImportedCSS-@importRule

@import is used to import an external stylesheet in a manner similar to the <link> element.Here is the generic
syntax of @import rule.

<head>
<@import "URL";
</head>
Here URL is the URL of the style sheet file having style rules. You can use another syntax aswell:
<@import url("URL");
</head>

Example
Following is the example showing you how to import a style sheet file into an HTML document:

<head>
@import "mystyle.css";
</head>

2.14.10 CSS Rules Overriding


We have discussed four ways to include style sheet rules in an HTML document. Here is the rule to override
any Style Sheet Rule.
Any inline style sheet takes the highest priority. So, it will override any rule defined in
<style>...</style> tags or the rules defined in any external style sheet file.
Any rule defined in <style>...</style> tags will override the rules defined in anyexternal style sheet file.
Any rule defined in the external style sheet file takes the lowest priority, and the rulesdefined in this file will be applied
only when the above two rules are not applicable.

2.14.11 Handling Old Browsers


There are still many old browsers who do not support CSS. So, we should take care while writing our
Embedded CSS in an HTML document. The following snippet shows how to use comment tags to hide CSS
from older browsers:

<style type="text/css">
<!--
body, td {
color: blue;
}
-->
</style>
2.14.13 CSS Comments
Many times, you may need to put additional comments in your style sheet blocks. So, it isvery easy to
comment any part in the style sheet. You can simply put your comments inside
/*.....this is a comment in style sheet */.
You can use /* ....*/ to comment multi-line blocks in similar way you do in C and C++programming
languages.

Example

/* This is an external style sheet file */


h1, h2, h3
{ color:
#36C;
font-weight:
normal; letter-
spacing: .4em;
margin-bottom: 1em;
text-transform: lowercase;
}
/* end of style rules. */

2.14.14 CSS ─ MEASUREMENT UNITS


Before we start the actual exercise, we would like to give a brief idea about the CSS Measurement Units. CSS
supports a number of measurements including absolute units such as inches, centimeters, points, and so on, as
well as relative measures such as percentages and em units. You need these values while specifying various
measurements in your Style rules e.g. border="1px solid red".
We have listed out all the CSS Measurement Units along with proper Examples:

Unit Description Example

Defines a measurement as a percentage relative to


another value, typically anenclosing element. p {font-size: 16pt;
%
line-height:125%;}
cm Defines a measurement in centimeters. div {margin-bottom: 2cm;}

A relative measurement for the height ofa font in em


spaces. Because an em unitis equivalent to the size of a
given font, ifyou assign a font to 12pt, each "em" unit
em would be 12pt; thus, 2em would be 24pt. p {letter-spacing: 7em;}

This value defines a measurement relative to a font's


x-height. The x-heightis determined by the height of
the font's lowercase letter x. p {font-size: 24pt;
ex
line-height:3ex;}

in Defines a measurement in inches. p {word-spacing: .15in;}


Defines a measurement in points. A pointis defined as
pt 1/72nd of an inch. body {font-size: 18pt;}
mm Defines a measurement in millimeters. p {word-spacing: 15mm;}

px Defines a measurement in screen pixels. p {padding: 25px;}


Defines a measurement in picas. A pica isequivalent to
12 points; thus, there are 6picas per inch.
pc p {font-size: 20pc;}

2.14.15 CSS ─ COLORS

CSS uses color values to specify a color. Typically, these are used to set a color either for theforeground of an
element (i.e., its text) or for the background of the element. They can alsobe used to affect the color of borders
and other decorative effects.
You can specify your color values in various formats. Following table lists all the possible formats:
Format Syntax Example

Hex Code #RRGGBB p{color:#FF0000;}

Short Hex Code #RGB p{color:#6A7;}

RGB % rgb(rrr%,ggg%,bbb%) p{color:rgb(50%,50%,50%);}

RGB Absolute rgb(rrr,ggg,bbb) p{color:rgb(0,0,255);}

keyword aqua, black, etc. p{color:teal;}


These formats are explained in more detail in the following sections:
2.14.16 CSS Colors - Hex Codes
A hexadecimal is a 6 digit representation of a color. The first two digits (RR) represent a redvalue, the next two
are a green value (GG), and the last are the blue value (BB).
A hexadecimal value can be taken from any graphics software like Adobe Photoshop, Jasc Paintshop Pro, or
even using Advanced Paint Brush.
Each hexadecimal code will be preceded by a pound or hash sign ‘#’. Following are the examples to use
Hexadecimal notation.

Color Color HEX

#000000

#FF0000

#00FF00

#0000FF

#FFFF00

#00FFFF

#FF00FF

#C0C0C0

#FFFFFF

2.14.17 CSS Colors - Short Hex Codes


This is a shorter form of the six-digit notation. In this format, each digit is replicated to arriveat an equivalent
six-digit value. For example: #6A7 becomes #66AA77.
A hexadecimal value can be taken from any graphics software like Adobe Photoshop, JascPaintshop Pro or
even using Advanced Paint Brush.
Each hexadecimal code will be preceded by a pound or hash sign #. Following are theexamples to use
the Hexadecimal notation.
Unit 3
Java script
JavaScript is the world's most popular programming language.

JavaScript is the programming language of the Web.

JavaScript is easy to learn.

This tutorial will teach you JavaScript from basic to advanced.

With our "Try it Yourself" editor, you can edit the source code and view the result.

3.1 JavaScript Can Change HTML Content

One of many JavaScript HTML methods is getElementById().

The example below "finds" an HTML element (with id="demo"), and changes the
element content (innerHTML) to "Hello JavaScript":

Example

document.getElementById("demo").innerHTML = "Hello JavaScript";

3.2 JavaScript Can Change HTML Attribute Values

In this example JavaScript changes the value of the src (source) attribute of an <img>
tag:

3.2.1 The Light Bulb


Turn on the light Turn off the light

3.3 JavaScript Statements

Example

let x, y, z; // Statement 1
x = 5; // Statement 2
y = 6; // Statement 3
z = x + y; // Statement 4

3.3.1 JavaScript Programs

A computer program is a list of "instructions" to be "executed" by a computer.

In a programming language, these programming instructions are called statements.

A JavaScript program is a list of programming statements.

In HTML, JavaScript programs are executed by the web browser.


3.4 JavaScript Statements

JavaScript statements are composed of:

Values, Operators, Expressions, Keywords, and Comments.

This statement tells the browser to write "Hello Dolly." inside an HTML element with
id="demo":

Example

document.getElementById("demo").innerHTML = "Hello Dolly.";

Most JavaScript programs contain many JavaScript statements.

The statements are executed, one by one, in the same order as they are written.

JavaScript programs (and JavaScript statements) are often called JavaScript code.

3.5 Semicolons ;
Semicolons separate JavaScript statements.

Add a semicolon at the end of each executable statement:

Examples

let a, b, c; // Declare 3 variables


a = 5; // Assign the value 5 to a
b = 6; // Assign the value 6 to b
c = a + b; // Assign the sum of a and b to c

When separated by semicolons, multiple statements on one line are allowed:

a = 5; b = 6; c = a + b;
On the web, you might see examples without semicolons.
Ending statements with semicolon is not required, but highly recommended.

3.6 JavaScript White Space

JavaScript ignores multiple spaces. You can add white space to your script to make it
more readable.

The following lines are equivalent:

let person = "Hege";


let person="Hege";

A good practice is to put spaces around operators ( = + - * / ):

let x = y + z;

3.7 JavaScript Line Length and Line Breaks

For best readability, programmers often like to avoid code lines longer than 80
characters.

If a JavaScript statement does not fit on one line, the best place to break it is after an
operator:

Example

document.getElementById("demo").innerHTML =
"Hello Dolly!";
3.8 JavaScript Code Blocks

JavaScript statements can be grouped together in code blocks, inside curly brackets
{...}.

The purpose of code blocks is to define statements to be executed together.

One place you will find statements grouped together in blocks, is in JavaScript
functions:

Example

function myFunction() {
document.getElementById("demo1").innerHTML = "Hello Dolly!";
document.getElementById("demo2").innerHTML = "How are you?";
}

In this tutorial we use 2 spaces of indentation for code blocks.


You will learn more about functions later in this tutorial.

3.9 JavaScript Keywords

JavaScript statements often start with a keyword to identify the JavaScript action to be
performed.

Our Reserved Words Reference lists all JavaScript keywords.

Here is a list of some of the keywords you will learn about in this tutorial:

Keyword Description

var Declares a variable


let Declares a block variable

const Declares a block constant

if Marks a block of statements to be


executed on a condition

switch Marks a block of statements to be


executed in different cases

for Marks a block of statements to be


executed in a loop
function Declares a function

return Exits a function

try Implements error handling to a block of


statements

JavaScript keywords are reserved words. Reserved words cannot be used as names for
variables.

3.10 JavaScript Functions

A JavaScript function is a block of code designed to perform a particular task.

A JavaScript function is executed when "something" invokes it (calls it).

Example

function myFunction(p1, p2) {


return p1 * p2; // The function returns the product of p1 and p2
}
3.11 JavaScript Function Syntax

A JavaScript function is defined with the function keyword, followed by a name,


followed by parentheses ().

Function names can contain letters, digits, underscores, and dollar signs (same rules as
variables).

The parentheses may include parameter names separated by commas:


(parameter1, parameter2, ...)

The code to be executed, by the function, is placed inside curly brackets: {}

function name(parameter1, parameter2, parameter3) {


// code to be executed
}

Function parameters are listed inside the parentheses () in the function definition.

Function arguments are the values received by the function when it is invoked.

Inside the function, the arguments (the parameters) behave as local variables.

A Function is much the same as a Procedure or a Subroutine, in other programming


languages.

3.12 Function Invocation

The code inside the function will execute when "something" invokes (calls) the
function:

 When an event occurs (when a user clicks a button)

 When it is invoked (called) from JavaScript code

 Automatically (self invoked)

You will learn a lot more about function invocation later in this tutorial.
3.13 Function Return

When JavaScript reaches a return statement, the function will stop executing.

If the function was invoked from a statement, JavaScript will "return" to execute the
code after the invoking statement.

Functions often compute a return value. The return value is "returned" back to the
"caller":

Example

Calculate the product of two numbers, and return the result:

let x = myFunction(4, 3); // Function is called, return value will end up in x

function myFunction(a, b) {
return a * b; // Function returns the product of a and b
}

The result in x will be:

12

Why Functions?

You can reuse code: Define the code once, and use it many times.

You can use the same code many times with different arguments, to produce different
results.

Example

Convert Fahrenheit to Celsius:

function toCelsius(fahrenheit) {
return (5/9) * (fahrenheit-32);
}
document.getElementById("demo").innerHTML = toCelsius(77);

3.13.1 The () Operator Invokes the Function

Using the example above, toCelsius refers to the function object, and toCelsius()
refers to the function result.

Accessing a function without () will return the function object instead of the function
result.

Example

function toCelsius(fahrenheit) {
return (5/9) * (fahrenheit-32);
}
document.getElementById("demo").innerHTML = toCelsius;

3.13.2 Functions Used as Variable Values

Functions can be used the same way as you use variables, in all types of formulas,
assignments, and calculations.

Example

Instead of using a variable to store the return value of a function:

let x = toCelsius(77);
let text = "The temperature is " + x + " Celsius";

You can use the function directly, as a variable value:

let text = "The temperature is " + toCelsius(77) + " Celsius";


You will learn a lot more about functions later in this tutorial.

3.14 Local Variables

Variables declared within a JavaScript function, become LOCAL to the function.

Local variables can only be accessed from within the function.

Example

// code here can NOT use carName

function myFunction() {
let carName = "Volvo";
// code here CAN use carName
}

// code here can NOT use carName

Since local variables are only recognized inside their functions, variables with the same
name can be used in different functions.

Local variables are created when a function starts, and deleted when the function is
completed.

Execute the function named myFunction.

function myFunction() {
alert("Hello World!");
}
;

JavaScript Objects
3.15 Real Life Objects, Properties, and Methods

In real life, a car is an object.

A car has properties like weight and color, and methods like start and stop:

Object Properties Methods

car.name = Fiat car.start()

car.model = 500 car.drive()

car.weight = car.brake()
850kg
car.stop()
car.color = white

All cars have the same properties, but the property values differ from car to car.

All cars have the same methods, but the methods are performed at different times.

JavaScript Objects

You have already learned that JavaScript variables are containers for data values.

This code assigns a simple value (Fiat) to a variable named car:

let car = "Fiat";


Objects are variables too. But objects can contain many values.

This code assigns many values (Fiat, 500, white) to a variable named car:

const car = {type:"Fiat", model:"500", color:"white"};

The values are written as name:value pairs (name and value separated by a colon).

It is a common practice to declare objects with the const keyword.

Learn more about using const with objects in the chapter: JS Const.

3.16 Object Definition

You define (and create) a JavaScript object with an object literal:

Example

const person = {firstName:"John", lastName:"Doe", age:50, eyeColor:"blue"};

Spaces and line breaks are not important. An object definition can span multiple lines:

Example

const person = {
firstName: "John",
lastName: "Doe",
age: 50,
eyeColor: "blue"
};

3.17 Object Properties


The name:values pairs in JavaScript objects are called properties:
Property Property Value

firstName John

lastName Doe

age 50

eyeColor blue

3.18 Accessing Object Properties

You can access object properties in two ways:

objectName.propertyName

or

objectName["propertyName"]
Example1

person.lastName;

Example2

person["lastName"];

JavaScript objects are containers for named values called properties.

3.19 Object Methods

Objects can also have methods.

Methods are actions that can be performed on objects.

Methods are stored in properties as function definitions.

Property Property Value

firstName John

lastName Doe
age 50

eyeColor blue

fullName function() {return this.firstName + " "


+ this.lastName;}

A method is a function stored as a property.

Example

const person = {
firstName: "John",
lastName : "Doe",
id : 5566,
fullName : function() {
return this.firstName + " " + this.lastName;
}
};

In the example above, this refers to the person object.

I.E. this.firstName means the firstName property of this.

I.E. this.firstName means the firstName property of person.


What is this?

In JavaScript, the this keyword refers to an object.

Which object depends on how this is being invoked (used or called).

The this keyword refers to different objects depending on how it is used:

In an object method, this refers to the object.

Alone, this refers to the global object.

In a function, this refers to the global object.

In a function, in strict mode, this is undefined.

In an event, this refers to the element that received the event.


Methods like call(), apply(), and bind() can refer this to any object.
Note

this is not a variable. It is a keyword. You cannot change the value of this.

The this Keyword

In a function definition, this refers to the "owner" of the function.

In the example above, this is the person object that "owns" the fullName function.

In other words, this.firstName means the firstName property of this object.

Accessing Object Methods

You access an object method with the following syntax:

objectName.methodName()

Example

name = person.fullName();

If you access a method without the () parentheses, it will return the function
definition:

Example

name = person.fullName;
Do Not Declare Strings, Numbers, and Booleans as Objects!

When a JavaScript variable is declared with the keyword "new", the variable is created
as an object:

x = new String(); // Declares x as a String object


y = new Number(); // Declares y as a Number object
z = new Boolean(); // Declares z as a Boolean object

Avoid String, Number, and Boolean objects. They complicate your code and slow down
execution speed.

You will learn more about objects later in this tutorial.

Alert "John" by extracting information from the person object.

const person = {
firstName: "John",
lastName: "Doe"
};

alert();

3.20 AJAX Introduction

AJAX is a developer's dream, because you can:

 Read data from a web server - after the page has loaded
 Update a web page without reloading the page
 Send data to a web server - in the background
3.20.1 AJAX Example
Let AJAX change this text
Change Content

3.20.2 AJAX Example Explained


HTML Page
<!DOCTYPE html>
<html>
<body>

<div id="demo">
<h2>Let AJAX change this text</h2>
<button type="button" onclick="loadDoc()">Change Content</button>
</div>

</body>
</html>

The HTML page contains a <div> section and a <button>.

The <div> section is used to display information from a server.

The <button> calls a function (if it is clicked).

The function requests data from a web server and displays it:

Function loadDoc()

function loadDoc() {
const xhttp = new XMLHttpRequest();
xhttp.onload = function() {
document.getElementById("demo").innerHTML = this.responseText;
}
xhttp.open("GET", "ajax_info.txt", true);
xhttp.send();
}

What is AJAX?

AJAX = Asynchronous JavaScript And XML.


AJAX is not a programming language.

AJAX just uses a combination of:

 A browser built-in XMLHttpRequest object (to request data from a web server)

 JavaScript and HTML DOM (to display or use the data)

AJAX is a misleading name. AJAX applications might use XML to transport data, but it is
equally common to transport data as plain text or JSON text.

AJAX allows web pages to be updated asynchronously by exchanging data with a web
server behind the scenes. This means that it is possible to update parts of a web page,
without reloading the whole page.

3.20.3 How AJAX Works

 1. An event occurs in a web page (the page is loaded, a button is clicked)

 2. An XMLHttpRequest object is created by JavaScript

 3. The XMLHttpRequest object sends a request to a web server

 4. The server processes the request

 5. The server sends a response back to the web page

 6. The response is read by JavaScript

 7. Proper action (like page update) is performed by JavaScript


Modern Browsers (Fetch API)

Modern Browsers can use Fetch API instead of the XMLHttpRequest Object.

The Fetch API interface allows web browser to make HTTP requests to web servers.

If you use the XMLHttpRequest Object, Fetch can do the same in a simpler way.

AJAX - The XMLHttpRequest Object

The keystone of AJAX is the XMLHttpRequest object.

1. Create an XMLHttpRequest object


2. Define a callback function
3. Open the XMLHttpRequest object
4. Send a Request to a server
3.20.3 The XMLHttpRequest Object

All modern browsers support the XMLHttpRequest object.

The XMLHttpRequest object can be used to exchange data with a web server behind the
scenes. This means that it is possible to update parts of a web page, without reloading
the whole page.

Create an XMLHttpRequest Object

All modern browsers (Chrome, Firefox, IE, Edge, Safari, Opera) have a built-in
XMLHttpRequest object.

Syntax for creating an XMLHttpRequest object:

variable = new XMLHttpRequest();


3.21 Define a Callback Function

A callback function is a function passed as a parameter to another function.

In this case, the callback function should contain the code to execute when the
response is ready.

xhttp.onload = function() {
// What to do when the response is ready
}

3.21.1 Send a Request

To send a request to a server, you can use the open() and send() methods of the
XMLHttpRequest object:

xhttp.open("GET", "ajax_info.txt");
xhttp.send();

Example

// Create an XMLHttpRequest object


const xhttp = new XMLHttpRequest();

// Define a callback function


xhttp.onload = function() {
// Here you can use the Data
}

// Send a request
xhttp.open("GET", "ajax_info.txt");
xhttp.send();

3.22 Access Across Domains

For security reasons, modern browsers do not allow access across domains.
This means that both the web page and the XML file it tries to load, must be located on
the same server.

The examples on W3Schools all open XML files located on the W3Schools domain.

If you want to use the example above on one of your own web pages, the XML files you
load must be located on your own server.

3.22.1 XMLHttpRequest Object Methods


Method Description

new XMLHttpRequest() Creates a new XMLHttpRequest object

abort() Cancels the current request

getAllResponseHeaders() Returns header information


getResponseHeader() Returns specific header information

open(method, url, async, Specifies the request


user, psw)
method: the request type GET or POST
url: the file location
async: true (asynchronous) or false (synchronous)
user: optional user name
psw: optional password

send() Sends the request to the server


Used for GET requests

send(string) Sends the request to the server.


Used for POST requests

setRequestHeader() Adds a label/value pair to the header to be sent


3.22.2 XMLHttpRequest Object Properties
Property Description

onload Defines a function to be called when the request is


recieved (loaded)

onreadystatechange Defines a function to be called when the readyState


property changes

readyState Holds the status of the XMLHttpRequest.


0: request not initialized
1: server connection established
2: request received
3: processing request
4: request finished and response is ready

responseText Returns the response data as a string


responseXML Returns the response data as XML data

status Returns the status-number of a request


200: "OK"
403: "Forbidden"
404: "Not Found"
For a complete list go to the Http Messages
Reference

statusText Returns the status-text (e.g. "OK" or "Not Found")

3.23 The onload Property

With the XMLHttpRequest object you can define a callback function to be executed when
the request receives an answer.

The function is defined in the onload property of the XMLHttpRequest object:

Example

xhttp.onload = function() {
document.getElementById("demo").innerHTML = this.responseText;
}
xhttp.open("GET", "ajax_info.txt");
xhttp.send();

Try it Yourself »
3.24 Multiple Callback Functions

If you have more than one AJAX task in a website, you should create one function for
executing the XMLHttpRequest object, and one callback function for each AJAX task.

The function call should contain the URL and what function to call when the response is
ready.

Example

loadDoc("url-1", myFunction1);

loadDoc("url-2", myFunction2);

function loadDoc(url, cFunction) {


const xhttp = new XMLHttpRequest();
xhttp.onload = function() {cFunction(this);}
xhttp.open("GET", url);
xhttp.send();
}

function myFunction1(xhttp) {
// action goes here
}
function myFunction2(xhttp) {
// action goes here
}

The onreadystatechange Property

The readyState property holds the status of the XMLHttpRequest.

The onreadystatechange property defines a callback function to be executed when the


readyState changes.

The status property and the statusText properties hold the status of the
XMLHttpRequest object.

Property Description
onreadystatechange Defines a function to be called when
the readyState property changes

readyState Holds the status of the


XMLHttpRequest.
0: request not initialized
1: server connection established
2: request received
3: processing request
4: request finished and response is
ready

status 200: "OK"


403: "Forbidden"
404: "Page not found"
For a complete list go to the Http
Messages Reference

statusText Returns the status-text (e.g. "OK" or


"Not Found")

The onreadystatechange function is called every time the readyState changes.

When readyState is 4 and status is 200, the response is ready:

Example
function loadDoc() {
const 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");
xhttp.send();
}

3.25 AJAX - XMLHttpRequest

The XMLHttpRequest object is used to request data from a server.

Send a Request To a Server

To send a request to a server, we use the open() and send() methods of the
XMLHttpRequest object:

xhttp.open("GET", "ajax_info.txt", true);


xhttp.send();

Method Description

open(method, url, async) Specifies the type of request

method: the type of request: GET or


POST
url: the server (file) location
async: true (asynchronous) or false
(synchronous)
send() Sends the request to the server (used
for GET)

send(string) Sends the request to the server (used


for POST)

The URL - a File on a Server

The url parameter of the open() method, is an address to a file on a server:

xhttp.open("GET", "ajax_test.asp", true);

The file can be any kind of file, like .txt and .xml, or server scripting files like .asp and
.php (which can perform actions on the server before sending the response back).

Asynchronous - True or False?

Server requests should be sent asynchronously.

The async parameter of the open() method should be set to true:

xhttp.open("GET", "ajax_test.asp", true);

By sending asynchronously, the JavaScript does not have to wait for the server
response, but can instead:

 execute other scripts while waiting for server response

 deal with the response after the response is ready

The default value for the async parameter is async = true.

You can safely remove the third parameter from your code.
Synchronous XMLHttpRequest (async = false) is not recommended because the
JavaScript will stop executing until the server response is ready. If the server is busy or
slow, the application will hang or stop.

3.26 GET or POST

GET is simpler and faster than POST, and can be used in most cases.

However, always use POST requests when:

 A cached file is not an option (update a file or database on the server).

 Sending a large amount of data to the server (POST has no size limitations).

 Sending user input (which can contain unknown characters), POST is more robust
and secure than GET.

GET Requests

A simple GET request:

Example

xhttp.open("GET", "demo_get.asp");
xhttp.send();

In the example above, you may get a cached result. To avoid this, add a unique ID to
the URL:

Example

xhttp.open("GET", "demo_get.asp?t=" + Math.random());


xhttp.send();

If you want to send information with the GET method, add the information to the URL:

Example
xhttp.open("GET", "demo_get2.asp?fname=Henry&lname=Ford");
xhttp.send();

How the server uses the input and how the server responds to a request, is explained in
a later chapter.

POST Requests
A simple POST request:

Example

xhttp.open("POST", "demo_post.asp");
xhttp.send();

To POST data like an HTML form, add an HTTP header with setRequestHeader(). Specify
the data you want to send in the send() method:

Example

xhttp.open("POST", "ajax_test.asp");
xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhttp.send("fname=Henry&lname=Ford");

Method Description

setRequestHeader(header, value) Adds HTTP headers to the request

header: specifies the header name


value: specifies the header value
3.27 Synchronous Request

To execute a synchronous request, change the third parameter in the open() method to
false:

xhttp.open("GET", "ajax_info.txt", false);

Sometimes async = false are used for quick testing. You will also find synchronous
requests in older JavaScript code.

Since the code will wait for server completion, there is no need for an
onreadystatechange function:

Example

xhttp.open("GET", "ajax_info.txt", false);


xhttp.send();
document.getElementById("demo").innerHTML = xhttp.responseText;

Synchronous XMLHttpRequest (async = false) is not recommended because the


JavaScript will stop executing until the server response is ready. If the server is busy or
slow, the application will hang or stop.

Modern developer tools are encouraged to warn about using synchronous requests and
may throw an InvalidAccessError exception when it occurs.

AJAX - Server Response

Server Response Properties


Property Description

responseText get the response data as a string


responseXML get the response data as XML data

The response Text Property

The responseText property returns the server response as a JavaScript string, and you
can use it accordingly:

Example

document.getElementById("demo").innerHTML = xhttp.responseText;

The responseXML Property

The XMLHttpRequest object has an in-built XML parser.

The responseXML property returns the server response as an XML DOM object.

Using this property you can parse the response as an XML DOM object:

Example

Request the file cd_catalog.xml and parse the response:

const xmlDoc = xhttp.responseXML;


const x = xmlDoc.getElementsByTagName("ARTIST");

let txt = "";


for (let i = 0; i < x.length; i++) {
txt += x[i].childNodes[0].nodeValue + "<br>";
}
document.getElementById("demo").innerHTML = txt;

xhttp.open("GET", "cd_catalog.xml");
xhttp.send();
Server Response Methods
Method Description

getResponseHeader() Returns specific header information


from the server resource

getAllResponseHeaders() Returns all the header information from


the server resource

The getAllResponseHeaders() Method

The getAllResponseHeaders() method returns all header information from the server
response.

Example

const xhttp = new XMLHttpRequest();


xhttp.onload = function() {
document.getElementById("demo").innerHTML =
this.getAllResponseHeaders();
}
xhttp.open("GET", "ajax_info.txt");
xhttp.send();

The getResponseHeader() Method


The getResponseHeader() method returns specific header information from the server
response.

Example

const xhttp = new XMLHttpRequest();


xhttp.onload = function() {
document.getElementById("demo").innerHTML =
this.getResponseHeader("Last-Modified");
}
xhttp.open("GET", "ajax_info.txt");
xhttp.send();

AJAX XML Example

AJAX can be used for interactive communication with an XML file.

AJAX XML Example

The following example will demonstrate how a web page can fetch information from an
XML file with AJAX:

Example Explained

When a user clicks on the "Get CD info" button above, the loadDoc() function is
executed.

The loadDoc() function creates an XMLHttpRequest object, adds the function to be


executed when the server response is ready, and sends the request off to the server.

When the server response is ready, an HTML table is built, nodes (elements) are
extracted from the XML file, and it finally updates the element "demo" with the HTML
table filled with XML data:

function loadDoc() {
const xhttp = new XMLHttpRequest();
xhttp.onload = function() {myFunction(this);}
xhttp.open("GET", "cd_catalog.xml");
xhttp.send();
}
function myFunction(xml) {
const xmlDoc = xml.responseXML;
const x = xmlDoc.getElementsByTagName("CD");
let table="<tr><th>Artist</th><th>Title</th></tr>";
for (let i = 0; i <x.length; i++) {
table += "<tr><td>" +
x[i].getElementsByTagName("ARTIST")[0].childNodes[0].nodeValue +
"</td><td>" +
x[i].getElementsByTagName("TITLE")[0].childNodes[0].nodeValue +
"</td></tr>";
}
document.getElementById("demo").innerHTML = table;
}

3.28 The XML File


AJAX PHP Example

AJAX is used to create more interactive applications.

AJAX PHP Example

The following example demonstrates how a web page can communicate with a web
server while a user types characters in an input field:

Example

Start typing a name in the input field below:

Suggestions:

First name:

Example Explained
In the example above, when a user types a character in the input field, a function called
showHint() is executed.

The function is triggered by the onkeyup event.

Here is the code:

Example

<p>Start typing a name in the input field below:</p>


<p>Suggestions: <span id="txtHint"></span></p>

<form>
First name: <input type="text" onkeyup="showHint(this.value)">
</form>
<script>
function showHint(str) {
if (str.length == 0) {
document.getElementById("txtHint").innerHTML = "";
return;
} else {
const xmlhttp = new XMLHttpRequest();
xmlhttp.onload = function() {
document.getElementById("txtHint").innerHTML = this.responseText;
}
xmlhttp.open("GET", "gethint.php?q=" + str);
xmlhttp.send();
}
}
</script>

Code explanation:

First, check if the input field is empty (str.length == 0). If it is, clear the content of the
txtHint placeholder and exit the function.

However, if the input field is not empty, do the following:

 Create an XMLHttpRequest object

 Create the function to be executed when the server response is ready

 Send the request off to a PHP file (gethint.php) on the server

 Notice that q parameter is added gethint.php?q="+str

 The str variable holds the content of the input field

3.29 The PHP File - "gethint.php"

The PHP file checks an array of names, and returns the corresponding name(s) to the
browser:

<?php
// Array with names
$a[] = "Anna";
$a[] = "Brittany";
$a[] = "Cinderella";
$a[] = "Diana";
$a[] = "Eva";
$a[] = "Fiona";
$a[] = "Gunda";
$a[] = "Hege";
$a[] = "Inga";
$a[] = "Johanna";
$a[] = "Kitty";
$a[] = "Linda";
$a[] = "Nina";
$a[] = "Ophelia";
$a[] = "Petunia";
$a[] = "Amanda";
$a[] = "Raquel";
$a[] = "Cindy";
$a[] = "Doris";
$a[] = "Eve";
$a[] = "Evita";
$a[] = "Sunniva";
$a[] = "Tove";
$a[] = "Unni";
$a[] = "Violet";
$a[] = "Liza";
$a[] = "Elizabeth";
$a[] = "Ellen";
$a[] = "Wenche";
$a[] = "Vicky";

// get the q parameter from URL


$q = $_REQUEST["q"];

$hint = "";

// lookup all hints from array if $q is different from ""


if ($q !== "") {
$q = strtolower($q);
$len=strlen($q);
foreach($a as $name) {
if (stristr($q, substr($name, 0, $len))) {
if ($hint === "") {
$hint = $name;
} else {
$hint .= ", $name";
}
}
}
}

// Output "no suggestion" if no hint was found or output correct values


echo $hint === "" ? "no suggestion" : $hint;
?>

3.30 Example Explained - The showCustomer() Function

When a user selects a customer in the dropdown list above, a function called
showCustomer() is executed. The function is triggered by the onchange event:

showCustomer
function showCustomer(str) {
if (str == "") {
document.getElementById("txtHint").innerHTML = "";
return;
}
const xhttp = new XMLHttpRequest();
xhttp.onload = function() {
document.getElementById("txtHint").innerHTML = this.responseText;
}
xhttp.open("GET", "getcustomer.php?q="+str);
xhttp.send();
}

The showCustomer() function does the following:

 Check if a customer is selected

 Create an XMLHttpRequest object

 Create the function to be executed when the server response is ready

 Send the request off to a file on the server

 Notice that a parameter (q) is added to the URL (with the content of the
dropdown list)

3.31 The AJAX Server Page

The page on the server called by the JavaScript above is a PHP file called
"getcustomer.php".
The source code in "getcustomer.php" runs a query against a database, and returns the
result in an HTML table:

<?php
$mysqli = new mysqli("servername", "username", "password", "dbname");
if($mysqli->connect_error) {
exit('Could not connect');
}

$sql = "SELECT customerid, companyname, contactname, address, city, postalcode,


country
FROM customers WHERE customerid = ?";

$stmt = $mysqli->prepare($sql);
$stmt->bind_param("s", $_GET['q']);
$stmt->execute();
$stmt->store_result();
$stmt->bind_result($cid, $cname, $name, $adr, $city, $pcode, $country);
$stmt->fetch();
$stmt->close();

echo "<table>";
echo "<tr>";
echo "<th>CustomerID</th>";
echo "<td>" . $cid . "</td>";
echo "<th>CompanyName</th>";
echo "<td>" . $cname . "</td>";
echo "<th>ContactName</th>";
echo "<td>" . $name . "</td>";
echo "<th>Address</th>";
echo "<td>" . $adr . "</td>";
echo "<th>City</th>";
echo "<td>" . $city . "</td>";
echo "<th>PostalCode</th>";
echo "<td>" . $pcode . "</td>";
echo "<th>Country</th>";
echo "<td>" . $country . "</td>";
echo "</tr>";
echo "</table>";
?>

3.33 XML Applications

This chapter demonstrates some HTML applications using XML, HTTP, DOM, and
JavaScript.
3.34 Display XML Data in an HTML Table

This example loops through each <CD> element, and displays the values of the
<ARTIST> and the <TITLE> elements in an HTML table:

Example

<table id="demo"></table>

<script>
function loadXMLDoc() {
const xmlhttp = new XMLHttpRequest();
xmlhttp.onload = function() {
const xmlDoc = xml.responseXML;
const cd = xmlDoc.getElementsByTagName("CD");
myFunction(cd);
}
xmlhttp.open("GET", "cd_catalog.xml");
xmlhttp.send();
}

function myFunction(cd) {
let table="<tr><th>Artist</th><th>Title</th></tr>";
for (let i = 0; i < cd.length; i++) {
table += "<tr><td>" +
cd[i].getElementsByTagName("ARTIST")[0].childNodes[0].nodeValue +
"</td><td>" +
cd[i].getElementsByTagName("TITLE")[0].childNodes[0].nodeValue +
"</td></tr>";
}
document.getElementById("demo").innerHTML = table;
}
</script>

</body>
</html>

3.35 Display the First CD in an HTML div Element


This example uses a function to display the first CD element in an HTML element with
id="showCD":

Example

const xhttp = new XMLHttpRequest();


xhttp.onload = function() {
const xmlDoc = xhttp.responseXML;
const cd = xmlDoc.getElementsByTagName("CD");
myFunction(cd, 0);
}
xhttp.open("GET", "cd_catalog.xml");
xhttp.send();

function myFunction(cd, i) {
document.getElementById("showCD").innerHTML =
"Artist: " +
cd[i].getElementsByTagName("ARTIST")[0].childNodes[0].nodeValue +
"<br>Title: " +
cd[i].getElementsByTagName("TITLE")[0].childNodes[0].nodeValue +
"<br>Year: " +
cd[i].getElementsByTagName("YEAR")[0].childNodes[0].nodeValue;
}

3.36 JavaBean

A JavaBean is a Java class that should follow the following conventions:

 It should have a no-arg constructor.

 It should be Serializable.

 It should provide methods to set and get the values of the properties, known as getter and
setter methods.
Why use JavaBean?

According to Java white paper, it is a reusable software component. A bean encapsulates many
objects into one object so that we can access this object from multiple places. Moreover, it provides
easy maintenance.

Simple example of JavaBean class


5. //Employee.java
6.
7. package mypack;

8. public class Employee implements java.io.Serializable{

9. private int id;

10. private String name;

11. public Employee(){}

12. public void setId(int id){this.id=id;}

13. public int getId(){return id;}

14. public void setName(String name){this.name=name;}

15. public String getName(){return name;}

16. }
How to access the JavaBean class?

To access the JavaBean class, we should use getter and setter methods.

17. package mypack;

18. public class Test{

19. public static void main(String args[]){

20. Employee e=new Employee();//object is created

21. e.setName("Arjun");//setting value to the object

22. System.out.println(e.getName());

23. }}
Note: There are two ways to provide values to the object. One way is by constructor and second is by setter
method.

3.36.1 JavaBean Properties


A JavaBean property is a named feature that can be accessed by the user of the object. The feature
can be of any Java data type, containing the classes that you define.

A JavaBean property may be read, write, read-only, or write-only. JavaBean features are accessed
through two methods in the JavaBean's implementation class:

1. getPropertyName ()

For example, if the property name is firstName, the method name would be getFirstName() to read
that property. This method is called the accessor.

2. setPropertyName ()

For example, if the property name is firstName, the method name would be setFirstName() to write
that property. This method is called the mutator.

3.36.2 Advantages of JavaBean

The following are the advantages of JavaBean:/p>

 The JavaBean properties and methods can be exposed to another application.

 It provides an easiness to reuse the software components.


3.36.3 Disadvantages of JavaBean

The following are the disadvantages of JavaBean:

 JavaBeans are mutable. So, it can't take advantages of immutable objects.

 Creating the setter and getter method for each property separately may lead to the
boilerplate code.
3.37
3.37EJB Tutorial

EJB (Enterprise Java Bean) is used to develop scalable, robust and secured enterprise applications in
java.

Unlike RMI, middleware services such as security, transaction management etc. are provided by EJB
Container to all EJB applications.
The current version of EJB is EJB 3.2. The development of EJB 3 is faster than EJB 2 because of
simplicity and annotations such as @EJB, @Stateless, @Stateful, @ModelDriven, @PreDestroy,
@PostConstruct etc.

Topics of EJB Specification

The topics of EJB specifications covered by javatpoint is given below.

What is EJB

What is enterprise java beans(EJB) and what are the advantages of EJB?

Session Bean

The session bean represents the business logic. It may be stateless, stateful or singleton.

Stateless Session Bean

What is stateless session bean, its lifecycle and example.

Stateful Session Bean

What is stateful session bean, its lifecycle and example.

JMS Tutorial

How to create robust and asynchronous message for distributed applications. What are messaging
domains?

What is Java Messsage Service and what are the advantages of JMS.

What is JMS Queue? It is used for peer to peer messaging where a single message is delivered to
only one receiver.

What is JMS Topic? It is also known as Publisher and Subscriber model where a single message is
delivered to all the subscribers.

Message Driven Bean


A MDB is a JMS client that is invoked by passing message. It is deployed on the application server.

Entity Bean

In EJB 3.2, it is deprecated. Now it is replaced with JPA.

3.38 The Java Beans API

The Java Beans functionality is provided by a set of classes and interfaces in the
java.beans package. This section provides a brief overview of its contents. Table 37-1
lists the interfaces in java.beans and provides a brief description of their functionality.
Table 37-2 lists the classes in java.beans.
Although it is beyond the scope of this chapter to discuss all of the classes, four are of
particular interest: Introspector, PropertyDescriptor, EventSetDescriptor, and
MethodDescriptor. Each is briefly examined here.

Introspector
The Introspector class provides several static methods that support introspection. Of
most interest is getBeanInfo( ). This method returns a BeanInfo object that can be
used to obtain information about the Bean. The getBeanInfo( ) method has several
forms, including the one shown here:

static BeanInfo getBeanInfo(Class<?> bean) throws IntrospectionException The


returned object contains information about the Bean specified by bean.

PropertyDescriptor
The PropertyDescriptor class describes the characteristics of a Bean property. It
supports several methods that manage and describe properties. For example, you can
determine if a property is bound by calling isBound( ). To determine if a property is
constrained, call isConstrained( ). You can obtain the name of a property by calling
getName( ).

EventSetDescriptor

The EventSetDescriptor class represents a Bean event. It supports several methods


that obtain the methods that a Bean uses to add or remove event listeners, and to
otherwise manage events. For example, to obtain the method used to add listeners, call
getAddListenerMethod( ). To obtain the method used to remove listeners, call
getRemoveListenerMethod( ). To obtain the type of a listener, call getListenerType(
). You can obtain the name of an event by calling getName( ).

MethodDescriptor
The MethodDescriptor class represents a Bean method. To obtain the name of the
method, call getName( ). You can obtain information about the method by calling
getMethod( ), shown here:

Method getMethod( )

An object of type Method that describes the method is returned.


Unit 4
4.1 EJB

EJB (Enterprise Java Bean) is used to develop scalable, robust and secured enterprise
applications in java.

Unlike RMI, middleware services such as security, transaction management etc. are provided
by EJB Container to all EJB applications.

4.2 JavaBean

A JavaBean is a Java class that should follow the following conventions:

Properties:

o It should have a no-arg constructor.


o It should be Serializable.
o It should provide methods to set and get the values of the properties, known as getter and
setter methods.

4.2.1 Creating a Java Bean

According to Java white paper, it is a reusable software component. A bean encapsulates


many objects into one object so that we can access this object from multiple places.
Moreover, it provides easy maintenance.

Simple example of JavaBean class


1. //Employee.java
2.
3. package mypack;
4. public class Employee implements java.io.Serializable{
5. private int id;
6. private String name;
7. public Employee(){}
8. public void setId(int id){this.id=id;}
9. public int getId(){return id;}
10. public void setName(String name){this.name=name;}
11. public String getName(){return name;}
12. }
How to access the JavaBean class?
To access the JavaBean class, we should use getter and setter methods.

1. package mypack;
2. public class Test{
3. public static void main(String args[]){
4. Employee e=new Employee();//object is created
5. e.setName("Arjun");//setting value to the object
6. System.out.println(e.getName());
7. }}

4.2.2 Types of Bean:

There are 3 types of enterprise bean in java.

Session Bean
Session bean contains business logic that can be invoked by local, remote or webservice client.
Message Driven Bean
Like Session Bean, it contains the business logic but it is invoked by passing message.
Entity Bean
It encapsulates the state that can be persisted in the database. It is deprecated. Now, it is replaced
with JPA (Java Persistent API).
4.2.3 Difference between RMI and EJB

Both RMI and EJB, provides services to access an object running in another JVM (known as
remote object) from another JVM. The differences between RMI and EJB are given below:

RMI EJB

In RMI, middleware services such as security, transaction In EJB, middleware


management, object pooling etc. need to be done by the java services are provided
programmer. by EJB Container
automatically.

RMI is not a server-side component. It is not required to be EJB is a server-side


deployed on the server. component, it is
required to be
deployed on the
server.

RMI is built on the top of socket programming. EJB technology is built


on the top of RMI.

4.2.4 EJB and Webservice


In EJB, bean component and bean client both must be written in java language.

If bean client need to be written in other language such as .net, php etc, we need to go
with webservices (SOAP or REST). So EJB with web service will be better option.

4.2.5Session Bean:

Session bean encapsulates business logic only, it can be invoked by local, remote and
webservice client.

It can be used for calculations, database access etc.

The life cycle of session bean is maintained by the application server (EJB Container).

4.2.6 Types of Session Bean

There are 3 types of session bean.

Stateless Session Bean: It doesn't maintain state of a client between multiple method calls.

2) Stateful Session Bean: It maintains state of a client across multiple requests.

3) Singleton Session Bean: One instance per application, it is shared between clients and
supports concurrent access.

4.2.7 Entity Bean in EJB 3.x

Entity bean represents the persistent data stored in the database. It is a server-side
component.

In EJB 2.x, there was two types of entity beans: bean managed persistence (BMP) and
container managed persistence (CMP).

Since EJB 3.x, it is deprecated and replaced by JPA (Java Persistence API) that is covered in
the hibernate tutorial.

In hibernate tutorial, there are given hibernate with annotation examples where we are using
JPA annotations. The JPA with Hibernate is widely used today.

4.2.8 Message Driven Bean

A message driven bean (MDB) is a bean that contains business logic. But, it is invoked by
passing the message. So, it is like JMS Receiver.
MDB asynchronously receives the message and processes it.

A message driven bean receives message from queue or topic, so you must have the
knowledge of JMS API.

4.2.9 Message Driven Bean Example

To create the message driven bean, you need to declare @MessageDriven annotation and
implement MessageListener interface.

In eclipse ide, create EJB Project then create a class as given below:

File: MyListener.java
1. package com.javatpoint;
2. import javax.ejb.MessageDriven;
3. import javax.jms.*;
4.
5. @MessageDriven(mappedName="myTopic")
6. public class MyListener implements MessageListener{
7. @Override
8. public void onMessage(Message msg) {
9. TextMessage m=(TextMessage)msg;
10. try{
11. System.out.println("message received: "+m.getText());
12. }catch(Exception e){System.out.println(e);}
13. }
14. }

4.3 JDBC :
JDBC stands for Java Database Connectivity. JDBC is a Java API to connect and execute the
query with the database. It is a part of JavaSE (Java Standard Edition). JDBC API uses JDBC
drivers to connect with the database. There are four types of JDBC drivers:

o JDBC-ODBC Bridge Driver,


o Native Driver,
o Network Protocol Driver, and
o Thin Driver
We have discussed the above four drivers in the next chapter.

We can use JDBC API to access tabular data stored in any relational database. By the help of
JDBC API, we can save, update, delete and fetch data from the database. It is like Open
Database Connectivity (ODBC) provided by Microsoft.

The current version of JDBC is 4.3. It is the stable release since 21st September, 2017. It is
based on the X/Open SQL Call Level Interface. The java.sql package contains classes and
interfaces for JDBC API. A list of popular interfaces of JDBC API are given below:

4.3.1 JDBC Drivers:


JDBC Driver is a software component that enables java application to interact with the database. There are 4
types of JDBC drivers:
1. JDBC-ODBC bridge driver
2. Native-API driver (partially java driver)
3. Network Protocol driver (fully java driver)
4. Thin driver (fully java driver)

1) JDBC-ODBC bridge driver


The JDBC-ODBC bridge driver uses ODBC driver to connect to the database. The JDBC-ODBC bridge driver
converts JDBC method calls into the ODBC function calls. This is now discouraged because of thin driver.
In Java 8, the JDBC-ODBC Bridge has been removed.

Oracle does not support the JDBC-ODBC Bridge from Java 8. Oracle recommends that you
use JDBC drivers provided by the vendor of your database instead of the JDBC-ODBC Bridge.

Advantages:
o easy to use.
o can be easily connected to any database.

Disadvantages:
o Performance degraded because JDBC method call is converted into the ODBC function calls.
o The ODBC driver needs to be installed on the client machine.

2) Native-API driver
The Native API driver uses the client-side libraries of the database. The driver converts JDBC method calls into
native calls of the database API. It is not written entirely in java.
Advantage:
o performance upgraded than JDBC-ODBC bridge driver.

Disadvantage:
o The Native driver needs to be installed on the each client machine.
o The Vendor client library needs to be installed on client machine.

3) Network Protocol driver

The Network Protocol driver uses middleware (application server) that converts JDBC calls
directly or indirectly into the vendor-specific database protocol. It is fully written in java.
Advantage:
o No client side library is required because of application server that can perform many tasks
like auditing, load balancing, logging etc.

Disadvantages:
o Network support is required on client machine.
o Requires database-specific coding to be done in the middle tier.
o Maintenance of Network Protocol driver becomes costly because it requires database-specific
coding to be done in the middle tier.

4) Thin driver
The thin driver converts JDBC calls directly into the vendor-specific database protocol. That is why it is known as
thin driver. It is fully written in Java language.
Advantage:
o Better performance than all other drivers.
o No software is required at client side or server side.

Disadvantage:
o Drivers depend on the Database.

4.4 Database with JDBC:


There are 5 steps to connect any java application with the database using JDBC. These steps are as follows:
o Register the Driver class
o Create connection
o Create statement
o Execute queries
o Close connection
1) Register the driver class
The forName() method of Class class is used to register the driver class. This method is used to dynamically load
the driver class.
Syntax of forName() method
1. public static void forName(String className)throws ClassNotFoundException
Note: Since JDBC 4.0, explicitly registering the driver is optional. We just need to put vender's
Jar in the classpath, and then JDBC driver manager can detect and load the driver
automatically.
Example to register the OracleDriver class

Here, Java program is loading oracle driver to esteblish database connection.

1. Class.forName("oracle.jdbc.driver.OracleDriver");

2) Create the connection object


The getConnection() method of DriverManager class is used to establish connection with the database.
Syntax of getConnection() method
1. 1) public static Connection getConnection(String url)throws SQLException
2. 2) public static Connection getConnection(String url,String name,String password)
3. throws SQLException
Example to establish connection with the Oracle database
1. Connection con=DriverManager.getConnection(
2. "jdbc:oracle:thin:@localhost:1521:xe","system","password");

3) Create the Statement object


The createStatement() method of Connection interface is used to create statement. The object of statement is
responsible to execute queries with the database.
Syntax of createStatement() method
1. public Statement createStatement()throws SQLException
Example to create the statement object
1. Statement stmt=con.createStatement();

4) Execute the query


The executeQuery() method of Statement interface is used to execute queries to the database. This method
returns the object of ResultSet that can be used to get all the records of a table.
Syntax of executeQuery() method
1. public ResultSet executeQuery(String sql)throws SQLException
Example to execute query
1. ResultSet rs=stmt.executeQuery("select * from emp");
2.
3. while(rs.next()){
4. System.out.println(rs.getInt(1)+" "+rs.getString(2));
5. }

5) Close the connection object


By closing connection object statement and ResultSet will be closed automatically. The close() method of
Connection interface is used to close the connection.
Syntax of close() method
1. public void close()throws SQLException
Example to close connection
1. con.close();
Note: Since Java 7, JDBC has ability to use try-with-resources statement to automatically
close resources of type Connection, ResultSet, and Statement.

It avoids explicit connection closing step.

PreparedStatement interface

The PreparedStatement interface is a subinterface of Statement. It is used to execute


parameterized query.

Let's see the example of parameterized query:

1. String sql="insert into emp values(?,?,?)";


As you can see, we are passing parameter (?) for the values. Its value will be set by calling the
setter methods of PreparedStatement.

Why use PreparedStatement?

Improves performance: The performance of the application will be faster if you use
PreparedStatement interface because query is compiled only once.

How to get the instance of PreparedStatement?

The prepareStatement() method of Connection interface is used to return the object of


PreparedStatement. Syntax:

1. public PreparedStatement prepareStatement(String query)throws SQLException{}

Methods of PreparedStatement interface

The important methods of PreparedStatement interface are given below:

Method Description

public void setInt(int paramIndex, int value) sets the integer value to the given parameter index.

public void setString(int paramIndex, String sets the String value to the given parameter index.
value)

public void setFloat(int paramIndex, float sets the float value to the given parameter index.
value)

public void setDouble(int paramIndex, double sets the double value to the given parameter index.
value)

public int executeUpdate() executes the query. It is used for create, drop, insert, update,
delete etc.

public ResultSet executeQuery() executes the select query. It returns an instance of ResultSet.
Example of PreparedStatement interface that inserts the record

First of all create table as given below:

1. create table emp(id number(10),name varchar2(50));


Now insert records in this table by the code given below:

1. import java.sql.*;
2. class InsertPrepared{
3. public static void main(String args[]){
4. try{
5. Class.forName("oracle.jdbc.driver.OracleDriver");
6.
7. Connection con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe","system
","oracle");
8.
9. PreparedStatement stmt=con.prepareStatement("insert into Emp values(?,?)");
10. stmt.setInt(1,101);//1 specifies the first parameter in the query
11. stmt.setString(2,"Ratan");
12.
13. int i=stmt.executeUpdate();
14. System.out.println(i+" records inserted");
15.
16. con.close();
17.
18. }catch(Exception e){ System.out.println(e);}
19.
20. }
21. }
4.5 Transaction Management in JDBC

Transaction represents a single unit of work.

The ACID properties describes the transaction management well. ACID stands for Atomicity,
Consistency, isolation and durability.

Atomicity means either all successful or none.

Consistency ensures bringing the database from one consistent state to another consistent
state.

Isolation ensures that transaction is isolated from other transaction.


Durability means once a transaction has been committed, it will remain so, even in the
event of errors, power loss etc.

Advantage of Transaction Mangaement

fast performance It makes the performance fast because database is hit at the time of
commit.

In JDBC, Connection interface provides methods to manage transaction.

Method Description

void setAutoCommit(boolean status) It is true bydefault means each transaction is committed bydefault.

void commit() commits the transaction.

void rollback() cancels the transaction.

Simple example of transaction management in jdbc using Statement

Let's see the simple example of transaction management using Statement.

1. import java.sql.*;
2. class FetchRecords{
3. public static void main(String args[])throws Exception{
4. Class.forName("oracle.jdbc.driver.OracleDriver");
5. Connection con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe","system
","oracle");
6. con.setAutoCommit(false);
7.
8. Statement stmt=con.createStatement();
9. stmt.executeUpdate("insert into user420 values(190,'abhi',40000)");
10. stmt.executeUpdate("insert into user420 values(191,'umesh',50000)");
11.
12. con.commit();
13. con.close();
14. }}
4.6Stored Procedures:
Java CallableStatement Interface

CallableStatement interface is used to call the stored procedures and functions.

We can have business logic on the database by the use of stored procedures and functions
that will make the performance better because these are precompiled.

Suppose you need the get the age of the employee based on the date of birth, you may
create a function that receives date as the input and returns age of the employee as the
output.

What is the difference between stored procedures and functions.

The differences between stored procedures and functions are given below:

00:00/06:36

Stored Procedure Function

is used to perform business logic. is used to perform calculation.

must not have the return type. must have the return type.

may return 0 or more values. may return only one values.

We can call functions from the procedure. Procedure cannot be called from
function.
Procedure supports input and output parameters. Function supports only input
parameter.

Exception handling using try/catch block can be used Exception handling using try/catch can't
in stored procedures. be used in user defined functions.

How to get the instance of CallableStatement?

The prepareCall() method of Connection interface returns the instance of CallableStatement.


Syntax is given below:

1. public CallableStatement prepareCall("{ call procedurename(?,?...?)}");

The example to get the instance of CallableStatement is given below:

1. CallableStatement stmt=con.prepareCall("{call myprocedure(?,?)}");

It calls the procedure myprocedure that receives 2 arguments.

4.7 Full example to call the stored procedure using JDBC

To call the stored procedure, you need to create it in the database. Here, we are assuming
that stored procedure looks like this.

1. create or replace procedure "INSERTR"


2. (id IN NUMBER,
3. name IN VARCHAR2)
4. is
5. begin
6. insert into user420 values(id,name);
7. end;
8. /

The table structure is given below:

1. create table user420(id number(10), name varchar2(200));


In this example, we are going to call the stored procedure INSERTR that receives id and
name as the parameter and inserts it into the table user420. Note that you need to create
the user420 table as well to run this application.

1. import java.sql.*;
2. public class Proc {
3. public static void main(String[] args) throws Exception{
4.
5. Class.forName("oracle.jdbc.driver.OracleDriver");
6. Connection con=DriverManager.getConnection(
7. "jdbc:oracle:thin:@localhost:1521:xe","system","oracle");
8.
9. CallableStatement stmt=con.prepareCall("{call insertR(?,?)}");
10. stmt.setInt(1,1011);
11. stmt.setString(2,"Amit");
12. stmt.execute();
13.
14. System.out.println("success");
15. }
16. }
UNIT 5

5.1 Servlets | Servlet Tutorial

Servlet technology is used to create a web application (resides at server side and generates
a dynamic web page).

Servlet technology is robust and scalable because of java language. Before Servlet, CGI
(Common Gateway Interface) scripting language was common as a server-side programming
language. However, there were many disadvantages to this technology. We have discussed
these disadvantages below.

There are many interfaces and classes in the Servlet API such as Servlet, GenericServlet,
HttpServlet, ServletRequest, ServletResponse, etc.

5.2 What is a Servlet?

Servlet can be described in many ways, depending on the context.

o Servlet is a technology which is used to create a web application.


o Servlet is an API that provides many interfaces and classes including documentation.
o Servlet is an interface that must be implemented for creating any Servlet.
o Servlet is a class that extends the capabilities of the servers and responds to the incoming
requests. It can respond to any requests.
o Servlet is a web component that is deployed on the server to create a dynamic web page.
5.3 Servlet Life Cycle:

The web container maintains the life cycle of a servlet instance. Let's see the life cycle of the servlet:

1. Servlet class is loaded.


2. Servlet instance is created.
3. init method is invoked.
4. service method is invoked.
5. destroy method is invoked.
As displayed in the above diagram, there are three states of a servlet: new, ready and end. The servlet
is in new state if servlet instance is created. After invoking the init() method, Servlet comes in the
ready state. In the ready state, servlet performs all the tasks. When the web container invokes the
destroy() method, it shifts to the end state.

1) Servlet class is loaded

The classloader is responsible to load the servlet class. The servlet class is loaded when the first
request for the servlet is received by the web container.

2) Servlet instance is created

The web container creates the instance of a servlet after loading the servlet class. The servlet instance
is created only once in the servlet life cycle.

5.4 Handling HTTP Request & HTTP Response:

There are given 6 steps to create a servlet example. These steps are required for all the
servers.
The servlet example can be created by three ways:

1. By implementing Servlet interface,


2. By inheriting GenericServlet class, (or)
3. By inheriting HttpServlet class

The mostly used approach is by extending HttpServlet because it provides http request
specific method such as doGet(), doPost(), doHead() etc.

Here, we are going to use apache tomcat server in this example. The steps are as follows:

1. Create a directory structure


2. Create a Servlet
3. Compile the Servlet
4. Create a deployment descriptor
5. Start the server and deploy the project
6. Access the servlet

5.5 Create a directory structures

The directory structure defines that where to put the different types of files so that web
container may get the information and respond to the client.

The Sun Microsystem defines a unique standard to be followed by all the server vendors.
Let's see the directory structure that must be followed to create the servlet.
As you can see that the servlet class file must be in the classes folder. The web.xml file must
be under the WEB-INF folder.

2)Create a Servlet
There are three ways to create the servlet.
1. By implementing the Servlet interface
2. By inheriting the GenericServlet class
3. By inheriting the HttpServlet class

The HttpServlet class is widely used to create the servlet because it provides methods to handle http requests
such as doGet(), doPost, doHead() etc.
In this example we are going to create a servlet that extends the HttpServlet class. In this example, we are
inheriting the HttpServlet class and providing the implementation of the doGet() method. Notice that get request
is the default request.

DemoServlet.java
1. import javax.servlet.http.*;
2. import javax.servlet.*;
3. import java.io.*;
4. public class DemoServlet extends HttpServlet{
5. public void doGet(HttpServletRequest req,HttpServletResponse res)
6. throws ServletException,IOException
7. {
8. res.setContentType("text/html");//setting the content type
9. PrintWriter pw=res.getWriter();//get the stream to write the data
10.
11. //writing html in the stream
12. pw.println("<html><body>");
13. pw.println("Welcome to servlet");
14. pw.println("</body></html>");
15.
16. pw.close();//closing the stream
17. }}

3)Compile the servlet

For compiling the Servlet, jar file is required to be loaded. Different Servers provide different
jar files:

Jar file Server

1) servlet-api.jar Apache Tomcat

2) weblogic.jar Weblogic

3) javaee.jar Glassfish

4) javaee.jar JBoss

Two ways to load the jar file


1. set classpath
2. paste the jar file in JRE/lib/ext folder
Put the java file in any folder. After compiling the java file, paste the class file of servlet
in WEB-INF/classes directory.

4)Create the deployment descriptor (web.xml file)


The deployment descriptor is an xml file, from which Web Container gets the information
about the servet to be invoked.

The web container uses the Parser to get the information from the web.xml file. There are
many xml parsers such as SAX, DOM and Pull.

There are many elements in the web.xml file. Here is given some necessary elements to run
the simple servlet program.

web.xml file

1. <web-app>
2.
3. <servlet>
4. <servlet-name>sonoojaiswal</servlet-name>
5. <servlet-class>DemoServlet</servlet-class>
6. </servlet>
7.
8. <servlet-mapping>
9. <servlet-name>sonoojaiswal</servlet-name>
10. <url-pattern>/welcome</url-pattern>
11. </servlet-mapping>
12.
13. </web-app>
Description of the elements of web.xml file
There are too many elements in the web.xml file. Here is the illustration of some elements
that is used in the above web.xml file. The elements are as follows:
<web-app> represents the whole application.
<servlet> is sub element of <web-app> and represents the servlet.
<servlet-name> is sub element of <servlet> represents the name of the servlet.
<servlet-class> is sub element of <servlet> represents the class of the servlet.
<servlet-mapping> is sub element of <web-app>. It is used to map the servlet.
<url-pattern> is sub element of <servlet-mapping>. This pattern is used at client side to invoke the servlet.

5)Start the Server and deploy the project


To start Apache Tomcat server, double click on the startup.bat file under apache-tomcat/bin
directory.

5.6 One Time Configuration for Apache Tomcat Server

You need to perform 2 tasks:

1. set JAVA_HOME or JRE_HOME in environment variable (It is required to start server).


2. Change the port number of tomcat (optional). It is required if another server is running on
same port (8080).

1) How to set JAVA_HOME in environment variable?

To start Apache Tomcat server JAVA_HOME and JRE_HOME must be set in Environment
variables.

Go to My Computer properties -> Click on advanced tab then environment variables -> Click
on the new tab of user variable -> Write JAVA_HOME in variable name and paste the path of
jdk folder in variable value -> ok -> ok -> ok.

5.7 Redirecting Request to Other Resource:

The RequestDispatcher interface provides the facility of dispatching the request to another
resource it may be html, servlet or jsp. This interface can also be used to include the content
of another resource also. It is one of the way of servlet collaboration.

There are two methods defined in the RequestDispatcher interface.

5.8 Methods of RequestDispatcher interface


The RequestDispatcher interface provides two methods. They are:

1. public void forward(ServletRequest request,ServletResponse response)throws


ServletException,java.io.IOException: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:Includes the content of a resource (servlet, JSP page,
or HTML file) in the response.

Competitive questions on Structures in Hindi


Keep Watching

As you see in the above figure, response of second servlet is sent to the client. Response of
the first servlet is not displayed to the user.
As you can see in the above figure, response of second servlet is included in the response of the first servlet that
is being sent to the client.

How to get the object of RequestDispatcher


The getRequestDispatcher() method of ServletRequest interface returns the object of
RequestDispatcher. Syntax:

Syntax of getRequestDispatcher method


1. public RequestDispatcher getRequestDispatcher(String resource);
Example of using getRequestDispatcher method
1. RequestDispatcher rd=request.getRequestDispatcher("servlet2");
2. //servlet2 is the url-pattern of the second servlet
3.
4. rd.forward(request, response);//method may be include or forward

Example of RequestDispatcher interface


In this example, we are validating the password entered by the user. If password is servlet, it
will forward the request to the WelcomeServlet, otherwise will show an error message: sorry
username or password error!. In this program, we are cheking for hardcoded information.
But you can check it to the database also that we will see in the development chapter. In this
example, we have created following files:

o index.html file: for getting input from the user.


o Login.java file: a servlet class for processing the response. If password is servet, it will
forward the request to the welcome servlet.
o WelcomeServlet.java file: a servlet class for displaying the welcome message.
o web.xml file: a deployment descriptor file that contains the information about the servlet.

index.html
1. <form action="servlet1" method="post">
2. Name:<input type="text" name="userName"/><br/>
3. Password:<input type="password" name="userPass"/><br/>
4. <input type="submit" value="login"/>
5. </form>

Login.java
1. import java.io.*;
2. import javax.servlet.*;
3. import javax.servlet.http.*;
4.
5.
6. public class Login extends HttpServlet {
7.
8. public void doPost(HttpServletRequest request, HttpServletResponse response)
9. throws ServletException, IOException {
10.
11. response.setContentType("text/html");
12. PrintWriter out = response.getWriter();
13.
14. String n=request.getParameter("userName");
15. String p=request.getParameter("userPass");
16.
17. if(p.equals("servlet"){
18. RequestDispatcher rd=request.getRequestDispatcher("servlet2");
19. rd.forward(request, response);
20. }
21. else{
22. out.print("Sorry UserName or Password Error!");
23. RequestDispatcher rd=request.getRequestDispatcher("/index.html");
24. rd.include(request, response);
25.
26. }
27. }
28.
29. }

WelcomeServlet.java
1. import java.io.*;
2. import javax.servlet.*;
3. import javax.servlet.http.*;
4.
5. public class WelcomeServlet extends HttpServlet {
6.
7. public void doPost(HttpServletRequest request, HttpServletResponse response)
8. throws ServletException, IOException {
9.
10. response.setContentType("text/html");
11. PrintWriter out = response.getWriter();
12.
13. String n=request.getParameter("userName");
14. out.print("Welcome "+n);
15. }
16.
17. }

web.xml
1. <web-app>
2. <servlet>
3. <servlet-name>Login</servlet-name>
4. <servlet-class>Login</servlet-class>
5. </servlet>
6. <servlet>
7. <servlet-name>WelcomeServlet</servlet-name>
8. <servlet-class>WelcomeServlet</servlet-class>
9. </servlet>
10.
11.
12. <servlet-mapping>
13. <servlet-name>Login</servlet-name>
14. <url-pattern>/servlet1</url-pattern>
15. </servlet-mapping>
16. <servlet-mapping>
17. <servlet-name>WelcomeServlet</servlet-name>
18. <url-pattern>/servlet2</url-pattern>
19. </servlet-mapping>
20.
21. <welcome-file-list>
22. <welcome-file>index.html</welcome-file>
23. </welcome-file-list>
24. </web-app>
5.7 Session Tracking:

Session simply means a particular interval of time.

Session Tracking is a way to maintain state (data) of an user. It is also known as session
management in servlet.

Http protocol is a stateless so we need to maintain state using session tracking techniques.
Each time user requests to the server, server treats the request as the new request. So we
need to maintain the state of an user to recognize to particular user.

HTTP is stateless that means each request is considered as the new request. It is shown in
the figure given below:

Keep Watching

Why use Session Tracking?

To recognize the user It is used to recognize the particular user.

Session Tracking Techniques

There are four techniques used in Session tracking:

1. Cookies
2. Hidden Form Field
3. URL Rewriting
4. HttpSession

5.8 Cookies:
Cookies in Servlet
A cookie is a small piece of information that is persisted between the multiple client
requests.

A cookie has a name, a single value, and optional attributes such as a comment, path and
domain qualifiers, a maximum age, and a version number.

How Cookie works


By default, each request is considered as a new request. In cookies technique, we add cookie
with response from the servlet. So cookie is stored in the cache of the browser. After that if
request is sent by the user, cookie is added with request by default. Thus, we recognize the
user as the old user.

5.9 Types of Cookie

There are 2 types of cookies in servlets.

1. Non-persistent cookie
2. Persistent cookie

Non-persistent cookie

It is valid for single session only. It is removed each time when user closes the browser.

Persistent cookie

It is valid for multiple session . It is not removed each time when user closes the browser. It
is removed only if user logout or signout.
5.9.1 Advantage of Cookies
1. Simplest technique of maintaining the state.
2. Cookies are maintained at client side.

5.9.2 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.

5.9.3 Session Tracking with Http Session:

In such case, container creates a session id for each user.The container uses this id to identify
the particular user.An object of HttpSession can be used to perform two tasks:

1. bind objects
2. view and manipulate information about a session, such as the session identifier, creation time,
and last accessed time.

How to get the HttpSession object ?

The HttpServletRequest interface provides two methods to get the object of HttpSession:

1. public HttpSession getSession():Returns the current session associated with this request, or
if the request does not have a session, creates one.
2. public HttpSession getSession(boolean create):Returns the current HttpSession associated
with this request or, if there is no current session and create is true, returns a new session.
Commonly used methods of HttpSession interface
1. public String getId():Returns a string containing the unique identifier value.
2. public long getCreationTime():Returns the time when this session was created, measured in
milliseconds since midnight January 1, 1970 GMT.
3. public long getLastAccessedTime():Returns the last time the client sent a request
associated with this session, as the number of milliseconds since midnight January 1, 1970
GMT.
4. public void invalidate():Invalidates this session then unbinds any objects bound to it.

Example of using HttpSession

In this example, we are setting the attribute in the session scope in one servlet and getting
that value from the session scope in another servlet. To set the attribute in the session
scope, we have used the setAttribute() method of HttpSession interface and to get the
attribute, we have used the getAttribute method.

index.html
1. <form action="servlet1">
2. Name:<input type="text" name="userName"/><br/>
3. <input type="submit" value="go"/>
4. </form>
FirstServlet.java
1. import java.io.*;
2. import javax.servlet.*;
3. import javax.servlet.http.*;
4.
5.
6. public class FirstServlet extends HttpServlet {
7.
8. public void doGet(HttpServletRequest request, HttpServletResponse response){
9. try{
10.
11. response.setContentType("text/html");
12. PrintWriter out = response.getWriter();
13.
14. String n=request.getParameter("userName");
15. out.print("Welcome "+n);
16.
17. HttpSession session=request.getSession();
18. session.setAttribute("uname",n);
19.
20. out.print("<a href='servlet2'>visit</a>");
21.
22. out.close();
23.
24. }catch(Exception e){System.out.println(e);}
25. }
26.
27. }
SecondServlet.java
1. import java.io.*;
2. import javax.servlet.*;
3. import javax.servlet.http.*;
4.
5. public class SecondServlet extends HttpServlet {
6.
7. public void doGet(HttpServletRequest request, HttpServletResponse response)
8. try{
9.
10. response.setContentType("text/html");
11. PrintWriter out = response.getWriter();
12.
13. HttpSession session=request.getSession(false);
14. String n=(String)session.getAttribute("uname");
15. out.print("Hello "+n);
16.
17. out.close();
18.
19. }catch(Exception e){System.out.println(e);}
20. }
21.
22.
23. }
web.xml
1. <web-app>
2.
3. <servlet>
4. <servlet-name>s1</servlet-name>
5. <servlet-class>FirstServlet</servlet-class>
6. </servlet>
7.
8. <servlet-mapping>
9. <servlet-name>s1</servlet-name>
10. <url-pattern>/servlet1</url-pattern>
11. </servlet-mapping>
12.
13. <servlet>
14. <servlet-name>s2</servlet-name>
15. <servlet-class>SecondServlet</servlet-class>
16. </servlet>
17.
18. <servlet-mapping>
19. <servlet-name>s2</servlet-name>
20. <url-pattern>/servlet2</url-pattern>
21. </servlet-mapping>
22.
23. </web-app>

5.10 Java Server Pages(JSP):


JSP Tutorial
JSP technology is used to create web application just like Servlet technology. It can be
thought of as an extension to Servlet because it provides more functionality than servlet
such as expression language, JSTL, etc.

A JSP page consists of HTML tags and JSP tags. The JSP pages are easier to maintain than
Servlet because we can separate designing and development. It provides some additional
features such as Expression Language, Custom Tags, etc.

5.10.1 Advantages of JSP over Servlet

There are many advantages of JSP over the Servlet. They are as follows:

1) Extension to Servlet

JSP technology is the extension to Servlet technology. We can use all the features of the
Servlet in JSP. In addition to, we can use implicit objects, predefined tags, expression
language and Custom tags in JSP, that makes JSP development easy.

00:00/01:27
2) Easy to maintain

JSP can be easily managed because we can easily separate our business logic with
presentation logic. In Servlet technology, we mix our business logic with the presentation
logic.

3) Fast Development: No need to recompile and redeploy

If JSP page is modified, we don't need to recompile and redeploy the project. The Servlet
code needs to be updated and recompiled if we have to change the look and feel of the
application.

4) Less code than Servlet

In JSP, we can use many tags such as action tags, JSTL, custom tags, etc. that reduces the
code. Moreover, we can use EL, implicit objects, etc.
5.10.2 The Lifecycle of a JSP Page

The JSP pages follow these phases:

o Translation of JSP Page


o Compilation of JSP Page
o Classloading (the classloader loads class file)
o Instantiation (Object of the Generated Servlet is created).
o Initialization ( the container invokes jspInit() method).
o Request processing ( the container invokes _jspService() method).
o Destroy ( the container invokes jspDestroy() method).

Note: jspInit(), _jspService() and jspDestroy() are the life cycle methods of JSP.

As depicted in the above diagram, JSP page is translated into Servlet by the help of JSP
translator. The JSP translator is a part of the web server which is responsible for translating
the JSP page into Servlet. After that, Servlet page is compiled by the compiler and gets
converted into the class file. Moreover, all the processes that happen in Servlet are
performed on JSP later like initialization, committing response to the browser and destroy.

A First Java Server Page Example:


To create the first JSP page, write some HTML code as given below, and save it by .jsp
extension. We have saved this file as index.jsp. Put it in a folder and paste the folder in the
web-apps directory in apache tomcat to run the JSP page.

index.jsp

Let's see the simple example of JSP where we are using the scriptlet tag to put Java code in
the JSP page. We will learn scriptlet tag later.

1. <html>
2. <body>
3. <% out.print(2*5); %>
4. </body>
5. </html>

It will print 10 on the browser.

How to run a simple JSP Page?

Follow the following steps to execute this JSP page:

o Start the server


o Put the JSP file in a folder and deploy on the server
o Visit the browser by the URL http://localhost:portno/contextRoot/jspfile, for example,
http://localhost:8888/myapplication/index.jsp

Do I need to follow the directory structure to run a simple JSP?

No, there is no need of directory structure if you don't have class files or TLD files. For
example, put JSP files in a folder directly and deploy that folder. It will be running fine.
However, if you are using Bean class, Servlet or TLD file, the directory structure is required.
5.10.3 The Directory structure of JSP

The directory structure of JSP page is same as Servlet. We contain the JSP page outside the
WEB-INF folder or in any directory.

5.11 Implicit Objects in JSP:

There are 9 jsp implicit objects. These objects are created by the web container that are
available to all the jsp pages.

The available implicit objects are out, request, config, session, application etc.

A list of the 9 implicit objects is given below:

Object Type

out JspWriter

request HttpServletRequest

response HttpServletResponse

config ServletConfig
application ServletContext

session HttpSession

pageContext PageContext

page Object

exception Throwable
1) JSP out implicit object

For writing any data to the buffer, JSP provides an implicit object named out. It is the object
of JspWriter. In case of servlet you need to write:

1. PrintWriter out=response.getWriter();

But in JSP, you don't need to write this code.

Example of out implicit object

In this example we are simply displaying date and time.

index.jsp
1. <html>
2. <body>
3. <% out.print("Today is:"+java.util.Calendar.getInstance().getTime()); %>
4. </body>
5. </html>
Output

5.12 JSP Directives:


The jsp directives are messages that tells the web container how to translate a JSP page
into the corresponding servlet.

There are three types of directives:

o page directive
o include directive
o taglib directive

Syntax of JSP Directive


1. <%@ directive attribute="value" %>

5.12.1 JSP page directive

The page directive defines attributes that apply to an entire JSP page.

Syntax of JSP page directive


1. <%@ page attribute="value" %>
Attributes of JSP page directive
o import
o contentType
o extends
o info
o buffer
o language
o isELIgnored
o isThreadSafe
o autoFlush
o session
o pageEncoding
o errorPage
o isErrorPage

1)import
The import attribute is used to import class,interface or all the members of a package.It is similar to import
keyword in java class or interface.
Example of import attribute
1. <html>
2. <body>
3.
4. <%@ page import="java.util.Date" %>
5. Today is: <%= new Date() %>
6.
7. </body>
8. </html>

2)contentType

The contentType attribute defines the MIME(Multipurpose Internet Mail Extension) type of
the HTTP response.The default value is "text/html;charset=ISO-8859-1".

Example of contentType attribute


1. <html>
2. <body>
3.
4. <%@ page contentType=application/msword %>
5. Today is: <%= new java.util.Date() %>
6.
7. </body>
8. </html>

3)extends

The extends attribute defines the parent class that will be inherited by the generated
servlet.It is rarely used.

4)info

This attribute simply sets the information of the JSP page which is retrieved later by using
getServletInfo() method of Servlet interface.

Example of info attribute


1. <html>
2. <body>
3.
4. <%@ page info="composed by Sonoo Jaiswal" %>
5. Today is: <%= new java.util.Date() %>
6.
7. </body>
8. </html>

The web container will create a method getServletInfo() in the resulting servlet.For example:

1. public String getServletInfo() {


2. return "composed by Sonoo Jaiswal";
3. }

5)buffer

The buffer attribute sets the buffer size in kilobytes to handle output generated by the JSP
page.The default size of the buffer is 8Kb.

Example of buffer attribute


1. <html>
2. <body>
3.
4. <%@ page buffer="16kb" %>
5. Today is: <%= new java.util.Date() %>
6.
7. </body>
8. </html>

6)language

The language attribute specifies the scripting language used in the JSP page. The default
value is "java".

7)isELIgnored
We can ignore the Expression Language (EL) in jsp by the isELIgnored attribute. By default its value is false i.e.
Expression Language is enabled by default. We see Expression Language later.
1. <%@ page isELIgnored="true" %>//Now EL will be ignored

8)isThreadSafe
Servlet and JSP both are multithreaded.If you want to control this behaviour of JSP page, you can use
isThreadSafe attribute of page directive.The value of isThreadSafe value is true.If you make it false, the web
container will serialize the multiple requests, i.e. it will wait until the JSP finishes responding to a request before
passing another request to it.If you make the value of isThreadSafe attribute like:

<%@ page isThreadSafe="false" %>

The web container in such a case, will generate the servlet as:

1. public class SimplePage_jsp extends HttpJspBase


2. implements SingleThreadModel{
3. .......
4. }

9)errorPage

The errorPage attribute is used to define the error page, if exception occurs in the current
page, it will be redirected to the error page.

Example of errorPage attribute


1. //index.jsp
2. <html>
3. <body>
4.
5. <%@ page errorPage="myerrorpage.jsp" %>
6.
7. <%= 100/0 %>
8.
9. </body>
10. </html>

10)isErrorPage

The isErrorPage attribute is used to declare that the current page is the error page.

Note: The exception object can only be used in the error page.
Example of isErrorPage attribute
1. //myerrorpage.jsp
2. <html>
3. <body>
4.
5. <%@ page isErrorPage="true" %>
6.
7. Sorry an exception occured!<br/>
8. The exception is: <%= exception %>
9.
10. </body>
11. </html>

5.12.2 JSP Standard Actions:

There are many JSP action tags or elements. Each JSP action tag is used to perform some specific
tasks.

The action tags are used to control the flow between pages and to use Java Bean. The Jsp action tags
are given below.

JSP Action Tags Description

jsp:forward forwards the request and response to another resource.

jsp:include includes another resource.

jsp:useBean creates or locates bean object.

jsp:setProperty sets the value of property in bean object.

jsp:getProperty prints the value of property of the bean.

jsp:plugin embeds another components such as applet.

jsp:param sets the parameter value. It is used in forward and include mostly.

jsp:fallback can be used to print the message if plugin is working. It is used in jsp:plugin.

The jsp:useBean, jsp:setProperty and jsp:getProperty tags are used for bean development. So we will
see these tags in bean developement.

jsp:forward action tag


The jsp:forward action tag is used to forward the request to another resource it may be jsp,
html or another resource.

Syntax of jsp:forward action tag without parameter

1. <jsp:forward page="relativeURL | <%= expression %>" />


Syntax of jsp:forward action tag with parameter

1. <jsp:forward page="relativeURL | <%= expression %>">


2. <jsp:param name="parametername" value="parametervalue | <%=expression%>" />
3. </jsp:forward>

Example of jsp:forward action tag without parameter

In this example, we are simply forwarding the request to the printdate.jsp file.

index.jsp

1. <html>
2. <body>
3. <h2>this is index page</h2>
4.
5. <jsp:forward page="printdate.jsp" />
6. </body>
7. </html>
printdate.jsp

1. <html>
2. <body>
3. <% out.print("Today is:"+java.util.Calendar.getInstance().getTime()); %>
4. </body>
5. </html>

The jsp:include action tag is used to include the content of another resource it may be jsp,
html or servlet.

The jsp include action tag includes the resource at request time so it is better for dynamic
pages because there might be changes in future.

The jsp:include tag can be used to include static as well as dynamic pages.

5.12.3 Advantage of jsp:include action tag

Code reusability : We can use a page many times such as including header and footer
pages in all pages. So it saves a lot of time.

5.12.4 Difference between jsp include directive and include action

JSP include directive JSP include action

includes resource at translation time. includes resource at request time.

better for static pages. better for dynamic pages.

includes the original content in the generated servlet. calls the include method.

Syntax of jsp:include action tag without parameter


1. <jsp:include page="relativeURL | <%= expression %>" />
Syntax of jsp:include action tag with parameter
1. <jsp:include page="relativeURL | <%= expression %>">
2. <jsp:param name="parametername" value="parametervalue | <%=expression%>" />
3. </jsp:include>

Example of jsp:include action tag without parameter

In this example, index.jsp file includes the content of the printdate.jsp file.

File: index.jsp
1. <h2>this is index page</h2>
2.
3. <jsp:include page="printdate.jsp" />
4.
5. <h2>end section of index page</h2>
File: printdate.jsp
1. <% out.print("Today is:"+java.util.Calendar.getInstance().getTime()); %>
5.13 Custom Tag in JSP:

Custom tags are user-defined tags. They eliminates the possibility of scriptlet tag and
separates the business logic from the JSP page.

The same business logic can be used many times by the use of custom tag.

Advantages of Custom Tags

The key advantages of Custom tags are as follows:

1. Eliminates the need of scriptlet tag The custom tags eliminates the need of scriptlet tag
which is considered bad programming approach in JSP.
2. Separation of business logic from JSP The custom tags separate the the business logic
from the JSP page so that it may be easy to maintain.
3. Re-usability The custom tags makes the possibility to reuse the same business logic again
and again.

Syntax to use custom tag

There are two ways to use the custom tag. They are given below:

00:00/05:19
1. <prefix:tagname attr1=value1....attrn=valuen />
1. <prefix:tagname attr1=value1....attrn=valuen >
2. body code
3. </prefix:tagname>

5.14 JSP Custom Tag API

The javax.servlet.jsp.tagext package contains classes and interfaces for JSP custom tag API.
The JspTag is the root interface in the Custom Tag hierarchy.
JspTag interface

The JspTag is the root interface for all the interfaces and classes used in custom tag. It is a
marker interface.

Tag interface

The Tag interface is the sub interface of JspTag interface. It provides methods to perform
action at the start and end of the tag.

Fields of Tag interface

There are four fields defined in the Tag interface. They are:

Field Name Description

public static int EVAL_BODY_INCLUDE it evaluates the body content.


public static int EVAL_PAGE it evaluates the JSP page content after the
custom tag.

public static int SKIP_BODY it skips the body content of the tag.

public static int SKIP_PAGE it skips the JSP page content after the
custom tag.
Methods of Tag interface

The methods of the Tag interface are as follows:

Method Name Description

public void it sets the given PageContext object.


setPageContext(PageContext pc)

public void setParent(Tag t) it sets the parent of the tag handler.

public Tag getParent() it returns the parent tag handler object.

public int doStartTag()throws it is invoked by the JSP page implementation


JspException object. The JSP programmer should override this
method and define the business logic to be
performed at the start of the tag.

public int doEndTag()throws it is invoked by the JSP page implementation


JspException object. The JSP programmer should override this
method and define the business logic to be
performed at the end of the tag.

public void release() it is invoked by the JSP page implementation


object to release the state.

IterationTag interface

The IterationTag interface is the sub interface of the Tag interface. It provides an additional
method to reevaluate the body.

Field of IterationTag interface

There is only one field defined in the IterationTag interface.

o public static int EVAL_BODY_AGAIN it reevaluates the body content.


Method of Tag interface

There is only one method defined in the IterationTag interface.

o public int doAfterBody()throws JspException it is invoked by the JSP page implementation


object after the evaluation of the body. If this method returns EVAL_BODY_INCLUDE, body
content will be reevaluated, if it returns SKIP_BODY, no more body cotent will be evaluated.
6 Question Bank
UNIT 1
 What is a web Project? Explain various web development strategies?
 Discuss Web Team and ity types?
 Discuss various roles of a web Team?
 Explain various Protocols used in web?
 Explain web page and its types?
 What are Keywords in java?
 Explain various Data types available in java?
 What are Packages and how they are created?
 Discuss Threads and how they are created in java?
 How String Handling is done in java?
 What is AWT? And how GUI can be created by it?
 Explain Layout Managers in java?

UNIT-II

1. Define Anchor tag with an example.

2. List the types of Style sheets.

3. Define image tag with an example.

4. Define Ordered list with an example.

5. Define Heading Tags with an example.

6. What is JavaScript? Write the advantages of JavaScript

7. What is the difference between GET and POST methods in JavaScript.

8. What is the scope of the variables in JavaScript.

9. Define Event. How events are handled in JavaScript.

10. What is DATE object in JavaScript.


11. Define XML? What are the advantages of XML.

12. Explain about the purpose of DTD.

13. Why are attributes used in XML.


14. Define DTD.

15. Define naming rules in XML.

16. Define XML Schema.

17. Distinguish between DTD and XSD.

18. Define SAX Parser.

19. Distinguish HTML and XHTML.

20. Define DOM

LONG QUESTIONS:

1. a) Explain the structure of the HTML webpage with an example.

b) Define List Tag with an example.

2. Define Frameset, Frame Tag. Divide the web page into four equal parts each individual part displays
different web page.
3. Define Form tag. Design a Registration page by using all Form controls.
4. Define Table tag and their attributes with an example.

5. Explain about Cascading Style Sheets with an example.


6. Explain various operators and data types available in java script with examples.

7. a) What is the need of scripting languages in web Technologies.


b) Build a JavaScript program to convert temperature from Celsius to Fahrenheit and vice versa.
8. How can both Internal and External DTDs be used in an XML File? Show with an Example
9. What is SAX? Write Advantages, Disadvantages and Features of SAX parser
10. Compare HTML and XML

11. Explain the procedure for validating the XML Documents

UNIT –III
 What is a client side scripting language?
 Discuss javascript and its advantage?
 Explain how function are written in java script?
 Explain various javascript objects with example?
 Discuss how event handling is done in java script?
 Write short note on VB SCRIPT?
 Discuss the working of AJAX?
 Discuss IPAdresses?
 What is subnetting and supernetting?
 Explain factory methods and instance methods?
 Discuss TCP/IP Client and server socket?
 What is Datagram?

UNIT-IV
 What are java Beans? Explain their Prperties?
 Discuss Enterprise java Beans?
 What are Application Servers? Give some example of it?
 Discuss types of EJB?
 What are session Beans? Explain its types?
 What are Entity Beans? Explain with example?
 Why message driven beans are used?
 What is a JDBC API?
 Explain various classes and Interfaces available in java.sql package?
 Discuss all the JDBC Drivers?
 WAP in java and connect it with any database like oracle using type-4 Driver?
 What are stored procedures and how they are called fron java application?

UNIT-V

1. How is Servlet different from an Applet.

2. Explain about Servlet API.

3. How to create a cookie using servlet

4. What is servlet?

5. What are the Difference between Generic Servlet and HTTPServlet?

6. Discuss about Http Request

7. What is Session?

8. Discuss about Http Responses

9. What are the different types of session tracking mechanism supported by Servlets?
10. Explain about Common gateway interface.
11. Define JSP expression.

12. What are the directives in jsp with syntax?

13. What is the syntax of jsp?

14. Explain about Scriptlet Tag.

15. What are implicit objects in jsp?


16. Explain about the methods of getProperty() and setProperty().

17. What is jsp?

18. What are the Beans in jsp page.

19. What are the difference between JSP and HTML.

20. How are Cookies used for Session tracking in JSP.

LONG TYPE:

1. Justify the Common Gateway Interface (CGI) with neat Diagram

2. What is Servlet? Explain about Servlet API

3. a)What are the advantages of Servlets over CGI.

b) Explain Life Cycle of a Servlet.

4. Explain about Lifecycle of a Servlet with neat diagram

5. a)Distinguish between CGI and Servlets

b)Develop a Servlet that handles an HTTP POST request.

6. Develop a Servlet that handles an HTTP POST request.

7. What is JDBC.What are the various drivers of JDBC.

8. a)Distinguish between Get request and Post request type in Servlets. b)Discuss about Session tracking
in Servlets with a suitable example.
9. What is JDBC? How to connecting to a database using JDBC

10. Demonstrate the use of Cookies in Servlets with an example.


1. Justify the differences between servlets and jsp.
2. Explain about the jsp processing.

3. Explain about the different methods used for Session tracking

4. Explain the components of jsp.

5. Discuss about the code snippets in detail.

6. Explain about the anatomy of jsp.

7. Explain about the getProperty() and setProperty() of beans in jsp.

8. Explain about the JSP directive Elements.Explain each of them in detail.


9. How does Jdbc allows to access database through java

10. Explain about the JDBC Drivers.

7 Multiple Choice Question

UNIT 1

. Who invented Java Programming?


a) Guido van Rossum
b) James Gosling
c) Dennis Ritchie
d) Bjarne Stroustrup
2. Which statement is true about Java?
a) Java is a sequence-dependent programming language
b) Java is a code dependent programming language
c) Java is a platform-dependent programming language
d) Java is a platform-independent programming language

3. Which component is used to compile, debug and execute the java programs?
a) JRE
b) JIT
c) JDK
d) JVM

4. Which of these cannot be used for a variable name in Java?


a) identifier & keyword
b) identifier
c) keyword
d) none of the mentioned

5. What is the extension of java code files?


a) .js
b) .txt
c) .class
d) .java

6. Which of the following is not an OOPS concept in Java?


a) Polymorphism
b) Inheritance
c) Compilation
d) Encapsulation

7. Which of the following is a type of polymorphism in Java Programming?


a) Multiple polymorphism
b) Compile time polymorphism
c) Multilevel polymorphism
d) Execution time polymorphism

8. What is the extension of compiled java classes?


a) .txt
b) .js
c) .class
d) .java

9. Which exception is thrown when java is out of memory?


a) MemoryError
b) OutOfMemoryError
c) MemoryOutOfBoundsException
d) MemoryFullException

10. Which of these are selection statements in Java?


a) break
b) continue
c) for()
d) if()

11. Which of these packages contains the exception Stack Overflow in Java?
a) java.io
b) java.system
c) java.lang
d) java.util

12. Which of these keywords are used for the block to be examined for exceptions?
a) check
b) throw
c) catch
d) try

13. Which one of the following is not an access modifier?


a) Protected
b) Void
c) Public
d) Private
14. Which class provides system independent server side implementation?
a) Server
b) ServerReader
c) Socket
d) ServerSocket

15.Which of these can be overloaded?


a) Methods
b) Constructors
c) All of the mentioned
d) None of the mentioned

UNIT 2

1. What is HTML?
a) HTML describes the structure of a webpage
b) HTML is the standard markup language mainly used to create web pages
c) HTML consists of a set of elements that helps the browser how to view the content
d) All of the mentioned

2. Who is the father of HTML?


a) Rasmus Lerdorf
b) Tim Berners-Lee
c) Brendan Eich
d) Sergey Brin

3. Which of the following is used to read an HTML page and render it?
a) Web server
b) Web network
c) Web browser
d) Web matrix

4. Which of the following tag is used for inserting the largest heading in HTML?
a) head
b) <h1>
c) <h6>
d) heading

5. What is DOM in HTML?


a) Language dependent application programming
b) Hierarchy of objects in ASP.NET
c) Application programming interface
d) Convention for representing and interacting with objects in html documents

6. Which element is used to get highlighted text in HTML5?


a) <u>
b) <mark>
c) <highlight>
d) <b>

7. Which of the following elements in HTML5 defines video or movie content?


a) <video>
b) <movie>
c) <audio>
d) <media>

8. Which HTML tag is used to insert an image?


a) <img url=”htmllogo.jpg” />
b) <img alt=”htmllogo.jpg” />
c) <img src=”htmllogo.jpg” />
d) <img link=”htmllogo.jpg” />

9. Which of the following HTML tag is used to create an unordered list?


a) <ol>
b) <ul>
c) <li>
d) <ll>

10. What is CSS?


a) CSS is a style sheet language
b) CSS is designed to separate the presentation and content, including layout, colors, and fonts
c) CSS is the language used to style the HTML documents
d) All of the mentioned

12. Which of the following tag is used to embed css in html page?
a) <css>
b) <!DOCTYPE html>
c) <script>
d) <style>

13. Which of the following has introduced text, list, box, margin, border, color, and background properties?
a) HTML
b) PHP
c) CSS
d) Ajax

13. Which of the following CSS selector is used to specify a rule to bind a particular unique element?
a) tag
b) id
c) class
d) both class and tag

14. Which of the following type of HTML tag is used to define an internal style sheet?
a) <script>
b) <link>
c) <class>
d) <style>
15. Which of the following CSS property is used to make the text bold?
a) text-decoration: bold
b) font-weight: bold
c) font-style: bold
d) text-align: bold

16. Which of the following CSS style property is used to specify an italic text?
a) style
b) font
c) font-style
d) @font-face

17. Which of the following is the correct syntax to link an external style sheet in the HTML file?
a) <link rel=”stylesheet” href=”style.css” />
b) <link rel=”stylesheet” src=”style.css” />
c) <style rel=”stylesheet” src=”style.css” />
d) <style rel=”stylesheet” link=”style.css” />

18. Which of the following is the first CSS specification to become an official W3C Recommendation?
a) CSS level 2
b) (X)HTML CSS
c) CSS level 1
d) CSS level 2.1

19. Which of the following CSS property can be used to set the image as a border instead of the border style?
a) background-image-source
b) background-image
c) border-image-source
d) border-image

20. Which of the following CSS property sets the font size of text?
a) font-size
b) text-size
c) text
d) size

UNIT 3
1. Which is not valid data type in Javascript
Undefinded
Boolean
float
Number

2. Which type of language is Javascript


Programming
Scripting
Markup
None of the above
3. By which javascript code is used
Classes
Methods/Functions
RMI
Events

4. Which tag is used to write the javascript code


<script>
<sp>
<javascript>
<java>

5. Which of the following function of String object causes a string to be italic, as if it were in an <i> tag?
fontsize()
fontcolor()
fixed()
italics()

6. Why so JavaScript and Java have similar name?


They both originated on the island of Java
JavaScript's syntax is loosely based on Java's
Both A and B
None of the above

7. Output is
<script type="text/javascript">
var a="GeeksforGeeks";
var x=a.lastIndexOf("G");
document.write(x);
</script>
8
9
0
Nothing

8. The escape sequence ‘\f’ stands for


Floating numbers
Representation of functions that returns a value
Form feed
None of the above

9. Purpose of designing the Javascript


To Perform Server Side Scripting Opertion
To add interactivity to HTML Pages
To Style HTML Pages
All of the above

10. Which of the following function of Array object removes the last element from an array and returns that
element?
push()
delete()
pop()
link()

11. A Javascript developed in Unix machine


will throw errors and exceptions
must be restricted to a Unix Machine only C.
will be displayed as a JavaScript text on the browser
will work perfectly well on a Windows Machine

12. Output is
<script type="text/javascript" language="javascript">

var a = "GeeksforGeeks";
var result = a.substring(4, 5);
document.write(result);

</script>
sf
s
sk
sfk

13. Original Name of Javascript is


Mocha
LiveScript
Escript
Javascript

14. What is the output?


int a==2;
int b=4;
int ans=a+b;
print(ans);
2
6
error
0

15. What are the types of Pop up boxes available in JavaScript?


Prompt
Alert
Confirm
All of the above

16. Javascript is which type of language


Interpreted
Compiled

17. Which of the following function of String object returns the characters in a string between two indexes into
the string?
substr()
substring()
string()
count()

18. Assume the Output


var a = '20';

var b = a = 30;

document.write(a+b);
60
20
30
50

19. Javascript is ideal to


increase the download time for the client
minimize storage requirements on the web server
make computations in HTML simpler
None of the above

20. A function definition expression is known as


Function calls
Function definiation
Function calling
Function literal

UNIT 4
1. Which of the following is true about session bean?
A. This type of bean stores data of a particular user for a single session
B. This is a type of enterprise bean which is invoked by EJB container when it receives a message from queue
or topic
C. This type of bean represents persistent data storage
D. None of the above

2. Which case of a session bean obtains the UserTransaction object via the EJBContext using the
getUserTransaction() method in EJB transaction management?
A. Bean-managed transactions
B. Container-managed transactions
C. Both A & B
D. None of the above

3. Which of the following is correct about @PreUpdate annotation for an entity bean?
A. Method is invoked before an entity is to be updated in the database
B. Method is invoked after an entity is created in database
C. Method is invoked when an entity is deleted from the database
D. Method is invoked after an entity is deleted from the database

4. Which middleware services are provided by EJB?


A. Security
B. Transaction Management
C. Both A & B
D. None of the above

5. Abbreviate the term JMS?


A. Java Message Service
B. Java Monitor Service
C. Java Message Session
D. Java Monitor Session

6. EJB is like COM, Abbreviate the term COM?


A. Component Object Model
B. Component Oriented Model
C. Common Object Model
D. Common Oriented Model

7. What represents a persistent global data from the database?


A. Entity Bean
B. Session Bean
C. Both A & B
D. None of the above

8. Which server-side component is required to be deployed on the server?


A. EJB
B. RMI
C. Both A & B
D. None of the above

9. From the following APIs, which API does NOT guarantees to be supported by EJB 2.0 containers?
A. JAXP
B. JDBC
C. JNDI
D. JXTA

10. Which of the following are guaranteed capabilities of EJB 2.0?


A. Run-as security identity functionality
B. The extension of JDBC 2.0
C. Both A and B
D. Neither A nor B

11. Which is the method available in SessionContext interface?


A. afterBegin()
B. getRollbackOnly()
C. setSessionCotext()
D. getUserTransaction()

12. Upon invoking getRollbackOnly() method by a business method in an entity bean, which transaction
attribute settings will lead the ejb container to throw an exception?
A. Required
B. Mandatory
C. RequiresNew
D. Never

13. Which of the following is true?


A. Preserving of any state across method calls does not performed by Stateless session beans
B. Multiple users can access Stateful session beans at the same time
C. Both are correct
D. None

14. You can configure the JNDI details for factory bean in
A. jndiEnvironment
B. jndiName
C. all of the mentioned
D. none of the mentioned

15. Which session bean does the conversational state between multiple method calls is not maintained by the
container?
A. Stateful Session Bean
B. Stateless Session Bean
C. Singleton Session Bean
D. None of the above

16. Which statement is correct?


A. public interface EnterpriseBean extends Serializable { }
B. public interface EnterpriseBean extends Remote{ }
C. public interface EnterpriseBean extends EJB{ }
D. None of the above

17. Proxying Spring services with EJB3s, injecting custom resources configured in Spring, or even using
Spring to isolate your EJBs from acquiring references to other distributed resources such as a REST endpoint
or an RMI endpoint.
A. SpringBeanAutowiringInterceptor
B. SpringBeanAutowiring
C. SpringBean
D. SpringBeanInterceptor

18. What are the requirements for session BEAN CLASS?


A. The class MUST implement, directly or indirectly, the javax.ejb.SessionBean interface
B. The class MUST NOT define the finalize() method
C. The class MUST define the finalize() method
D. both 1 and 2

19. Which two of the following is responsible to creates ejb-jar files?

1. The bean provider


2. The application assembler
3. The deployer
4. The system administrator
A. 3rd and 4th
B. 1st and 2nd
C. 2nd and 3rd
D. 4th and 1st
20. Stateful Session beans contains
A. Remote Interface
B. All options are correct
C. Home Interface
D. Bean class

21. Which of the following is not a life-cycle method for a Stateful Session Bean?
A. Pre Construction
B. Pre Destruction
C. Post Construction
D. Post Activation

22. Which type of instances retain no data or conversational state for a specific client?
A. Message-Driven Bean
B. Session Bean
C. Entity Bean
D. None of the above

23. Which of the following is true about EJBQL EJB?


A. EJBQL stand for EJB Query Language
B. ejb query language is quite handy to write custom queries without worrying about underlying database
details
C. It is quite similar to HQL, hibernate query language
D. All of the above

24. EJB system’s performance tuning is the responsibility of


A. Bean Provider
B. EJB Deployer
C. Application Assembler
D. Tool Vendor

25. Which of the following is correct about a transaction in EJB?


A. A transaction is a single unit of work items
B. A transaction follows the ACID properties
C. Both of the above
D. None of the above

1. EJB stands for ?

A. Express Java Bean


B. Enterprise JS Bean
C. Enterprise Java Bean
D. Enterprise Java Business

2. How many types of enterprise bean in java?

A. 2
B. 3
C. 4
D. 5
View Answer

3. ____________ encapsulates business logic.

A. Message Driven Bean


B. Entity Bean
C. Object Bean
D. Session Bean

4. How many types of session bean?

1) What are the major components of the JDBC?

DriverManager, Driver, Connection, Statement, and ResultSet


DriverManager, Driver, Connection, and Statement
DriverManager, Statement, and ResultSet
DriverManager, Connection, Statement, and ResultSet

2) Select the packages in which JDBC classes are defined?

jdbc and javax.jdbc


rdb and javax.rdb
jdbc and java.jdbc.sql
sql and javax.sql

3) Thin driver is also known as?

Type 3 Driver
Type-2 Driver
Type-4 Driver
Type-1 Driver

4) What is the correct sequence to create a database connection?

i. Import JDBC packages.

ii. Open a connection to the database.

iii. Load and register the JDBC driver.

iv. Execute the statement object and return a query resultset.

v. Create a statement object to perform a query.


vi. Close the resultset and statement objects.

vii. Process the resultset.

viii. Close the connection.

i, ii, iii, v, iv, vii, viii, vi


i, iii, ii, v, iv, vii, vi, viii
ii, i, iii, iv, viii, vii, v, vi
i, iii, ii, iv, v, vi, vii, viii

5) Which of the following method is used to perform DML statements in JDBC?

executeResult()
executeQuery()
executeUpdate()
execute()

6) How many transaction isolation levels provide the JDBC through the Connection interface?

3
4
7
2

7) Which of the following method is static and synchronized in JDBC API?

getConnection()
prepareCall()
executeUpdate()
executeQuery()

8) Which methods are required to load a database driver in JDBC?

getConnection()
registerDriver()
forName()
Both b and c

9) Parameterized queries can be executed by?

ParameterizedStatement
PreparedStatement
CallableStatement and Parameterized Statement
All kinds of Statements

10) Which of the following is not a valid statement in JDBC?

Statement
PreparedStatement
QueryStatement
CallableStatement

11) Identify the isolation level that prevents the dirty in the JDBC Connection class?

TRANSACTION_READABLE_READ
TRANSACTION_READ_COMMITTED
TRANSACTION_READ_UNCOMMITTED
TRANSACTION_NONE

12) What does setAutoCommit(false) do?

It will not commit transactions automatically after each query.


It explicitly commits the transaction.
It never commits the transactions.
It does not commit transaction automatically after each query.

13) Stored procedure can be called by using the ????..?

CallableStatement
Statement
CalledStatement
PreparedStatement

14) What should be the correct order to close the database resource?What should be the correct order to close
the database resource?

Connection, Statements, and then ResultSet


ResultSet, Connection, and then Statements
Statements, ResultSet, and then Connection
ResultSet, Statements, and then Connection

15) A good way to debug JDBC-related problems is to enable???..?

JDBC tracing
Exception handling
Both a and b
Only b

16) Which JDBC driver can be used in servlet and applet both?

Type 3
Type 4
Type 3 and Type 2
Type 3 and Type 4

17) JDBC-ODBC driver is also known as?

Type 4
Type 3
Type 1
Type 2
18) Which of the following driver is the fastest one?

JDBC-ODBC Bridge Driver


Native API Partly Java Driver
Network Protocol Driver
JDBC Net Pure Java Driver

19) Which of the following is not a type of ResultSet object?

TYPE_FORWARD_ONLY
CONCUR_WRITE_ONLY
TYPE_SCROLL_INSENSITIVE
TYPE_SCROLL_SENSITIVE

20) What is JDBC Savepoint?

An intermediate or checkpoint in a transaction


A point where we can store queries
A point where the JDBC application starts execution
A memory where we can store transaction

21) How many stages are used by Java programmers while using JDBC in their programs?

3
2
5
6

22) Which of the following is the correct to register a JdbcOdbcDriver?

jdbc.odbc.JdbcOdbcDriver obj = new sun.jdbc.odbc.JdbcOdbcDriver();


odbc.JdbcOdbcDriver obj = new sun.odbc.JdbcOdbcDriver();
jdbc.JdbcOdbcDriver obj = new sun.jdbc.JdbcOdbcDriver();
jdbc.odbc.JdbcOdbc obj = new sun.jdbc.odbc.JdbcOdbc();

23) How many ways to register a driver?

2
3
4
5

24) Identify the DSN in the following statement:

DriverManager.getConnection("jdbc:odbc:oradsn", "scott", "tiger")


jdbc
odbc
scott
oradsn
25) Which statement is correct if we want to connect the Oracle database using the thin driver provided by
Oracle Corp.?

getConnection("jdbc::thin@localhost:1521:oracle", "scott", "tiger");


getConnection("jdbc:thin@localhost:1521:oracle", "scott", "tiger");
getConnection("jdbc::thin@localhost:1522:oracle", "scott", "tiger");
getConnection("jdbc::oracle@localhost:1521:thin", "scott", "tiger");

26) What are the types of ResultSet in JDBC?

Forward ResultSet
Scrollable ResultSet
Only a
Both a and b

27) What is blob in the following statement?

create table profilepic(photo blob);


Variable
Object
Data type
Keyword

28) Which data type is used to store files in the database table?

BLOB
CLOB
File
Both a and b

29) DatabaseMetaData interface is used to get?????..?

Comprehensive information about the database as a whole.


Comprehensive information about the table as a whole.
Comprehensive information about the column as a whole.
Both b and c

30) Which of the following driver converts the JDBC calls into database-specific calls?

JDBC-ODBC Bridge Driver (Type 1)


Native API-partly Java Driver (Type 2)
Net Protocol-pure Java Driver (Type 3)
Native Protocol-pure Java Driver (Type 4)

31) Are ResultSets updateable?

Yes, but only if we call the method openCursor() on the ResultSet and if the driver and database support this
option.
Yes, but only if we indicate a concurrency strategy when executing the statement, and if the driver and
database support this option.
Yes, but only if the ResultSet is an object of class UpdateableResultSet and if the driver and database support
this option.
No, ResultSets are never updateable. We must explicitly execute a DML statement to change the data in the
underlying database.

32) Which of the following interface provides the commit() and rollback() methods?

Statement Interface
ResultSet Interface
Connection Interface
RowSet Interface

33) How many statement objects can be created using a Connection?

2
1
3
Multiple

34) JDBC API supports____________ and __________ architecture model for accessing the database.

Two-tier
Three-tier
Both a and b
Only b

35) Which statement(s) is/ are true about transactions?

i. A transaction is a set of one or more SQL statements that make up a logical unit of work.

ii. A transaction ends with either a commit or a rollback, depending on whether there are any problems with
data consistency or data concurrency.

iii. A lock is a mechanism that allows two transactions from manipulating the same data at the same time.

iv. To avoid conflicts during a transaction, a DBMS uses locks, mechanisms for blocking access by others to
the data that is being accessed by the transaction.

Only i and ii
Only i and iii
Only i, ii, and iv
All the above

UNIT 5

1. Which option is true about session scope?


A. Objects are accessible only from the page in which they are created
B. Objects are accessible only from the pages which are in same session
C. Objects are accessible only from the pages which are processing the same request
D. Objects are accessible only from the pages which reside in same application
2. Which of the following is not a directive in JSP?
a) include
b) page
c) export
d) useBean

3. What is media type of JSP?


a) application/jsp
b) text/javax
c) java/jsp
d) java/text

4. What is default value of autoFlush attribute in JSP?


a) True
b) Null
c) False

5. In JSP config is instance of which class?


a) javax.servlet.ServletContext
b) javax.servlet.ServletConfig
c) javax.servlet.Context
d) javax.servlet.Application

6. For What JSP is used?


a) Server-side dynamic content generation
b) Client Side language for validation

7. In JSP Action tags which tags are used for bean development?
a) jsp:useBean
b) jsp:setPoperty
c) jsp:getProperty
d) All of above

8. What is the default value of isScriptingEnabled attribute?


a) True
b) False

9. Which of the following is true about <jsp:getProperty> action?


a) The getProperty action gets the properties of a bean.
b) The getProperty action converts the property of a bean to a string, and finally inserts it into the output.
c) Both of the above.
d) None of the above.

10. All servlet classes are required to be mapped and configured in web.xml.
a) Yes
b) No

11. What is Full form of JSTL?


a) JSP Tag Library
b) JavaServer Pages Standard Tag Library
c) Java Standard Tag Library
d) None of the above.

12. Which of the following do not supports JSP directly?


a) Weblogic Server
b) Apache HTTP Server
c) WebSphere Server
d) Tomcat Server

13. Where filters are defined?


a) Filters are defined in the deployment descriptor file web.xml.
b) Filters are defined in the jsp pages.
c) Both of the above.
d) None of these

14. Which of the following is not a directive?


a) page
b) include
c) export
d) useBean

15. “request” is instance of which one of the following classes?


a) HttpRequest
b) Request
c) HttpServletRequest
d) ServletRequest

16. Which method of the Component class is used to set the position and size of a component in JSP?
a) setPosition()
b) setSizePosition()
c) setBounds()
d) etSize()

17. Which of the following is not a directive?


a) export
b) page
c) include
d) useBean

18. Which of the following action variable is used to include a file in JSP?
a) jsp:getProperty
b) jsp:include
c) jsp:setProperty
d) jsp:plugin

19. Which attribute uniquely identification element?


a) Class
b) Name
c) Scope
d) ID

20. Which tag is used to set a value of a JavaBean?


a) <c:choose>
b) <c:set>
c) <c:param>
d) <c:forward>

21. Which of the following is the correct order of phases in JSP life cycle?
a) Initialization, Compilation, Cleanup, Execution
b) Compilation, Initialization, Execution, Cleanup
c) Initialization, Compilation, Cleanup, Execution
d) None of the above

22. Can a JSP page process HTML FORM data?


a) Yes
b) No

23. Which of the following page directive should be used in JSP to generate a PDF page?
a) typePDF
b) contentPDF
c) contentType
d) generatePdf

24. ........... are the valid scopes in JSP.


a) request, page, session, global
b) request, page, session, application
c) request, page, context, application
d) None of the above

25. Which of the following is correct for directive in JSP?


a) <%@directive%>
b) <%directive%>
c) <%!directive%>
d) None of the above

1) Connection Pooling Class manages no of user requests for connections to improve the performance.
- Published on 19 Oct 15

a. True
b. False

2) Which object of HttpSession can be used to view and manipulate information about a session?
- Published on 19 Oct 15

a. session identifier
b. creation time
c. last accessed time
d. All mentioned above
3) Using mail API we cannot send mail from a servlet.
- Published on 22 Jul 15

a. True
b. False

4) Which class provides stream to read binary data such as image etc. from the request object?
- Published on 22 Jul 15

a. ServltInputStream
b. ServletOutputStream
c. Both A & B
d. None of the above

5) The sendRedirect() method of HttpServletResponse interface can be used to redirect response to another
resource, it may be servlet, jsp or html file.
- Published on 22 Jul 15

a. True
b. False

6) Which of these ways used to communicate from an applet to servlet?


- Published on 22 Jul 15

a. RMI Communication
b. HTTP Communication
c. Socket Communication
d. All mentioned above

7) Which methods are used to bind the objects on HttpSession instance and get the objects?
- Published on 22 Jul 15

a. setAttribute
b. getAttribute
c. Both A & B
d. None of the above

8) Which type of ServletEngine is a server that includes built-in support for servlets?
- Published on 21 Jul 15

a. Add-on ServletEngine
b. Embedded ServletEngine
c. Standalone ServletEngine
d. None of the above

9) What type of servlets use these methods doGet(), doPost(),doHead, doDelete(), doTrace()?

- Published on 21 Jul 15

a. Genereic Servlets
b. HttpServlets
c. All of the above
d. None of the above

10) Which cookie it is valid for single session only and it is removed each time when the user closes the
browser?
- Published on 20 Jul 15

a. Persistent cookie
b. Non-persistent cookie
c. All the above
d. None of the above

11) Sessions is a part of the SessionTracking and it is for maintaining the client state at server side.
- Published on 20 Jul 15

a. True
b. False

12) Web server is used for loading the init() method of servlet.
- Published on 20 Jul 15

a. True
b. False

13) Servlets handle multiple simultaneous requests by using threads.


- Published on 20 Jul 15

a. True
b. False

14) Which method is used to send the same request and response objects to another servlet in
RequestDispacher ?
- Published on 20 Jul 15

a. forward()
b. sendRedirect()
c. Both A & B
d. None of the above

15) Which packages represent interfaces and classes for servlet API?
- Published on 17 Jul 15

a. javax.servlet
b. javax.servlet.http
c. Both A & B
d. None of the above

16) Which class can handle any type of request so that it is protocol-independent?
- Published on 17 Jul 15

a. GenericServlet
b. HttpServlet
c. Both A & B
d. None of the above

17) Which HTTP Request method is non-idempotent?


- Published on 16 Jul 15

a. GET
b. POST
c. BOTH A & B
d. None of the above

18) Which object is created by the web container at time of deploying the project?
- Published on 15 Jul 15

a. ServletConfig
b. ServletContext
c. Both A & B
d. None of the above

19) What is the lifecycle of a servlet?


- Published on 15 Jul 15

a. Servlet class is loaded


b. Servlet instance is created
c. init,Service,destroy method is invoked
d. All mentioned above

20) Which method in session tracking is used in a bit of information that is sent by a web server to a browser
and which can later be read back from that browser?
- Published on 15 Jul 15

a. HttpSession
b. URL rewriting
c. Cookies
d. Hidden form fields

8 Previous Year Question Papers

2010 to 2015

You might also like