Web Technology PDF
Web Technology PDF
Web Technology PDF
Web Technology
® ®
TECHNICAL
PUBLICATIONS
SINCE 1993 An Up-Thrust for Knowledge
(i)
Web Technology
Subject Code : 310252
Published by :
® ® Amit Residency, Office No.1, 412, Shaniwar Peth,
TECHNICAL Pune - 411030, M.S. INDIA Ph.: +91-020-24495496/97
PUBLICATIONS
SINCE 1993 An Up-Thrust for Knowledge Email : [email protected] Website : www.technicalpublications.org
Printer :
Yogiraj Printers & Binders
Sr. No. 10/1A,
Ghule Industrial Estate, Nanded Village Road,
Tal. - Haveli, Dist. - Pune - 411041.
ISBN 978-93-91567-28-6
Author
A. A. Puntambekar
Dedicated to God
(iii)
Syllabus
Web Technology - (310252)
Credit : Examination Scheme :
(iv)
Unit V Server Side Scripting Languages
PHP : Introduction to PHP, uses of PHP, general syntactic characteristics, Primitives,
operations and expressions, output, control statements, arrays, functions, pattern matching,
form handling, files, cookies, session tracking, using MySQL with PHP, WAP and WML.
Introduction to ASP.NET : Overview of the .NET Framework, Overview of C#,
Introduction to ASP.NET, ASP.NET Controls, Web Services. Overview of Node JS.
(Chapter - 5)
(v)
Table of Contents
Unit - I
Chapter - 1 Web Essentials and Mark - up Language - HTML
(1 - 1) to (1 - 146)
Part I : Web Essentials
1.1 Basic Concepts ................................................................................................. 1 - 3
1.1.1 What is Web Technology ? ................................................................................ 1 - 3
1.1.2 Concept of Internet ........................................................................................... 1 - 3
1.1.3 Concept of World Wide Web............................................................................. 1 - 3
1.1.4 Internet or WWW ? ........................................................................................... 1 - 4
(vi)
1.10 History and Versions .................................................................................... 1 - 23
1.11 Structure of HTML ....................................................................................... 1 - 24
1.12 HTML Elements ............................................................................................ 1 - 25
1.12.1 Heading .......................................................................................................... 1 - 25
1.12.2 Paragraphs ..................................................................................................... 1 - 26
1.12.3 Line Break ...................................................................................................... 1 - 27
1.12.4 Setting Font Style ........................................................................................... 1 - 28
1.12.5 Text Alignment .............................................................................................. 1 - 29
1.12.6 Setting the Font and Color............................................................................. 1 - 30
1.12.7 Special Character ........................................................................................... 1 - 34
(vii)
1.18.6 Menus ............................................................................................................ 1 - 81
(viii)
1.26.5 Font Weights ............................................................................................... 1 - 117
1.26.6 Font Shorthands .......................................................................................... 1 - 118
1.26.7 Text Decoration ........................................................................................... 1 - 119
1.26.8 Alignment of Text ........................................................................................ 1 - 120
(ix)
2.11 Statements ................................................................................................... 2 - 12
2.11.1 If Statement ................................................................................................... 2 - 12
2.11.2 Switch Statement .......................................................................................... 2 - 15
2.11.3 Loop Statement ............................................................................................. 2 - 17
2.11.3.1 while Loop .................................................................................................. 2 - 17
2.11.3.2 do..while Loop ............................................................................................ 2 - 18
2.11.3.3 for Loop ...................................................................................................... 2 - 19
2.11.3.4 break Statement ......................................................................................... 2 - 20
2.11.3.5 The continue Statement ............................................................................. 2 - 21
(x)
2.16.2 Initializing an Array ........................................................................................ 2 - 49
2.16.3 Defining an Array Elements ........................................................................... 2 - 49
2.16.4 Looping an Array............................................................................................ 2 - 52
2.16.5 Adding an Array Element ............................................................................... 2 - 53
2.16.6 Sorting an Array Element ............................................................................... 2 - 54
2.16.7 Combining Array Elements into String........................................................... 2 - 56
2.16.8 Changing Elements of an Array ..................................................................... 2 - 57
(xi)
Part III : jQuery
2.25 jQuery ........................................................................................................ 2 - 103
2.25.1 Introduction to jQuery ................................................................................. 2 - 103
2.25.2 Basic Syntax ................................................................................................. 2 - 104
2.25.3 Loading jQuery............................................................................................. 2 - 104
2.25.4 Selecting Elements....................................................................................... 2 - 106
2.25.5 Changing Styles ............................................................................................ 2 - 113
2.25.6 Creating Elements........................................................................................ 2 - 114
2.25.7 Appending Elements.................................................................................... 2 - 116
2.25.8 Removing Elements ..................................................................................... 2 - 117
Part IV : Angular JS
2.26 Overview of Angular JS .............................................................................. 2 - 120
2.26.1 MVC with Angular JS.................................................................................... 2 - 121
2.26.2 Directives ..................................................................................................... 2 - 122
2.26.3 Expression .................................................................................................... 2 - 127
2.26.4 Controllers ................................................................................................... 2 - 129
2.26.5 Filters ........................................................................................................... 2 - 133
2.26.6 Tables........................................................................................................... 2 - 140
2.26.7 Modules ....................................................................................................... 2 - 143
2.26.8 Forms ........................................................................................................... 2 - 146
2.26.9 Includes........................................................................................................ 2 - 152
2.26.10 Views ......................................................................................................... 2 - 154
2.26.11 Scopes ........................................................................................................ 2 - 156
2.26.12 Services ...................................................................................................... 2 - 158
2.26.13 Dependency Injection ................................................................................ 2 - 164
2.26.14 Custom Directives ...................................................................................... 2 - 167
2.26.15 Internationalization ................................................................................... 2 - 169
(xii)
Unit - III
Chapter - 3 Java Servlets and XML (3 - 1) to (3 - 130)
Part I : Servlet
3.1 Introduction to Server Side Programming ....................................................... 3 - 3
3.2 Servlet Architecture Overview......................................................................... 3 - 3
3.2.1 Need and Advantages........................................................................................ 3 - 5
(xiii)
3.14 Databases (MySQL) and Java Servlets ......................................................... 3 - 52
3.14.1 Structured Query Language using MySQL ..................................................... 3 - 52
3.14.2 JDBC Perspectives .......................................................................................... 3 - 57
3.14.2.1 How JDBC Works ? ..................................................................................... 3 - 58
3.14.2.2 Difference between JDBC and ODBC.......................................................... 3 - 58
3.14.2.3 Uses of JDBC ............................................................................................... 3 - 58
3.14.3 Steps for Connectivity between Servlet and Database ................................. 3 - 59
3.14.4 Implementation ............................................................................................. 3 - 60
Part II : XML
3.15 XML Documents and Vocabularies .............................................................. 3 - 81
3.16 XML Declaration .......................................................................................... 3 - 83
3.16.1 Declaring Elements ........................................................................................ 3 - 84
3.16.2 Declaring Attributes....................................................................................... 3 - 85
3.16.3 Declaring Entities ........................................................................................... 3 - 87
3.17 Rules............................................................................................................. 3 - 88
3.18 XML Namespaces ......................................................................................... 3 - 89
3.19 Document Type Definition (DTD) ................................................................ 3 - 89
3.20 Schema......................................................................................................... 3 - 94
3.20.1 Data Types ..................................................................................................... 3 - 96
3.20.2 Advantages and Disadvantages of Schema ................................................... 3 - 98
(xiv)
3.26 Coding AJAX Script ..................................................................................... 3 - 121
3.27 Multiple Choice Questions with Answers .................................................. 3 - 127
Unit - IV
Chapter - 4 JSP and Web Services (4 - 1) to (4 - 100)
Part I : JSP
(xv)
Part III : Struts
4.11 Overview ...................................................................................................... 4 - 53
4.12 Architecture ................................................................................................. 4 - 54
4.13 Execution of First Struts Applications .......................................................... 4 - 55
4.14 Configuration ............................................................................................... 4 - 62
4.15 Actions ......................................................................................................... 4 - 63
4.16 Interceptors ................................................................................................. 4 - 71
4.17 Result Types ................................................................................................. 4 - 77
4.18 Validations ................................................................................................... 4 - 80
4.19 Localization .................................................................................................. 4 - 84
4.20 Exception Handling ...................................................................................... 4 - 90
4.21 Annotations ................................................................................................. 4 - 95
4.22 Multiple Choice Questions with Answers .................................................... 4 - 98
Unit - V
Chapter - 5 Server Side Scripting Languages (5 - 1) to (5 - 138)
Part I : PHP
5.1 Introduction to PHP ......................................................................................... 5 - 3
5.1.1 Origins and Uses of PHP .................................................................................... 5 - 3
5.1.2 Overview ............................................................................................................ 5 - 3
5.1.3 Installation of PHP ............................................................................................. 5 - 3
(xvi)
5.4 Type Conversion .............................................................................................. 5 - 7
5.5 Operations and Expressions ............................................................................ 5 - 8
5.5.1 Arithmetic Operators......................................................................................... 5 - 8
5.5.2 Relational Operators.......................................................................................... 5 - 9
5.5.3 Boolean Operators............................................................................................. 5 - 9
5.5.4 String Operators ................................................................................................ 5 - 9
5.9 Functions........................................................................................................ 5 - 29
5.9.1 General Characteristics of Functions ............................................................... 5 - 29
5.9.2 Parameters ...................................................................................................... 5 - 30
(xvii)
5.14 Cookies......................................................................................................... 5 - 50
5.14.1 Introduction to Cookies ................................................................................. 5 - 50
5.14.2 PHP Support for Cookies................................................................................ 5 - 50
5.15 Session Tracking........................................................................................... 5 - 51
5.16 Using MySQL with PHP ................................................................................ 5 - 53
5.16.1 Connecting to Database ................................................................................ 5 - 53
5.16.2 Creating Database ......................................................................................... 5 - 54
5.16.3 Selecting Database ........................................................................................ 5 - 55
5.16.4 Listing Database............................................................................................. 5 - 55
5.16.5 Listing Table Names ....................................................................................... 5 - 56
5.16.6 Creating a Table ............................................................................................. 5 - 56
5.16.7 Inserting Data ................................................................................................ 5 - 57
5.16.8 Altering Table ................................................................................................ 5 - 58
5.16.9 Deleting Database ......................................................................................... 5 - 59
5.17 WAP ............................................................................................................. 5 - 67
5.18 WML............................................................................................................. 5 - 68
5.18.1 Cards and Decks............................................................................................. 5 - 69
5.18.2 Sample Program ............................................................................................ 5 - 69
5.18.3 Comments ..................................................................................................... 5 - 71
5.18.4 Paragraph ...................................................................................................... 5 - 71
5.18.5 Line Break ...................................................................................................... 5 - 72
5.18.6 Table .............................................................................................................. 5 - 73
5.18.7 Image ............................................................................................................. 5 - 74
5.18.8 Hyperlinks ...................................................................................................... 5 - 75
5.18.9 Inputs ............................................................................................................. 5 - 77
5.18.10 Select ........................................................................................................... 5 - 78
5.18.11 Event ............................................................................................................ 5 - 79
Part II : ASP.NET
5.19 Introduction to ASP.NET .............................................................................. 5 - 86
5.19.1 How does ASP.NET Works ? .......................................................................... 5 - 86
5.19.2 Features of ASP.NET ...................................................................................... 5 - 86
(xviii)
5.20 Overview of the .NET Framework................................................................ 5 - 87
5.21 Overview of C#............................................................................................. 5 - 88
5.21.1 Parts of C# Program ....................................................................................... 5 - 89
5.21.2 Creating First C# Program.............................................................................. 5 - 89
5.21.3 Variables ........................................................................................................ 5 - 93
5.21.4 Data Types ..................................................................................................... 5 - 93
5.21.5 Input and Output ........................................................................................... 5 - 93
5.21.6 Operators....................................................................................................... 5 - 94
5.21.7 Control Structure ........................................................................................... 5 - 99
5.21.8 The Break and Continue Statements ........................................................... 5 - 103
5.21.9 Class and Object .......................................................................................... 5 - 105
(xx)
Part II : Introduction to Rails
6.11 Overview of Rails ......................................................................................... 6 - 28
6.12 Document Requests..................................................................................... 6 - 29
6.12.1 Static Documents - Creation of First Application in Rails .............................. 6 - 30
6.12.2 Dynamic Documents...................................................................................... 6 - 35
(xxi)
Notes
(xxii)
UNIT- I
Contents
1.1 Basic Concepts
1.2 Basic Internet Protocol
1.3 The Web Site Design Issues ....................................... Dec.-18, May-19, .................. Marks 5
1.4 HTTP Request Message and Response Message ..... May-18, March-19, ............... Marks 5
1.13 Links
1.14 Frames
1.15 Lists
1.16 Tables
(1 - 1)
Web Technology 1-2 Web Essentials and Mark - up Language - HTML
1.17 Images
1.18 Forms
1.19 HTML5 ............................................... May-19, Dec.-19, .................. Marks 5
Definition : Internet is global system in which millions of computers are connected together. It is
basically a network of networks.
Using internet many people can share resources and can communicate with each
other. To have internet service one must go to the service providers. That means
your computer must be connected to the Internet Service Providers (ISP) through
phone-line modem or DSL.
There are some privately owned internet service providers from which we can hire
the internet services.
Definition : World Wide Web (WWW) is collections of software and corresponding protocols used to
access the resources over the network.
When client makes a request for particular file download then using the data
transfer connection actual data gets transmitted from server to the client.
At the same time server keeps track of how much data is sent so far and how much
is remaining. This tracking can be done using the control transfer connection.
Hence during the file downloading/uploading we can see a message about how
many bytes are getting transferred and how much time is remaining.
2) HTTP
The Hyper Text Transfer Protocol (HTTP) is a request/response protocol.
It is a communication protocol used to transfer the information on local area
network and World Wide Web (WWW).
It is the network protocol used to deliver virtually all files and other data
(collectively called resources) on the World Wide Web, whether they're HTML files,
image files, query results, or anything else. Usually, HTTP takes place through
TCP/IP sockets.
It is also called as a stateless protocol because this protocol is not able to maintain
the previous conversation/information.
3) SNMP
Simple Network Management Protocol (SNMP) is a protocol which enables
network administrators to manage network devices and to diagnose network
problems.
The network management system is based on two main elements : a supervisor and
agents.
o The supervisor is the terminal at which the network administrator requests for
network management.
o The agents are found at the level of each interface connecting the managed
devices to the network. With the help of these agents information on the
different objects (such as switch, hub, routers) can be collected.
4) SMTP
Simple Mail Transfer Protocol (SMTP) is a simple protocol which is extensively
used for transfer of e-mails to remote servers.
It is an asynchronous protocol, because it allows delayed delivery of message.
With the help of mail transfer agent and user agent the SMTP sends and receives
the emails.
5) POP3
Post Office Protocol version 3 (POP3) is used by local email clients (such as
Microsoft Outlook Express).
The POP3 protocol works only at the receivers end and has no work at the sender’s
end.
The POP protocol has two parts, a client POP i.e. receiver’s POP and a server POP
i.e. receiver’s email server. The client i.e. the receiver opens TCP connection with
receiver’s POP server. This client must be authenticated first by using the user name
and password. Then the client can receive the emails from the mailbox.
6) TCP
The transmission control protocol is used for,
1. Safe delivery of data
2. Error detection
3. Assurance of the correct sequencing of data being received.
This protocol is called connection oriented protocol because before sending the
data this protocol requires that two computers have established connections.
The TCP allows the transmission of arbitrary amount of data by breaking it into
stream of separate IP packets.
These IP packets are numbered so that it could be reassembled properly at arrivals.
Along with the data an acknowledgement is also sent/received in order to know
whether the reliable connection has occurred or not.
7) UDP
The user datagram protocol is a connectionless protocol without any error
detection facility.
This protocol is used for simply transmission of data.
The UDP is known as an unreliable protocol however this is much faster than TCP.
8) IP
Internet Protocol (IP) is a network layer protocol which consists of addressing
information.
Using this information the communication between uniquely addressed computers
is possible.
1.3 The Web Site Design Issues SPPU : Dec.-18, May-19, Marks 5
2. Identity :
Web design must be based on the nature of the web application. It is driven by the
objective of the web application, category of user using it. A web engineer must
work to establish an identity for the web application through the design.
3. Consistency :
The users always expect robust contents and functions of the web application.
That means any required functionality should not be missing at all, If any function
or content is missing or insufficient then that web application will fail.
5. Navigability :
The navigation should be simple and consistent. The design of navigations should
intuitive and predictable in nature. That means any novice user should be in a
position to make use of navigation links without any help.
6. Visual appeal :
The web applications are most visual and most dynamic and aesthetic in nature.
There are various factors that contribute to visual appeal. These factors are -
Look and feel of the content, interface layout, color co-ordination, the balance of
text, graphics and other media, navigation mechanism and so on.
7. Compatibility :
1.3.2 Bandwidth
The term bandwidth means amount of data that can be carried from one point to
another in a given period of time. The bandwidth is generally used to define user’s
internet connection speed. It is expressed in terms of bits per seconds (bps).
The web pages get slowly displayed on the browser as they contain large and
detailed graphics and flash animations. Normally user never prefer to view the web
pages that are displayed slowly on the browser window.
The web designer must test the execution of web pages at variety of connection
speed.
The iphones, or other cellular handsets that display the web pages have lower
bandwidth than the home or business computers.
1.3.3 Cache
The term cache means the temporary storage area.
The computer on which all the web pages are stored is called web server. When we
type URL address in the browser, it connects to appropriate web server and
requests the file specified by the user. The server sends the file to the user and the
user’s browser can download it.
The first time when user visit the web site, entire contents, including images,
stylesheets and so on get downloaded on user’s hard disk. The next time when user
visits the web site, the user’s browser downloads and parses the web page from the
site. The browser checks if any specified image is already present on the computer’s
hard drive in the cache.
Cache is the browser’s temporary storage area for web pages and images.
Thus the browser always try to load images from the cache instead of downloading
it from the web server.
The browser cache is useful for displaying the frequently visited web pages more
efficiently.
The cookie is a small text file that server embeds in clients web browser. Each time
when user makes a request for the web page, it sends the cookies as well. The
browser retrieves the values from cookies.
Review Question
The basic feature of HTTP protocol is that it follows the request response model.
The client makes a request for desired web page by giving the URL in the address
bar. This request is submitted to the web server and then web server gives the
response to the web browser by returning the required web page.
1. HTTP Request Message Structure
The basic structure of request message is given by following general form -
<Start line>
<Header fields>
<Blank Line>
<Message Body>
<start Line>
The start line consists of three parts which are separated by a single space. These parts
are -
i) Request method ii) Request-URI iii) HTTP version
i) Request method : Various methods used for making the request are enlisted in
the following table.
HTTP method Description
GET The GET method is used to retrieve information from a specified URI and is
assumed to be a safe, repeatable operation by browsers.
POST The POST method is used to request the server for desired web page and the
request made is accepted as a new subordinate of the resource identified.
The POST method is used for operations that have side effects and cannot be
safely repeated. For example, transferring money from one bank account to
another has side effects and should not be repeated without explicit approval
by the user.
HEAD The HEAD method is identical to GET. The only difference is that the server
should not return a message-body in the response. The meta-information
contained in the HTTP headers in response to a HEAD request should be
similar to the information sent in response to a GET request.
OPTION This method supports for the specified URL. It can be used to check the
functionality of a web server by requesting '*' instead of a specific resource.
TRACE When request is made using TRACE method the server echoes back the
received request so that a client can see what intermediate servers are adding
or changing in the request.
(ii) Request-URI :
The Uniform Resource Identifier (URI) is a string used to identify the names or
resources on the Internet.
The URI is a combination of URL and URN.
The URL stands for Uniform Resource Locator and URN stands for Uniform
Resource Name.
The web address denotes the URL and specific name of the place or a person or
item denotes the URN. For example
(iii) HTTP Version : The first HTTP version was HTTP/0.9 but the official version of
HTTP was HTTP/1.1
<Header Field> and <Message Body>
The host header filed is associated with the http request.
The header fields are in the form of field name and field value.
Thus typical structure of http request is given be following example -
<Status line>
<Header fields>
<Blank Line>
<Message Body>
<Status Line>
Status line is similar to the start line in the request message. It consists of three fields.
HTTP version Status code reason phrase
The HTTP version denotes the HTTP version such as HTTP/1.1. The status code is a
numeric code indicating the type of response. The reason phrase is in the text string form
and presents the information about the status code.
For example -
201 Created It shows that the request is fulfilled and a new resource is
being created.
202 Accepted When the request is accepted for processing but is not
processed yet is denoted by this status code.
301 Moved The URI for requested resource is moved at some another
permanently location.
403 Forbidden The requested resource is present on the server but the server
is not able to respond it.
404 Not Found The requested resource is not present currently but may be
available in future.
500 Internal Server It is a generic error message that appears due to software
Error internal failure.
<Header Fields>
The header field in response message is similar to that of request message.
<Message Body>
The message body consists of response message.
For example
HTTP/1.1 200 OK
Date: Sat, 30 Mar 2019 07:59:01 GMT
Server: Apache/2.0.50 (Unix) mod_perl/1.99_10 Perl/v5.8.4
mod_ssl/2.0.50 OpenSSL/0.9.7d DAV/2 PHP/4.3.8
Last-Modified: Mon, 23 Feb 2009 08:32:41 GMT
Accept-Ranges: bytes
Content-Length: 2010
Content-Type: text/html
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>...</html>
The response header fields are enlisted in following table.
Date It represents the date and time at which the response is generated.
Last-Modified The date and time at which the response is last modified.
Accept-ranges It specifies the unit which is used by the client to accept the range request. For
example if there is a large document and only a single web page is currently
needed then this specifies the Accept-range.
Solution : HTTP protocol defines a set of request methods. A client can use one of these
request methods to send a request message to an HTTP server.
Method Purpose
GET Client can use the GET request to get a web resource from the server.
HEAD Client can use HEAD request to get the header that a GET request would have
obtained.
Example 1.4.2 Describe the steps involved when a web browser requests for and obtains a web
page from a web server.
SPPU : March-19, Marks 5
Solution : The steps in web browser and web server communication are :
Step 1 : The user submits the request for web page via web browser.
Step 2 : The web server software routes the request to the server.
Step 3 : The web server decodes the request and then processes it.
Step 4 : The web server then encodes the response as HTML web page. Then the
server submits back the response to web browser.
Step 5 : The web browser updates the display for displaying the requested web page.
Web browser is a kind of software which is basically used to use resources on the
web.
Over the networks, two computers communicate with each other. In this
communication, when request is made by one computer then that computer is
called a client and when the request gets served by another computer then that
computer is called server. Thus exchange of information takes place via
Client-Server communication.
When user wants some web document then he makes the request for it using the
web browser.
The browsers are the programs that are running on the clients’ machines. The
request then gets served by the server and the requested page is then returned to
the client. It is getting displayed to the client on the web browser.
The commonly used web browsers are (i) Internet explorer (ii) Mozilla Firefox
(iii) Netscape Navigator (iv) Opera (v) Google Chrome (vi) Safari.
Web browser supports variety of protocols but the most commonly used protocol
on the web browser is Hyper Text Transfer Protocol (HTTP). This protocol is
typically used when browser communicates with the server.
3. The web browser establishes a TCP connection with the Web browser while
processing the user’s request.
4. The web browsers send the HTTP request to the web server.
5. The web server processes the HTTP request sent by the web browser and returns
the desired web page to the client machine. The web browser on the client’s
machine displays this web page in appropriate format.
1.6.2 URL
The Uniform Resource Locator (URL) is unique address for the file that has to be
accessed over the internet.
When we want to access some website we enter it’s URL in the address bar of the
web browser.
For example if we want to access www.google.com then we must specify its URL in
the address bar as shown.
However any other file such as some text file or image file or some HTML file can
also be specified. The URL contains name of the protocol such as http://
The URL may contain the name of the protocol as such as ftp. For example
ftp://ftp.funet.fi/pub/standards/RFC/rfc2166.txt
The protocol identifier and the resource name are separated by a colon and two
forward slashes. The syntax of writing URL is as given below,
protocol://username@hostname/path/filename
Sometimes instead of domain name servers IP addresses can also be use. For
example,
http://192.168.0.1
But use of IP address as URL is not preferred because human can not remember
numbers very easily but they can remember names easily.
Web server is a special type of server to which the web browser submits the request
of web page which is desired by the client.
There are some popularly used web servers such as Apache and IIS from Microsoft.
Fig. 1.7.1
Step 1 : Web client requests for the desired web page by providing the IP address of
the website.
Step 2 : The web server locates the desired web page on the website and responds by
sending back the requested page. If the page doesn’t exist, it will send back
the appropriate error page.
Step 3 : The web browser receives the page and renders it as required.
1.7.1 Apache
It is an excellent server because of its two important features : Reliability and
Efficiency.
Secondly it is more popular because it is an open source software. That means it is
freely available to anybody. Apache web server is best suitable for UNIX systems
but it can also be used on Windows box.
The apache web server can be configured as per the requirements using the file
httpd.conf. This file is present in the Apache software package.
1.7.2 IIS
Solution :
i) Website : It is a set of related web pages located under a single domain name.
ii) Web page : It is hypertext document connected to world wide web.
iii) Web server : Web server is a server software that delivers content or services to end
users over internet.
iv) URL : The Uniform Resource Locator (URL) is unique address for the file that has to
be accessed over the internet. When we want to access some website we enter it’s
URL in the address bar of the web browser.
v) Home page : It is the introductory web page of web site that acts as a start-up page.
Example 1.7.2 What are the technologies used in traditional web programing ? Also identify
location of each technology used in this model.
SPPU : April-18, Marks 5
Solution : The server side technologies and client side technologies are used in traditional
web programming. The server side technologies work at the server level and client side
technologies are used at the client level. Following table illustrates the comparative
description of these technologies.
1. The server side scripting is used to The client side scripting is used to create the
create the web pages that provide some web pages as a request or response to
services. server. These pages are displayed to the
user on web browser.
2. These scripts generally run on web These scripts generally run on web browser.
servers.
3. A user's request is fulfilled by running a The processing of these scripts takes place
script directly on the web server to on the end users computer. The source code
generate dynamic HTML pages. This is transferred from the web server to the
HTML is then sent to the client browser. users computer over the internet and run
directly in the browser.
4. Uses : Processing of user request, Uses : Making interactive web pages, for
5. Example : PHP, ASP.NET, nearly all the Example : HTML, CSS, JavaScript
Java and C#
Review Question
1. Write the difference between client side scripting and server side scripting.
SPPU : Dec.-18, Marks 4
Working
Step 1 : The client PC or web client submits the request for desired web page to the web
server.
Step 2 : The work of server is distributed among application server and database
servers. Application server possesses the required communication functions.
Step 3 : The data required by this business logic is present on database server. The
required data is returned to application servers
Step 4 : The web server or application server prepares the response page and sends
it to the web client.
Advantages :
1. High performance and persistent objects take part in communication.
2. This architecture is scalable. That means it can support increased number of
users and resources.
3. High degree of flexibility in deployment platform and configurations.
4. Code/data reusability can be achieved.
5. Improved data integrity
6. Improved security as clients can not directly access the database.
7. The maintenance and modifications can be done effectively without disturbing
other modules in the architecture.
Disadvantages :
1. The complexity gets increased.
2. Cost for network maintenance and deployment is increased.
Part II : HTML
1.9 Introduction
HTML stands for HyperText Markup Language. Hypertext is simply a piece of text
that works as a link.
Markup Language is language of writing layout information within documents.
Basically an HTML document is a plain text file.
It contains rich text. The rich text means text with tags.
HTML is not a case sensitive language.
Any HTML program can be written in simple Notepad or WordPad text editors.
The extension to this program should be either html or htm.
This program then can be opened in some web browser and the corresponding web
page can be viewed. Let us create our first web page using HTML.
HTML Document
<html>
<head>
<title>My webpage</title>
</head>
<body>
This is my first Web Page!!!
</body>
</html>
Script Explanation
1) Note that the program consists of some strings enclosed within angular brackets.
Such strings are called tags.
2) The HTML program should be written within <html> and </html>. The <html>
indicates the start of html program and </html> denotes end of html program.
Use of slash (/) in the angular bracket indicates end of that particular tag.
3) Any HTML program has two prominent parts : head and body. The head part
acts as a header of a file and contains some information like setting the title of
web page.
Comments in HTML
There should not be a space between angular bracket and exclamation mark. This
comment is beginning with <!-- and ending with -->. Also note one thing that there
should not be any -- inside the comment.
1. Doctype : The Doctype stands for Document type which tells the browser what
type of document (HTML) it is about to process.
2. HTML : The <html> element is sometimes called the root element as it contains
all the other HTML elements in the document.
3. Head : HTML pages are divided into two sections : The head and the body,
which correspond to the <head> and <body> elements. The head contains
descriptive elements about the document, such as its title, any style sheets or
JavaScript files it uses.
4. Body : The body contains content (both HTML elements and regular text) that
will be displayed by the browser.
5. Character encoding : The <meta> element specifies that the character encoding
for the document is UTF-8. Character encoding refers to which character set
standard is being used to encode the characters in the document. UTF-8 is a more
complete variable-width encoding system that can encode all 110,000 characters
in the unicode character set.
6. External style sheet : The external stylesheet such as css can be used with HTML
document. We can specify the name of the CSS stylesheet.
7. External scripts : Sometimes external JavaScript files can be associated with
HTML document.
In all HTML/XHTML documents the root element is <html> which has two
children : head and body.
Any text contained within the head element does not appear directly in the client
area of web browser. The head element is used for providing certain information to
web browser. The <title> element is used to give title to the web page. Note that this
title does not appear in client area. Rather
it appears at the top of web browser.
The <body> element contains the
information which is to be displayed in the
client area of web browser.
The body element can contain several
fundamental elements such as <p>, <h1>,
<div>, <a>, <hr>, <br> and so on. The
elements within the body part is for
Fig. 1.12.1 Element tree
deciding the layout of your web page.
1.12.1 Heading
There are header tags which help to display the text as some header.
The header tag is denoted by h1, h2 and so on upto h6.
Following HTML document along with its output is itself self explanatory.
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<h1> This is a first header </h1>
<h2> This is a second header </h2>
<h3> This is a third header </h3>
<h4> This is a forth header </h4>
<h5> This is a fifth header </h5>
<h6> This is a sixth header </h6>
</body>
</html>
Output
1.12.2 Paragraphs
Following are the tags that are used for creating paragraphs.
Tag Meaning
<pre> This tag is used to preserve the white spaces and lines in the text.
<div> This tag is used to make division of sections in the XHTML document.
For example
HTML Document[TextFormat.html]
<!DOCTYPE html>
<html >
<head>
</head>
<body>
<p>
Once upon a time, there was a king who kept a monkey as a pet.
The monkey served the king by all the possible ways.
</p>
<div>
It was very hot in those days. So one day, when the king was sleeping, monkey was
fanning the king. Suddenly monkey noticed a fly on the chest of the king. The monkey tried to
swish it away. But fly would go away for one moment and come back again.
</div>
<div> So monkey decided to teach a lesson to the fly.</div>
<pre>
The monkey then looked for something to hit a fly.
It then found a stick.
It picked up the stick and tried to beat the fly using stick.
Hmmm at last it found a fly and
with all the force it hit the fly as a result of which the king died.
For example
<!DOCTYPE html>
<html>
<head>
<title>Line Break Demo</title>
</head>
<body>
<p>
We can align the text at left, right or at the center using a <div> tag. Here is a HTML
program which shows the text aligned left, right and centre.
HTML Document[TextAlign.html]
<!DOCTYPE html >
<html>
<head>
<title>Font Style Demo</title>
</head>
<body>
<div align="center">This line is aligned at center</div>
<div align="left">This line is aligned at left</div>
<div align="right">This line is aligned at right</div>
</body>
</html>
Output
For example -
HTML Document[SetFont.html]
<!DOCTYPE html>
<html >
<head>
<title>Setting the Text </title>
</head>
<body>
<basefont face="arial" size="10">
Varsha is sweet and <br/>
Jayashree is very naughty!!<br/>
But Sachin is a serious guy<br/>
And Rashmi is a new-comer in this group
</body>
</html>
Output
The <basefont> tag is supported in Internet Explorer 9 and not by FireFox, Chrome,
Opera and so on.
Most of the web designers prefer to have their web pages white in color. HTML allows
the web developer to use color attribute for coloring the text or for setting the background
color.
First of all we will learn how to display a text colourful on the webpage.
HTML Document[ColorFont.html]
<!DOCTYPE html>
<html>
<head>
<title>coloring the text</title>
</head>
<body>
<basefont face="arial" size="5" color="blue">
Great people are simple and <br>
<font face="Times new roman" color="red" size="8">
Simple people are great!!!<br>
<font face="GoudyHandtooled BT" color="green" size="14">
Great people rule the world.
</body>
</html>
Output
Script Explanation :
1) In the above HTML document, we have used font face tag to set the font.
2) Using the attributes color and size we can specify values color and size in double
quotes.
We can set the background color of the web page using the attribute bgcolor.
Following program sets the background color of the web page to red.
HTML Document[BgColor.html]
<!DOCTYPE html>
<html>
<head>
<title>Coloring the background</title>
</head>
<body bgcolor="#FFFF00">
<h3>This is document has colored background</h3>
</body>
</html>
Script Explanation :
1) In above document we have specified background color using the bgcolor
attribute.
2) The color can be specified by either using the color name in double quotes or
using the hex.code as given in above document.
3) The first two digits of hex code represents the red value, then next two digits
specify the green value and final two digits specify the blue value. Hence the
corresponding output will be as follows -
Output
Note that the background color is specified by the hexadecimal value. Following table
shows the hex and corresponding decimal values -
Decimal value Hexadecimal value
1 1
2 2
3 3
4 4
5 5
6 6
7 7
8 8
9 9
10 A
11 B
12 C
13 D
14 E
15 F
In HTML, the colors are specified by beginning with # and the FF denotes 255. In this
color code first two digits specify the amount of red color then next two digits specify the
green color and the last two digits specify blue color.
# FF 00 00
red colour
Hence is used to set the background color red. Each pair of digits specifies 0 to 255
color values. Thus hexadecimal color coding helps us to specify.
256 * 256 * 256 = 16777216 colors.
The color can also be specified by its name as follows -
<html>
<body bgcolor=yellow>
</html>
Following is a list of colors that can be specified for setting the background colors.
Aqua Navy
Black Olive
Blue Purple
Fuchsia Red
Gray Silver
Green Teal
Lime White
Maroon Yellow
’ apostrophes '
© copyright ©
Another type of entity reference that is used frequently is that is non
breaking space character.
This entity reference is useful for defining the space between two string and
informing browser for not performing the word wrapper between the strings.
Following is a sample script that makes use of  .
HTML Document[SpaceDemo.html]
<!DOCTYPE html>
<html>
<head>
<title>Space Demo</title>
</head>
<body>
<h3>
Method 1:
</h3>
<p>
Jony Jony Yes Papa  Eating
sugar no Papa Open Your
mouth Ha!Ha!Ha
</p>
<h3>
Method 2:
</h3>
<p>
Jony Jony Yes Papa Eating sugar no Papa Open Your mouth Ha!Ha!Ha
</p>
</body>
</html>
Output
Example 1.12.1 How divide and pound symbol can be put on HTML document ?
SPPU : May-18, Marks 5
Solution : With the help of entity references denoted using & these two symbols can be
put in HTML document. The code can be
<html>
Output
<head>
</head>
<body>
<p>This ÷ symbol</p>
<p>This £ symbol</p>
</body>
</html>
Review Question
1.13 Links
There is a common practice to specify the web link in the web page. The link acts as
a pointer to some web page or some resource.
Use of hyperlink in the web page allows that page to link logically with other page.
We can use hyperlinks by using a tag <a> and by specifying the URL for href.
The value assigned to href specifies the target of the link.
The <a> means beginning of the web link and </a> means end of the web link.
The most important attribute of the <a> element is the href attribute, which indicates
the link's destination.
By default, links will appear as follows in all browsers :
1) An unvisited link is underlined and blue.
2) A visited link is underlined and purple.
3) An active link is underlined and red.
Following are the steps to be followed to specify web link in the web page.
Step 1 : The beginning of web link can be specified by the tag <a href = “ “.
Inside the double quotes mention the URL of desired link.
If you click on the hyperlink book then you will get the following output.
Solution :
Step 1 : Write the HTML document containing an hyperlink to an image. When we click
on the image the html page referred by the <a href> tag must get opened.
XHTML Document[ImgLink.html]
<!DOCTYPE html>
<html>
<head>
<title> Image Demo </title>
</head>
<body>
<h1> Indian Heritage </h1>
</p>
<a href="TajMahal.html" target ="_blank">
<img src= "TajMahal.jpg" alt= "Taj Mahal!!" />
</a>
<br/>History of Taj Mahal
<br/>
</body>
</html>
Step 2 : Write the HTML document(TajMahal.html) mentioned by the <a href> tag in
Step 1 as follows.
HTML Document[TajMahal.html]
<!DOCTYPE html>
<html>
<head>
<title> Information on TajMahal </title>
</head>
<body>
<h1> Indian Heritage </h1>
<p>
Taj Mahal is one of the wonders of the World. It is located in Agra,India.
<br/>
The above script executes in almost all the web browsers such as Internet explorer,
Mozilla Firefox, Opera and so on. But the above HTML document launches the Media
player software and then the audio file is played within it. For playing the audio files
using hyperlinks it is necessary to get the audio file downloaded first.
1.14 Frames
HTML frames allow us to present documents in
multiple views.
Using multiple views we can keep certain information
visible and at the same time other views are scrolled
or replaced.
For example, within the same window, one frame can
display a company information, a second frame can be
Fig. 1.14.1 Frames
a navigation menu and a third frame may display
selected document that can be scrolled through or replaced by navigating in the
second frame.
Various frames can be set in one browser window.
To set the frames in the browser window we use frame set.
For example -
<frameset cols="150,*">
will allow us to divide the window into two columns (i.e. in two vertical frames). One
frame occupying the size of 150 pixels and the other occupies the remaining portion of the
window. Here * means any number of pixels.
Similarly
<frameset rows="*,120">
will divide the window into two rows (i.e. in two horizontal frames). The second part
of horizontal frame will be of 120 pixels and upper horizontal frame will occupy
remaining portion of the window.
Similarly we can also specify the frameset in percentage form. For example
<frameset rows="30%,70%">
Using frameset we can divide the rows and columns in any number of frames. For
example
<frameset rows = “20%,30%,50%” cols = “30%,*”>
frameborder 0 or 1 Value 1 specifies that the frame is displayed with border and 0
indicates that there is no border.
scolling yes, no or It specifies whether or not to display the scrollbar along with the
auto frame.
src URL It specifies the name of the Document to be displayed within the
frame.
FrameSet.html
<!DOCTYPE html>
<html>
<frameset cols="25%,*,50%">
<frame src="frame1.html">
<frame src="frame2.html">
<frame src="frame3.html">
</frameset>
</html>
Frame1.html
<!DOCTYPE html>
<html>
<body>
<h1> Frame 1 </h1>
</body>
</html>
Frame2.html
<!DOCTYPE html>
<html>
<body>
<h1> Frame 2 </h1>
</body>
</html>
Frame3.html
<!DOCTYPE html>
<html>
<body>
<h1> Frame 3 </h1>
</body>
</html>
Output
Script explanation : The above HTML document, the <frameset> tag is used to define
frameset. The col attribute is used to create the three column frames.
To set the scroll bar we should assign the value auto to the scrolling parameter and if
we do not want the scroll bar accompanying the frame then we must assign the value no
to the scrolling parameter.
Example 1.14.1 Create XHTML document that has two frames. The left frame displays the
contents.html and the right frame displays the cars.html where second frame is the target of
link from the first frame. [Note : Contents.html is a list of links for the cars description].
Solution :
Step 1 : We will create the basic html file that contains the left and right frames. The
HTML document is as follows :
CarDemo.html
<!DOCTYPE html >
<html>
<head>
<title>My Frames Page</title>
</head>
<frameset cols="50%,50%">
<frame src="contents.html" name="Left_Vertical" noresize />
<frame src="Description.html" name="Right_Vertical" scrolling=no/>
</frameset>
</html>
Step 2 : Following is a HTML document that displays the contents that are loaded at
first. The left frame HTML document is as follows –
contents.html
<!DOCTYPE html >
<html >
<head>
<title>My Frames Page</title>
</head>
<body>
<h3>
<a href="Innova.html" target="Right_Vertical">Toyota Innova</a>
<h3/>
<h3>
<a href="Scorpio.html" target="Right_Vertical">Mahindra Scorpio</a>
<h3/>
<h3>
<a href="Etios.html" target="Right_Vertical">Toyota Etios Liva</a>
<h3/>
</body>
</html>
Description.html
<!DOCTYPE html >
<html >
<head>
<title>My Frames Page</title>
</head>
<body>
<center>
<h3> WELCOME <h3/>
This page displays the details of a car you have chosen.
</center>
</body>
</html>
Step 3 : Following are the three html documents each containing the description of each
car.
Innova.html
<!DOCTYPE html >
<html>
<head>
<title>My Frames Page</title>
</head>
<body>
<h2> TOYOTA INNOVA</h2>
<ul type="disc">
<li>Price: Rs.9,35,731-Rs.14,82,852</li>
<li><td>Mileage: </td><td>10Kmpl(City) and 13 Kmpl(hwy)</li>
</ul>
</body>
</html>
Scorpio.html
<!DOCTYPE html>
<html >
<head>
<title>My Frames Page</title>
</head>
<body>
<h2> MAHINDRA SCORPIO</h2>
<ul type="disc">
<li>Price: </td><td>Rs.7,49,583-Rs.12,85,479</li>
<li>Mileage: </td><td>12Kmpl(City) and 16 Kmpl(hwy)</li>
</ul>
</body>
</html>
Etios.html
<!DOCTYPE html>
<html >
<head>
<title>My Frames Page</title>
</head>
<body>
<h2> TOYOTA ETIOS LIVA</h2>
<ul type="disc">
<li> Price: </td><td>Rs.4,46,276-Rs.6,86,426</li>
<li> Mileage: </td><td>17Kmpl(City) and 19 Kmpl(hwy)</li>
</ul>
</body>
</html>
Step 4 : Open the suitable web browser and invoke the CarDemo.html(created in Step 1),
the output will be as follows -
Example 1.14.2 Create a HTML document for a company home page and explain.
Solution : For creation of this web page the frames are used.
Step 1 : The main page is created as follows -
Main.html
<?xml version = "1.0" encoding ="utf-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Frameset//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-frameset.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<frameset rows="20%,80%">
<frame src="logo.html">
<frameset cols="30%,70%">
<frame src="menu.html">
<frame src="contents.html">
</frameset>
</frameset>
</html>
Step 2 : In the main page a layout of the company home page is created. Various html
files that are called in this HTML document are as given below -
Menu.html
<html>
<head><title>LOGO</title></head>
<body bgcolor="aqua">
<h3><a href="about.html"> About us<a/></h3>
<h3><a href="download1.html"> Free Downloads<a/></h3>
<h3><a href="download2.html"> Download Catalogue<a/></h3>
<h3><a href="download3.html">Download Orderform<a/></h3>
<h3><a href="catalogues.html">Catalogues<a/></h3>
<h3><a href="distributors.html">Distributors<a/></h3>
<h3><a href="Contacts.html">Contact Us<a/></h3>
<h3><a href="feedback.html">Feedback<a/></h3>
</body>
</html>
Logo.html
<html>
<head><title>LOGO</title></head>
<body bgcolor="magenta">
<h1><img src="books.jpg"/> Technical Publications</h1>
</body>
</html>
Contents.html
<html>
<head><title>LOGO</title></head>
<body bgcolor="khaki">
<center>
<h2>BOOKS</h2>
</center>
<p>TECHNICAL PUBLICATIONS is known for commitment to quality and innovation. We are
Leaders in our chosen scholarly and educational markets, serving the book Industry & Academic
Institutions.
</p>
<p>We have been in the industry for the last 18 years and are known for the quality and scholarly
publications in Engineering books. We publish more than 1000 titles of text books, for various
Universities across the India.
</p>
<p>We are specialized in Engineering text books and have been publishing titles for various
Engineering branches such as Electrical, Electronics, Computer Science, Information
Technology,Mechanical etc. and other management
books.
</p>
</body>
</html>
Step 3 : Open the suitable web browser and type the address for main.html. The output
will be as follows -
1.15 Lists
List is nothing but the collections of items or elements. There are two types of lists -
unordered lists and ordered lists.
The unordered list is useful for simply listing the items but if we want the items in
some specific sequence then the ordered lists are used. Let us discuss how to use
these types lists in the HTML document.
Output
Script explanation :
In above script we have used the tag <ul> for specifying the unordered list. The list
items can be mentioned using the tag <li> Due to which the list items can appear in
bulleted form. The style of the bullet can be as given below -
tags meaning
Tags Meaning
A.
B.
C.
i.
ii.
iii.
I.
II.
III.
1.
2.
3.
<body>
<h4>Information of Nations</h4>
<ol type="1">
<li>India
<ol type="i">
<li>National Bird: Peacock</li>
<li>National animal:Tiger</li>
<li>National game:Hockey</li>
</ol>
</li>
<li>Australia
<ol type="i">
<li>National Bird: Emu</li>
<li>National animal:Kangaroo</li>
<li>National game:Cricket</li>
</ol>
</li>
</ol>
</body>
</html>
Output
1.16 Tables
For systematic arrangement of information we often require tabular structure.
HTML allows us to create tables on the web pages.
Many web designers are using invisible tables on the web pages.
The biggest advantage of using tables on the web pages is that the information gets
arranged systematically.
The table is a matrix of rows and columns and the area formed due to intersection
of a row and a column is called cell.
HTML Document[TabDemo.html]
<!DOCTYPE html>
<html>
<head>
<title> Table Demo </title>
</head>
<body>
<br/><br/>
<center>
<table border="5">
<caption align="bottom">
<b> Table Demo </b>
</caption>
<tr>
<td>This is Left cell-row 1</td>
<td>This is Right cell -row 1</td>
</tr>
<tr>
<td>This is Left cell-row 2</td>
<td>This is Right cell-row 2</td>
</tr>
</table>
</center>
</body>
</html>
Output
Script Explanation
1) In above program, the parameter border = “5” is set in order to set the table border.
You can give any value to set the desired border.
2) The caption to the table is given by the parameter caption, we can set this caption
either at the top or at the bottom by using the parameter align.
3) Then using the tag <tr> the table row can be set. The <td> tag is used to create
columns from left to right.
4) Thus in the above program we are filling up the table values from top to bottom
and from left to right. Just refer the output provided along with the program for
clear understanding of look and feel of the table.
Example 1.16.1 Write HTML document to create a table with header to each column.
Solution : We can set the header to each column of the table by <th> tag. Here is a simple
HTML program that simply adds the header to each column.
HTML Document [TabDemo1.html]
<!DOCTYPE html >
<html >
<head>
<title> Table Demo </title> Output
</head>
<body>
<br/><br/>
<center>
<table border="3">
<caption align="bottom">
<b> Students Record </b>
</caption>
<th>Name</th>
<th>Marks</th>
<tr align=center>
<td>Lekhana</td>
<td>89</td>
</tr>
<tr align=center>
<td>Savita</td>
<td>92</td></tr>
</tr>
</table>
</center>
</html>
The data in each row can be aligned centrally by using <tr align=center> Other types of
alignment can be left or right by <tr align=left> or <tr align=right> respectively.
Example 1.16.2 Discuss the process of dividing the table into columns with an example. How
would you give headers to the table columns ?
Example 1.16.3 Following HTML document divides the table in columns and gives the header
to the column.
Solution :
<!DOCTYPE html>
<html>
Output
<head>
<title>Table Demo</title>
</head>
<body>
<table border ="1">
<th>Name</th>
<th>Marks</th>
<tr>
<td>AAA</td>
<td>50</td>
</tr>
<tr>
<td>BBB</td>
<td>90</td>
</tr>
</table>
</body>
</html>
colspan
Example 1.16.4 Explain the structure of HTML. Write code to display following table.
College Name
Sr. No. Section A Section B
X Y X Y
1
2
3
Solution : ImageDemo.html
<html>
<head>
<title>My Table</title>
</head>
<body>
<table border=1>
<tr>
<td rowspan="3">
<p align=center>Sr.No.</p>
<p> </td>
</td>
<td colspan="4">
<p align="center">College Name</p>
</td>
</tr>
<tr>
<td width="40%" colspan="2" align="center">Section A</td>
<td width="40%" colspan="2" align="center">Section B</td>
</tr>
<tr>
<td align="center">X</td>
<td align="center">Y</td>
<td align="center">X</td>
<td align="center">Y</td>
</tr>
<tr>
<td align="center">1</td>
<td align="center"> </td>
<td align="center"> </td>
<td align="center"> </td>
<td align="center"> </td>
</tr>
<tr>
<td align="center">2</td>
<td align="center"> </td>
<td align="center"> </td>
<td align="center"> </td>
<td align="center"> </td>
</tr>
<tr>
<td align="center">3</td>
<td align="center"> </td>
<td align="center"> </td>
<td align="center"> </td>
<td align="center"> </td>
</tr>
</table>
</body>
</html>
Output
Schedule
1
Type 1
2
3
Type 2
4
Solution : ImageDemo.html
<html>
<head>
<title>My Table</title>
</head>
<body>
<table border=1>
<tr>
<td width="20%" align=center><img src="logo.jpg"/></td>
<th width="80%" align=center>TopTech Solutions</th>
</tr>
<tr>
<td> </td>
<td align=center>Schedule</td>
</tr>
<tr>
<td align=center>1</td>
<td rowspan="2" align=center>Type 1</td>
</tr>
<tr>
<td align=center>2</td>
</tr>
<tr>
<td align=center>3</td>
<td rowspan="2" align=center>Type 2</td>
</tr>
<tr>
<td align=center>4</td>
</tr>
</table>
</body>
</html>
Output
Items Price
`. 400/- `. 600/-
Solution :
<html> Output
<head>
<title>Item-Price List</title>
</head>
<body>
<table border=1>
<tr>
<th colspan="2"><center>Items</center></th>
<th>Price</th>
</tr>
<tr>
<th><center>Shirt</center></th>
<th><center>Trouser</center></th>
<td rowspan="2"><center>Rs.<br/>1000/-</center></td>
<tr>
<td><center>Rs.400/-</td>
<td><center>Rs.600/-</td>
</tr>
</table>
</body>
</html>
Example 1.16.7 Write HTML code which includes table, Hyperlink, character formatting
ordered and unordered list to display your resume.
Solution : resume.html
<html>
<head>
<title>RESUME APPLICATION</title>
</head>
<body>
<center><h2>RESUME</h2></center>
<a href="my_photo.jpg">PHOTO</a>
<br/><br/>
<strong>Name: </strong> Mr.Sachin Patil<br/>
<strong>Address: </strong> D10,SunEmpire,SunCityRd,Pune<br/>
<strong>Sex: </strong>Male<br/>
<strong>Phone: </strong>9229229221<br/>
<strong>Email: </strong>[email protected]
<br/><br/>
<strong>Educational Qualification:</strong>
<table border=2>
<tr>
<th>Examination</th>
<th>Year Of Passing</th>
<th>Board/University</th>
<th>Marks obtained</th>
</tr>
<tr>
<td>S.S.C</td><td>1991</td><td>Pune</td><td>93%</td>
</tr>
<tr>
<td>H.S.C</td><td>1993</td><td>Pune</td><td>90%</td>
</tr>
<tr>
<td>B.E.(Computer)</td><td>1997</td><td>Pune</td><td>72%</td>
</tr>
<tr>
<td>M.Tech(Computer)</td><td>2001</td><td>IIT(Kanpur)</td><td>A grade</td>
</tr>
</table>
<strong>
<br/><br/>
<li>Visual Basic
<li>Java
</ul>
<br/><br/>
<div align=left>Date:</div>
<div align=right>Place:</div>
<br/>
<div align=left>Signature</div>
</body>
</html>
Solution :
<html>
<head>
<title> Train Time Table </title>
</head>
<body>
<table border="1">
<tr>
<th rowspan=2>Name of Train</th>
<th rowspan=2>Place</th>
<th rowspan=2>Destination</th>
<th colspan=2>Time</th>
<th rowspan=2>Fare</th>
</tr>
<tr><th>Arrival</th><th>Departure</th></tr>
<tr>
<td>Rajdhani</td><td>Mumbai</td><td>Delhi</td>
<td>7.30</td><td>08.45</td>
<td>Rs.989.00</td>
</tr>
<tr>
<td>Madras Mail</td><td>Mumbai</td><td>Madras</td>
<td>09.00</td><td>10.15</td>
<td>Rs.450.00</td>
</tr>
<tr>
<td>Konkan Exp.</td><td>Mumbai</td><td>Manglore</td>
<td>13.30</td><td>14.45</td>
<td>Rs.756.00</td>
</tr>
<tr>
<td>Deccan Exp.</td><td>Mumbai</td><td>Pune</td>
<td>16.00</td><td>17.30</td>
<td>Rs.345.00</td>
</tr>
</table>
</body>
</html>
Output
Solution : i) <table width=”400” height=”200”> denotes that the table width is 400 pixels
and height is 200 pixels. It denotes the absolute value.
For example
<html>
<head>
</head>
<body>
<table border="1" width="100" height="50">
<tr>
<th>Name</th>
<th>City</th>
<th>Age</th>
</tr>
<tr>
<td>AAA</td><td>Mumbai</td><td>10 yrs.</td>
</tr>
<tr>
<td>BBB</td><td>Pune</td><td>20 yrs.</td>
</tr>
<tr>
<td>CCC</td><td>Chennai</td><td>50 yrs.</td>
</tr>
</table>
</body>
</html>
Output
ii) On the other hand <table width=”100%” and height=”50%”> denotes the width of
the table is 100% of the screen and height is 50% of the browser screen. It denotes
the relative value.
For example
<html>
<head>
</head>
<body>
<table border="1" width="100%" height="50%">
<tr>
<th>Name</th>
<th>City</th>
<th>Age</th>
</tr>
<tr>
<td>AAA</td><td>Mumbai</td><td>10 yrs.</td>
</tr>
<tr>
<td>BBB</td><td>Pune</td><td>20 yrs.</td>
</tr>
<tr>
<td>CCC</td><td>Chennai</td><td>50 yrs.</td>
</tr>
</table>
</body>
</html>
Output
The <col> tag is useful for applying styles to entire columns, instead of repeating
the styles for each cell, for each row.
For example –
<!DOCTYPE html>
<html>
<head>
<style>
table, th, td {
border: 1px solid black;
}
</style>
</head>
<body>
<table>
<colgroup>
<col span="2" style="background-color:pink">
<col span="2" style="background-color:aqua">
</colgroup>
<tr>
<th>RollNo</th>
Output
<th>Name</th>
<th>City</th>
<th>Marks</th>
</tr>
<tr>
<td>1</td>
<td>AAA</td>
<td>Pune</td>
<td>78</td>
</tr>
<tr>
<td>2</td>
<td>BBB</td>
<td>Mumbai</td>
<td>88</td>
</tr>
<tr>
<td>3</td>
<td>CCC</td>
<td>Bangalore</td>
<td>97</td>
</tr>
<tr>
<td>4</td>
<td>DDD</td>
<td>Hyderabad</td>
<td>84</td>
</tr>
</table>
</body>
</html>
The <tbody> tag is used to group the body content in an HTML table.
The <tbody> element is used in conjunction with the <thead> and <tfoot> elements
to specify each part of a table such as body, header, and footer.
For example –
<!DOCTYPE html>
<html>
<head>
<style>
table, th, td {
border: 1px solid black;
}
thead {color:red;}
tbody {color:green;}
tfoot {color:blue;}
</style>
</head>
<body>
<table>
<thead>
<tr>
<th>RollNo</th>
<th>Name</th>
<th>City</th>
<th>Marks</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>AAA</td>
<td>Pune</td>
<td>78</td>
Output
</tr>
<tr>
<td>2</td>
<td>BBB</td>
<td>Mumbai</td>
<td>88</td>
</tr>
<tr>
<td>3</td>
<td>CCC</td>
<td>Bangalore</td>
<td>97</td>
</tr>
<tr>
</tbody>
<tfoot>
<td>4</td>
<td>DDD</td>
<td>Hyderabad</td>
<td>84</td>
</tr>
</tfoot>
</table>
</body>
</html>
1.17 Images
We can display images as a link. We have to use the <img src =“ ” > tag for this
purpose.
Within the double quotes image file should be mentioned. Normally .gif or .jpg files
are used to display the images on the web browser.
Example
Following HTML Script shows how to insert an image in the web page.
HTML Document [imagedemo.html]
<!DOCTYPE html>
<html>
<head>
<title> Image Demo </title>
</head>
<body>
<h1> Indian Heritage </h1>
<p>
In India, People celebrate the festival of light <br/>
Which is called as <strong>Diwali</strong>
</p>
<img src= "lamp1.jpg" alt= "Light!!" />
<br/>
Diwali suggests us to enlighten our life with hope,health and wealth
<br/>
</body>
</html>
Output
Script explanation : In above script we have used <img /> tag in order to display an image.
Types of Images
There are two types of images that are more commonly used -
1. Graphic Interchange Format (GIF) : It uses 8-bit color representation for pixels.
Hence a single pixel can have 256 different colors. This file have the extension
.gif.
2. Joint Photographic Expert Group (JPEG) : This format uses 24-bit color
representation for pixel. Hence a JPEG can have 16 million different colors. The
file have the extension .jpg or .jpeg.
The JPEG image have more color information than a GIF image. Secondly JPEG can be
smaller than GIF image. Hence normally JPEG image is preferred. But the drawback of
JPEG is that it does not support transparency.
1.18 Forms
Form is a typical layout on the web page by which a user can interact with the web
page.
Typical component of forms are text, text area, checkboxes, radio buttons and push
buttons.
HTML allows us to place these form components on the web page and send the
desired information to the destination server.
All these form contents appear in the <form> tag. The form has an attribute action
which gets executed when user clicks a button on the form.
Various attributes of form are –
Attribute Description
Let us learn various form components with the help of simple HTML documents.
1.18.1 Text
Text is typically required to place one line text. For example if you want to enter
some name then it is always preferred to have Text field on the form.
The text field can be set using
<input type="text" size=”30” name =”username” value=" ">
The input type is text and the value of this text field is “ ” That means the blank text
field is displayed initially and we can enter the text of our choice into it. There is size
parameter which allows us to enter some size of the text field.
Some other parameters or attributes can be
o maxlength that allows us to enter the text of some maximum length.
o name indicates name of the text field.
o align denotes the alignment of the text in the text field. The alignment can
be left, right, bottom and top.
Example code
<title>My Page</title>
</head>
<body>
<form>
<b>Input String:</b><br/><input type="text" size="25" value="">
</form>
</body>
</html>
Output
Example 1.18.1 How will you create password field in a HTML form ?
Solution : The password field is typically created on the form. Hence following code can
be written to create it -
<form name=”form1”>
Password:<input type=”password”/>
</form>
Various parameters that can be set for the text area can be,
wrap can be virtual or physical. If the wrap is virtual then the line breaks
get disappeared when the text is actually submitted to the server. But if the
wrap is assigned to the physical then the line breaks (if any) appear as it is
in the text.
1.18.3 Checkbox
It is the simplest component which is used particularly when we want to make
some selection from several options.
For having the checkbox we have to specify the input type as checkbox. For
example
<input type="checkbox" name="option1" value="mango"
checked="checked">Mango<br/>
If we want to get the checkbox displayed as checked then set checked="checked"
Example Code
HTML Document[ChkBoxDemo.html]
<!DOCTYPE html>
<html>
<head>
<title>My Form with Check box</title>
</head>
<body>
<form name ="checkboxForm">
<div align="center"><br>
Select the fruit(s) of your choice<br/>
<input type="checkbox" name="option1" value="mango"
checked="checked">Mango<br/>
<input type="checkbox" name="option2" value="apple">Apple<br/>
<input type="checkbox" name="option3" value="guava">Guava<br/>
</div>
</form>
</body>
</html>
Output
Script explanation
1) In the above program to set some checkbox in checked state we can
mention the attribute checked as checked.
2) We can set the value attribute as “ “ but this then the checkbox will not
get associated with any value. The Mango, Apple and Guava are the
labels of the checkboxes.
<br/><br/><br/>
<b>Select Flower which you like the most</b><br/>
<input type="radio" name="group2" value="Rose"> Rose<br/>
<input type="radio" name="group2" value="Lotus">Lotus<br/>
<input type="radio" name="group2" value="Jasmine" checked>Jasmine<br/>
</div>
</form>
</body>
</html>
Output
Example 1.18.2 What is the difference between group of checkbox buttons and group of radio
buttons ?
Solution :
The checkbox and radio buttons are used for making the selection from a
group of choices.
When a user selects (checks) a checkbox, its value gets assigned as the
current value of the checkbox group's control name.
A checkbox group's control name may get paired with several current
values if the user selects more than one checkbox.
Radio buttons work just like checkboxes except they are typically set up to
be mutually exclusive of one another, i.e. when one is selected, all the
others are automatically deselected.
1.18.5 Button
We can create the button using <input type =”button”> tag.
There are two types of buttons that can be created in HTML. One is called
submit button and the another one is reset button.
Example code
HTML Document[Button.html]
<!DOCTYPE html>
<html >
<head>
<title> My Page </title>
</head>
<body>
<form name="myform" action="http://www.localhost.com/cgi-bin/hello.cgi" method="POST">
<div align="center">
<br/><br/>
<input type="text" size="35" value=" ">
<br><input type="submit" value="Send">
<input type="reset" value="Reset"><br>
</div>
</form>
</body>
</html>
Output
Script explanation
1) In above HTML document, we have used the form whose name is “myform”.
2) There are two attributes associated with the form tag and those are action and
method. The action parameter indicates the address and the cgi script where the
contents should go and method parameter is for the methods for submitting the
data. The method can be get or post. Thus by specifying the action and method
for a form we can send the desired data at desired location.
1.18.6 Menus
HTML allows us to have pop down menu on the web page so that the
desired selection can be made.
The parameter select is for the menu component and option parameter is
for setting the values to the options of drop down menu.
We can make some specific option selected by selected value = .
In the following HTML document we have created one drop down menu
in which various fruits are enlisted. By default “Banana” is set as selected.
Output
Example 1.18.3 Create a HTML document that has the form with the following controls
Solution :
<!DOCTYPE html>
<html >
<body>
<center><h2>REGISTRATION FORM</h2></center>
<hr/>
<form>
<table>
<tr>
<td>Name:</td>
<td><input type="text" size="25"value=""></td>
</tr>
<tr>
<td>Select the desired Items:</td>
<td>
<select name="f">
<option value="4 HTML Books(Rs. 1000)">4 HTML Books(Rs. 1000)</option>
<option value="8 XML Books(Rs. 2000)">8 XML Books(Rs. 2000)</option>
<option value="4 JavaBeans Books(Rs.2500)">4 JavaBeans Books(Rs.2500)</option>
<option value="8 UML Books(Rs.1500)">8 UML Books(Rs.1500)</option>
</select>
</td>
</tr>
<tr>
<td>
Mode of Payment:
</td>
</tr>
<tr>
<td><input type="radio" name="group1" value="Cash">Cash</td>
</tr>
<tr>
<td><input type="radio" name="group1" value="Cheque/DD">Cheque/DD</td>
</tr>
<tr>
<td><input type="radio" name="group1" value="Credit Card">Credit Card</td>
</tr>
<tr></tr><tr></tr><tr></tr>
<td><input type="submit" value="Submit"></td>
<td><input type="reset" value="Reset"></td>
</tr>
</table>
</form>
</body>
Example 1.18.4 Write a form to collect details of a user such as name, address, radio button to
choose subject of book he wants to buy, dropdown to choose favorite author, comments for the
last book he read.
Solution :
<!DOCTYPE html >
<html >
<head>
<title>My Page</title>
</head>
<body>
<form>
<b>Name:</b><input type="text" size="20" value=""><br/>
<b>Address:</b><input type="text" size="35" value=""><br/>
<b>Subjects:</b><br/>
<input type="radio" name="authors" value="Web Programming">Web Programming<br/>
Output
The HTML 5.0 is the fifth revision of HTML standard of World Wide Consortium
(W3C) which is finalized in October 2014.
The earlier version was HTML 4.0 which was released in 1997.
The objective of this markup language version was - i) To provide support for latest
multimedia and ii) To make the script readable and consistently understood by the
developer.
The HTML5 adds many new syntactic features. It includes the elements such as
<video>, <audio> and <canvas> elements. It also has integration of Scalable Vector
Graphics (SVG) contents and MathML for mathematical Formula.
1. The DOCTYPE declaration is much longer such as The DOCTYPE declaration is simple
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML <!DOCTYPE html>
1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml11.dtd">
2. <audio> and <video> tags are not supported. <audio> and <video> tags are
supported for playing audio and video
files.
3. Finding out geographic location is impossible using The HTML5 supports the API for
HTML identifying the geographic location.
4. It supports the tag such as <applet>, <big>, <center>, The tags that are removed from
<font>, <frame>, <strike> HTML5 are
<applet>, <big>, <center>, <font>,
<frame>, <strike>
7. It needs external plugins such as flash. The need for external plugin is
reduced.
Review Questions
By combining CSS with the html document, considerable amount of flexibility into
the content submission can be achieved.
Similarly, separating out the style from actual contents help in managing large-scale
complex sites. Thus CSS facilitates publication of content in multiple presentation
formats.
If CSS is used, effectively then global style sheet can be applied to a web document.
This helps in maintaining the consistency in the web document.
If a small change needs to be done in the style of web content, then CSS makes it
more convenient.
All above mentioned advantages of CSS show the need for it in web development.
For the document cascading style sheet the style specification appear as the content
of a style element within the header of a document.
The type attribute tells the browser that what it is reading is text which is affected by
the Cascading Style Sheet. The type specification is necessary because there is one more
specification used in JavaScript.
The external style sheet makes use of style specification in the same manner as in
document cascading style sheet.
The most commonly used CSS properties are enlisted in the following table -
Fonts font
font-family
font-size
font-style
font-weight
@font-face
Text letter-spacing
line-height
text-align
text-decoration
text-indent
background-color
background-image
background-position
background-repeat
color
Borders border
border-color
border-width
border-style
border-top
border-top-color
border-top-width
Spacing padding
padding-top
margin
margin-top
Sizing height
max-height
max-width
min-height
min-width
width
clear
display
float
overflow
position
visibility
z-index
Lists list-style
list-style-image
list-style-type
1.23 Selector
1.23.1 Simple Selector Form
The simple selector form is a single element to which the property and value is
applied.
We can also apply property and value to group of elements.
Following is an illustration for simple selector form.
HTML Document[SimpleSel.html]
<!DOCTYPE html>
<html >
<head>
<title>Simple Selector Form</title>
<style type="text/css">
h1
{
font-family:Arial;
color:green;
} We can apply style to
h2,h3 more than one selector
{
font-family:Monotype Corsiva;
color:red;
font-size: 28pt;
}
</style>
` </head>
<body>
<h1>India is My Country</h1>
<h2>All the Indians are my brothers and sisters</h3>
<h3>I love my country</h3>
</body>
</html>
Output
Similarly the style can also be applied to the elements at specific positions.
For example :
body b p {font-size:18pt;}
Note that there are more than one element to which the style is applied and these
elements are separated by the white spaces.
1.23.2 Class Selectors
Using class selector we can assign different styles to the same element.
These different styles appear on different occurrences of that element.
For example
HTML Document[ClassSel.html]
<!DOCTYPE html>
<html>
<head>
<title>Class Selector Form</title>
<style type="text/css">
h1.RedText
{
font-family:Monotype Corsiva;
color:red;
font-size: 14pt;
}
h1.BlueText
{
font-family:Arial;
color:blue;
font-size: 10pt;
}
</style>
</head>
<body>
<h1 class ="RedText">India is My Country</h1>
<h1 class="BlueText">All the Indians are my brothers and sisters</h1>
<h3>I love my country</h3>
</body>
</html>
Output
Script explanation :
Note that in above given script we have used two different classes for the element h1.
One class selector is for displaying the string in red color and another is for displaying the
string in blue color. This definition is given in the head section. In the body section these
class names appear in double quotes inside the h1 tag.
Example 1.23.1 Create a HTML document that displays a table of basketball scores at national
games in which the team names have their respective team colors. The score of the
leading/wining team should appear larger and in different font than the losing team. Use
CSS.
Solution : Football.html
<!DOCTYPE html>
<html >
<head>
<style type="text/css">
tr.one
{
background-color:pink;
color:blue;
}
tr.two
{
font-family:cursive;
background-color:black;
color:yellow;
font-size:50px;
} Output
tr.three
{
background-color:green;
color:white;
}
</style>
</head>
<body>
<table border="3">
<th>Team</th>
<th>Score</th>
<tr class="one"><td>ABC</td><td>7</td>
</tr>
<tr class="two"><td>XYZ</td><td>10</td>
</tr>
<tr class="three"><td>PQR</td><td>5</td>
</tr>
</body>
</html>
}
</style>
</head>
<body>
<center>
<h1> Tongue Twister</h1>
</center>
<h2 class="RedText">
She sells sea shells on the sea shore.
</h2>
<h3 class="RedText">
The shells she sells are sea shells, I'm sure.
</h3>
<h4 class="RedText">
And if she sells sea shells on the sea shore,
</h4>
<p class="RedText">
Then l'm sure she sells seashore shells.
</p>
</body>
</html>
Output
1.23.4 Id Selectors
The id selector is similar to the class selector but the only difference between the
two is that class selector can be applied to more than one elements where as using
the id selector the style can be applied to the one specific element.
The syntax of using id selector is as follows -
#name_of_id {property:value list;}
Following HTML document makes use of id selector.
HTML Document[IdSel.html]
<!DOCTYPE html>
<html>
<head>
<title>id Selector</title>
<style type="text/css">
#top
{
font-family:Monotype Corsiva;
color:blue;
font-size:16pt;
}
</style>
</head>
<body>
<div id="top">
It is the mark of an educated mind to be able to
entertain a thought without accepting it.
</div>
<p>
-Aristotle
</p>
</body>
</html>
Output
HTML Document[UniverSel.html]
<!DOCTYPE html>
<html >
<head>
<title>Universal Selector</title>
<style type="text/css">
*{
color:green;
}
</style>
</head>
<body>
<h2> Famous Proverbs</h2>
<hr/>
<ul type="disc">
<li>A friend in need is a friend indeed</li>
<li>Cleanliness is next to Godliness</li>
<li>All is fair in love and war</li>
<li>An apple a day keeps the doctor away</li>
<li>God helps them who help themselves</li>
<br/><br/>
<em>
-From My Collection.
</em>
</body>
</html>
Output
As we have defined the universal selector that sets the green color. Hence the text that
is appearing on the above web page is in green color.
</head>
<body>
<p>The links with a target attribute gets a RED background:</p>
<h1><a href="https://www.google.com">Google</a> </h1>
<h2><a href="http://www.facebook.com" target="_blank">Facebook</a></h2>
</body>
</html>
Output
HTML Document[PsedoCls.htmll]
<!DOCTYPE html>
<html>
<head>
<title>Pseudo classes</title>
<style type="text/css">
input:focus
{
background-color:skyblue;
color:white;
}
</style>
</head>
<body>
<form>
Enter some string:<input type="text" name="my_txt"/>
<br/>
<input type="submit" value="Enter"/>
</form>
</body>
</html>
Output
Let us now see one more illustration in which the pseudo class is used.
HTML Document[PsedoCls1.html]
<!DOCTYPE html>
<html>
<head>
<title>Pseudo classes for hyperlinks</title>
<style type="text/css">
a.ColoredTxt:link {color: red}
a.ColoredTxt:visited {color: blue} We have defined two
a.ColoredTxt:hover {color: green} pseudo classes named
ColoredTxt and BigTxt
a.BigTxt:link {color: red}
a.BigTxt:visited {color: blue}
</style>
</head>
<body>
<h3>Move Mouse over following text</h3>
<p>
<em>
<a class="ColoredTxt" href="mypage.html" target="_blank">The text
changes color
</a>
</em>
</p>
<p>
<em>
<a class="BigTxt" href="mypage.html" target="_blank">The text is getting
Big in size
</a>
</em>
</p>
</body>
Output
For example -
<!DOCTYPE html>
<html>
<head>
<style>
pb{
font-family: Times, serif; /* Font family */
font-weight: bold; /* heavy faced type*/
color: blue; /* blue colour of the text */
}
</style>
</head>
<body>
<div><b>This line is in bold face font</b></div>
<p><b>This line is in bold face with the color of the text - blue </b></p>
<p> Good Bye</p>
</body>
</html>
Output
Tag
{
property: value
}
For example :
<p style="font-family: Arial;color:red" >
Here for the tag p two properties are used such as font-family and color and those are
associated with the values such as arial and red respectively.
Note that if we want to use more than one property then we have to use separator
such as semicolon. In the following HTML document we have used cascading style sheet-
HTML Document [InlineStyle.html]
<!DOCTYPE html >
<html>
<head>
<title>Inline Cascading Style Sheet</title>
</head>
<body>
<p>This is simple text</p>
<p style="font-size: 30pt ;font-family:Script">This text is different </p>
<p style="font-size: 40pt ;color:#ff0000">This text is colored.</p>
</body>
</html>
Script explanation
1) In this document, in the body section the style sheets are created.
2) In this section first of all we have displayed a simple sentence This is simple text.
There is no style for this sentence.
3) In the next line, we have applied style in which font-size is set to the size of 30
point and font-family is set by the font name "Script".
4) Then colored text will be displayed by color:#ff0000". The first two digits ff
denote the red color, there is no green and blue color as the values next to ff are
00. Hence the text will be displayed in red.
This can be very well illustrated in output.
Output
left:20px
}
h3
{
font-family:arial;
color:blue;
}
p
{
font-size:14pt;
font-family:verdana
}
</style>
</head>
<body>
<h1>
<center>
This page is created using Document Level Style Sheet
</center>
</h1>
<h2>
This line is aligned left and red colored.
</h2>
<p>
The embedded style sheet is the most commonly used style sheet.
This paragraph is written in Verdana font with font size of 14.
</p>
<h3>
This is a blue <a href="colorname.html">colored</a> line.
</h3>
</body>
</html>
Output
Script explanation
1) In above program, we have defined all the selectors in the head sections only.
And these HTML elements are then used along with the web page contents.
2) The setting defined in the selectors will affect the web page contents. For
example we have defined the selector h2 as,
h2
Selector
{
font-family:Arial;
Script explanation
When we want to link the external style sheet then we have to use <link> tag which is
to be written in the head section.
link tells the browser some file must be linked to the page.
rel=stylesheet tells the browser that this hyperlink is a style sheet.
href=" " denotes the path name of style sheet file.
type="text/css" tells the browser that what it is reading is text which is affected by
the cascading style sheet.
When the specification is marked by !important then it actually specifies the weight.
The weight can be either important or normal.
The origin can be author origin, user origin and user agent origin. These terms can
be defined as follows -
o Author is a person who writes the XHTML document and associated style
sheets.
o User is a person who interacts with user agent and use the web document
along with the associated style sheets.
o User agent is a program that interprets the web document written in scripting
language and applies the style sheet according to the specification. For
example, HTML is an user agent.
The sorting order can be determined by applying following rules with highest
precedence to lowest -
1. Important declaration having user origin.
2. Important declaration having author origin.
3. Normal declaration having author origin.
4. Normal declaration having user origin.
5. Any declaration (either important or normal) with user agent (i.e. browser)
origin.
Following rules are also be used to decide the sorting order of the elements from
highest precedence to lowest -
1. id selectors have the highest precedence.
2. class and pseudo class selectors
3. Contextual selectors
4. Universal selectors
If the conflict still occurs then it can be resolved writing the properties in the
specification. The rules that are defined later in the document tree have the highest
precedence than those defined earlier.
Style rule cascading can be defined as the process which is used to resolve the
conflicts in the style specification. Fig. 1.25.1 shows the steps in CSS cascade.
1.25.2 Inheritance
In CSS, if a property of an element has no associated declarations then using
inheritance technique the value for this property can be obtained.
In an HTML document, the tags have parent-child relationships. For example,
<title> tag is always inside the <head> tag, so the <head> tag is the parent of the
<title> tag. Similarly <p> tag is defined inside the <body> tag. Then <body> becomes
parent of <p> tag.
In cascading style sheets, inheritance is based on tree structure of the document
itself.
An element inherits the value for its properties by checking the parent element. If
the parent has the value for the property demanded by the child then this property
value can be inherited. If the parent down not have this value, then its parent (i.e.
grandparent) is checked. If this parent has no such property value then its parent is
checked. This process is continued until a root element is obtained.
Thus the search will be made in upward direction from the parent of the element to
the root of the tree or to the <html> tag of the document.
Inheritance can be defined as a concept in which child always inherits the properties
of parent tag along with its own properties.
Following is an HML document in which inheritance is demonstrated.
HTML Document
<!DOCTYPE html>
<html>
<head>
<title>Inheritance Demo</title>
<style type="text/css">
p
{
font-family:Arial;
color:blue;
background-color:yellow;
}
strong
{
font-size:24px;
}
</style>
</head>
<body>
<center>
<p>This is a blue text <strong>with</strong> yellow background</p>
</center>
</body>
</html>
Output
Script explanation :
In above, script <p> tag has some properties as Arial font, blue font color and yellow
background. The <strong> tag has only one property can that is font-size which is
assigned by the value 24px. But in the body section, <strong> tag is the child of <p> tag.
And note that <strong> inherits the properties of <p> tag. Hence the text defined
under<strong> tag is also blue colored with yellow background.
Now just modify by the above script as follows and observe the sample output.
Output
Note that the above style sheet contains the nested tags -
<li>
…..<p>
………….<strong>
………….</strong>
…..</p>
</li>
The <li> tag contains the italic property. Hence the text inside the <strong> tag becomes
italic. That means <strong> tag has inherited the italic property from its grandchild.
1.26 Text Properties SPPU : March-20, Marks 5
The font properties can be setting different types of fonts, styles and sizes.
cursive Zapf-chancery
</body>
</html>
If the font name has more than one word then the name should be enclosed by the
single quotes. Although quotes are not mandatory, it is a good practice to use quotes for
specifying the font name.
HTML Document[FontSize.html]
<!DOCTYPE html>
<html>
<head>
Output
<title>Font-Size Demo</title>
<style type="text/css">
h1
{
font-size:10pt;
}
h2
{
font-size:20px;
}
h3
{
font-size:xx-large;
}
h4
{
font-size:250%;
}
</style>
</head>
<body>
<h1>Programming the Web</h1>
<h2>Programming the Web</h2>
<h3>Programming the Web</h3>
<h4>Programming the Web</h4>
</body>
</html>
Value Meaning
</style>
</head>
<body>
<h1>Programming the Web</h1>
</body>
</html>
HTML Document[FontSt.html]
<!DOCTYPE html>
<html
<head>
<title>Font-Style Demo</title>
<style type="text/css">
h3.normal { font-style:normal;}
h3.italic { font-style:italic;}
h3.oblique { font-style:oblique;}
</style>
</head>
<body>
<h3 class="normal">Programming the Web</h3>
<h3 class="italic">Programming the Web</h3>
<h3 class="oblique">Programming the Web</h3>
</body>
</html>
Output
HTML Document[FontWt.html]
<!DOCTYPE html>
<html>
<head>
<title>Font-Weight Demo</title>
<style type="text/css">
p.normal { font-weight:normal;}
p.bold { font-weight:bold;}
p.bolder { font-weight:bolder;}
p.lighter { font-weight:lighter;}
</style>
</head>
<body>
<p class="normal">Programming the Web</p>
<p class="bold">Programming the Web</p>
<p class="lighter">Programming the Web</p>
<p class="bolder">Programming the Web</p>
</body>
</html>
Output
HTML Document[Fontshrthnd.html]
<!DOCTYPE html>
<html>
<head>
<title>Font Properties</title>
<style type="text/css">
p.myfont {font-family:Courier New;
font-style:italic;
font-weight:bold;
font-size:28pt;
}
</style>
</head>
<body>
<p class="myfont">I Love my Country!!!</p>
</body>
</html>
Output
HTML Document[TxtDecor.html]
<!DOCTYPE html>
<html>
<head>
<title>Text Decoration</title>
<style type="text/css">
p.linethrough {text-decoration:line-through;}
p.underline {text-decoration:underline;}
p.overline {text-decoration:overline;}
p.normal {text-decoration:normal;}
</style>
</head>
<body>
<p class="linethrough"> This text is having linethrough </p>
<p class="overline"> This text is having overline </p>
<p class="underline"> This text is having underline </p>
<p class="normal"> This text is a normal text </p>
</body>
</html>
Output
<body>
<h1>This line is aligned at left</h1>
<h2>This line is aligned at right</h2>
<h3>This line is aligned at center</h3>
</body>
</html>
Output
Example 1.26.1 How to you create a multi colour text on a web page using CSS ?
Bootstrap is open source, front end web framework. It is used for designing
web-site and web applications.
Bootstrap helps the developer to create responsive designs. Responsive web design
means creating the web site which automatically adjusts itself to look good on all
the devices. These devices range from small phones to large desktops screens.
Bootstrap includes HTML, CSS and JavaScript based design templates which
includes forms, buttons, tables, navigation, modals and so on.
Features of Bootstrap
Setting up Environment
There are two ways to use Bootstrap in a webpage.
1) The first way is to use a CDN or Content Delivery Network. Using
bootstrap CDN means that we will not download and store the bootstrap
files in our server or local machine. We will just include the bootstrap CSS
and JavaScript links on our page.
2) The second way is downloading and storing a copy Bootstrap files in our
web server or local machine. We can download the Bootstrap from
https://getbootstrap.com/
I have created a folder named bootstrap-3.3.7 and downloaded my Bootstrap in this
folder. After getting downloaded I can see three folders in it namely css, fonts and js
If we want to use the CDN then we will include Bootstrap CSS as follows -
<link rel="stylesheet"
href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
If we want to use our own downloaded copy then we will use
<link rel="stylesheet"
href="bootstrap-3.3.7/css/bootstrap.min.css">
Similarly the jquery can be used as
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.0.0/jquery.min.js"></script>
Or
<script src="jquery-3.0.0.min.js"></script>
Components of Bootstrap
1. HTML 5 : The Bootstrap uses the HTML elements and CSS properties, hence the
code is contained within the <doctype>.
<!DOCTYPE html>
<html lang=”en”>
<head>
<meta charset="utf-8">
… …
Script declarations
</head>
<body>
…
…
</body>
</html>
2. The mobile-first : Bootstrap 3 is designed to be responsive to mobile devices.
Mobile-first styles are part of the core framework.
For proper rendering the <meta> tag inside the <head> section is specified. It is
specified as follows -
<meta name="viewport" content="width=device-width, initial-scale=1">
The width=device-width part sets the width of page which is based on the
screen-width of the device.
The initial-scale = 1 part sets the initial zoom level when the page is loaded on the
browser.
3. Container
The container element is for wrapping the site contents. There are two classes for the
container -
i) Container : It provides a responsive fixed width container.
ii) Container-fluid : It provides full width container occupying the entire width of
the viewport.
BootstrapDemo.html
<!DOCTYPE html>
<html lang="en">
<head>
<title>Bootstrap Example</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet"
href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script
src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</head>
<body>
<div class="container" style="background-color:grey;">
<h1 >Enjoying Web Page Design with Bootstrap</h1>
<p>The .container class is here and it provides fixed width container</p>
</div>
</body>
</html>
Output
Similarly if we change the <div> element class to container-fluid we will get the
content to be occupied the entire web page. It can be demonstrated by modifying the
above script as follows -
BootstrapDemo.html
<!DOCTYPE html>
<html lang="en">
<head>
<title>Bootstrap Example</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet"
href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script
src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</head>
<body>
</body>
</html>
Output
The above classes can be combined to create more dynamic and flexible display.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script
src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</head>
<body>
<div class="container-fluid">
<div class="row">
<div class="col-sm-3" style="background-color:grey;">One</div>
<div class="col-sm-3" style="background-color:aqua;">Two</div>
If we resize the browser window we get the columns to be stacked one upon other
Similarly we can create the columns of unequal width, if we change the <col-sm>. For
example -
<div class="col-sm-8" style="background-color:grey;">One</div>
<div class="col-sm-4" style="background-color:aqua;">Two</div>
1.27.2 Typography
In this section we will learn how to display the text in different style using
Bootstrap elements.
By default font size is 14 px.
The HTML elements will be displayed with different style in Bootstrap.
Heading
The tags <h1> to <h6> are used to display the heading. For example
HeadingDemo.html
<!DOCTYPE html>
<html lang="en">
<head>
<title>Bootstrap Example</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet"
href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script
src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
Output
</head>
<body>
<div class="container">
<h1> This line is of 36px </h1>
<h2> This line is of 30px </h2>
<h3> This line is of 24px </h3>
<h4> This line is of 18px </h4>
<h5> This line is of 14px </h5>
<h6> This line is of 12px </h6>
</div>
</body>
</html>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script
src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
Output
</head>
<body>
<div class="container">
<h1> This line is of <small>36px</small> </h1>
<h2> This line is of <small>30px</small> </h2>
</div>
</body>
</html>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script
src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</head>
<body>
<div class="container">
<p> This line is an <mark>important</mark> message </p>
</div>
</body>
</html>
Output
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script
src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</head> Output
<body>
<div class="container">
<pre>
Humty Dumty
sat on a wall.
Jack and Jill
went up the hill.
Twinkle Twinkle
little star
How I wonder
What you are!!!
</pre>
</div>
</body>
</html>
TextDemo.html
<!DOCTYPE html>
<html lang="en">
<head>
<title>Bootstrap Example</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet"
href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script
src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</head>
<body>
<div class="container">
<p class="text-left">This line is left aligned</p>
<p class="text-right">This line is right aligned</p>
<p class="text-center">This line is at center </p>
<p class="text-muted">This line is using muted class</p>
<p class="text-primary">This line is using primary class</p>
<p class="text-success">This line is using success class</p>
<p class="text-info">This line is using info class</p>
<p class="text-warning">This line is using warning class</p>
<p class="text-danger">This line is using danger class</p>
</div>
</body>
</html>
Output
TextBGDemo.html
<!DOCTYPE html>
<html lang="en">
<head>
<title>Bootstrap Example</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet"
href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script
src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</head>
<body>
<div class="container">
<p class="bg-primary">This line is using primary class</p>
<p class="bg-success">This line is using success class</p>
<p class="bg-info">This line is using info class</p>
<p class="bg-warning">This line is using warning class</p>
<p class="bg-danger">This line is using danger class</p>
</div>
</body>
</html>
Output
1.27.3 Tables
The <table> tag is used to create the table. The <tr> tag is used for rows and <td> tag is
used for columns. The heading in the table can be denoted within <thead><th> </th>
</thead> tag while remaining contents of the table are specified in <tbody> tag.
The following example demonstrates the use of table tag.
TableDemo1.html
<!DOCTYPE html>
<html lang="en">
<head>
<title>Bootstrap Example</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet"
href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script
src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</head>
<body>
<div class="container">
<table class="table">
<thead>
<tr><th> Name </th><th> City </th></tr>
</thead>
<tbody>
<tr>
<td>AAA</td>
<td>Pune</td>
</tr>
<tr>
<td>BBB</td> Output
<td>Mumbai</td>
</tr>
<tr>
<td>CCC</td>
<td>Chennai</td>
</tr>
</tbody>
</div>
</body>
</html>
1.27.4 Images
For displaying the images the <img src=””> tag is used. You have to specify the
image file name within the double quotes.
There are three classes that are used to display the image. These classes are -
1. img-rounded : The image is displayed in a border-circle of radius 6px.
2. img-circle : The image is displayed in circle of radius 500px
3. img-thumbnail : The image is displayed in a rectangle having padding and grey
border.
Here is illustrative example of displaying images.
ImgDemo.html
<!DOCTYPE html>
<html lang="en">
<head>
<title>Bootstrap Example</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet"
href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script
src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</head>
<body>
<img src = "bookImg.jpg" class = "img-rounded">
<img src = "bookImg.jpg" class = "img-circle">
<img src = "bookImg.jpg" class = "img-thumbnail">
</body>
</html>
Output
1.27.5 Button
In Bootstrap we can create the buttons of different styles. Various button classes are
used as follows -
.btn, .btn-default, .btn-primary, .btn-success, .btn-info, .btn-warning,
.btn-danger, .btn-link
The example code is as follows -
ButtonDemo.html
<!DOCTYPE html>
<html lang="en">
<head>
<title>Bootstrap Example</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet"
href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script
src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</head>
<body>
We can also create active or disabled buttons using active and disabled class. The
illustration is as follows -
ButtonDemo1.html
<!DOCTYPE html>
<html lang="en">
<head>
<title>Bootstrap Example</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet"
href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script
src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</head>
<body>
<button type="button" class="btn btn-success">Success</button>
<button type="button" class="btn btn-success active">Active</button>
<button type="button" class="btn btn-success disabled">Disabled</button>
</body>
</html>
Output
1.27.6 Form
In Bootstrap there are three types of form layouts.
1. Vertical Form 2. Horizontal Form 3. Inline Form
For using the form we must add the <div> element as <div class=”form-group”>.
The required controls such as <input>, <select>, <textarea> and so on can be added
within this <div> class.
Let us discuss and learn how to create the above mentioned types of forms –
FormDemo1.html
<!DOCTYPE html>
<html lang="en">
<head>
<title>Bootstrap Example</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet"
href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script
src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</head>
<body>
<form role = "form">
</div>
</div>
</form>
</body>
</html>
Output
2. Horizontal Form
To create the vertical or basic form use following steps –
Step 1 : Add a role to form element as -
<form role=”form”> and form class=”form-horizontal”
Step 2 : Inside the <div class=”from-group”> wrap all the labels and controls
Step 3 : While adding any textual control such as <text>, <textarea> and <select> add the
class “form-control”
Step 4 : Add a class of “control-label” to the labels.
Here is example code –
FormDemo2.html
<!DOCTYPE html>
<html lang="en">
<head>
<title>Bootstrap Example</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet"
href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script
src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</head>
<body>
<form class ="form-horizontal" role = "form">
<div class = "form-group">
<label class="control-label col-sm-4" for = "name">User Name</label>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet"
href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script
src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</head>
<body>
<form class="form-inline" role = "form">
<div class = "form-group">
<label for = "name">User Name</label>
<input type = "text" class = "form-control" id = "name">
</div>
</form>
</body>
</html>
Output
Review Questions
a HTML b TCP/IP
c IPX d None of these
Q.3 FTP stands for _____.
a HTTP b SGML
c XML d None of these
a <?> b <>
c ## d {}
Q.10 What does <br> tag do ?
a Long break b Paragraph break
c Line break d None of these
Q.11 Which tag tells the browser where the page starts and stops ?
a <html> b <body>
c <head> d <title>
Q.12 The main container for <TR>, <TD> and <TH> is _______.
a <list> b <frame>
c <table> d none of the above
Q.13 Which of the following is not a newly added element in HTML5 ?
a Article b Audio
c Nav d Frameset
Q.14 In HTML5, which element may be used within content to represent material that is
tangential _____.
a aside b cite
c article d class
Q.15 CSS stands for _____.
a Color and Style Specification b Cascading Style Sheets
c Concurrent Style Specification d None of these
Q.16 The property in CSS used to change the background color of an element is _____.
a bgcolor b color
c background-color d all of the above
Q.17 The property in CSS used to change the color of a text is _____.
a bgcolor b color
c background-color d all of the above
Q.18 Which of the following attributes is used to specify elements to bind style rules to ____.
a id b class
c tag d all of the above
Notes
Contents
2.1 Introduction to JavaScript
2.2 JavaScript in Perspective
2.6 Literals
2.9 Operators
2.10 Input and Output
2.11 Statements
2.17 Strings
(2 - 1)
Web Technology 2-2 Client Side Technologies : JavaScript and DOM
Part - I : JavaScript
3. Java is strongly typed language and the In JavaScript variables need not be
type checking is done at compile time. declared before their use. Checking the
compatibility of type can be done
dynamically.
4. Objects in Java are static. That means the In JavaScript the objects are dynamic.
number of data members and method are That means we can change the total
fixed at compile time. data members and method of an object
during execution.
4. Dynamic Typing : It supports dynamic typing, that means the data type is
bound to the value and not to the variable. For example one can assign integer
value to a variable say ‘a’ and later on can assign some strg the ing value to the
same variable in JavaScript.
5. Run Time Evaluation : Using the eval function the expression can be evaluated
at run time.
6. Support for Object : JavaScript is object oriented scripting language. However
handling of objects in JavaScript is somewhat different that the conventional
object oriented programming languages. JavaScript has a small number of in-
built objects.
7. Regular Expression : JavaScript supports use of regular expressions using which
the text-pattern matching can be done. This feature can be used to validate the
data on the web page before submitting it to the server.
8. Function Programming : In JavaScript functions are used. One function can
accept another function as a parameter. Even, one function can be assigned to a
variable just like some data type. The function can be run without giving the
name.
<body>
<center>
<script type="text/javascript">
/*This is the First JavaScript*/
document.write(" Welcome to First Page of Javascript");
</script>
</center>
</body>
</html>
Output
Script Explanation :
In above script
1) We have embedded the javaScript within
<script type="text/javascript">
…
</script>
2) A comment statement using /* and */. Note that this type of comment will be
recognized only within the <script> tag. Because, JavaScript supports this kind of
comment statement and not the XHTML document.
If we want to embed the JavaScript indirectly, that means if the script is written in
some another file and we want to embed that script in the HTML document then we must
write the script tag as follows -
XHTML Document[FirstPg.html]
<!DOCTYPE html >
<html>
<head> This is an external javascript
<title> My First Javascript </title> file; it can be specified with the
</head> attribute src
<body>
<center>
<script type="text/javascript" src="my_script.js">
</script>
</center>
</body>
</html>
Step 2 :
JavaScript[my_script.js]
/*This is the First JavaScript*/
document.write(" Welcome to First Page of Javascript");
Step 3 : Open the HTML document in Internet Explorer and same above mentioned
output can be obtained.
1. Identifiers
Identifiers are the names given to the variables. These variables hold the data value.
Following are some conventions used in JavaScript for handling the identifiers -
1. Identifiers must begin with either letter or underscore or dollar sign. It is then
followed by any number of letters, underscores, dollars or digits.
2. There is no limit on the length of identifiers.
3. The letters in the identifiers are case-sensitive. That means the identifier INDEX,
Index, index, inDex are considered to be distinct.
4. Programmer defined variable names must not have upper case letters.
2. Reserved words
Reserved words are the special words associated with some meaning. Various reserve
words that are used in JavaScript are enlisted as below -
3. Comments
JavaScript supports following comments.
1. The // i.e a single line comment can be used in JavaScript.
2. The /* and */ can be used as a multi-line comment.
3. The XHTML <!--> and <--> is also allowed in JavaScript
4. Semicolon
While writing the JavaScript the web programmer must give semicolon at the end of the
statements.
JavaScript uses six types of values - number, string, boolean, null, object and function
Number : Number is a numeric value that can be integer or float. It can be used
calculation.
String : String is a collection of characters. It is enclosed within single quote or double
quote. A string may contain numbers but these numbers can not be used for calculations.
Boolean : The Boolean values are true and false. These values can be compared with the
variables or can be used in assignment statement.
Null : The null value can be assigned by using the reserved word null. The null means no
value. If we try to access the null value then a runtime error will occur.
Object : Object is for an entity that represents some value. For example - window object is
a value using which the window is created. Form is an object upon which some
components such as button, checkbox, radio buttons can be placed and used.
Review Questions
1. Explain the different data types available in JavaScript. SPPU : May-18, Marks 5
2. What are different data types available in JavaScript ? Explain with correct syntax of
declaration of it. SPPU : May-19, Marks 5
2.6 Literals
There are two types of literals used in JavaScript and those are numeric literals and
string literals. The numeric literals are called numbers. These numbers can include
integer values, floating point or double precision values. For example -
10
10.3
10.0
10.
10E3
10.2E4
10.e2
10e-3
are all valid numeric literals.
The string literals are the sequence of characters. It can be written in double quotes “ ”
or in single quotes ‘ ‘. For example
‘Rain Rain come soon ‘
2.8 Variables
In JavaScript we can declare the variable using the reserved word var. The value of
this variable can be anything; it can be numeric or it can be string or it can be a Boolean
value.
JavaScript[VarDemo.html]
<!DOCTYPE html >
<html >
<head>
<title> Variables in Javascript </title>
</head>
<body>
<script type="text/javascript">
var a,b,c;
var string;
Variable declaration is done using var.
a=2;
Note that there is no data type required
b=3; for handling variables.
c=a+b;
string ="The result = ";
document.write("Performing addition of 2 and 3. "+"<br/>");
document.write(string);
document.write(c);
</script>
</body>
</html>
Output
Note that using var we can define the variable which is of type numbers (2, 3 or 5) as
well as the string “The result”.
2.9 Operators
Various operators used by JavaScript are as shown in following Table -
* Multiplication c = a*b
/ Division c = a/b
% Mod c = a%b
== Equal to x == 100
!= Not equal to m != 8
|| Or operator 0 ||1
a=a+5
a = a – 10
Conditional operator
The conditional operator is ? The syntax of conditional operator is
Condition?expression1:expression 2
Where expression1 denotes the true condition and expression2 denotes false condition.
For example :
a>b?true:false
This means that if a is greater than b then the expression will return the value true
otherwise it will return false.
Expressions
JavaScript makes use of mathematical statements using operators
and operands.
These statements are called expressions.
For example - Following Fig. 2.9.1 shows a simple expression.
2.11 Statements
2.11.1 If Statement
As a selection statement we use various types of if statements. These statements are -
1. if - The syntax of if is
if(condition)
statement if the condition is true
2. if…else - The syntax of if…else is
if(condition)
statement if the condition is true
else
statement if the condition is false
3. if…else if - The syntax of if…else if is
if(condition)
have compared a with b, if a is greater than b then we have compared a with c. Similarly
in the else part b is compared with c. Thus all the three numbers get compared with each
other and the largest number is found out among the three. Since already in our program
we have set the a, b and c values as 10, 20 and 30 respectively the output should be c is
largest number and here comes the output on web browser.
Output
We can use various operators such as arithmetic operator, logical operator, relational
operators and so on in the if statement. Following JavaScript makes use of such operators.
JavaScript[IfElseDemo.html]
<!DOCTYPE html>
<html>
<head>
<title>If else Demo</title>
</head>
<body>
<script type="text/javascript">
var marks;
marks=80;
if(marks<40)
document.write("You are failed");
else if(marks>=40 && marks<50)
document.write("You are passed");
else if(marks>=50 && marks<60)
document.write("You have got Second class");
else if(marks>=60 && marks<66)
document.write("You have got First class");
else
document.write("You are Distinction Holder");
</script>
</body>
</html>
Output
In above script if we change the values of the marks variable then appropriate message
will get displayed on the web browser.
<script type="text/javascript">
d=new Date();
ch=d.getMonth();
switch(ch)
{
case 0: document.write("January");
break;
case 1: document.write("February");
break;
case 2: document.write("March");
break;
case 3: document.write("April");
break;
case 4: document.write("May");
break;
case 5: document.write("June");
break;
case 6: document.write("July");
break;
case 7: document.write("August");
break;
case 8: document.write("September");
break;
case 9: document.write("October");
break;
case 10: document.write("November");
break;
case 11: document.write("December");
break;
}
</script>
</body>
</html>
Output
Output
}while(counter<=5);
</script>
</body>
</html>
Output
Output
Output
Output
JavaScript[PopupBox.html]
<!DOCTYPE html>
<html >
<head>
<title>Introduction to pop up box</title>
</head>
<body>
<p>Experiment with the popup boxes by clicking the buttons(OK and Cancel) on them</p>
<script type="text/javascript">
if(confirm("do you agree?"))
alert("You have agreed");
else
input_text=prompt("Enter some string here..."," ");
/*the value entered in prompt box is returned
and stored in the variable text */
alert("Hi "+input_text);
</script>
</body>
</html>
Output
On load, the confirm box appears and if we click on Cancel button then the prompt
box will appear. We can type some string within it.
Thus alert, confirm and prompt boxes cause the browser to wait for user response. The
user responds by clicking the button on these popup boxes.
Script Explanation
On loading this script using web browser first of all a confirm box will be displayed. If
we click on OK button an alert box will appear. Otherwise a prompt box will be
displayed. Again if we click on the OK button of prompt box again an alert box will
appear which will display the string which you have entered on prompt box. If you run
the above script you will get all these effects.
n=num%10;
n=parseInt(n);
num=num/10;
num=parseInt(num);
sum=sum+(n*n*n);
}
if(sum==i)
{
document.write("<tr><td>"+i+"</td></tr>");
}
i++;
}while(i<=1000);
</script>
</table>
</body>
</html>
Example 2.12.2 Write a JavaScript that displays table as per following : (Calculate the squares
and cubes of the numbers from 0 to 10).
Number Square Cube
1 1 1
2 4 8
3 9 27
4 16 64
5 25 125
6 36 216
7 49 343
8 64 512
9 81 729
10 100 1000
Solution :
<html>
<head>
<title>Sqaure and Cube value table</title>
</head>
<body>
<table border=1 align="center">
<th>Number</th><th>Square</th><th>Cube</th>
<script type="text/javascript">
for (i=1; i<=10; i++)
{
document.write("<tr><td>"+i+"</td><td>"+(i*i)+"</td><td>"+(i*i*i)+"</td></tr>");
}
</script>
</table>
</body>
</html>
Example 2.12.3 Write a script that reads an integer and displays whether it is a prime number
or not.
Solution :
<html>
<head>
<title>PRIME NUMBER DEMO</title>
</head>
<body>
<script type="text/javascript">
var num=prompt("Type number here.","");
var b;
var flag=1;
for(i=2;i<num;i++)
{
b=num%i;
if(b==0)
{
flag=0;
break;
}
}
if(flag==0)
alert(num+" is not a prime number");
else
alert(num+" is a prime number");
</script>
</body>
</html>
Output
2.13 Functions
SPPU : April-18, Dec.-18, Marks 5
We can write the functions in the JavaScript for bringing the modularity in the
script.
Separate functions can be created for each separate task. This ultimately helps in
finding the bug from the program efficiently.
<!DOCTYPE html>
<html>
<head>
<title>Function Demo</title>
<script type="text/javascript">
function my_fun()
{
document.write("This statement is within the function"); Definition of function
}
</script>
</head>
<body>
<center>
<script type="text/javascript">
document.write("This statement is before a function call");
document.write("<br>");
my_fun(); // call to the function
</script>
</center>
</body>
</html>
Output
Script Explanation
The above code is pretty simple. We have defined one function named my_fun in the
head section of the HTML document and called it from the body section. The
corresponding write statements are used to display the messages on the browser
window.
Script Explanation :
In above JavaScript,
1) We have created two functions namely A() and B().
2) Inside the A() function variable a is declared and initialized to the value 100. The
value of this variable is displayed using the element<p>…</p>
3) Inside the B() function, we are trying to display the value of same variable a
using <p>…</p> . But note that the output does not display value of variable a
through function B(). This is because variable a is a local variable declared in
function A(). Hence its scope is upto the function A(). Outside this function, the
variable a is undefined.
Global Scope
A variable is called global variable, if it is defined outside the function. The variable
having global scope is accessible by any function.
Following example illustrates the use of global variable.
JavaScript example for demonstrating the scope of global variable
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
var a=100//Global variable
function A()
{
document.getElementById("id1").innerHTML
="From function A(): a = "+a
}
function B()
{
document.getElementById("id2").innerHTML
="From function B(): a = "+a
}
</script>
</head>
<body>
<p id="id1"></p>
<p id="id2"></p>
<script type="text/javascript">
A()
B()
</script>
</body>
</html>
Output
Output
Output
For calling a function from HTML normally, JavaScript events are used. For example -
JavaScript Document
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
function A()
{
alert("Inside the function A");
}
</script>
</head>
<body onload="A()">
</script>
</body>
</html>
Output
Output
Review Questions
1. List and brief any five functions in JavaScript. SPPU : April-18, Marks 5
2. Explain how to call JavaScript function from HTML page. SPPU : Dec.-18, Marks 5
For performing the mathematical computations there are some useful methods
available from math object.
For example if we want to find out minimum of two numbers then we can write -
document.write(math.min(4.5,7.8));
The above statement will result in 4.5. Thus using various useful methods we can
perform many mathematical computations.
Method Meaning
ceil(num) This method returns the ceil value of num. For example ceil(10.3) will return 11.
floor(num) This method returns the floor value of num. For example floor(10.3) will return 10.
log(num) This method returns the natural logarithmic value of num. For example log(7.9) will
return 2.
pow(a,b) This method will compute the ab. For example pow(2,5) will return 32.
JavaScript Program[MathDemo.html]
<!DOCTYPE html>
<html >
<head>
<title>Math Demo</title>
</head>
<body>
<center>
<h3>Square root of 100 is </h3>
<script type="text/javascript">
var num=100;
document.write("<h3>"+Math.sqrt(num)+"</h3>");
</script>
</center>
</body>
</html>
Output
Property Meaning
JavaScript[NumberDemo.html]
<!DOCTYPE html>
<html>
<head>
<title>Number Object Demo</title>
</head>
<body>
<center>
<script type="text/javascript">
document.write(Number.NEGATIVE_INFINITY);
</script>
</center>
</body>
</html>
Output
Method Meaning
getDay() Returns the current day. The day number is from 0 to 6 i.e. from
Sunday to Saturday.
getUTCDay() Returns the current day based on UTC. The day number is from 0 to
6 i.e. from Sunday to Saturday.
getHours() Returns the hour value ranging from 0 to 23, based on local time.
getUTCHours() Returns the hour value ranging from 0 to 23, based on UTC timing
zone.
getMilliseconds() Returns the milliseconds value ranging from 0 to 999, based on local
time.
getUTCMilliseconds() Returns the milliseconds value ranging from 0 to 999, based on UTC
timing zone.
getMinutes() Returns the minute value ranging from 0 to 59, based on local time.
getUTCMinutes() Returns the minute value ranging from 0 to 59, based on UTC timing
zone.
getSeconds() Returns the second value ranging from 0 to 59, based on local time.
getUTCSeconds() Returns the second value ranging from 0 to 59, based on UTC timing
zone.
setDate(value) This function helps to set the desired date using local timing or UTC
timing zone.
setHour(hr,minute,second,ms) This function helps to set the desired time using local or UTC timing
zone. The parameters that can be passed to this function are hour,
minute, seconds and milliseconds. Only hour parameter is
compulsory and rest all are the optional parameters.
In the following web document we are making use of Date() object and some useful
methods of it.
JavaScript[DateDemo.html]
<!DOCTYPE html>
<html>
<head>
<title>Date Demo</title>
</head>
<body>
<script type="text/javascript">
var my_date=new Date();
document.write("The date is: "+my_date.toString()+"<br>");
document.write("Today's date is "+my_date.getDate()+"<br>");
document.write("This is the month of "+my_date.getMonth()+"<br>");
document.write("The current year is "+my_date.getFullYear()+"<br>");
document.write("Now, Hour = "+my_date.getHours()+"<br>");
document.write("Minutes = "+my_date.getMinutes()+"<br>");
document.write("Seconds = "+my_date.getSeconds()+"<br>");
</script>
</body>
</html>
Output
Script Explanation :
1. In the above script we have created an instance my_date of the object Date().
2. Then using my_date.toString() method we can display the current date along
with the time.
3. Then using the functions like getDate(), getMonth(), getFullYear() we are
displaying the date, month and year separately.
4. Similarly using the functions getHours(), getMinutes() and getSeconds() we can
display the current hour, minute and seconds separately.
Javascript Program
<html>
<body>
<script type="text/javascript">
var temp=new Boolean(false);
document.write("<b>"+"The boolean value is: ");
document.write(temp.toString());
</script>
</body>
</html>
Output
Method Meaning
concat(str) This method concatenates the two strings. For example - s1.concat(s2) will
result in concatenation of string s1 with s2.
charAt(index_val) This method will return the character specified by value index_val.
substring(begin,end) This method returns the substring specified by begin and end character.
toLowerCase() This function is used to convert all the uppercase letters to lower case.
toUpperCase() This function is used to convert all the lowercase letters to upper case.
valueOf() This method returns the value of the string.
There is one important property of string object and that is length. For example
var my_str=”Hello”;
var len; Length of the string “Hello” will be
len=my_str.length; stored in the variable len
Here is sample program in which some methods of string object are used.
JavaScript[StringDemo.html]
<!DOCTYPE html>
<html>
<head>
<title>String Properties and Methods Demo</title>
</head>
<body>
<strong>
<script type="text/javascript">
var s1="Hello ";
var s2="Parth!";
document.write("First string is: "+s1+"<br>");
document.write("Second string is: "+s2+"<br>");
document.write("Concatenating two strings: "+s1.concat(s2)+"<br>");
document.write("Finding length of Second string : "+s2.length+"<br>");
document.write("The character at 0th position of First string is : "+s1.charAt(0)+"<br>");
document.write("The First string can be converted to upper case as : "+s1.toUpperCase());
</script>
</strong>
</body>
</html>
Output
Example 2.14.1 Write a script that inputs a line of text, tokenizes it with String method split
and displays the tokens in reverse order.
Solution :
<html>
<body>
<script type="text/javascript">
The web designer can create an object and can set its properties as per his
requirements.
The object can be created using new expression.
Initially the object with no properties can be set using following statements.
Myobj=new Object();
Then using dot operator we can set the properties for that object.
The object can then be modified by assigning the values to this object.
JavaScript[ObjectDemo.html]
<!DOCTYPE html>
<html>
<head>
<title>Object Creation Demo</title>
</head>
<body>
<strong>
<script type="text/javascript">
var Myobj;
var n,i;
//creating an object
Myobj=new Object();
//setting the propertis for newly created object
Myobj.id=10;
Myobj.name="Anuradha";
document.write("The ID is "+Myobj.id+"<br/>");
document.write("The Name is "+Myobj.name);
</script>
</strong>
</body>
</html>
Output
Review Question
Normally the first element in an array is stored at 0th location, however we can start
storing the element from any position.
Using new operator we can allocate the memory dynamically for the arrays.
In the brackets the size of an array is mentioned and the var ar denotes the name of
the array. Thus by the above sentence an array ar will be created in which we can
store 10 elements at the most. Sometimes the above statement can be written like
this
var ar;
ar=new Array(10);
Fig. 2.16.2
Fig. 2.16.3
JavaScript Document
<!DOCTYPE html>
<html>
<head>
<title>Array Demo</title>
</head>
<body>
<strong>
<script type="text/javascript">
a=new Array(5);//creation of array
for(i=0;i<5;i++)
{
a[i]=i;
document.write(a[i]+"<br>");//displaying array
}
document.write("Another way of initialization"+"<br>");
b=new Array(11,22,33,44,55);//creation of array
for(i=0;i<5;i++)
{
document.write(b[i]+"<br>");//displaying array
}
document.write("Yet another way of initialization"+"<br>");
var c=[100,200,300,400,500];//creation of array
for(i=0;i<5;i++)
{
document.write(c[i]+"<br>");//displaying array
}
</script>
</strong>
</body>
</html>
Script Explanation : In above JavaScript, as you can notice that, an array can be
initialized in three different ways which is shown by boldface. Hence an output of above
script will be
Output
Example 2.16.1 Write a JavaScript to define the array elements and to find the length of array.
Solution :
<!DOCTYPE html>
<html>
<head>
<title>Array Demo</title>
</head>
<body>
<script type="text/javascript">
a=new Array(11,22,33,44,55);//creation of array
var len=a.length
document.write("The length of array is: "+len)
</script>
</body>
</html>
Output
Output
<body>
<script type="text/javascript">
a=new Array();
a[0]=40;
a[1]=30;
a[2]=10
a[3]=50
a[4]=20;
document.write("The elements in the array are...<br/>");
for(i=0;i<a.length;i++)
{
document.write(a[i]+" ");
}
document.write("<br/><br/><b>The array is sorted...</b><br/>");
a.sort();
document.write("<br/>Now, The elements in the array are...<br/>");
for(i=0;i<a.length;i++)
{
document.write(a[i]+" ");
}
</script>
</body>
</html>
Output
</script>
</body>
</html>
Output
This method removes the first element of the array. For example -
<!DOCTYPE html>
<html>
<head>
<title>Changing Array Demo</title>
</head>
<body>
<script type="text/javascript">
a=new Array();
a[0]=10
a[1]=20
a[2]=30
a[3]=40
a[4]=50
document.write("<h4> The shift() method</h4>");
var num=a.shift();
document.write(num);
document.write("<h4>The elements in array are ...</h4>");
for(i=0;i<a.length;i++)
document.write(a[i]+" ");
</script>
</body>
</html>
Output
2) Push Method
The push method is used to create a new element at the end of the array.
For example -
<!DOCTYPE html>
<html>
<head>
<title>Changing Array Demo</title>
</head>
<body>
<script type="text/javascript">
a=new Array();
a[0]=10
a[1]=20
a[2]=30
a[3]=40
a[4]=50
document.write("<h4>The elements in array are ...</h4>");
for(i=0;i<a.length;i++)
document.write(a[i]+" ");
document.write("<h4> Calling The push() method</h4>");
a.push(60);
document.write("<h4>The elements in array are ...</h4>");
for(i=0;i<a.length;i++)
document.write(a[i]+" ");
</script>
</body>
</html>
Output
3) Pop Method
This method returns and removes the last element of the array. For example -
<!DOCTYPE html>
<html>
<head>
<title>Changing Array Demo</title>
</head>
<body>
<script type="text/javascript">
a=new Array();
a[0]=10
a[1]=20
a[2]=30
a[3]=40
a[4]=50
document.write("<h4>The elements in array are ...</h4>");
for(i=0;i<a.length;i++)
document.write(a[i]+" ");
document.write("<h4> Calling The pop() method</h4>");
var val=a.pop();
document.write("The element returned is "+val)
document.write("<h4>The elements in array are ...</h4>");
for(i=0;i<a.length;i++)
document.write(a[i]+" ");
</script>
</body>
</html>
Output
4) Reverse Method
The reverse method is used to reverse the elements present in the array. For example
<!DOCTYPE html>
<html>
<head>
<title>Changing Array Demo</title>
</head>
<body>
<script type="text/javascript">
a=new Array();
a[0]=10
a[1]=20
a[2]=30
a[3]=40
a[4]=50
document.write("<h4>The elements in array are ...</h4>");
for(i=0;i<a.length;i++)
document.write(a[i]+" ");
document.write("<h4> Calling The reverse() method</h4>");
a.reverse();
document.write("<h4>The elements in array are ...</h4>");
for(i=0;i<a.length;i++)
document.write(a[i]+" ");
</script>
</body>
</html>
Output
Review Question
2.17 Strings
String is a collection of characters.
Some commonly used methods of string object are concatenating two strings,
converting the string to upper case or lower case, finding the substring of a given
string and so on.
The string is written within the quotes- either single quote or double quote.
For example -
var myname=’ABC’
Method Meaning
concat(str) This method concatenates the two strings. For example s1.concat(s2) will
result in concatenation of string s1 with s2.
charAt(index_val) This method will return the character specified by value index_val.
substring(begin,end) This method returns the substring specified by begin and end character.
toLowerCase() This function is used to convert all the uppercase letters to lower case.
toUpperCase() This function is used to convert all the lowercase letters to upper case.
There is one important property of string object and that is length. For example
var my_str=”Hello”;
var len; Length of the string “Hello” will be
len=my_str.length; stored in the variable len
JavaScript Document
<!DOCTYPE html>
<html>
<script type="text/javascript">
var str="ABC"
alert("The character at first position of string: "+str+" is: "+str.charAt(0))
</script>
</body>
</html>
Output
Output
Output
1. Use of substring
2. Use of substr
The substr method is also used to extract the substring from the text. The syntax for
substr is as follows
substr(start,length)
where start indicates the starting index and length indicates the number of characters to
be extracted.
Following example shows how to extract some substring using substr() method and then
copy this substring to another text.
JavaScript Document
<!DOCTYPE html>
<html>
<script type="text/javascript">
var Name1="Shivaji Shahaji Bhosale"
var Name2="Sambhaji"
var sub_str=Name1.substr(16,7)
document.write("<br/>The Name1: "+Name1)
document.write("<br/>The Surname: "+sub_str)
For converting string to number we have different types of functions based on type of
numbers - That means if string is to be converted to integer(a number without decimal
point) then the method parseInt() is used. If string is to be converted to float value then
the method parseFloat() is used.
Example
<!DOCTYPE html>
<html>
<script type="text/javascript">
var str="100";
var a=parseInt(str)//converting string 100 to number 100
var b=200;
result=str+b
Output
Using toUpperCase() method we can convert the small letters to capital letters.
For example -
<!DOCTYPE html>
<html>
<script type="text/javascript">
var str="welcome friends";
var newstr=str.toUpperCase()
document.write("<br/>The "+str+" is converted to: "+newstr)
</script>
</body>
</html>
Output
var ch='a'
var n=ch.charCodeAt()
document.write("<br/>The letter '"+ch+"' has a unicode as: "+n)
</script>
</body>
</html>
Output
Similarly, we can obtain the letter or character from a Unicode using the method
fromCharCode(). For example
<!DOCTYPE html>
<html>
<script type="text/javascript">
var n=97
var ch=String.fromCharCode(n)
document.write("<br/>The unicode "+n+" is for letter : "+ch)
</script>
</body>
</html>
Output
Part - II : DOM
What is DOM ?
Document Object Model (DOM) is a set of platform independent and language neutral application
programming interface (API) which describes how to access and manipulate the information stored in
XML, HTML and JavaScript documents.
Review Question
DOM 0 This model is supported by the early browsers. This level could support JavaScript. This
version was implemented in Netscape 3.0 and Internet Explorer 3.0 browsers.
DOM 1 This version was issued in 1998 which was focused on XHTML and XML.
DOM 2 This version was issued in 2000 that could specify the style sheet. It also supports the
event model and traversal with in the documents.
DOM 3 This is the current release of DOM specification published in 2004. This version could
deal with XML with DTD and schema, document validations, document views and
formatting.
Review Question
1. What is the purpose of DOM node tree ? Draw DOM node tree for simple HTML page.
SPPU : April-18, May-19, Marks 5
We can access or change the contents of document by using various methods. Some
commonly used properties and methods of DOM are as follows :
Methods
Method Meaning
getElementById This method is used to obtain the specific element which is specified by
some id within the script.
appendChild For adding a new child to specified node, this method is used.
removeChild For removing a child node of a specific node, this method is used.
getAttribute This method is useful for returning the specified attribute value.
setAttribute This method is useful for setting or changing the specified attribute to the
specified value.
Properties
Property Meaning
attributes This property is used to get the attribute nodes of the node.
parentNode This DOM property is useful for obtaining the parent node of the specific
node.
childNodes This DOM property is useful for obtaining the child nodes of the specific
node.
Method 1
Every XHTML document element is associated with some address. This address is
called DOM address.
The document has the collection of forms and elements. Hence we can refer the text
box element as
var Dom_Obj=document.forms[0].elements[0];
But this is not the suitable method of addressing the elements. Because if we change
the above script as
…
<form name=“form1”>
<input type=“button” name= “mybutton”/>
<input type=”text” name=“myinput”/>
</form>
…
then index reference gets changed. Hence another approach of accessing the elements
is developed.
Method 2
We can access the desired element from the web document using JavaScript method
getElementById. The element access can be made as follows -
var Dom_Obj=document.getElementById(“myinput”);
But if the element is in particular group, that means if there are certain elements on
the form such as radio buttons or check boxes then they normally appear in the
groups. Hence to access these elements we make use of its index. Consider the
following code sample
<form id=”Food”>
<input type=“checkbox” name=“vegetables” value=”Spinach” />Spinach
<input type=“checkbox” name=“vegetables” value=”FenuGreek” />FenuGreek
<input type=“checkbox” name=“vegetables” value=”Cabbage” />Cabbage
</form>
For getting the values of these checkboxes we can write following code.
var Dom_obj=document.getElementById(“Food”);
for(i = 0 ; i < Dom_Obj.vegetables.length ; i++)
document.write(Dom_Obj.vegetables[i]+“<br/>”);
<div id="div1">
<p id="p1">The first sentence in HTML document.</p>
<p id="p2">The second sentence in HTML document.</p>
</div>
<script>
var pnode = document.createElement("p");
var node = document.createTextNode("This is newly added sentence in HTML document.");
pnode.appendChild(node);
var element = document.getElementById("div1");
element.appendChild(pnode);
</script>
</body>
</html>
Output
<div id="div1">
<p id="p1">First Sentence</p>
<p id="p2">Second Sentence</p>
</div>
<script>
var pnode = document.createElement("p");
var node = document.createTextNode("Newly Added Sentence!!!");
pnode.appendChild(node);
var element = document.getElementById("div1");
var nextnode = document.getElementById("p2");
element.insertBefore(pnode,nextnode);
</script>
</body>
</html>
Output
<div id="div1">
<p id="p1">First Sentence</p>
<p id="p2">Second Sentence</p>
<p id="p3">Third Sentence</p>
</div>
<script>
var parentnode = document.getElementById("div1");
var node = document.getElementById("p2");
parentnode.removeChild(node);
</script>
</body>
</html>
Output
Example 2.22.1 Write a JavaScript to display sum of two elements. Make use of appropriate
DOM method.
Solution :
<!Doctype html>
<html>
<head>
<script type="text/javascript">
function getSum()
{
var number1=document.getElementById("number1").value;
var number2=document.getElementById("number2").value;
var num1=Number(number1);
var num2=Number(number2);
alert(num1+num2);
}
</script>
</head>
<body>
<form>
Enter Num1:<input type="text" id="number1" /><br/> <br/>
Enter Num2:<input type="text" id="number2" /><br/>
<input type="button" value="SUM" onclick="getSum()"/>
</form>
</body>
</html>
Output
Example 2.22.2 Write a JavaScript to welcome the user by his/her name when he enters his/her
name in textbox. Make use of appropriate DOM method.
Solution :
<!Doctype html>
<html>
<head>
<script type="text/javascript">
function display()
{
var name=document.getElementsByName("user");
alert("Welcome "+name[0].value);
}
</script>
</head>
<body>
<form>
Enter Name:<input type="text" name="user" /><br/> <br/>
<input type="button" value="Greet" onclick="display()"/>
</form>
</body>
</html>
Output
Review Questions
2.23 DOM Event Handling SPPU : April-18, Dec.-18, May-19, March-20, Marks 5
Internet Programming
On occurrence of events the tag attribute must be assigned with some user defined
functionalities. This will help to execute certain action on occurrence of particular event.
Commonly used events and tag attributes are enlisted in the following table -
<button>
<input>
blur onblur Losing the focus. <a>
<textarea>
<select>
<input>
change onchange On occurrence of some change. <textarea>
<select>
When user clicks the mouse button. <a>
click onclick
<input>
When user releases the key from the Form elements such as
keyup onkeyup keyboard. input,button,text,textarea
and so on.
On selection. <input>
select onselect
<textarea>
The use of these tag attributes for handling the events is illustrated by following code sample.
That means when the user clicks the button then as an event handler a user defined
function My_fun() gets called. Basically in this function user writes the instructions that
need to be executed on the button click event.
Example 2.23.1 Discuss the properties of mouse events associated with DOM2 with an
example.
Solution : Various types of mouse events associated with DOM2 are click, mousedown,
mouseup, mouseout and mouseover.
Following is an example in which image can be dragged and dropped anywhere in the
HTML document. Accordingly the co-ordinates will be displayed.
<html>
<head>
<title> Drag and Drop Demo</title>
<script type = "text/javascript">
var X_offset, Y_offset, Item;
function Catch_function(e)
{
Registering the mouse event with
Item = e.currentTarget; the help of addEventListener
var posX = parseInt(Item.style.left); function.
var posY = parseInt(Item.style.top);
X_offset = e.clientX - posX;
Y_offset = e.clientY - posY;
document.addEventListener("mousemove", Move_function, true);
document.addEventListener("mouseup", Drop_function, true);
e.stopPropagation();
e.preventDefault();
}
function Move_function(e)
{
Item.style.left = (e.clientX - X_offset) + "px";
Item.style.top = (e.clientY - Y_offset) + "px";
e.stopPropagation();
}
function Drop_function(e)
{
document.removeEventListener("mouseup", Drop_function, true);
document.removeEventListener("mousemove", Move_function, true);
e.stopPropagation();
}
</script>
</head>
<body>
<h3>
Click on image below-drag it, move it and then drop anywhere!!!
<br /><br />
<img src="lamp1.jpg"
style = "position: absolute;
top: 100px;
left: 100px;
border:2px solid;"
onmousedown = "Catch_function(event);" />
</h3>
</body>
</html>
Output
JavaScript[OnloadDemo.html]
alert("Welcome");
} When web document gets
</script> loaded on the browser window
</head>
then my_fun() will be called
<body onload="my_fun()">
</body>
</html>
Output
Example 2.23.2 Write an HTML page and also provide a JavaScript for accepting a user ID and
password from the user to ensure that input is not empty.
SPPU : April-18, In Sem, Marks 5
Solution :
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
function my_fun()
{
var mypwd=document.getElementById("pwd");
var myuname=document.getElementById("uname");
if(myuname.value=="")
{
alert("You have not entered the name");
myuname.focus();
return false;
}
if(mypwd.value=="")
{
alert("You have not entered the password");
mypwd.focus();
return false;
}
else
{
alert("Congratulations!!!");
return true;
}
}
</script>
</head>
<body>
<center>
<form id="form1">
<label> Enter your name
<input type="text" value="" id="uname" />
</label>
<label> Enter your password
<input type="password" value="" id="pwd" />
</label>
<br/><br/>
<input type="submit" onsubmit="my_fun();"/>
<input type="reset" value="Reset" name="reset"/><br/>
</form>
</center>
</body>
</html>
Example 2.23.3 Explain with example how to access values of textbox of form using JavaScript ?
SPPU : March-20, Marks 5
Solution :
<!DOCTYPE html>
<html>
<head>
<script type = "text/javascript">
function getNum()
{
var num = document.getElementById("Data").value;
var a = Number(num);
alert(a);
}
</script>
</head>
<body>
<form>
Enter some Number: <input type="text" id="Data"/><br/><br/>
<input type ="button" value="Click Me" onclick='getNum()'/>
</form>
</body>
</html>
Review Question
Various control objects are placed on the form. These control objects are called
widgets.
These widgets used in JavaScript are - Textbox, Push button, Radio button,
Checkbox and so on.
In JavaScript the validation of these widgets is an important task.
Let us understand the validation of form elements with the help of examples -
Solution :
<!DOCTYPE html>
<html>
<head>
<title>Demo of onlclick Tag Attibute</title>
<script type="text/javascript">
function my_fun()
{
var mypwd=document.getElementById("pwd");
var my_re_pwd=document.getElementById("re_pwd");
if(mypwd.value=="")
{
alert("You have not entered the password");
mypwd.focus();
return false;
}
if(mypwd.value!=my_re_pwd.value)
{
alert("Password is not verified, Re-enter both the passwords");
mypwd.focus();
mypwd.select();
return false;
}
else
{
alert("Congratulations!!!");
return true;
}
}
</script>
</head>
<body>
<center>
<form id="form1">
<label> Enter your password
<input type="password" value="" id="pwd" />
</label>
<br/><br/>
<label> Re-Enter the password
<input type="password" value="" id="re_pwd" onblur="my_fun();"/>
</label><br/>
<input type="submit" value="Submit" name="submit" onsubmit="my_fun();"/>
<input type="reset" value="Reset" name="reset"/><br/>
</form>
</center>
</body>
</html>
Output (Run1)
Output (Run2)
Output(Run3)
Example 2.24.2 Write JavaScript to validate a for consisting of Name, Age, Address, EmailID,
hobby (check box), Gender(radio box), country(Drop down menu).
Solution : ApplicationForm.html
<html>
<head>
<title>The Student Registration Form</title>
<script type=text/javascript>
function validate()
{
var i;
var name_str=document.my_form.name;
var phoneID=document.my_form.ph_txt;
var ph_str=document.my_form.ph_txt.value;
var str=document.my_form.Email_txt.value;
if((name_str.value==null)||(name_str.value==""))
{
alert("Enter some name") Validating Name
return false
}
if(document.my_form.Age_txt.value=="")// validating age
{
alert("Enter Some Age")
return false
}
if((document.my_form.Age_txt.value<"5")&&(document.my_form.Age_txt.value>"21"))
{
alert("Invalid Age")
return false
}
if(ph_str.length<1 ||ph_str.length>11)
{
alert("Invalid length of Phone Number")
return false
} Validating Phone Number
for (i = 0; i < ph_str.length; i++)
{
var ch = ph_str.charAt(i);
if (((ch < "0") || (ch > "9"))){
alert("Invalid Phone Number")
phoneID.focus()
return false
}
}
var index_at=str.indexOf("@")
var len=str.length
var index_dot=str.indexOf(".")
var emailID=document.my_form.Email_txt
if ((emailID.value==null)||(emailID.value==""))
{ Validating Email ID
alert("Please Enter your Email ID")
emailID.focus()
return false
}
if (str.indexOf("@")==-1)
{
alert("Invalid E-mail ID")
return false
}
if (str.indexOf(".")==-1 || str.indexOf(".")==0
|| str.indexOf(".")==index_at)
{
alert("Invalid E-mail ID")
return false Validating Email ID
}
if (str.indexOf("@",(index_at+1))!=-1)
{
alert("Invalid E-mail ID")
return false
}
if (str.indexOf(" ")!=-1)
{
alert("Invalid E-mail ID")
return false
}
if (!document.my_form.group1[0].checked && !document.my_form.group1[0].checked)
{
alert("Please Select Sex");
return false;
}
if (!document.my_form.group1[0].checked && !document.my_form.group1[0].checked)
{
alert("Please Select Sex");
return false;
}
return true
}
</script>
</head>
<body bgcolor=aqua>
<center><h3>Application Form</h3></center>
<form name=my_form onsubmit=validate()>
<strong>Name: </strong>
<input type=text name=name><br/>
<strong>Age: </strong>
<input type=text name=Age_txt><br/>
<strong>Phone No:</strong>
<input type=text name=ph_txt><br/>
<strong>Email: </strong>
<input type=text name=Email_txt><br/><br/>
<strong>Sex: </strong>
<input type="radio" name="group1" value="Male">Male
<input type="radio" name="group1" value="Female">Female<br/><br/><br/>
<strong>Hoby: </strong>
<input type="checkbox" name ="option1" value="Singing">Singing<br/>
<input type="checkbox" name ="option1" value="Reading">Reading<br/>
<input type="checkbox" name ="option1" value="T.V.">Watching T.V<br/>
<br/><br/>
<strong>Country:</strong>
<select name="My_Menu">
<option value="India">India</option>
<option value="China">China</option>
<option value="Shrilanka">Shrilanka</option>
</select>
<center>
<input type=submit value=Submit></br>
</center>
</body>
</html>
Output
Example 2.24.3 Design a HTML form for validation the users with fields user name and
password and ok button which should receive the input from the user and responses as
authorized or invalid user name or invalid password.
Solution :
<head>
<title>HTML FORM</title>
<script type=text/javascript>
function validate()
{
var user=document.form1.username;
var pass=document.form1.password;
if((user.value==null)||(user.value==""))
{
alert("Enter some user name");
}
if((pass.value==null)||(pass.value==""))
{
alert("Enter some password");
}
if(user.value=="admin")
{
alert("Valid user name");
}
if(pass.value=="password")
{
alert("Valid password");
}
else
alert("Invalid username/password");
}
</script>
</head>
<body>
<form id="form1" name="form1" onsubmit=validate()>
<table width="510" border="0" align="center">
<tr> <td>Username:</td>
<td><input type="text" name="username"/></td>
</tr>
<tr> <td>Password</td>
<td><input type="password" name="password"/></td>
</tr>
<tr>
<td> </td>
<td><input type="submit" name="button" value="OK" /></td>
</tr>
</table>
</form>
</body>
</html>
Example 2.24.4 Write a Javascript to validate radio button, operator field and check box.
function ValidateForm(form)
{
onClick="ValidateForm(this.form)">
<input type="reset" value="Reset">
</form>
</body>
</html>
Example 2.24.5 Design a form to accept workshop registration details from participants and
validate any five fields using JavaScript ? (Assume suitable structure)
SPPU : Dec.-18, Marks 5
Solution :
<html>
<head>
<title>The Workshop Registration Form</title>
<script type=text/javascript>
function validate()
{
var i;
var name_str=document.my_form.name;
var phoneID=document.my_form.ph_txt;
var ph_str=document.my_form.ph_txt.value;
var str=document.my_form.Email_txt.value;
if((name_str.value==null)||(name_str.value==""))//validating name
{
alert("Enter some name")
return false
}
if(document.my_form.Age_txt.value=="")// validating age
{
alert("Enter Some Age")
return false
}
if((document.my_form.Age_txt.value<"5")&&(document.my_form.Age_txt.value>"21"))
{
alert("Invalid Age")
return false
}
}
for (i = 0; i < ph_str.length; i++)
{
var ch = ph_str.charAt(i);
if (((ch < "0") || (ch > "9"))){
alert("Invalid Phone Number")
phoneID.focus()
return false
}
}
var index_at=str.indexOf("@")
var len=str.length
var index_dot=str.indexOf(".")
var emailID=document.my_form.Email_txt
if ((emailID.value==null)||(emailID.value==""))
{
alert("Please Enter your Email ID")
emailID.focus()
return false
}
if (str.indexOf("@")==-1) //validating email ID
{
alert("Invalid E-mail ID")
return false
}
if (str.indexOf(".")==-1 || str.indexOf(".")==0
|| str.indexOf(".")==index_at)
{
alert("Invalid E-mail ID")
return false
}
if (str.indexOf("@",(index_at+1))!=-1)
{
alert("Invalid E-mail ID")
return false
}
if (str.indexOf(" ")!=-1)
{
alert("Invalid E-mail ID")
return false
}
if (!document.my_form.group1[0].checked && !document.my_form.group1[0].checked)
{
alert("Please Select Sex");
return false;
}
if (!document.my_form.group1[0].checked && !document.my_form.group1[0].checked)
{
alert("Please Select Sex");
return false;
}
return true
}
</script>
</head>
<body bgcolor=aqua>
<center><h3>Registration Form</h3></center>
<form name=my_form onsubmit=validate()>
<strong>Name: </strong>
<input type=text name=name><br/>
<strong>Age: </strong>
<input type=text name=Age_txt><br/>
<strong>Phone No:</strong>
<input type=text name=ph_txt><br/>
<strong>Email: </strong>
<input type=text name=Email_txt><br/><br/>
<strong>Sex: </strong>
<input type="radio" name="group1" value="Male">Male
<input type="radio" name="group1" value="Female">Female<br/><br/><br/>
<strong>Hoby: </strong>
<input type="checkbox" name ="option1" value="Singing">Singing<br/>
<input type="checkbox" name ="option1" value="Reading">Reading<br/>
<input type="checkbox" name ="option1" value="T.V.">Watching T.V<br/>
<br/><br/>
<strong>Country:</strong>
<select name="My_Menu">
<option value="India">India</option>
<option value="China">China</option>
<option value="Shrilanka">Shrilanka</option>
</select>
<center>
<input type=submit value=Submit></br>
</center>
</body>
</html>
1. Without the use of jquery-1.10.2.min.js either locally or from the internet we can
not make use of the library functions of jQuery.
2. The jQuery coding must be done in support of JavaScript, AJAX, ASP, PHP and
so on to get the advantage of its library functionality.
jQuery Document[LoadDemo.html]
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script>
$(document).ready(function()
{
$("img").load();
});
</script>
</head>
<body>
<h2> Loading Image</h2>
<img src="img1.jpg" alt="flower">
</body>
</html>
Output
We can load some external file using the load function for that purpose we need to pass
URL to the load function.
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("button").click(function(){
$("#div1").load("input.html");
});
});
</script>
</head>
<body>
<div id="div1"><h2>Loading File</h2></div>
<button>Click to load file</button>
</body>
</html>
SelectorDemo.html
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js">
</script>
<script>
$(document).ready(function()
{
$("button").click(
function()
{
$("p").hide();
}
);
});
</script>
</head>
<body>
<div>This statement is remains on browser</div>
<p>This statement will disappear</p>
<button>Click</button>
</body>
</html>
Output
Script Explanation :
In the above code, within the ready function the jQuery code is written.
For the button element selector the action is click. This action invokes the <p> element
and the action associated with this element is hide. This means that when user clicks the
button the text written within the <p> </p> will be hidden or disappeared.
2. Use of * as a selector
The * means all. If we include selector as * then the corresponding action will be
associated with all the HTML elements. The sample code for demonstrating this action is
as follows -
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js">
</script>
<script>
$(document).ready(function()
{
$("button").click(
function()
{
$("*").hide();
}
);
});
</script>
</head>
<body>
<h1> This is a header </h1>
<div>This second statement</div>
<p>This is another statement</p>
<button>Click</button>
</body>
</html>
Output
On clicking the click button all the contents of the web page will be hidden and black document
will be displayed.
3. The id selector
The id can be associated with the HTML element. In the following example we have
used <div> element to which the id named myid is associated. On button click event the
function is invoked to hide the sentence written using the <div id=”myid”>.
To find the element with particular id write # and then name of the id.
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js">
</script>
<script>
$(document).ready(function(){
$("button").click(function(){
$("#myid").hide();
});
});
</script>
</head>
<body>
<div>This is first line</div>
<p>This is another line for paragraph</p>
<div id="myid">This sentence will be hidden on clicking the button</div>
<button>Click to Hide</button>
</body>
</html>
Output
Output
<body>
<h3>This is a heading</h3>
<div>This is First paragraph.</div>
<div>
<a href="https://www.vtubooks.com">For Technical Books, Click here</a>
</div>
<button>Click to Hide</button>
</body>
</html>
Output
6. The tr selector
The element tr is used to define the rows of the table. We can denote this selector along
with the css style. It is demonstrated by following web document
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js">
</script>
<script>
$(document).ready(function(){
$("tr:even").css("background-color","grey");
});
</script>
</head>
<body>
<h3>Employee Database</h3>
<table border="1">
<tr>
<th>Name</th>
<th>Department</th>
<th>Address</th>
</tr>
<tr>
<td>Archana</td>
<td>Marketing</td>
<td>Shivaji Nagar</td>
</tr>
<tr>
<td>Sujata</td>
<td>Accounts</td>
<td>M.J.Road</td>
</tr>
<tr>
<td>Amit</td>
<td>Purchase</td>
<td>Shastri Road</td>
</tr>
<tr>
<td>Nalini</td>
<td>H.R</td>
<td>ChandaniChowk</td>
</tr>
</body>
</html>
Output
For example -
jQuery Document[changeStyle.html]
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js">
</script>
<script>
$(document).ready(function(){
$("button").click(function(){
$("div").css("background-color", "red");
});
});
</script>
</head>
<body>
<div style="background-color:blue">This line is blue and will be changed to red</div><br/>
Example
jQuery Document[InsertElement.html]
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("#button1").click(function(){
$("ol").before("<b>Element:Before</b>");
});
$("#button2").click(function(){
$("ol").after("<b>Element: After</b>");
});
});
</script>
</head>
<body>
<ol>
<li>item#1</li>
<li>item#2</li>
<li>item#3</li>
</ol>
<br/><br/>
<button id="button1">Insert before</button>
<button id="button2">Insert after</button>
</body>
</html>
Output
$( ".content" ).remove();
Example of .remove()
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("button").click(function(){
$("#tbl").remove();
});
});
</script>
</head>
<body>
<table id="tbl" border='1'>
<tr><td> First Row</td> </tr>
<tr><td> Second Row </td></tr>
</table>
<button>Remove Element</button>
</body>
</html>
Output
Example of .empty()
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("button").click(function(){
$("#tbl tr td").empty();
});
});
</script>
</head>
<body>
<table id="tbl" border='1'>
<tr><td> First Row</td> </tr>
<tr><td> Second Row </td></tr>
</table>
<button>Remove Element</button>
</body>
</html>
Output
Review Question
1. When to use jQuery ? What are the advantages of using jQuery over JavaScript.
SPPU : May-19, Marks 5
Part - IV : Angular JS
Advantages
Following are the advantages of Angular JS.
1. Built by Google Engineers : The Angular JS is maintained by dedicated Google
Engineers. That means - there is huge community for development and
enhancement.
2. MVC Support - It is based on Model View Controller (MVC) architecture which
provides separation of model, view and controller components.
3. Intuitive - It is more intuitive as it makes use of HTML as a declarative language.
Moreover, it is less brittle for reorganizing.
4. Comprehensive : AngularJS is a comprehensive solution for rapid front-end
development. It does not need any other plugins or frameworks.
5. Rich Features : There is a wide range of features supported by Angular JS such
as Data binding, dependency injection, enterprise level testing and so on.
6. Unit Testing : The Angular JS code is unit testable.
7. Reusable Code : Angular JS support for using the reusable components.
8. Less Code : It support for less code and more functionality.
Disadvantages
1. As Angular JS is based on JavaScript framework, it is not secure.
2. There are multiple ways to do the same thing with AngularJS. Sometimes, it can
be hard for novices to say which way is better for a task.
Features of Angular JS
There are core features Angular JS that are widely used by web developers. These are -
1. Data Binding : It allows the automatic synchronization between model and view
components.
2. Scope : There are some objects from model that can be correlated to controller
and view.
3. Controller : These are basically JavaScript functions that are bound to particular
scope.
4. Directives : The directives is designed to give HTML new functionality.
5. Filters : This feature allows to select subset from array of items.
6. Routing : This feature allows to switch between multiple views.
7. Services : There is a support for many built in services for Angular JS
8. Dependency Injection : It is a software design pattern that helps the developer
to develop and understand the application easily.
MVC in Angular JS
Modules in AngularJS serve as containers to help you organize your application
into logical units.
2.26.2 Directives
In Angular JS, the capacity of HTML is extended using the ng-directives.
The directives are specified with ng prefix.
The three commonly used ng-directives are
1. ng-app : This directive defines an AngularJS application.
2. ng-model : This directive binds the value of HTML controls to application data.
These controls can be input, select, textarea and so on.
3. ng-bind : This directive binds application data to HTML view.
Step 1 : Create an Angular JS code as follows in a Notepad. Save it using the extension
.htm or .html
AngularJS Document[FirstApp.html]
<html>
<head>
<title>My First AngularJS Application</title>
<script src =
"https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
</head>
<body>
<h1>AngularJS Application</h1>
<div ng-app = "">
<p>Enter your Name: <input type = "text" ng-model = "name"></p>
<p>Welcome <span ng-bind = "name"></span></p>
</div>
</body>
</html>
Output
Script Explanation :
1. The AngularJS script is written within <html> tags. The AngualarJS is based on
JavaScript framework. The framework for AngularJS is loaded using the <script>
tag. It is as follows -
<script src =
"https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
2. Defining np-app directive : The np-app directive is defined in above script as
follows -
<div ng-app = "">
…
…
</div>
3. Defining np-model directive : The textbox control is modeled using np-model
directive
<p>Enter your Name: <input type = "text" ng-model = "name"></p>
4. Defining np-bind : We can bind the value entered in the textbox with name
using np-bind directive.
<p>Welcome <span ng-bind = "name"></span></p>
Hence, we can see on the output screenshot, that whatever name entered by the user
gets bound with the Welcome message.
The above output can be viewed by opening any popular web browser and by
entering the URL of corresponding AngularJS script.
Various Directives supported by AngularJS are -
1. ng-app 2. ng-init
3. ng-model 4. ng-repeat
Let us discuss these directives with suitable scripting examples
1. ng-app Directive :
This directive starts the AngularJS application. It basically defines the root element. It
initializes the application automatically when the web page containing the AngularJS
code is loaded. For example -
<div ng-app="">
…
</div>
2. ng-init Directive :
The ng-init directive is used for initialization of AngularJS data.
For example :
DirectiveDemo1.html
<html>
<script src = "https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
<body>
<div ng-app="" ng-init="msg='I love my country!!!'">
<h3>{{msg}}</h3>
</div>
</body>
</html>
Output
AngularJS Document[FirstApp.html]
<html>
<head>
<title>My First AngularJS Application</title>
<script src =
"https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
</head>
<body>
<h1>AngularJS Application</h1>
<div ng-app = "">
<p>Enter your Name: <input type = "text" ng-model = "name"></p>
<p>Welcome <span ng-bind = "name"></span></p>
</div>
</body>
</html>
Output
Output
2.26.3 Expression
In AngularJS the expressions are written within {{ }}. For example - {{2 + 3}} is
expression.
AngularJS binds data to HTML using Expressions.
AngularJS solves the expression and return the result of evaluation.
The expressions in AngularJS are just similar to JavaScript expressions. The
expression contains literals, variables and operators.
AngularJS Document[ExpressionDemo.html]
<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
<body>
<div ng-app="">
<h4>Expression Demo</h4>
<p> Addition of 10 and 20 = {{ 10+20 }}</p>
</div>
</body>
</html>
Output
Now from above code if we remove ng-app directive then the expression won't be
evaluated. For instance -
<body>
<div>
<h4>Expression Demo</h4>
<p> Addition of 10 and 20 = {{ 10+20 }}</p>
</div>
</body>
</html>
We can assign the values to variables and then evaluate an expression. This
initialization of variable can be using ng-init. For example -
<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
<body>
<div ng-app="" ng-init="a=10;b=20">
<h4>Expression Demo</h4>
<p> Addition = {{ a+b }}</p>
<p> Multiplication = {{ a*b }}</p>
</div>
</body>
</html>
Output
The output will be displayed as 30 and 200
Similarly we can assign strings to variables and can display them. For example
AngularJS Document[ExpressionDemo1.html]
<html>
<script src = "https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
<body>
<h1>Expression Demo</h1>
2.26.4 Controllers
The use of controller in AngularJS is to control the flow of data. The ng-controller
directive is used for this purpose.
The controller is JavaScript object containing properties and functions.
Each controller accept $scope as a parameter which refers to the application/module
that controller is to control.
We can use controller with properties, methods and external files.
</div>
<script>
var app = angular.module('MyApp', []);
app.controller('MyController', function($scope)
{
$scope.user = "AAA";
$scope.city = "Pune"; Properties
});
</script>
</body>
</html>
Output
Script Explanation :
In above script,
1. We have used two directives div-app and div-controller which are defined with
some suitable attribute name. In above case div-app attribute is "MyApp" and
div-controller attribute is "MyController".
2. The MyController function is basically a JavaScript function and AngularJS will
invoke the controller using $scope object.
3. The controller creates two properties namely - 'user' and 'city'. Using $scope
object these properties are assigned with values 'AAA' and 'Pune'
4. The ng-model binds these input fields to the controller properties.
AngularJS Document[ControllerMethodDemo.html]
<!DOCTYPE html>
<html>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
<body>
<div ng-app="MyApp" ng-controller="MyController">
User: <input type="text" ng-model="user"><br/><br/>
City: <input type="text" ng-model="city"><br/>
<br/>
Address: {{address_function()}}
</div>
<script>
Output
Script Explanation :
In above script
1. The two properties user and city are defined. Along with them, a method named
Address_function() is invoked.
2. This function returns the string containing values to the properties.
3. This function is then bounded to HTML.
We can write and save the controller in some external file. This file can be then
invoked in the HTML document. Here is the illustration.
Step 1 : Create a file in Notepad. Name it with extension .js.
External File[MyController.js]
angular.module('MyApp', []).controller('MyController', function($scope) {
$scope.user = "AAA";
$scope.city = "Pune";
$scope.address_function=function() {
return $scope.user+" "+$scope.city;
}
});
Step 2 : Create a HTML document invoking the external js file created in above step.
HTML Document[ControllerFileDemo.html]
<!DOCTYPE html>
<html>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
<body>
2.26.5 Filters
Filters are used to modify the data.
These are used along with expressions or directives using pipe (|) character.
Commonly used filters are -
Filter Purpose
</div>
<script>
angular.module('MyApp', []).controller('MyController', function($scope) {
$scope.user = "aaa"
});
</script>
</body>
</html>
Output
</div>
<script>
angular.module('MyApp', []).controller('MyController', function($scope) {
$scope.user = "AAA"
});
</script>
</body>
</html>
Output
</div>
<script>
angular.module('MyApp', []).controller('MyController', function($scope) {
$scope.amount = 100
});
</script>
</body>
</html>
Output
<script>
angular.module('MyApp', []).controller('MyController', function($scope) {
$scope.city = [
'Pune',
'Mumbai',
'Delhi',
'Chennai',
'Surat',
'Kolkatta',
'Dehradun'
];
});
</script>
</body>
</html>
Output
The above code can be modified in such a way that user is allowed to type a character
in textbox. The list of cities containing the character typed by the user can be displayed.
AngularJS Document[FilterDemo4.html]
<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
<body>
<script>
angular.module('MyApp', []).controller('MyController', function($scope) {
$scope.city = [
'Pune',
'Mumbai',
'Delhi',
'Chennai',
'Surat',
'Kolkatta',
'Dehradun'
];
});
</script>
</body>
</html>
Output
<ul>
<li ng-repeat="i in personinfo | orderBy:'city'">
{{i.name +" lives in " +i.city}}
</li>
</ul>
</div>
<script>
angular.module('MyApp', []).controller('MyController', function($scope) {
$scope.personinfo = [
{name:'AAA',city:'Pune'},
{name:'BBB',city:'Banglore'},
{name:'CCC',city:'Chennai'},
{name:'DDD',city:'Delhi'},
{name:'EEE',city:'Mumbai'},
];
});
</script>
</body>
</html>
Output
2.26.6 Tables
The ng-repeat directive is used for displaying each row of the table.
Following script demonstrates how to display the information in tabular form
AngularJS Document[TableDemo.html]
<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
<body>
<div ng-app="MyApp" ng-controller="MyController">
<h3>Student Data</h3>
<table border="1">
<tr>
<th>Name</th><th>City</th>
</tr>
<tr ng-repeat="p in personinfo">
<td>{{p.name}}</td>
<td>{{p.city}}</td>
</tr>
</table>
</div>
<script>
angular.module('MyApp', []).controller('MyController', function($scope) {
$scope.personinfo = [
{name:'AAA',city:'Pune'},
{name:'BBB',city:'Banglore'},
{name:'CCC',city:'Chennai'},
{name:'DDD',city:'Delhi'},
{name:'EEE',city:'Mumbai'},
];
});
</script>
</body>
</html>
Output
We can display the above table using the ascending order of city names and for that
purpose we need to use the filter orderBy. The illustrative code is as follows -
AngularJS Document
<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
<body>
<script>
angular.module('MyApp', []).controller('MyController', function($scope) {
$scope.personinfo = [
{name:'AAA',city:'Pune'},
{name:'BBB',city:'Banglore'},
{name:'CCC',city:'Chennai'},
{name:'DDD',city:'Delhi'},
{name:'EEE',city:'Mumbai'},
];
});
</script>
</body>
</html>
</style>
<body>
<div ng-app="MyApp" ng-controller="MyController">
<h3>Student Data</h3>
<table>
<tr>
</tr>
<tr ng-repeat="p in personinfo">
<td>{{p.name}}</td> Displaying table with ng-repeat
<td>{{p.city}}</td> directive
</tr>
</table>
</div>
<script>
angular.module('MyApp', []).controller('MyController', function($scope) {
$scope.personinfo = [
{name:'AAA',city:'Pune'},
{name:'BBB',city:'Banglore'},
{name:'CCC',city:'Chennai'},
{name:'DDD',city:'Delhi'},
{name:'EEE',city:'Mumbai'},
];
});
</script>
</body>
</html>
Output
2.26.7 Modules
We can write the script in AngularJs using different modules. Basically the modules
help in separation of logic such as controller, service, application etc.
The modules can be defined in separate .js files.
Most commonly there are two modules - application module and controller
module.
Let us understand how to use modules in AngularJs with the help of example.
First consider the following code without module -
AngularJS Document
<!DOCTYPE html>
<html>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
<body>
AngularJS Document[MyControllerDemo.js]
App.controller('MyController', function($scope) {
$scope.user = "AAA";
$scope.city= "Pune"
$scope.address_function=function() {
return $scope.user+" "+$scope.city;
}
});
Step 3 : Creating Driver or use Module
This module will invoke the above modules and will display the result. The two
scripts defined in above steps are included in this document using the <script src> tag.
Then using ng-app and ng-controller directives the MyAppDemo.js and
MyController.js modules are mapped.
AngularJS Document[ModuleDemo.html]
<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
<script src = "MyAppDemo.js"></script> Invoking external modules
<script src = "MyControllerDemo.js"></script>
<body>
<div ng-app="MyApp" ng-controller="MyController">
User: <input type="text" ng-model="user"><br/><br/>
City: <input type="text" ng-model="city"><br/>
<br/>
Address:{{user + " lives in " + city}}
</div>
</body>
</html>
2.26.8 Forms
Form is a collection of various controls.
AngularJS support two types of controls - data binding and validation controls.
Various controls supported by AngularJS forms are -
o Input
o Select
o Button
o textarea
1. Input Control
User can type some text in the text box and the same text can be displayed on the
AngularJS document. For this binding we use inside the <form> tag.
<input type="text" ng-model ="name">
Following example illustrates the use of input control. When user types the text inside
the text box, it will be displayed along with the Welcome message.
AngularJS Document[InputDemo.html]
<html>
<head>
<title>Input Control Demo</title>
<script src =
"https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
</head>
<body>
<div ng-app = "">
<form>
<p>Enter your Name: <input type = "text" ng-model = "name"></p>
</form>
<p>Welcome {{name}}</p>
</div>
</body>
</html>
Output
2. Checkbox
We can have checkbox components on the Web document using AngularJS. For
having checkbox , the input type must be "checkbox"
<input type="checkbox" ng-model="chked">
Here is an illustrative example for checkbox
AngularJS Document[CheckBoxDemo.html]
<!DOCTYPE html>
<html>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
<body>
<div ng-app="">
<form>
Check the checkbox
<input type="checkbox" ng-model="chked">
</form>
<h4 ng-show="chked">When you check the checkbox this message will be displayed</h4>
</div>
</body>
</html>
Output
3. Radio Button
The radio button is basically a group of buttons which allows you to choose one value
at a time.
Let us see an illustrative script that uses Radio button control
AngularJS Document[RadioButtonDemo.html]
<!DOCTYPE html>
<html>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
<body ng-app="">
<form>
Select the color:<br/>
<input type="radio" ng-model="color" value="r">Red <br/>
<input type="radio" ng-model="color" value="g">Green <br/>
<input type="radio" ng-model="color" value="b">Blue <br/>
</form>
<div ng-switch="color">
<div ng-switch-when="r">
<p> You have chosen Red Color </p>
</div>
<div ng-switch-when="g">
<p> You have chosen Green Color </p>
</div>
<div ng-switch-when="b">
<p> You have chosen Blue Color </p>
</div>
</div>
</body>
</html>
Output
Script Explanation
1. We have used <form> </form> tag inside which the <input type="radio"> is taken
for display of radio button.
2. The ng-model directive is used to bind radio buttons with HTML document, the
ng-model is created for a group "color". the values are set as "r", "g" or "b".
3. In this script we have taken ng-switch directive to hide and show HTML sections
depending on the value of the radio buttons. When the value of particular radio
button is matched, then corresponding message is displayed.
4. The selectbox
The dropdown list can be created using <select> <option> tags. For example -
AngularJS Document[SelectBoxDemo.html]
<!DOCTYPE html>
<html>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
<body ng-app="">
<form>
Select the color:<br/>
<select ng-model="color">
<option value="r">Red <br/>
<option value="g">Green <br/>
<option value="b">Blue <br/>
</select>
</form>
<div ng-switch="color">
<div ng-switch-when="r">
<p> You have chosen Red Color </p>
</div>
<div ng-switch-when="g">
<p> You have chosen Green Color </p>
</div>
<div ng-switch-when="b">
<p> You have chosen Blue Color </p>
</div>
</div>
</body>
</html>
Output
5. The button
We can create a button control and invoke some functionality at its click event. For
example
AngularJS Document[ButtonDemo.html]
<html>
<script src =
"https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
<body>
<div ng-app = "MyApp" ng-controller="MyController">
<form>
<p>Enter your Name: <input type = "text" ng-model = "name"></p>
<input type = "button" value = "Click Me" ng-click="display()"></p>
</form>
<p>Welcome {{username}}</p>
</div>
<script>
var app = angular.module('MyApp', []);
app.controller('MyController', function($scope) {
$scope.name = "AAA";
$scope.display=function() {
$scope.username=$scope.name;
};
});
</script>
</body>
</html>
Output
In above script on ng-click event the function display is invoked. This function
displays the name typed by the user in the input text box.
2.26.9 Includes
We cannot include one HTML document inside another HTML document. But using
AngularJS we can include html document. Following program illustrates it
Step 1 : Create a simple HTML document as follows -
HTML Document[TestFile.html]
<html>
<body>
<h2> Hello!!!</h2>
</body>
</html>
Step 2 : Now create AngularJS script. Make use of ng-include directive.
AngularJS Document[IncludeDemo.html]
<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
<body ng-app="">
<div ng-include="'TestFile.html'"></div>
</body>
</html>
Step 3 : Open the web browser and get the output as follows -
We can also define the input controls in one HTML document, and initialize the values
to input control in another file.For example
Step 1 : Create an AngularJS document as follows -
AngularJS Document[IncludeDemo1.html]
<html>
<script src =
"https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
<body>
App.controller('MyController', function($scope) {
$scope.user = "AAA";
$scope.city = "Pune";
$scope.address_function=function() {
return $scope.user +" lives in city "+$scope.city;
};
});
</script>
</body>
</html>
Step 2 : The myFile.html document that is included in above step is as follows -
HTML Document : [myFile.html]
<table border = "1">
<tr>
<td>Enter user name:</td>
<td><input type = "text" ng-model = "user"></td>
</tr>
<tr>
<td>Enter city: </td>
<td><input type = "text" ng-model = "city"></td>
</tr>
<tr>
<td>Information: </td>
<td>{{user +" lives in "+city}}</td>
</tr>
</table>
Output
2.26.10 Views
View is basically the content which is shown to the user. User can wish to see the
application in different views, accordingly that view can be displayed to the user.
In AngularJS it is possible to have multiple views for single page application.
The ng-view and ng-template and ng-route directives support the concept of views.
The $routeProvider services are required for supporting the application containing
views.
The $routeProvider services are used to map the particular view with
corresponding HTML page using templateUrl.
The ngRoute module routes your application to different pages without reloading
the entire application. It is used in angular.module.
Step 1 : Create the main page for invoking the view pages.
AngularJS Document[ViewDemo.html]
<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular-route.js"></script>
<body ng-app="myApp">
<p><a href="#/!">Main</a></p>
<div ng-view></div>
<script>
var app = angular.module("myApp", ["ngRoute"]);
app.config(function($routeProvider) {
$routeProvider
.when("/", {
templateUrl : "ViewDemo.html"
})
.when("/view1", {
templateUrl : "view1.html"
})
.when("/view2", {
templateUrl : "view2.html"
});
});
</script>
</body>
</html>
Step 2 : Create view1.html page to display first view -
view1.html
<html>
<head>
<style>
h2 {
color:red;
}
</style>
</head>
<body>
<h2> This message is in RED Color </h2>
</body>
</html>
Step 3 : Create another web page for displaying second view.
view2.html
<html>
<head>
<style>
h2 {
color:green;
}
</style>
</head>
<body>
<h2> This message is in Green Color </h2>
</body>
</html>
Output
On clicking the first view or second view hyperlink the corresponding page will be
displayed.
2.26.11 Scopes
The scope is an object that binds the HTML with JavaScript. In other words scope
object binds view with controller. The view part is normally written in HTML and
controller part is written as JavaScript.
Let us understand the use of scope object with the help of illustrative example.
AngularJS Document[ScopeDemo.html]
<html>
<body>
<div ng-app = "MyApp" ng-controller = "MyController">
<p>Message: {{message}} <br/>Color: {{colorname}} </p>
</div>
<script src =
"https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
<script>
var App = angular.module("MyApp", []);
App.controller("MyController", function($scope) {
$scope.message = "In Color Demo controller";
$scope.colorname = "No-Name";
});
App.controller("RedController", function($scope) {
$scope.message = "In Red Color controller";
});
App.controller("BlueController", function($scope) {
$scope.message = "In Blue Color controller";
$scope.colorname = "BLUE";
});
</script>
</body>
</html>
Output
Script Explanation :
In above code
1. We have created three controllers namely MyController, RedController and
BlueController.
2. There are two properties namely message and colorname.
3. Note that RedController does not have colorname property; hence it inherits this
value from MyController.
4. The scope object is used to define that values for these properties. Hence in
HTML (view) part we can simply invoke the name of the property as message
and colorname inside {{ }} and get the values assigned in respective controller.
5. Thus job of scope object is to bind the controller with view part of AngularJS
document.
2.26.12 Services
The services are functions or objects that are intended to carry out specific task.
In AngularJS there are 30 built-in services used to carry out variety of tasks.
Built-in Services
Let us understand the use of services with the help of examples -
1. The $http Service
This is a commonly used service in AngularJS. By using this service, the request
can be made to the server and the application handles the response.
Step 1 : Create a simple web document as follows -
msg.html
Well Done!!!
Step 2 : Now create a web document that will make use of $http service to get the
message stored in above html file and to display the contents.
AngularJS Document[ServiceDemo1.html]
<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
<body>
</div>
<script>
var App = angular.module('MyApp', []);
App.controller('MyController', function($scope, $http) {
$http.get("msg.html").then(function (response) {
$scope.message = response.data;
});
});
</script>
</body>
</html>
Output
AngularJS Document[ServiceDemo2.html]
<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
<body>
<div ng-app="MyApp" ng-controller="MyController">
</div>
<script>
var App = angular.module('MyApp', []);
App.controller('MyController', function($scope, $timeout) {
$scope.message = "Welcome User";
$timeout(function() {
$scope.message = "Good Bye!!!";
},5000);
});
</script>
</body>
</html>
Output
For example
var App = angular.module("MyApp", []);
App.factory('AddService', function() {
var factory = {};
factory.addition = function(a, b) {
return a + b
}
return factory;
});
Step 2 : Using service method we can define the service and a method is then assigned to
it.
For example
App.service('CalculateService', function(AddService){
this.add = function(a,b) {
return AddService.addition(a,b);
}
});
Step 3 : Then a controller is defined and the scope object and service method is invoked in
it.
App.controller('MyController', function($scope, CalculateService) {
$scope.add = function() {
$scope.result = CalculateService.add($scope.number1,$scope.number2);
}
});
The above three steps must be applied within the <script> </script>, which acts as a
controller.
The view part is specified in <div> </div> tag.
Let us create a service for addition of two numbers.
AngularJS Document[ServiceDemo3.html]
<html>
<script src =
"https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
<body>
<h3> Addition of two numbers </h3>
<div ng-app = "MyApp" ng-controller = "MyController">
<p>Enter first number: <input type = "number" ng-model = "number1" /></p>
<p>Enter second number: <input type = "number" ng-model = "number2" /></p>
<button ng-click = "add()">ADDITION</sup></button>
<p>Answer = {{result}}</p>
</div>
<script>
var App = angular.module("MyApp", []);
App.factory('AddService', function() {
var factory = {};
factory.addition = function(a, b) {
return a + b
}
return factory;
});
App.service('CalculateService', function(AddService){
this.add = function(a,b) {
return AddService.addition(a,b);
}
});
</body>
</html>
Output
Example 2.26.1 Write a user defined service in AngularJS for reversing the given string.
Solution :
<html>
<script src =
"https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
<body>
<h3> Reversing of String </h3>
<div ng-app = "MyApp" ng-controller = "MyController">
<p>Enter some string: <input type = "text" ng-model = "s" /></p>
<button ng-click = "reverse_str()">Click to Reverse</sup></button>
<p>Reversed String is: {{result}}</p>
</div>
<script>
var App = angular.module("MyApp", []);
App.factory('MyService', function() {
var factory = {};
factory.str_operation = function(str) {
var r="";
for(var i=str.length-1;i>=0;i--)
r+=str[i];
return r;
}
return factory;
});
App.service('DisplayService', function(MyService){
this.reverse_str = function(str) {
return MyService.str_operation(str);
}
});
2. factory
The factory function is used to return some value. Inside this factory function the
values based on the demand of user or services are created. Typically factory function is
injected within a service to utilize the methods. For example -
3. service
The service is a JavaScript object which contains set of functions to perform some
specific task. The services are injected into controller.
//creation of service named 'CalculateService'
App.service('CalculateService', function(AddService){
this.add = function(a,b) {
return AddService.addition(a,b);
}
});
//Injection of service to controller 'MyController'
App.controller('MyController', function($scope, CalculateService) {
$scope.add = function() {
$scope.result = CalculateService.add($scope.number1,$scope.number2);
}
});
4. provider
The provider is a special factory method with get() function.
In AngularJS the provider is used internally to create services, factory during the
configuration phase.
The get() function of provider is used to return the value or service or factory.
For example -
//define a module
var App = angular.module("MyApp", []);
...
//create a service using provider which defines a method addition to return addition of two
numbers
App.config(function($provide) {
$provide.provider('AddService', function() {
this.$get = function() {
var factory = {};
factory.addition = function(a, b) {
return a + b;
}
return factory;
};
});
});
5. constant
The values can not be injected into module.config() , hence the constants are used to
pass the values to config. For example
App.constant("configparam","value");
Code Explanation :
The directive object is defined inside the
mainApp.directive("person", function() {
Code Explanation :
Note that we have used the directive named person as HTML element as well as
attribute with <div> tag.
Step 4 : The complete code can be given as follows -
AngularJS Document[DirectiveDemo.html]
<html>
<body ng-app = "myApp">
2.26.15 Internationalization
AngularJS has built-in support for internationalization of numbers and dates.
There are built-in filters such as date, currency and number.
date Filter
The date filter the date is following format -
i) Short ii) medium
currency Filter
The currency filter will use the currency symbol associated with the chosen locale
when formatting a number as a currency. We can specify the currency symbol to the
currency filter like this :
{{ curr | currency : '$' }} //dollars
{{ curr | currency : '£' }} //pounds
number Filter
The number filter formats numbers according to the chosen locale. For example in
Danish the thousand separators is specified by comma.
Setting Locale
For Internationalization we need to set the locale. The Danish locale can be set using
following script
<script src = "https://code.angularjs.org/1.2.5/i18n/angular-locale_da-dk.js"></script>
Example
Let us discuss AngularJS Document having display of date and currency in specific
form.
AngularJS Document[Internationalization.html]
<!DOCTYPE html>
<html>
<script
src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.5/angular.min.js"></script>
<script src="https://code.angularjs.org/1.2.5/i18n/angular-locale_da-dk.js"></script>
<body ng-app="myapp">
<div ng-controller="mycontroller">
<strong>Today:</strong> {{dt | date : "fullDate"}} <br/>
<strong>Amount:</strong> {{val | currency }}
</div>
<script>
var module = angular.module("myapp", []);
module.controller("mycontroller", function($scope) {
$scope.dt = new Date();
$scope.val = 555.44;
});
</script>
</body>
</html>
Output
Review Questions
1. Does Angular JS support single page application via multiple views on a single page ? Justify
your answer. SPPU : May-18, Marks 6
2. List and explain events supported by angular JS to enrich form filling and validation.
SPPU : May-18, Marks 4
3. What are different ways to create service in angular JS ? Explain separation of concern in
angular JS. SPPU : May-18, Marks 6
4. Create simple angular JS application to display “Hello, Input Name” using proper directive.
SPPU : Dec.-18, May-19, Marks 6
5. List and explain various directives in angular JS. SPPU : Dec.-18, Marks 4
6. Write sample angular JS application which can demonstrate use of different expressions.
SPPU : May-19, Marks 8
a programming b scripting
c application d none of these
Q.2 JavaScript is designed for this purpose.
a + b :
c – d ?
Q.7 Which of the following attribute can hold the JavaScript version ?
a Language b Script
c Version d None of the above
Q.8 JavaScript was invented by _______.
a False b True
c 0 d 1
Q.15 jQuery is a _______.
a Java program b query language
c JavaScript library d none of these
Q.16 _______ is the sign used as a shortcut in jQuery.
a $ b %
c @ d &
Q.17 _______ is the method used to set one or more style properties to the selected element.
a html() method b style() method
c css() method d all of the above
Q.18 Which of the jQuery function prevents the code from running before the loading of the
document finishes ?
a $(document).load() b $(document).unload()
c $(document).ready() d $(document).trim()
Q.19 AngularJS expressions are written using _______.
a (expression) b [expression]
c [[expression]] d {{expression}}
Syllabus
Servlet : Servlet architecture overview, A “Hello World” servlet, Servlets generating dynamic
content, Servlet life cycle, parameter data, sessions, cookies, URL rewriting, other Servlet
capabilities, data storage, Servlets concurrency, databases (MySQL) and Java Servlets.
XML : XML documents and vocabularies, XML declaration, XML Namespaces, DOM based XML
processing, transforming XML documents, DTD : Schema, elements, attributes.
AJAX : Introduction, Working of AJAX.
Contents
3.1 Introduction to Server Side Programming
3.8 Sessions
3.9 Cookies ................................................... Dec.-19,................................. Marks 5
(3 - 1)
Web Technology 3-2 Java Servlets and XML
3.17 Rules
3.23 Introduction
Part I : Servlet
1. The server side scripting is used to create The client side scripting is used to create the web
the web pages that provide some services. pages as a request or response to server. These
pages are displayed to the user on web browser.
2. These scripts generally run on web These scripts generally run on web browser.
servers.
3. A user's request is fulfilled by running a The processing of these scripts takes place on the
script directly on the web server to end users computer. The source code is
generate dynamic HTML pages. This transferred from the web server to the users
HTML is then sent to the client browser. computer over the internet and run directly in
the browser.
4. Uses : Processing of user request, Uses : Making interactive web pages, for
accessing to databases. interacting with temporary storages such as
cookies or local storage, sending request to server
and getting the response and displaying that
response in web browser.
5. Example : PHP, ASP.NET, nearly all the Example : HTML, CSS, JavaScript(primarily)
programming languages including C++,
Java and C#
The servlet class is instantiated when web server begins the execution.
The execution of servlet is managed by servlet container, such as Tomcat.
The servlet container is used in java for dynamically generate the web pages on the
server side. Therefore the servlet container is the part of a web server that interacts
with the servlet for handling the dynamic web pages from the client.
Servlets are most commonly used with HTTP (i.e. Hyper Text Transfer Protocol) hence
sometimes servlets are also called as "HTTP Servlet".
The main purpose of servlets is to add up the functionality to a web server.
1. When a client make a request for some servlet, he/she actually uses the Web
browser in which request is written as a URL.
2. The web browser then sends this request to Web server. The web server first
finds the requested servlet.
3. The obtained servlet gathers the relevant information in order to satisfy the
client’s request and builds a web page accordingly.
4. This web page is then displayed to the client. Thus the request made by the
client gets satisfied by the servlets.
Advantages
The servlets are very efficient in their performance and get executed in the address
space of the belonging web server.
The servlets are platform independent and can be executed on different web servers.
The servlets working is based on Request-Response. Any HTML form can take the
user input and can forward this input to the servlet. The servlets are then responsible to
communicate with the back-end database and manipulate the required business logic.
These servlets embedded on the web servers using Servlets API.
Servlets provide a way to generate the dynamic document. For instance : A servlet can
display the information of current user logged in, his logging time, his last access, total
number of access he made so far and so on.
Multiple users can keep a co-ordination for some application among themselves using
servlets.
Using servlets multiple requests can be synchronized and then can be concurrently
handled.
Disadvantages
Servlet is a mixture of java skills and web related HTML skills. Hence it is difficult to
write servlets.
It slows down the application execution.
The java runtime environment is required on the server, if you want to execute servlet
application.
FirstServlet.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
Program Explanation :
In the above program, we have imported following files,
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
Out of these files java.io package is useful for taking care of I/O operations.
The javax.servlet and javax.servlet.http are important packages containing the classes
and interfaces that are required for the operation of servlets. The most commonly used
interface from javax.servlet package is Servlet. Similarly most commonly used class in
this package is GenericServlet. The ServletRequest and ServletResponse are another
two commonly used interfaces defined in javax.servlet package.
In the javax.servlet.http package HttpServletRequest and HttpServletResponse are
two commonly used interfaces. The HttpServletRequest enables the servlet to read
data from the HTTP request and HttpServletResponse enables the servlet to write data
to HTTP response. The cookie and HttpServlet are two commonly used classes that are
defined in this package.
We have given class name FirstServlet which should be derived from the class
HttpServlet. (Sometimes we can derive our class from GenericServlet).
Then we have defined doGet method to which the HTTP request and response are
passed as parameters. The commonly used basic exceptions for the servlets are
IOException and ServletException.
The MIME type is specified as using the setContentType() method. This method sets
the content type for the HTTP response to type. In this method “text/html” is specified
as the MIME type. This means that the browser should interpret the contents as the
HTML source code.
Then an output stream is created using PrintWriter(). The getWriter() method is used
for obtaining the output stream. Anything written to this stream is sent to the client as
a response. Hence using the object of output stream ‘out’, we can write the HTML
source code in println method as HTTP response.
<servlet-name>FirstServlet</servlet-name>
alias. All this is for security. Observe, the names are given in two different XML tags, in
the web.xml file, to make it difficult for hacking.
To invoke the FirstServlet Servlet, the client calls the server with the name
servlet/FirstServlet.
When servlet/FirstServlet call reaches the server, the Tomcat server opens the
web.xml file to check the deployment particulars. Searches such a <servlet-mapping> tag
that matches servlet/FirstServlet. servlet/FirstServlet is exchanged with FirstServlet.
Then, searches such a <servlet> tag that matches FirstServlet and exchanges with
FirstServlet class. Now the server, loads FirstServlet Servlet, executes and sends the
output of execution as response to client.
Review Question
1. Write a Java servlet program which will display "welcome to servlet" message.
SPPU : May-19, Marks 5
Following is a simple servlet program that displays the current date and time. Note
that the time is continuously changing and on refreshing the same page, we can
note down the changes.
Example Program
import java.io.*;
import javax.servlet.*;
public class DynamicServletDemo extends GenericServlet
{
//implement service()
public void service(ServletRequest req, ServletResponse res)
throws IOException, ServletException
{
//set response content type
res.setContentType("text/html");
//get stream obj
PrintWriter out = res.getWriter();
java.util.Date date = new java.util.Date();
out.println("<h2>"+"Current Date & Time: " +date.toString()+"</h2>");
//close stream object
out.close();
}
}
Output
Press F5 and refresh the current page, you will get the some changes in the output.
1. We have used Date() method of java.util class that is intended to display current
date and time.
2. The date is displayed using the date.toString() method.
In the life cycle of servlet there are three important methods. These methods are,
1. Init
2. Service
3. Destroy
The client enters the URL in the web browser and makes a request. The browser then
generates the HTTP request and sends it to the Web server. (Refer Fig. 3.5.1)
Web server maps this request to the corresponding servlet.
1. Init ( ) Method : The server basically invokes the init() method of servlet. This
method is called only when the servlet is loaded in the memory for the first time.
Using this method initialization parameters can also be passed to the servlet in order to
configure itself.
2. service ( ) Method : Server can invoke the service for particular HTTP request using
service() method. The servlets can then read the data provided by the HTTP request
with the help of service() method.
3. destroy ( ) Method : Finally server unloads the servlet from the memory using the
destroy() method.
Example Program
Following is a simple servlet in which these three methods viz. init(), service() and
destroy() are used -
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
ServletResponse parameters are passed for making the HTTP request and
getting the HTTP response from the sevlet.
3. The output stream is created using getWriter() and along this output stream
some messages are written. These messages will then be displayed on the web
browser when the servlet gets executed.
4. Finally the destroy() function is written in order to unload the servlet from the
memory.
Review Question
1. Explain the lifecycle of servlet. Write a simple servlet to print "Hello, Good Day".
SPPU : March-20, Marks 5
1) javax.servlet
2) javax.servlet.http
The classes and interfaces defined in these packages help in implementing the servlet.
Let us discuss them in detail -
3.6.1.1 Interfaces
Interface Description
ServletRequest This interface is useful in reading the data from the client request.
ServletResponse This interface is useful in writing the data to the client response.
void init(ServletConfig s) This method is called for initialising the servlet. The
initialisation parameter is obtained from the ServletConfig
interface.
void destroy() This method is called when the servlet has to be unloaded.
void Service(ServletRequest req, This method is used to implement the service that a servlet
ServletResponse res) should provide. The clients request is processed and a
response is given.
String getServletName() This method is used to obtain the name of the servlet.
ServletContext getServletContext() This method returns the context for the servlet.
getReader() This method is useful for reading the text from the
request.
void setContentLength(int size) This method sets the length of the content equal to
the size.
void setContentType(String Type) This methods sets the type of the content
3.6.1.2 Classes
The javax.servlet package contains following classes.
Class Description
ServletInputStream This class provides the input stream for reading the client’s request.
ServletOutputStream This class provides the output stream for writing the client’s response.
ServletException This class is used to raise the exception when an error occurs.
3.6.2.1 Interface
The following table describes the interfaces that are provided in this package
Interface Description
HttpSession The session data can be read or written using this interface.
HttpServletRequest The servlet can read the information from the HTTP request
using this interface.
HttpServletResponse The servlet can write the data to HTTP response using this
interface.
HttpSessionBindingListener This interface tells the object about its binding with the
particular session.
1. The HttpSession
At every HTTP session, the state information is gathered. The servlet can read or
write this information using HTTPSession interface. This interface is implemented
by the server.
Various methods used by this interface are as given below -
Method Description
2. The HttpServletRequest
The HTTPServletRequest is used to obtain the information from client’s HTTP
request.
Method Description
String getMethod() It returns the HTTP method for the client request.
String getPathInfo() Returns the path information about the servlet path.
Cookie [ ] getCookies() It returns the information in the cookies in the request made.
3. The HttpServletResponse
This HtttpServletResponse interface is used to formulate an HTTP response to the
client. Various methods are -
Method Description
void addCookie(Cookie cookie) This method is used to add cookie in the response.
String encodeURL(String url) This method is used to encode the specified URL.
4. The HttpSessionBindingListener
When particular listener gets bound or unbound from a value within HttpSession
object then this class is required. It extends the HttpSessionEvent. Various methods
that can be defined by this interface are -
Method Description
Object getValue() This function returns the value of bounded or unbounded attribute.
String getName() This function returns the name being bound or unbound.
HttpSession getSession() This function returns the session to which the listener can be bound
or unbound.
3.6.2.2 Classes
The following table describes the classes that are provided in this package
Class Description
HttpServlet It is used when developing servlets that receive and process HTTP
requests.
HttpSessionEvent This class is used to handle the session events.
3) The HttpSessionEvent
This method encapsulates the session event.
4) HttpSessionBindingEvent
The HttpSessionBindingEvent class extends HttpSessionEvent. It is generated
when a listener is bound to a value. The getSession() method obtains the session to
which the listener is being bound or unbound.
To make the form works with Java servlet, we need to specify the following attributes
for the <form> tag :
i) method=”method name”: To send the form data as an HTTP POST request to
the server.
ii) action=”URL/address of the servlet”: Specifies relative URL of the servlet which
is responsible for handling data posted from this form.
The browser uses two methods to pass this information to web server. These methods
are GET Method and POST Method.
i) GET method : The GET method sends user information along with ? symbol
called query string. For instance
http://localhost/hello?user = aaaa&age = 20
In servlet, this information is processed using doGet() method.
ii) POST method : This is the most reliable method of sending user information to
the server from HTML form. Servlet handles this request using doPost method.
Using GET request limited amount of Using POST large amount of information can be
information can be sent. sent.
Programming Examples
Example 3.7.1 Write a HTML that shows the following list :
C,C++,JAVA,C#
Define a form that contains a select statement and submit button. If the user selects the java
and press the submit the web page displays “The selected language is Java”.
Write a servlet program using HttpServlet and doGet method.
Solution :
We will write two source files first one is the HTML file named test.html in which
the list of all the desired languages is displayed along with the submit button. User
has to select the language of his choice and then press the submit button.
This data made by this request will be received by the servlet named
my_choiceservlet.java which reads the selected parameter and displays the
message about the selection made. The source files are as follows -
test.html
<html>
<body>
<center>
<form name="form1" method=GET
action="http://localhost:4040/servlets-examples/servlet/my_choiceservlet">
<b>Language:</b>
<select name="Language" size="1">
<option value="C">C</option>
<option value="C++">C++</option>
<option value="Java">Java</option>
<option value="C#">C#</option>
</select>
<br><br>
<input type="submit" value="Submit">
</form>
</body>
</html>
my_choiceservlet.java
import java.io.*;
importjavax.servlet.*;
importjavax.servlet.http.*;
throwsServletException,IOException
{
String lang=req.getParameter("Language");
res.setContentType("text/html");
PrintWriter out=res.getWriter();
out.println("The selected language is "+lang);
out.close();
}
}
Example 3.7.2 Write HTML form to read user name and password. This data is sent to the
servlet. If the correct user name and password is given then welcome him/her by his/her
name otherwise display the message for invalid user.
Solution :
Step 1 : Create HTML form for accepting user name and password
Input.html
<html>
<head>
</head>
<body>
<form action="http://localhost/examples/servlets/servlet/Welcome" method ="get">
User Name:<input type="text" name="uname"/>
<br/>
Password:<input type="password" name="pwd"/>
<input type="submit" value="Submit"/>
</form>
</body>
</html>
Step 2 : Create the servlet program to read user name and password and validate it.
Welcome.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
String username=req.getParameter("uname");
String password=req.getParameter("pwd");
if ((username=="Ankita")&&(password=="1234"))
out.print("Welcome "+username);
else
out.println("Invalid username");
}
}
Example 3.7.3 Write a servlet which accept two numbers using POST methods and display the
maximum of them.
Solution :
NumbersInput.html
<html>
<head>
<body>
<div align="center">
<br> <br>
<form action="http ://localhost/examples/servlets/servlet/MaxNumber" method="post">
Enter First Number :
<input type="text" value="" name="Number1" size=’5’>
<br/><br/> Enter Second Number :
<input type="text" value="" name="Number2" size=’5’>
<br/> <br/> <br/>
<input type="submit" value="Submit">
</form>
</div>
</body>
</html>
Step 2 : The servlet code that handles the post method and finds the maximum of the two
input numbers is as follows -
MaxNumber.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
if (a>b)
out.println(“<h4>The maximum number is:”+a+"</h4>");
else
out.println(“<h4>The maximum number is :”+b+"</h4>");
}
}
Step 3 : The output is as follows -
Solution :
Step 1 : We will write the simple HTML document, which will create the interface. The
user can select the type of currencies and will enter the value.
<html>
<body>
<formname="form1"method="post"
action="http://localhost/examples/servlets/servlet/DollarDemo">
Select the type of Currency:
<Select name="currency">
<option value="Euro">Euro</option>
<option value="Pound">Pound</option>
<option value="Rupees">Rupees</option>
</select>
<br/> <br/>
Enter the value:
<input type="text" name="currencyVal" value=""/>
<br/> <br/>
<input type="submit" value="Submit"/>
</form>
</body>
</html>
Step 2 : The java servlet for converting the currency value to dollar is as given below -
import java.io.*;
import java.net.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class DollarDemo extends HttpServlet {
public void doPost(HttpServletRequest req,HttpServletResponse res)throws
ServletException,IOException,NullPointerException
{
res.setContentType("text/html");
PrintWriter out=res.getWriter();
String c=req.getParameter("currency");
double RupeeValue,EuroValue,PoundValue;
double DollarValue=0;
String value=req.getParameter("currencyVal");
if(c.equals("Rupees"))
{
RupeeValue=Double.parseDouble(value);
DollarValue=RupeeValue/61;
}
if(c.equals("Euro"))
{
EuroValue=Double.parseDouble(value);
DollarValue=EuroValue/0.77;
}
if(c.equals("Pound"))
{
PoundValue=Double.parseDouble(value);
DollarValue=PoundValue*1.62;
}
out.println("<p> The dollar value= "+DollarValue+"</p>");
out.close();
}
}
Output
3.8 Sessions
When you open some application, use it for some time and then close it. This entire
scenario is named as session.
Session state is a server-based state mechanism that lets web applications store and
retrieve objects of any type for each unique user session. That is, each browser session
has its own session state stored as a serialized file on the server, which is deserialized
and loaded into memory as needed for each request. Refer Fig. 3.8.1.
Because server storage is a finite resource, objects loaded into memory are released
when the request completes, making room for other requests and their session objects.
This means there can be more active sessions on disk than in memory at any one time.
Sometimes the information about the session is required by the server. This
information can be collected during the session. This process is called session tracking.
There are three commonly used techniques used for session tracking and those are,
o Session ID
o Cookies
o URL Rewriting.
Thus session-ID is passed between the browser and server while processing the
information. This method of keeping track of all the information between server and
browser using session-ID is called session tracking.
In servlets, for creating the sessions getSession() method can be used. This method
returns the object which stores the bindings with the names that use this object. And
these bindings can be managed using getAttribute(), setAttribute(), removeAttribute()
methods. Actually in session tracking two things are playing an important role -
1. One is HttpServletRequest interface which supports getSession() method.
2. The another class is HttpSession class which supports the binding managing
functions such as getAttribute(), setAttribute(), removeAttribute() and
getAttributeNames().
Let us first discuss the servlet program which returns the number of previous sessions
established between client and server. Note that any client can communicate with the
server using some web browser only!
Example 3.8.1 Write a servlet program to keep track of number of times user is visiting the
page. Display the count appropriately.
cnt=new Integer(cnt.intValue()+1);
}
session.setAttribute("cnt",cnt);
PrintWriter out=res.getWriter();
out.println("<html>");
out.println("<head>");
out.println("</head>");
out.println("<body>");
out.println("<center>");
out.println("<h1>"+heading);
out.println("<h2> The number of previous access= "+cnt);
out.println("</center>");
out.println("</body>");
out.println("</html>");
}
}
Output
To get an output we will use following steps -
1. Compile the Servlet (i.e. a java program) using javac. This will generate a class
file.
2. Copy this class file to C:\your tomcat directory\examples-folder\WEB-INF\classes
3. Edit the web.xml file present at C:\your tomcat directory\examples-folder\WEB-
INF like this
…
<servlet>
<servlet-name>SessionServletDemo</servlet-name>
<servlet-class>SessionServletDemo</servlet-class>
</servlet>
…
<servlet-mapping>
<servlet-name>SessionServletDemo</servlet-name>
<url-pattern>/servlet/SessionServletDemo</url-pattern>
</servlet-mapping>
4. Start tomcat server.
5. Open the web browser and give the URL for SessionServletDemo. Following
output can be seen.
If you simply refresh your browser either by pressing F5 or clicking the refresh button
then you will get following kind of output.
Program Explanation
1. Our class SessionServletDemo is inherited from HttpServlet class. And inside the
doGet() method we can create an object session of HttpSession class. This
method returns the current session for the corresponding request.
2. The getAttribute(string attribute) returns the value associated with the attribute.
We can pass this attribute as a parameter to this method. If there is no attribute
present then this method returns null. The data type of getAttribute() method is
void.
3. The setAttribute(string attribute, object value) is a method which assigns the
value passed as the object value to the attribute name. The data type of this
method is void.
Definition : Cookies are some little information that can be left on your computer by
the other computer when we access an internet.
Generally this information is left on your computer by some advertising agencies on
the internet. Using the information stored in the cookies these advertising agencies can
keep track of your internet usage, liking of users.
For the applications like on-line purchase systems once you enter your personal
information such as your name or your e-mail ID then it can be remembered by these
systems with the help of cookies.
Sometimes cookies are very much dangerous because by using information from your
local disk some malicious data may be passed to you. So it is upto you how to maintain
your own privacy and security.
6. public Cookie[] getCookies() All the cookies can be returned using this method
with the help of HttpServletRequest interface.
3.9.2 Examples
Below is simple HTML form in which a servlet is invoked. This servlet creates a cookie
by the name My_Cookie and stores the value entered by you in the textbox of HTML
form. You can further get the information stored in the cookie by another servlet program
getCookieServlet. Hence we will write three programs -
1. Our normal HTML script in which some value is entered in the textbox.
2. The servlet program named mycookieservlet which will set a cookies and take
the value entered by you in the HTML form.
3. The another servlet program named getCookieServlet which helps us to view the
cookie.
HTML Program
<html>
<head>
<title>Demo of Cookie</title>
</head>
<body>
<form name="form1" method="post"
action="http ://localhost:8080/examples/servlet/mycookieservlet">
<h3> Enter the value for my Cookie: </h3>
<input type=text name="txt_data" size =30 value=" ">
<input type=submit value="Submit">
</form>
</body>
</html>
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class getCookieServlet extends HttpServlet
{
public void doGet(HttpServletRequest req,HttpServletResponse res)
throws ServletException,IOException
{
Cookie[ ] my_cookies=req.getCookies();
res.setContentType("text/html");
PrintWriter out=res.getWriter();
out.println("<b>");
int n=my_cookies.length;
for(int i=0;i<n;i++)
{
String name=my_cookies[i].getName();
String value=my_cookies[i].getValue();
out.println("name= "+name);
out.println("and value= "+value);
}
out.close();
}
}
In the above program using getName() and getValue() functions we can get the name
of the cookie as well as the value of the cookie respectively. The output of all the above
given three programs is as given below -
Output
Example 3.9.1 Write a program that allows the user to select a favorite programming language
and post the choice to the servlet. The response is a web page in which user can click a link to
view list of book recommendations. The cookies previously stored on the client are read by the
servlet and form a web page containing the book recommendation. Use servlet, cookies and
HTML.
Solution :
Step 1 : Create an HTML page which allows the user to select the favourite programming
language. The user can submit his choice by clicking the submit button.
InputForm.html
<html>
<body>
<form name="form1" method="post"
action="http://localhost/examples/servlets/servlet/MyProgram">
<h3> Enter the favourite Programming Language: </h3>
<select name="Lang_ch">
<option value="C++">C++</option>
<option value="Java">Java</option>
<option value="PHP">PHP</option>
</select>
<input type=submit value="Submit">
</form>
</body>
</html>
Step 2 : Now create a web servlet program which reads the choice of programming
language and set this choice as cookie. The web page containing a hyperlink is created in
this servlet program. The code for this Servlet program is as follows -
MyProgram.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class MyProgram extends HttpServlet
{
public void doPost(HttpServletRequest req,HttpServletResponse res)
throws ServletException, IOException
{
String choice = req.getParameter("Lang_ch");
// Create cookie.
Cookie cookie = new Cookie("My_Cookie", choice);
Review Question
1. Explain session and cookies in servlets ? Write any one program to demonstrate session or
cookies SPPU : Dec.-19, Marks 5
The browser will demand for the required web page by putting the same URL string in
the request.
When browser makes requests for another page same URL is embedded. There by
server will come to know that the request is related to previous page and the work in
same session will get co-related.
We can send the name-value pair from one page to another using URL rewriting
method. In this method the token of name-value pair can be added at the end of URL.
The URL writing occurs in the following format
The parameter sent by the URL is obtained at the server side by getParameter method.
The syntax of this method is
String getParameter(String)
Example 3.10.1 Write a servlet that Welcomes the user by his/her name only if the valid
password is entered by the user. Make use of URL rewriting method.
Solution :
Step 1 : Create a registration form. I have named it as registration.html. The code for it is
as follows :
registration.html
<!doctype html>
<html>
<head>
<title> Demo For URL Rewriting </title>
<body>
<form method ="post" action="http://localhost/examples/servlets/servlet/firstpg">
User:<input type ="text" name="user" ><br/>
Password:<input type ="password" name="pwd"> <br/><br/>
<input type="submit" value="Submit">
</form>
</body>
Step 2 : Create a servlet program that reads the user name and password values entered
by the user. This servlet also compares the entered password with the valid password. If
the user enters valid password, then the request is redirected to another servlet page.
Otherwise wrong password message will be displayed. The first servlet is,
firstservlet.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class firstpg extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
String uname = request.getParameter("user");
String pass = request.getParameter("pwd");
if(pass.equals("password"))
{
response.sendRedirect("secondpg?user_name="+uname+"");
}
else
out.println("<i> You have entered wrong password!!!</i>");
}
}
Step 3 : If user enters the valid password, then he/she is redirected to main page. This
page welcomes him/her by his/her name. The code for this servlet is as follows -
secondpg.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class secondpg extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
String user = request.getParameter("user_name");
out.println("<h3>Welcome "+user+" to main page!!!</h3>");
}
}
Step 4 : Compile the java files created in step 2 and step 3. Copy the class files to classes
folder of Tomcat's WEB-INF folder. Modify the web.xml file as follows -
<?xml version="1.0" encoding="ISO-8859-1"?>
...
<servlet>
<servlet-name>firstpg</servlet-name>
<servlet-class>firstpg</servlet-class>
</servlet>
<servlet>
<servlet-name>secondpg</servlet-name>
<servlet-class>secondpg</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>firstpg</servlet-name>
<url-pattern>/servlets/servlet/firstpg</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>secondpg</servlet-name>
<url-pattern>/servlets/servlet/secondpg</url-pattern>
</servlet-mapping>
</web-app>
Start the Tomcat web server.
Open the suitable web browser and invoke the HTML document as given in Step 1.
The output will be,
On clicking submit button we will get the following page on valid password
String getRemoteAddr() This method returns IP address of the client who is making the
request.
String getRemoteHost() This method returns the name of the client who is making the
request.
String getProtocol() This method returns the name of the protocol, client is using.
String getHeader(String field) When the field name is given the value for the header is returned.
StringBuffer getRequestURL() This method returns the String containing the URL which is used to
access the servlet. This string does not contain the query string
appended to URL.
void sendRedirect(String location) Sends a temporary redirect response to the client using
the specified redirect location URL and clears the
buffer.
String getHeader(String name) Gets the value of the response header with the given
name.
void setHeader(String name, String value) Sets a response header with the given name and value.
void setStatus(int sc) Sets the status code for this response.
void sendError(int sc, String msg) Sends an error response to the client using the specified
status and clears the buffer.
Example Program
Step 1 :
<html>
<head>
</head>
<body>
<form action="http://localhost:8080/examples/servlets/servlet/ClientAddressServlet"
method ="get">
User Name:<input type="text" name="uname"/>
<input type="submit" value="Submit"/>
</form>
</body>
</html>
Step 2 :
ClientAddressServlet.java
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
public class ClientAddressServlet extends HttpServlet
{
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
// Get client's IP address
String name = request.getParameter("uname");
String clientIP = request.getRemoteAddr();
// Get client's host name
String clintHost = request.getRemoteHost();
String queryString = request.getQueryString();
String protocol = request.getProtocol();
int localPort = request.getLocalPort();
response.setContentType("text/plain");
PrintWriter out = response.getWriter();
Output
Java Program[SerializProg.java]
import java.io.*;
class SerializProg
{
public static void main(String[] args)throws ClassNotFoundException,IOException
{
Myclass myobject=new Myclass("Parth",10);//creating the object
System.out.println("The object is: "+myobject);//displaying the contents of the object
ObjectOutputStream o=new ObjectOutputStream(new FileOutputStream("object.txt"));
o.writeObject(myobject);//writing the object to a file
o.flush();
o.close();
ObjectInputStream i=new ObjectInputStream(new FileInputStream("object.txt"));
Myclass newobject=(Myclass)(i.readObject());//reading the object from the file
i.close();
System.out.println("\nYou have stored :"+newobject);//displaying the object's value
}
static class Myclass implements Serializable
{
String name; Implements the serializable interface
int roll;
Program Explanation
In above program,
1. We have created an object of class named Myclass. The members of this class are
name and roll number.
2. From the main function assigns the values to these members. This object is
written to the file named object.txt using the writeObject method.
3. Later on the value of this object can be read using the readObject method.
4. For the creation of the object we have to define a class who implements the
Serializable interface.
5. It is necessary to throw the exceptions ClassNotFoundException and
IOException
On the server side the situation is different. There can be hundreds or even
thousands of users simultaneously accessing a web site.
Concurrent web servers handle multiple users as follows - It begins with one
servlet, executes some instruction, then suspends it for a while and start executing
the other servlet. Eventually completes the second servlet and returns back to first
servlet to execute the remaining instructions. Refer Fig. 3.13.1.
Concept of Thread :
Thread is a light weight process. It is used for concurrent execution of the tasks.
The Java Virtual Machine maintains a data structure containing the information
about each thread. The server creates a thread for each HTTP request. The data
structure maintains the information about the state of the thread along with the
references to the HttpServletRequest and HttpServletResponse objects created by
the server.
The Java Virtual Machine also maintains the information whether the particular
thread is currently running or not.
When one thread is suspended then the state of other executing thread is loaded
into Java Virtual Machine.
Following example shows the concurrent execution of the servlet with the help of
threads
Step 1 :
<HTML>
<BODY>
<TABLE>
<TR>
<TD>
<a href ="http://localhost:8080/examples/servlets/servlet/SimpleServlet">servlet1</a>
</TD>
</TR>
<TR>
<TD>
<a href ="http://localhost:8080/examples/servlets/servlet/SimpleServlet">servlet2</a>
</TD>
</TR>
<TR>
<TD>
<a href ="http://localhost:8080/examples/servlets/servlet/SimpleServlet">servlet3</a>
</TD>
</TR>
</TABLE>
</BODY>
</HTML>
Step 2 :
import java.io.IOException;
import javax.servlet.*;
import javax.servlet.http.*;
import java.math.*;
public class SimpleServlet extends HttpServlet
{
{
int counter = 0;
resp.getWriter().println(this);
for (int i = 0; i < 10; i++)
{
resp.getWriter().println("Counter = " + counter);
try
{
Thread.currentThread().sleep((long) Math.random() * 1000);
counter++;
}
catch (InterruptedException exc) { }
}
}
}
Output
Now let us go through some MYSQL query statements which are required while
handling the database.
1. Creating database
mysql> CREATE DATABASE mydb;
Query OK, 1 row affected (0.15 sec)
4. Creating table
We must create a table inside a database hence it is a common practice to use create
table command after USE database command. While creating a table we must specify the
table fields.
mysql> CREATE TABLE my_table(id INT(4),name VARCHAR(20));
Query OK, 0 rows affected (0.28 sec)
Use of Primary Key : The primary key contains the unique value. The primary key
column can not contain NUL value. Each table can have only one primary key. Following
is a SQL statement used to create PRIMARY KEY.
CREATE TABLE student_table(
roll_no INT(4) NOT NULL AUTO_INCREMENT,
name VARCHAR(50) NOT NULL,
address VARACHAR(50) NOT NULL,
PRIMARY KEY(roll_no)
);
In above example the roll_no acts as a primary key for the student_table.
5. Displaying a table
After creating the table using SHOW command we can see all the existing tables in the
current database.
mysql> SHOW TABLES;
+-----------------------+
| Tables_in_mydb |
+-----------------------+
| my_table |
+-----------------------+
1 row in set (0.00 sec)
For example
Consider table Customer
Cust_Id Name City
1 Rahul Bombay
2 Priyanka Pune
3 Supriya Banglore
id name
4 MONIKA
1 SHILPA
2 SUPRIYA
3 YOGESH
For instance :
SELECT * from students_table WHERE name=?
The placeholder represented by ? is used in this type of statement. There are special
type setter methods that assign the values to the placeholders before the SQL statement is
executed.
3) ResultSet - This interface is used to represent the database result set. After using
SELECT SQL statement, the information obtained from the database can be
displayed using ResultSet.
4) SQLException - For handling SQL exceptions this interface is used.
Solution : JDBC URL with examples : The databases are referenced by Java runtime
engine using JDBC URL. The syntax of these URLs depends on the database driver you
are using.
The list of common drivers along with JDBC URL is,
1. ODBC Driver
Syntax :
jdbc:odbc:<data source name>
Example :
jdbc:odbc:MyDataSource
2. MYSQL
Syntax :
jdbc:mysql://[host][:port]/[database]
Example :
jdbc:mysql://localhost:3306/Mydatabase
3. ORACLE
Syntax :
jdbc:oracle:<drivertype>:<user>/<password>@<database>
Example :
jdbc:oracle:thin:myuser/mypassword@localhost:mydatabse
3.14.4 Implementation
Username : The default username for the mysql database is root. If you haven't set any
user name it could be blank.
Password : Password is given by the user at the time of installing the mysql database.
The connection URL can be obtained using the method getConnection. This
method is defined in class named DriverManager. Note that this DriverManager
class is defined in java.sql.* package. We can obtain the instance for connection
using following statement,
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/my_database","","");
Let us understand this with the help of examples.
Example 3.14.2 Write a Servlet program to connect to a MySQL database. Create a student
database named StudentDB.
Solution :
1. Create a StudentDB in MySQL using following query
create database StudentDB;
2. The Servlet program can be written as follows
import java.io.*;
import java.sql.Connection;
import java.sql.DriverManager;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
Example 3.14.3 Create a students database in any relational database package. The table which
you create in this database must have following fields - Roll_No, name, address and phone.
The Roll_No must be a primary key. You have to create a servlet at the fornt end which will
perform following operations - 1. Insertion of record 2. Deletion of the record using the
primary key 3. Updation on any one field of the record. 4. Display of all the records from
the database.
Step 1 : First of all we will create a database named students and then create a table
named students_table in this database in MYSQL. This can be down using following SQL
commands -
mysql>CREATE DATABASE students;
mysql>use students;
mysql>create table students_table(Roll_no INT(4) NOT NULL AUTO_INCREMENT,name
VARCHAR(50) NOT NULL,address VARCHAR(30) NOT NULL,phone VARCHAR(11) NOT
NULL,PRIMARY KEY(Roll_no));
Now we have simply created a table without any content within it. Our intention is to
insert the records in this table using the front end - servlet program.
Step 2 : The first page of this application will be Databasedemo.html. The code for this
html document will be as given below -
DatabaseDemo.html
<html>
<head>
<title>Database Connectivity using JDBC</title>
</head>
<frameset rows="100,*">
<framesrc="http://www.localhost.com:4040/servlets-examples/Head.html"
name="top_frame">
<frameset cols="200,*">
<framesrc="http://www.localhost.com:4040/servlets-examples/Menu.html"
name="left_frame">
<framesrc="http://www.localhost.com:4040/servlets-examples/display.html"
name="right_frame">
</frameset>
</frameset>
</html>
The Databasedemo.html will simply provide the initial interface for this application.
This HTML document consists of three frames. The top frame will simply display the
name of the application. The left frame consists of another html page in which the four
links for each operation are specified. Each link will be a separate servlet program
communication with the database. The right frame will display the results of each
operation.
The output will be as follows -
Step 1 : Open the DatabaseDemo.html web page by giving the path for this html file on
the address bar of Internet explorer -
Head.html
Menu.html
display.html
Head.html
<html>
<head>
<title>Database Connectivity</title>
</head>
<body>
<center><h1>Operations on Student Database</h1></center>
</body>
</html>
Menu.html
<html>
<body>
<h2> Main Menu</h2>
<h3>
<a href="http://www.localhost.com:4040/servlets-examples/servlet/Insert_Query"
target="right_frame">Insert Record</a>
<br/>
<a href="http://www.localhost.com:4040/servlets-examples/servlet/Delete_Query"
target="right_frame">Delete Record</a>
<br/>
<a href="http://www.localhost.com:4040/servlets-examples/servlet/Update_Query"
target="right_frame">Update Record</a>
<br/>
<a href="http://www.localhost.com:4040/servlets-examples/servlet/ServletDBDemo"
target="right_frame">Display Records</a>
</h3>
</body>
</html>
display.html
<html>
<body>
<p> This is a demo application for database connectivity</p>
<p>This connectivity is between Servlet and MYSQL</p>
<p>Just click the links given in left frame and the corresponding form will
appear in the right frame for inputting the values to perform the desired operation
</p>
</body>
</html>
Step 3 : The top frame simply displays the name of the application the left frame displays
the various operations that can be performed on the database. There are four sample
operations like insertion, deletion, updation and displaying of data from the database.
Just click on corresponding links to get the desired operation done. For instance I have
clicked on Insert Record hyperlink and in the right frame a form appears. Fill up this
form and then click the Submit button.
Class.forName("com.mysql.jdbc.Driver");
con=DriverManager.getConnection("jdbc:mysql://localhost:3306/students","root", "system");
stmt = con.createStatement();
out.println("\n\n");
String Studname=request.getParameter("Sname");
String Studaddress=request.getParameter("Sadd");
String Studphone=request.getParameter("Sph");
if(Studname!=null&&Studaddress!=null&Studphone!=null)
if(Studname.length()>0)
stmt.executeUpdate("insert into students_table(name,address,phone)
values('"+Studname+"','"+Studaddress+"','"+Studphone+"')");
}catch (SQLException e)
{
throw new ServletException("Servlet Could not display records.", e);
}
catch (ClassNotFoundException e)
{
throw new ServletException("JDBC Driver not found.", e);
}
finally
{
try
{
if(rs != null)
{
rs.close();
rs = null;
}
if(stmt != null)
{
stmt.close();
stmt = null;
}
if(con != null)
{
con.close();
con = null;
}
}
catch (SQLException e) {}
}//end of finally
out.close();
}//end of service function
} //end of class
Now save this program at the path
C://your_tomcat_directory/webapps/servlets-examples/WEB-INF/classes
Then compile the above code using following command at this path -
javac Insert_Query.java
If the code is error free then a class file named Insert_Query.class gets generated at the
above mentioned path.
Now edit the web.xml file present in the ../servlets-examples/WEB-INF directory as
follows [Note that at two fragments of code must be added in the web.xml file which are
given below]
<servlet>
<servlet-name>Insert_Query</servlet-name>
<servlet-class>Insert_Query</servlet-class>
</servlet>
…
…
…
<servlet-mapping>
<servlet-name>Insert_Query</servlet-name>
<url-pattern>/servlet/Insert_Query</url-pattern>
</servlet-mapping>
Save and close this web.xml file.
The other operations can be performed using following servlet programs. What you
need to do is create the following files in Notepad, execute them individually using javac
command and then edit the web.xml file by specifying the name of corresponding servlet.
Delete_Query.java
import java.io.*;
import java.lang.*;
import java.util.*;
import javax.sql.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
}catch (SQLException e)
{
throw new ServletException("Servlet Could not display records.", e);
}
catch (ClassNotFoundException e)
{
throw new ServletException("JDBC Driver not found.", e);
}
finally
{
try
{
if(rs != null)
{
rs.close();
rs = null;
}
if(stmt != null)
{
stmt.close();
stmt = null;
}
if(con != null)
{
con.close();
con = null;
}
}
catch (SQLException e) {}
}//end of finally
out.close();
}//end of service function
} //end of class
Update_Query.java
import java.io.*;
import java.lang.*;
import java.util.*;
import javax.sql.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
out.println("<br/><br/>");
out.println("<input type='submit' value='Submit'>");
out.println("</form>");
out.println("</body>");
out.println("</html>");
}catch (SQLException e)
{
throw new ServletException("Servlet Could not display records.", e);
}
catch (ClassNotFoundException e)
{
throw new ServletException("JDBC Driver not found.", e);
}
finally
{
try
{
if(rs != null)
{
rs.close();
rs = null;
}
if(stmt != null)
{
stmt.close();
stmt = null;
}
if(con != null)
{
con.close();
con = null;
}
}
catch (SQLException e) {}
}//end of finally
out.close();
}//end of service function
} //end of class
ServletDBDemo.java
import java.io.*;
import java.util.*;
import javax.sql.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
out.print("<td>");
out.print(rs.getObject(4).toString());
out.print("</td>");
out.print("</tr>");
}
out.print("</table>");
out.print("</center>");
}catch (SQLException e) {
throw new ServletException("Servlet Could not display records.", e);
} catch (ClassNotFoundException e) {
throw new ServletException("JDBC Driver not found.", e);
} finally {
try {
if(rs != null) {
rs.close();
rs = null;
}
if(stmt != null) {
stmt.close();
stmt = null;
}
if(con != null) {
con.close();
con = null;
}
} catch (SQLException e) {}
}
out.close();
}
}
Key Point All the above servlet code must be compiled in order to generate the class file. Note
that all these class files must be present in the folder
C:\your_tomcat_directory\webapps\servlets-examples\WEB-INF\classes
And the web.xml file must be edited by specifying the class file of each of these
servlets.
Step 3 : Click on the hyperlink Display Records present in the left frame. The contents
from the database will be displayed in the right frame. The sample output is -
Step 4 : We can insert as many records as we want by clicking the Insert Record and
filling up the form.
Step 5 : If we want to delete particular record then using the primary key Roll_No the
corresponding record can be deleted. Just click on the Delete Record link present in the
left frame and enter the roll number for the record to be deleted. And then click the
Submit button. The sample output is follows -
Step 6 : For updating of record click the link Update Record present in the left frame. This
application allows to update the address using the Roll number. The sample output will
be as follows -
Step 7 : You can each time click on the Display Records link to see the effects of these
operations. The sample output will be -
Example 3.14.4 Consider a database table with the following schema.(PNR No,status). Write a
servlet program to display the status, given the PNR number.
try
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
con =DriverManager.getConnection ("jdbc:odbc:PNRDemo","","");
}catch(ClassNotFoundException e){e.printStackTrace();}
catch(SQLException e){e.printStackTrace();}
catch(Exception e){e.printStackTrace();}
try
{
stmt = con.createStatement();
rs = stmt.executeQuery("SELECT * FROM PNR_table");
// displaying records
response.setContentType("text/html");
out.println("<html>");
out.println("<head><title>PNR Status Display</title></head>");
out.println("<body>");
out.print("<center>");
out.print("<h2>PNR Details </h2>");
out.print("<table border=3>");
out.print("<th>PNR No.</th>");
out.print("<th>Status</th>");
while(rs.next())
{
out.print("<tr>");
out.print("<td>");
out.print(rs.getObject(1).toString());
out.print("</td>");
out.print("<td>");
out.print(rs.getObject(2).toString());
out.print("</td>");
out.print("</tr>");
}
out.print("</table>");
out.print("</center>");
out.println("</body></html>");
}catch (SQLException e) { }
finally {
try {
if(rs != null) {
rs.close();
rs = null;
}
if(stmt != null) {
stmt.close();
stmt = null;
}
if(con != null) {
con.close();
con = null;
}
} catch (SQLException e) {}
}
out.close();
}//end of service function
} //end of class
Output
Example 3.14.5 Assume that a database has a table Employee with two columns EmployeeID
and Name. Assume that the administrator user id and password to access the database table
are, scott and tiger. Write a JDBC program that can query and print all the entries in the
table Employee. Make the database connection using a type2 driver database.driver and
connection string jdbc:db:oci
Solution : The JDBC code for displaying the employees in Employee table is as follows -
DisplayEmp.java
import java.io.*;
import java.util.*;
import javax.sql.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.sql.*;
{
public void service(HttpServletRequest request,HttpServletResponse response)
throws IOException, ServletException
{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<html>");
out.println("<head><title>Servlet Database Connectivity</title></head>");
out.println("<body>");
// connecting to database
Connection con = null;
Statement stmt = null;
ResultSet rs=null;
try
{
Class.forName("oracle.jdbc.OracleDriver");
String dbURL = "jdbc:oracle:oci:@my_database";
Properties properties = new Properties();
properties.put("user", "scott");
properties.put("password", "tiger");
properties.put("defaultRowPrefetch", "20");
con =DriverManager.getConnection (dbURL,properties);
stmt = con.createStatement();
rs=stmt.executeQuery("select * from Employee");
out.print("<table border=1>");
out.print("<tr><td>EmployeeID</td><td>Name</td></tr>");
while(rs.next())
{
//Retrieve by column name
int id = rs.getInt("ID");
String name = rs.getString("Name");
out.print("<tr><td>"+id+"</td><td>"+name);
out.print("</td></tr>");
}
out.println("</table></body></html>");
}catch (SQLException e)
{
throw new ServletException("Servlet Could not display records.", e);
}
catch (ClassNotFoundException e)
{
throw new ServletException("JDBC Driver not found.", e);
}
finally
{
try
{
if(rs != null)
{
rs.close();
rs = null;
}
if(stmt != null)
{
stmt.close();
stmt = null;
}
if(con != null)
{
con.close();
con = null;
}
}
catch (SQLException e) {}
}//end of finally
out.close();
}//end of service function
} //end of class
Output
Part II : XML
3.15 XML Documents and Vocabularies SPPU : Dec.-18, 19, May-19, Marks 5
Uses of XML
1. XML is used to display the meta contents i.e. XML describes the content of the
document.
2. XML is useful in exchanging data between the applications.
3. The data can be extracted from database and can be used in more than one
application. Different applications can perform different tasks on this data.
Advantages of XML
1. XML document is human readable and we can edit any XML document in
simple text editors.
2. The XML document is language neutral. That means a Java program can
generate an XML document and this document can be parsed by Perl.
3. Every XML document has a tree structure. Hence complex data can be arranged
systematically and can be understood in simple manner.
4. XML files are independent of an operating system.
Goals of XML
Following are the goals of XML -
1. User must be able to define and use his own tag. This allows us to restrict the use
of the set of tags defined by proprietary vendors.
2. Allow user to build his own tag library based on his web requirement.
3. Allow user to define the formatting rules for the user defined tags.
4. XML must support for storage or transport of data.
Features of XML
Following are some features which are most suitable for creating web related
applications.
XML is EXtesible Markup Language intended for transport or storage of the data.
The most important feature of XML is that user is able to define and use his own tag.
XML contains only data and does not contain any formatting information. Hence
document developers can decide how to display the data.
XML permits the document writer to create the tags for any type of information. Due to
this virtually any kind of information can be such as mathematical formulae, chemical
structures, or some other kind of data can be described using XML.
Searching sorting, rendering or manipulating the XML document is possible using
Extended Stylesheet Language (XSL).
The XML document can be validated using some external tools.
Some commonly used web browsers like Internet Explorer and Firefox Mozilla provide
support to the tags in XML. Hence XML is not at all vendor specific or browser specific.
1. HTML stands for Hypertext Markup XML stands for eXtensible Markup
Language. Language.
2. HTML is designed to display data with the XML is used to transport and store data, with
focus on look and feel of data. focus on what data is.
3. HTML is case insensitive. XML is case sensitive.
4. HTML has predefined tags. XML has custom tags can be defined and the
tags are invented by the author of the XML
document.
5. As HTML is for displaying the data it is As XML is for carrying the data it is dynamic.
static.
6. It can not preserve white space. It can preserve the white space.
Strengths :
1. XML document is human readable and we can edit any XML document in
simple text editors.
2. The XML document is language neutral. That means a Java program can
generate an XML document and this document can be parsed by Perl.
3. Every XML document has a tree structure. Hence complex data can be arranged
systematically and can be understood in simple manner.
4. XML files are independent of an operating system.
Limitations :
1. XML syntax is verbose and redundant as compared to other text based data
transmission formats.
2. Redundancy in syntax of XML causes higher storage and transportation cost
when there is large volume of data.
3. XML does not support array.
4. XML document is less readable.
5. Due to verbose nature of XML syntax the XML file size is usually very large.
Review Questions
1. What are the strengths of XML technology ? Also list the limitations of using XML.
SPPU : Dec.-18, Marks 5
2. What are the strengths of XML technology ? Explain the need for XML.
SPPU : May-19, Marks 5
3. Describe the following web technology : XML. SPPU : Dec.-19, Marks 2
3. CDATA
CDATA stands for Character Data. This character data will be parsed by the parser.
4. PCDATA
It stands for Parsed Character Data (i.e. text).
The ELEMENT must be defined in the beginning of the XML file. It must be enclosed
within <!DOCTYPEroot_element ….>
There are various ways by which the actual element can be defined. It is enlisted in the
following table -
Category Syntax Description
Sometimes we can define the ELEMENT along with the iterator characters. The iterator
characters are the special character which are associated with some meaning.
Some commonly used iterator characters are as given below -
Iterator Meaning Example
character
For example
]>
<student>
<name>Anand</name>
<address phone="9898123123">Pune</address>
<std>Tenth</std>
<br />
<marks>70 percent</marks>
</student>
Output
Name token list NMTOKENS Attribute value is a list of valid XML names.
#IMPLIED The default value is not provided and attribute can be optionally used.
]>
<Book>&writer; &title;</Book>
Output
Note that we can define the predefined entities   along with the other entity
declaration.
The entity can be used using following syntax.
&name_of_entity;
In above script we have used two entities namely writer and title. For displaying
the space within these two entities we have used an entity nbsp and for defining it
we have used #160.
3.17 Rules
Rules that must be followed while writing XML -
Here are some rules that must be followed while writing the XML programs -
1. XML is a case sensitive. For example -
<hobby>I like drawing</Hobby>or
<Hobby>I like drawing</hobby>
is not allowed because the words hobby and Hobby are treated differently.
2. In XML each start tag must have matching end tag. For example -
<staring> XML is funny to write
<simple> It is simple to implement </simple>
That means a closing tag is a must.
3. The elements in XML must be properly nested. For example-
<one><two>Hello how are you?</one></two> is wrong but
<one><two>Hello how are you?</two></one> is correct
The document type definition is used to define the basic building block of any xml
document.
Using DTD we can specify the various elements types, attributes and their relationship
with one another.
Basically DTD is used to specify the set of rules for structuring data in any XML file.
For example : If we want to put some information about some students in XML file
then, generally we use tag student followed by his/her name, address, standard and
marks. That means we are actually specifying the manner by which the information
should be arranged in the XML file. And for this purpose the document type definition
is used.
Various building blocks of XML are -
1. Elements
The basic entity is element. The elements are used for defining the tags. The elements
typically consist of opening and closing tag. Mostly only one element is used to
define a single tag.
2. Attribute
The attributes are generally used to specify the values of the element. These are
specified within the double quotes.
For example -
<flag type="True">
The type attribute of the element flag is having the value True.
3. CDATA
CDATA stands for character data. This character data will be parsed by the parser.
4. PCDATA
It stands for Parsed Character Data (i.e. text). Any parsable character data should
not contain the markup characters. The markup characters are < or > or &. If we
want to use less than, greater than or ampersand characters then make use of < ,
> or &
There are two ways by which DTD can be defined.
Internal DTD
Consider following xml document -
XML Document [DTDDemo1.xml]
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE student [
<!ELEMENT student (name,address,std,marks)>
<!ELEMENT name (#PCDATA)> Here we are defining the
<!ELEMENT address (#PCDATA)> DTD internally
<!ELEMENT std (#PCDATA)>
<!ELEMENT marks (#PCDATA)>
]>
<student>
<name>Anand</name>
<address>Pune</address>
<std>Second</std>
<marks>70 percent</marks>
</student>
Output
External DTD
In this type, an external DTD file is created and its name must be specified in the
corresponding XML file. Following XML document illustrates the use of external DTD.
<marks>70 percent</marks>
</student>
Example 3.19.1 Create a DTD for a catalog of four stroke motorbikes, where each motor bike has
the following child elements -make, model, year, colo, engine, chasis number and accessories.
The engine element has the child elements engine number, number of cylinders, type of fuel.
The accessories element has the attributes like disc brake,auto-start and radio, each of which
is required and has the possible values yes and no.
Solution :
automobile.dtd
<!ELEMENT Catalog (MotorBike)*>
<!ELEMENT MotorBike (make, model, year,color, engine,chasis-num,accessories ) >
<!ELEMENT make (#PCDATA)>
<!ELEMENT model (#PCDATA)>
<!ELEMENT year (#PCDATA)>
<!ELEMENT color (#PCDATA)>
<!ELEMENT engine (engin-num,cylinders-num,fuel-type)>
<!ELEMENT chasis-num (#PCDATA)>
<!ELEMENT accessories (#PCDATA)>
<!ATTLIST accessories disc-brake (yes|no) #REQUIRED
auto-start (yes|no) #REQUIRED
radio (yes|no) #REQUIRED>
Example 3.19.2 Consider a hospital management system. Write a DTD program to consolidate
and show the bill to be paid by the inpatients (Assume your own data).
Solution : Patients.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE Patients [
<!ELEMENT Patients (Patient)*>
<!ELEMENT Patient (Name, Address,Test,Date,Doctor,Bill)>
<!ELEMENT Name (#PCDATA)>
<!ELEMENT Address (#PCDATA)>
<!ELEMENT Test (#PCDATA)>
<!ELEMENT Date (#PCDATA)>
<!ELEMENT Doctor (#PCDATA)>
<!ELEMENT Bill (#PCDATA)>
]>
<Patients>
<Patient>
<Name>Anuradha</Name>
<Address>Pune</Address>
<Test>ECG</Test>
<Date>1-1-2010</Date>
<Doctor>Mr.XYZ</Doctor>
<Bill>Rs.500</Bill>
</Patient>
<Patient>
<Name>Archana</Name>
<Address>Mumbai</Address>
<Test>Blood Test</Test>
<Date>10-3-2010</Date>
<Doctor>Mr.PQR</Doctor>
<Bill>Rs.100</Bill>
</Patient>
</Patients>
Merits of DTD
1. DTDs are used to define the structural components of XML document
2. These are relatively simple and compact.
3. DTDs can be defined inline and hence can be embedded directly in the XML
document.
Demerits of DTD
1. The DTDs are very basic and hence cannot be much specific for complex
documents.
2. The language that DTD uses is not an XML document. Hence various
frameworks used by XML cannot be supported by the DTDs.
3. The DTD cannot define the type of data contained within the XML document.
Hence using DTD we cannot specify whether the element is numeric, or string or
of date type.
4. There are some XML processor which do not understand DTDs.
5. The DTDs are not aware of namespace concept.
Review Question
1. Explain the differences between external and internal DTD. SPPU : May-18, Marks 5
The XML schemas are used to represent the structure of XML document.
The goal or purpose of XML schema is to define the building blocks of an XML
document. These can be used as an alternative to XML DTD.
The XML schema language is called as XML Schema Definition (XSD) language.
XML schema defines elements, attributes, elements having child elements, order of
child elements. It also defines fixed and default values of elements and attributes.
XML schema also allows the developer to use data types.
How to write a simple schema ?
Step 1 : We will first write a simple xsd file in which the desired structure of the XML
document is defined. I have named it as StudentSchema.xsd
This file contains the complex type with four child simple type elements.
XML Schema [StudentSchema.xsd]
<?xml version="1.0"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
<xs:element name="Student">
<xs:complexType>
<xs:sequence>
<xs:element name="name" type="xs:string"/>
<xs:element name="address" type="xs:string"/>
<xs:element name="std" type="xs:string"/>
<xs:element name="marks" type="xs:string"/>
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:schema>
Script Explanation :
1. The xs is qualifier used to identify the schema elements and types.
2. The document element of schema is xs:schema. The xs:schema is the root
element. It takes the attribute xmlns:xs which has the value
http://www.w3.org/2001/XMLSchema. This declaration indicates that document
should follow the rules of XML schema. The XML schema rules are defined by
the W3 recommendation in year 2001.
3. Then comes xs:element which is used to define the xml element. In above case
the element Student is of complex type who have four child elements : name,
address, std and marks. All these elements are of simple type string.
Step 2 : Now develop XML document in which the desired values to the XML elements
can be given. I have named this file as MySchema.xml
Program Explanation :
1. In above XML document, the first line is typical in which the version and encoding
is specified.
2. There is xmlns:xsi attribute of document which indicates that XML document is an
instance of XML schema. And it has come from the namespace
“http://www.w3.org/2001/XMLSchema-instance.”
3. To tie this XML document with the some Schema definition we use the attribute
xsi:noNamespace SchemaLocation. The value that can be passed to this attribute is
the name of xsd file “StudentSchema.xsd”.
4. After this we can define the child elements.
XML Document
<?xml version="1.0" encoding="UTF-8"?>
<Date_of_Birth xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="dateType.xsd">
2009-09-01-01:57
</Date_of_Birth>
3. Numeric
If we want to use numeric value for some element then we can use the data types as
either decimal or integer.
Using decimal data type we can specify the value that may contain some decimal
point. We can have another data type called integer which is used to specify the numeric
values that are without any decimal point.
4. Boolean
For specifying the true or false values we must use the boolean data type.
Advantages of schema
Disadvantages of schema
Review Question
1. What are XML schemas ? How are they better than DTDs ? SPPU : May-18, Marks 5
What is DOM ?
Document Object Model (DOM) is a set of platform independent and language neutral
Application Programming Interface (API) which describes how to access and manipulate
the information stored in XML or in HTML documents.
Thus XML DOM is for
Loading the XML document.
Accessing the elements of XML document.
Deleting the elements of XML document.
Changing the elements of XML document.
Step 1 : Open some simple text editor like Notepad and type the following script. I have
named it as first.html
<html>
<!--Simple DOM example for loading some xml file -->
<body>
<script type="text/javascript">
try
{
xmlDocument=new ActiveXObject("Microsoft.XMLDOM");
}
catch(e)
{
try
{
xmlDocument=document.implementation.createDocument("","",null);
}
catch(e) {alert(e.message)}
}
try
{
xmlDocument.async=false;
xmlDocument.load("student.xml");
document.write("XML Document student.xml is loaded");
}
catch(e) {alert(e.message)}
</script>
</body>
</html>
The load function is used to load the desired XML file. Note that when we specify
some xml file for loading then it must be present at the current path. As an illustration the
student.xml file is given as below -
<Subject>Mathematics</Subject>
<Marks>100</Marks>
</student>
Step 2 : Then open some web browser like Firefox or Internet explorer and the output for
the above script can be seen as follows -
Script Explanation
There is an XML parser which reads any XML file. All the modern web browsers like
Internet explorer have built in XML parser. The parser converts the XML into javascript
accessible object. Hence we have mentioned the script type as -
<script type="text/javascript">
The parser reads the XML file, stores it into a memory and converts it into the XML
DOM object. These objects can be accessible by the JavaScript.
Internet Explorer 5 and above have the built in XML parser. Hence in above given
script we have written -
xmlDocument=new ActiveXObject("Microsoft.XMLDOM");
This statement means create an empty XML document object. We have taken this
object in the variable xmlDocument.
After getting the document loaded fully in the memory the parser will continue for
execution of the script, hence we must set -
xmlDocument.async=false;
Then we should specify the name of the xml file which we want to get loaded.
xmlDocument.load("student.xml");
Then by using the document.write we can display the desired message on the web
browser to indicate that the XML file is loaded. Hence we have written
document.write("XML Document student.xml is loaded");
Property Meaning
nodeName Finding the name of the node.
Method Meaning
getElementsByTagName(name) This method is used to access all the elements
that are specified with the tag name.
Let us understand the use of properties and methods with the help of following
example -
<html>
<!-- loading and accessing the contents of xml file -->
<head>
<script type="text/javascript" src="my_function_file.js"></script>
</head>
<body>
<script type="text/javascript">
xmlDocument=My_Function("student.xml");
document.write("xml File loaded and following are the contents of this file -");
document.write("</br>");
document.write("Roll_No :
"+xmlDocument.getElementsByTagName("Roll_No")[0].childNodes[0].nodeValue);
document.write("</br>");
document.write("Name :
"+xmlDocument.getElementsByTagName("Name")[0].childNodes[0].nodeValue);
document.write("</br>");
document.write("Address :
"+xmlDocument.getElementsByTagName("Address")[0].childNodes[0].nodeValue);
document.write("</br>");
document.write("Phone :
"+xmlDocument.getElementsByTagName("Phone")[0].childNodes[0].nodeValue);
document.write("</br>");
document.write("class :
"+xmlDocument.getElementsByTagName("class")[0].childNodes[0].nodeValue);
document.write("</br>");
document.write("Subject :
"+xmlDocument.getElementsByTagName("Subject")[0].childNodes[0].nodeValue);
document.write("</br>");
document.write("Marks :
"+xmlDocument.getElementsByTagName("Marks")[0].childNodes[0].nodeValue);
document.write("</br>");
</script>
</body>
</html>
Output
Script Explanation
xmlDocument.getElementsByTagName("Roll_No")[0].childNodes[0].nodeValue);
This method is used for Tag name The first The value of
accessing the element by from child of the node Roll_No
specifying the tag name student.xml <Roll_No> (i.e. text)
Hence as an output we can see the value of every element. That means the contents of
student.xml file will be displayed.
The XSLT stands for XSL Transformations and XSL stands for eXtensible
Stylesheet Language.
An XSLT is a W3C recommendation.
The XSLT is used for defining the XML document transformations and
presentations. Hence XSL decides how an XML document should look on the web
browser.
XSL consists of three parts :
1. XSLT is a language for transforming XML documents.
2. XPath is a language for navigating in XML documents. In other words we can
reach to any node of XML document using XPath.
3. XSL-FO is a language for formatting XML documents for displaying it in desired
manner.
The XSL document is used along with the application so that particular application can
be displayed on the web browser in some desired manner.
The XSLT document makes use of templates using which particular code can be
described in XML document.
XML document and then particular code in XSLT is executed when the match is found.
XSLT processor processes the XML document sequentially by reading each line one by
one.
The XSLT model can be described as template driven or data driven model.
1. The <xsl:template>
The <xsl:template> is for building the templates.
The match attribute is associated with the template element. The match attribute can
also be used to define a template for the entire XML document. The match="/" defines
the whole document.
In the following example we store the XML elements in the tabular form using the
<xsl:template> and <match>
XML Document[SimpleXml.xml]
<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type="text/xsl" href="SimpleXml.xsl"?>
<Student>
We have defined this
<Person-Details>
<name>Anand</name>
file in step 2
<address>Pune</address>
<std>Second</std>
<marks>70 percent</marks>
</Person-Details>
<Person-Details>
<name>Anuradha</name>
<address>Chennai</address>
<std>Second</std>
<marks>90 percent</marks>
</Person-Details>
<Person-Details>
<name>Archana</name>
<address>Mumbai</address>
<std>Forth</std>
<marks>80 percent</marks>
</Person-Details>
<Person-Details>
<name>Monika</name>
<address>Delhi</address>
<std>Tenth</std>
<marks>77 percent</marks>
</Person-Details>
</Student>
Step 2 : Now create a XSL stylesheet. Note that this document must have file name
extension as .xsl. Open notepad and save following code in it.
<td>**</td>
</tr>
</table>
</body>
</html>
</xsl:template>
</xsl:stylesheet>
Step 3 : Open the web browser and the output will be as follows -
2. The <xsl:value-of>
The value-of is used to extract the value of xml element and add it to output stream of
the XSL transformation. Following example illustrates this :
Step 1 : Keep the same xml[SimpleXml.xml] file which you have created in
section 3.22.2 (1) Step 1.
<trbgcolor="pink">
<td><xsl:value-of select="Student/Person-Details/name"/></td>
<td><xsl:value-of select="Student/Person-Details/address"/></td>
<td><xsl:value-of select="Student/Person-Details/std"/></td>
<td><xsl:value-of select="Student/Person-Details/marks"/></td>
</tr>
</table>
</body>
</html>
</xsl:template>
</xsl:stylesheet>
Step 3 : Open the web browser and the output will be as follows -
3. The <xsl:for-each>
The for-each element allows to traverse through each element of the node
Step 1 : Keep the same xml[SimpleXml.xml] file which you have created in
section 3.22.2(1) Step 1.
<th>Marks</th>
</tr>
<xsl:for-each select="Student/Person-Details" >
<trbgcolor="pink">
<td><xsl:value-of select="name"/></td>
<td><xsl:value-of select="address"/></td>
<td><xsl:value-of select="std"/></td>
<td><xsl:value-of select="marks"/></td>
</tr>
</xsl:for-each>
</table>
</body>
</html>
</xsl:template>
</xsl:stylesheet>
Step 3 : Open the web browser and the output will be as follows -
4. The <xsl:sort>
We can also display the sorted data using <xsl:sort>.
Step 1 : Keep the same xml[SimpleXml.xml] file which you have created in
section 3.22.2 (1) Step 1.
SimpleXml.xsl
<?xml version="1.0" encoding="ISO-8859-1"?>
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="/">
<html>
<body>
<h2>Students Database</h2>
<table border="1">
<trbgcolor="gray">
<th>Name</th>
<th>Address</th>
<th>Standard</th>
<th>Marks</th>
</tr>
<xsl:for-each select="Student/Person-Details">
<xsl:sort select="marks"/>
<trbgcolor="pink">
<td><xsl:value-of select="name"/></td>
<td><xsl:value-of select="address"/></td>
<td><xsl:value-of select="std"/></td>
<td><xsl:value-of select="marks"/></td>
</tr>
</xsl:for-each>
</table>
</body>
</html>
</xsl:template>
</xsl:stylesheet>
Output
5. The <xsl:if>
For selection specific record based on some condition the <xsl:if> is used.
Step 1 : Keep the same xml[SimpleXml.xml] file which you have created in
section 3.22.2(1) Step 1.
6. The <xsl:choose>
The <xsl:choose> element is used along with <xsl:when> and <xsl:otherwise> to express
multiple conditional tests.
Step 1 : Keep the same xml[SimpleXml.xml] file which you have created in
section 3.22.2 (1) Step 1.
1. XML stands for extensible markup XSLT stands for extensible stylesheet language
language. transformations.
2. XML is used to store data in XSLT is used for transforming and formatting
structured format. the XML file.
3. XML does not perform XSLT can transform one XML format into
transformations. another XML format or into HTML or into
plain text.
4. XML contains the user defined tags. XSLT contains special XSL tags and
programming constructs.
5. XML uses the user defined raw data XSLT uses XPath for transformation and
for storage. formatting of XML file.
Review Questions
3.23 Introduction
AJAX is a Asynchronous Java Script and XML
Here
o Asynchronous means, the execution of script does not disturb the user’s work.
o JavaScript because, it makes use of Javascripting to do the actual work.
o XML because along with JavaScript the XML is also supported to perform the given
task in AJAX.
It is not a new programming language but it is a kind of web document which adopts
certain standards.
AJAX allows the developer to exchange the data with the server and updates the part
of web document without reloading the web page.
The server processes this request and sends the required data to the browser.
At the browser side the returned data is processed using JavaScript and the web
document gets updated accordingly by sending the appropriate response.
Following Fig. 3.24.1 illustrates this working.
1. The web applications architectures are based on HTTP request response protocol.
2. At the client side the browser client has At the client side the browser client has user
only one component and that is – user interface and AJAX Engine due to which the
interface. client gets quick response from the server.
5. With traditional web application With AJAX architecture user gets rich user
architecture user cannot get rich user interface experience.
interface experience.
Merits of AJAX
1. Response time is faster, hence increases performance and speed.
2. XMLHttpRequest object call as a asynchronous HTTP request to the Server for
transferring data both side. It's used for making requests to the non-Ajax pages.
3. It is used in form validation.
4. It performs fetching of data from database and storing of data into database
without reloading page.
Demerits of AJAX
Syntax
Variable = new XMLHttpRequest();
Property Description
2: request received
3: processing request
onreadystatechange When readystate property changes the onreadystatechange event listener will
be automatically invoked
status Returns the status number. Following is the meaning of various numbers
returned by the status property
200: “OK”
403: “Forbidden”
Example 3.25.1 Create an XMLHttpRequest to retrieve data from an XML file and display the
data in an HTML table. The data to be retrieved is a collection of stationary items stored in
an XML file.
Solution : Step 1 : Create an xml file storing the stationary items. The code is as follows -
/ELEMENTS>
<STATIONARY>
<ITEM>Notebook</ITEM>
<PRICE>40</PRICE>
</STATIONARY>
<STATIONARY>
<ITEM>Punching Machine</ITEM>
<PRICE>60</PRICE>
</STATIONARY>
<STATIONARY>
<ITEM>Pencil Box</ITEM>
<PRICE>40</PRICE>
</STATIONARY>
<STATIONARY>
<ITEM>Eraser</ITEM>
<PRICE>5</PRICE>
</STATIONARY>
</ELEMENTS>
Step 2 : The XML file displaying the stationary items in a tabular form is as given below -
test.html
<!DOCTYPE html>
<html>
<body>
<button type="button" onclick="loadXMLDoc()">Display Stationary Items</button>
<br><br>
<table id="demo" border="1"></table>
<script>
function loadXMLDoc()
{
if(window.XMLHttpRequest)
{
xmlhttp = new XMLHttpRequest();
}
else
{
xmlhttp = new ActiveXObject("Microsoft.req");//to execute on Inter. Explorer
}
xmlhttp.onreadystatechange = function()
{
if (this.readyState == 4 && this.status == 200) {
myFunction(this);
}
};
xmlhttp.open("GET","stationary.xml",true);
xmlhttp.send();
}
function myFunction(xml)
{
var i;
var xmlDoc = xml.responseXML;
var table="<tr><th>Item</th><th>Price(Rs.)</th></tr>";
var x = xmlDoc.getElementsByTagName("STATIONARY");
for (i = 0; i <x.length; i++)
{
table += "<tr><td>" +
x[i].getElementsByTagName("ITEM")[0].childNodes[0].nodeValue +
"</td><td>" +
x[i].getElementsByTagName("PRICE")[0].childNodes[0].nodeValue +
"</td></tr>";
}
document.getElementById("demo").innerHTML = table;
}
</script>
</body>
</html>
Output
3.26 Coding AJAX Script SPPU : Dec.-18, 19, May-18, 19, Marks 8
Let understand how AJAX works with the help of programming example
<html>
<head>
<script type="text/javascript">
function MyFun()
{
if (window.XMLHttpRequest)
{
req=new XMLHttpRequest(); 2
}
else
{
req=new ActiveXObject("Microsoft.req");
}
req.onreadystatechange=function()
{
if (req.readyState==4 && req.status==200) 3
{
document.getElementById("myID").innerHTML=req.responseText;
}
}
req.open("GET","newdata.txt",true); 4
req.send();
5
}
</script>
</head>
<body>
<div id="myID">This text can be changed</div>
1
<button type="button" onclick="MyFun()">Change</button>
</body>
</html>
4. The request can be sent to the server by using two functions open() and send().
req.open("GET","newdata.txt",true);
newdata.txt
Example 3.26.1 Write AJAX script to obtain the student information stored in XML document.
The information should be displayed on clicking the button. It should be displayed in tabular
form.
Solution :
Step 1 : Create an XML file for storing the student information. The XML file is as follows
Student.xml
<Student>
<student_data>
<Name>AAA</Name>
<Marks>45</Marks>
</student_data>
<student_data>
<Name>BBB</Name>
<Marks>55</Marks>
</student_data>
<student_data>
<Name>CCC</Name>
<Marks>67</Marks>
</student_data>
<student_data>
<Name>DDD</Name>
<Marks>84</Marks>
</student_data>
</Student>
AjaxXMLDemo.html
<!DOCTYPE html>
<html>
<body>
<h1>STUDENT INFORMATION</h1>
<button type="button" onclick="MyFun()">Click</button>
<br><br>
<table border="1" id="demo"></table>
<script>
function MyFun()
{
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function()
{
if (this.readyState == 4 && this.status == 200)
{
Load_XML_File(this);
}
};
xhttp.open("GET", "Student.xml", true);
xhttp.send();
}
function Load_XML_File(xml)
{
var i;
var xmlDoc = xml.responseXML;
var table="<tr><th>Name</th><th>Marks</th></tr>";
var x = xmlDoc.getElementsByTagName("student_data");
for (i = 0; i <x.length; i++)
{
table += "<tr><td>" +
x[i].getElementsByTagName("Name")[0].childNodes[0].nodeValue +
"</td><td>" +
x[i].getElementsByTagName("Marks")[0].childNodes[0].nodeValue +
"</td></tr>";
}
document.getElementById("demo").innerHTML = table;
}
</script>
</body>
</html>
Step 3 : Open the web browser and the output will be as follows -
Example 3.26.2 List and explain different values of ready state and status property of the
HTTPRequestObject.
SPPU : Dec.-18, Marks 6
Solution :
2: request received
3: processing request
400:“Bad Request”
403: "Forbidden"
Review Questions
1. Draw and explain how AJAX works with the help of suitable example.
SPPU : May-18, Marks 6
2. What is use of XMLHttpRequest object ? Explain its use with the help of simple JavaScript
document. SPPU : May-18, Marks 6
3. Write different applications without AJAX and with AJAX. SPPU : May-18, Marks 4
4. Explain with simple example the XMLHttp request object. List and explain different values of
readystate and status property of the HTTP request object. SPPU : May-19, Marks 5
5. What is the purpose of AJAX ? Explain with relevant example. SPPU : Dec.-19, Marks 8
Q.8 What type of servlets use these methods doGet(), doPost(),doHead, doDelete(),
doTrace() ?
a Genereic Servlets b HttpServlets
c All of the above d None of the above
Q.9 Which of the following code is used to get cookies in servlet ?
a response.getCookies() b request.getCookies()
c Cookies.getCookies() d None of the above.
Q.10 If the client has disabled cookie in the browser which session management mechanism
could the web container employ ?
a Session management using URL rewriting
b Session management using Cookies
c Either Cookies or URL rewriting
d Cookies and URL rewriting must be used together
Q.11 Servlet is initialized by calling the following method :
a service() b destroy()
c init() d none
Q.12 Common gateway interface is used to :
a generate executable files from web content by web server
b generate web pages
c stream video
d none
Q.13 The Java _________ specification defines an application programming interface for
communication between the web server and the application program.
a Servlet b Server
c Program d Randomize
Q.14 Which JDBC driver type(s) can be used in either applet or servlet code.
a Both type 1 and type 2 b Both type 1 and type 3
c Both type 3 and type 4 d Type 4 only
Q.15 XML stands for _____ .
a Extensible Markup Language b Extended Markup Language
c XYZ Markup Language d Exclusive Markup Language
Q.16 Correct version of the declaration which defines the XML version _____ .
a <?xml version ="1.0"/> b ?xml version="1.0"?>
c <xml version="1.0"> d none of these
Q.17 XML is _____ .
a platform independent b language independent
c both a and b d none of these
Q.18 Which language is case sensitive ?
a HTML b XML
c Both a and b d None of these
Q.19 DTD stands for _____ .
a Document Trial Data b Document Trial Definition
c Data Type Definition d Document Type Definition
Q.20 XML DOM is a standard for performing the following operation on XML elements ____.
a change b add
c delete d all the above
Q.21 DOM parser is used on _____ .
a client side b server side
c both a and b d none
Q.22 Which are techniques for defining the structure of a specific type of XML documents ?
a Schema b DTD
c Both a and b d none of the above
Q.23 Which statement is true ?
a All the statements are true
b All XML elements must have a closing tag
c All XML elements must be lower case
d All XML documents must have a DTD
Q.24 DTD includes the specifications about the markup that can be used within the
document, the specifications consists of all EXCEPT _____.
a the browser name b the size of element name
c entity declarations d element declarations
Syllabus
JSP : Introduction to Java Server Pages, JSP and Servlets, running JSP applications, Basic JSP,
JavaBeans classes and JSP, Support for the Model-View-Controller paradigm, JSP related
technologies. Web Services : Web Service concepts, Writing a Java Web Service, Writing a Java web
service client, Describing Web Services : WSDL, Communicating Object data: SOAP. Struts :
Overview, architecture, configuration, actions, interceptors, result types, validations, localization,
exception handling, annotations.
Contents
4.1 Introduction to Java Server Pages
4.2 JSP and Servlets ............................................... April-18, .............................. Marks 5
4.3 Basics of JSP ............................................... April-18, May-18, 19,
............................................... Dec.-18, 19,........................... Marks 5
4.4 Implicit Objects ............................................... May-18, 19, Dec.-18, ............ Marks 5
(4 - 1)
Web Technology 4-2 JSP and Web Services
4.18 Validations
4.19 Localization
4.21 Annotations
4.22 Multiple Choice Questions
Part I : JSP
2. JSP runs slower than servlet. Servlet runs faster than JSP.
3. In Model View Controller JSP acts as In Model View Controller servlet acts as
view. controller.
4. JSP can build custom tags. There is no facility of creating custom tags.
5. JSP can directly call Java beans. Servlets have no facility of calling Java bean.
Review Question
1. Write advantages of JSP over servlets. Also explain the life cycle of JSP.
SPPU : April-18, Marks 5
4.3 Basics of JSP SPPU : April-18, May-18, 19, Dec.-18, 19, Marks 5
For example
<jsp:include> This tag works as a subroutine. It includes the response from servlet or
JSP when request is being processed.
<jsp:forward> This tag helps in forwarding the current request to servlet or to JSP page.
<jsp:text> This tag is used to handle template text. When JSP pages are written as
XML documents then this tag is used.
3. Directives : JSP directives control the processing of entire JSP Page. It gives
direction to the server regarding the processing of a page. The directive elements
are enclosed within the <%@ …. %> delimiters. For example -
<%@page import="java.io.*” %>
<%@page language="java” %>
<%@page contentType="text/html” %>
4. Scriptlets : Scriptlets are nothing but java code enclosed within <% and %> tags.
For example we can write following statement in JSP document
<p>
<% out.print("JSP is eqaul to HTML and JAVA "); %> //Scriptlet
</p>
Fig. 4.3.1
Every JSP element is converted into corresponding Java code. This phase is
called translation phase. The output of translation phase is a servlet. For
instance : our xyz.jsp gets converted to xyzServlet.java.
3. This servlet is then compiled to generate the servlet class file. Using this class the
response can be generated. This phase is called request processing phase.
4. The JSP container thus executes the servlet class file.
5. A requested page is then returned to the client as a response. Refer Fig. 4.3.2.
Example 4.3.1 Write a simple JSP page for displaying the message “This is my first JSP
page!!!”
SPPU : May-18, Marks 5
hello.jsp
<%@ page language="java" contentType="text/html" %>
<%@ page import ="java.util.*" %>
<html>
<!-- This is basic JSP page -->
<title>JSP Demo </title>
<body>
<%-- Displaying the message on the browser --%>
<% out.println("This my first JSP page!!!"); %>
</body>
</html>
Step 2 : Copy this file to webapps directory of your tomcat folder.
Step 3 : Start the Tomcat Web server.
Step 4 : Open some suitable web browser like Firefox or Internet Explorer. Type the path
for the JSP document and the output will be as follows -
Script explanation
The first line is the page directive statement
<%@ page language="java" contentType="text/html" %>
using this line we are specifying that the language used in this script is Java and the
contentType specifies the MIME type which is text/html.
Then on the next line we have imported the Java library package java.util using
import statement -
<%@ page import ="java.util.*" %>
We can specify the JSP comments in two ways
<!—HTML style comment statement -->
<%-- JSP comment statement --%>
As JSP is commonly used along with HTML, it also supports the HTML comments.
For displaying the message on the web browser we have written the message using
the Java statement
out.println("This my first JSP page!!!");
Normally any Java code must be written within <% and %>.
Then all the corresponding tags are closed.
4.3.4 Directives
JSP directives control the processing of entire JSP Page. It gives direction to the server
regarding the processing of a page.
Syntax
<%@ directive name [attribute name=“value” attribute name=“value” ........]%>
1. Page directive :
The page directive is used to provide the information about the page. Various
attributes of page directive are -
i) import ii) language iii) ContentType
iv) extends v) session vi) buffer
vii) autoFlush viii) isThreadSafe ix) info
x) errorPage xi) IsErrorPage
For example -
<%@page import="java.io.*” %>
<%@page language="java” %>
<%@page contentType="text/html” %>
2. Include directive :
Include directive is used to copy the content of one JSP page to another. It’s like
including the code of one file into another.
For example
<% @include file=calculate.jsp %>
3. Taglib directive :
This directive basically allows user to use custom tags in JSP. The custom tags are
those which are created by user.
For example -
<%@ taglib uri="mytaglib" prefix="sampletag" %>
Example 4.3.2 Write a JSP program to display current date and time.
Solution : DateDemo.jsp
<%@ page language="java" contentType="text/html" %>
<%@ page import ="java.util.*" %>
<html>
<body>Today's Date is:
<%= new Date().toString() %>
</body>
</html>
Output
4.3.5 Comments
We can specify the JSP comments in two ways
<!—HTML style comment statement -->
<%-- JSP comment statement --%>
As JSP is commonly used along with HTML, it also supports the HTML comments.
1. Expression
The expression tag is used to represent the expression in JSP page. The syntax of
writing expression is -
<%= Java Expression %>
For example -
<html>
<head>
<title>JSP Expression Demo</title>
</head>
<body>
Value of Expression is :
<%= (10*20) %>
</body>
</html>
Output
2. Scriptlet
The code that appears between the <% and %> delimiters is called a scriptlet.
Scriptlets are nothing but java code enclosed within <% and %> tags.
The everything other than a JSP statement in the JSP is called template text. For
example.
Templatetext.jsp
<%@ page language="java" contentType="text/html" %>
<html>
<head>
<title>Demo for Tempplate Text</title>
</head>
<body bgcolor="gray">
<h1>Twinkle Twinkle little stars</h1>
<h2>How I wonder what you are!!!</h2>
<li>like a diamond in the sky</li>
<p>
<% out.print("JSP is eqaul to HTML and JAVA "); %>
</p>
</body>
</html>
In the above code the boldfaced code is a template text. The output for the above code
will be
Output
3. Declaration
We can declare a variable or method in JSP inside declaration tag. We can declare
static member, instance variable and methods inside declaration tag. Syntax of
declaration tag -
<%! Declaration code %>
For example -
<html>
<head>
<title>JSP Declaration Demo</title>
</head>
Output
<%!
String msg = "Hello";
%>
<body>
Message is:
<% out.println(msg); %>
</body>
</html>
The above JSP code contains the declaration within <%! %> tag.
Example 4.3.3 Develop a simple JSP application that accepts user’s age and displays a message
according to the following rules :
i) Age<15 : Message : You are a kid!
ii) Age between 16 and 40 : You are young!
iii) Age above 40 : You are old!
Solution : For developing this application we will create an HTML form for inputting the
age value and then invoke the JSP page on which the appropriate messages are given
based on the age.
Step 1 :
InputAge.html
<html>
<head>
</head>
<body>
<form method="get" action="AgeMessage.jsp">
<strong>Enter Age:</strong>
<br/>
<input type="text" name="Age">
<br/>
<input type="submit" value="Enter">
</form>
</body>
</html>
Step 2 : The JSP code is as follows -
AgeMessage.jsp
<html>
<body>
<%@ page language="java" contentType="text/html" %>
<%@page import="java.io.*" %>
<%
String msg="";
String age;
int age_val;
age=request.getParameter("Age");
age_val=Integer.parseInt(age);
if(age_val<15)
msg+="You are a kid!";
if((age_val>16)&&(age_val<40))
msg+="You are young!";
if(age_val>40)
msg+="You are old!";
out.println("<h3>"+msg+"</h3>");
%>
</body>
</html>
Example 4.3.4 Write a JSP scriptlet for displaying even numbers between 1 to 50.
Solution :
<html>
<body>
<%@ page language="java" contentType="text/html"%>
<%@ page import="java.io.*"%>
<%
for(int i=1;i<=50;i++)
{
if(i%2==0)
out.println("<p>"+i+"</p>");
}
%>
</body>
</html>
<jsp:setProperty> This tag is used to set the property value for the java bean.
<jsp:getProperty> This tag is used to get the property value from the java bean.
<jsp:include> This tag works as a subroutine. It includes the response from servlet or
JSP when request is being processed.
<jsp:param> For adding the specific parameter to the request this tag is used. Normally
this tag is used inside <jsp:include> or <jsp:forward>
<jsp:forward> This tag helps in forwarding the current request to servlet or to JSP page.
<jsp:plugin> This tag is used to generate HTML code and to embed the applet into it.
<jsp:text> This tag is used to handle template text. When JSP pages are written as
XML documents then this tag is used.
Let us now discuss the standard actions by creating appropriate JSP pages.
Include action
Using the <jsp:include> action we can include different files in current jsp pages.
For example -
Include_action.jsp
<html>
<head>
<title> Include action Demo </title>
</head>
<body>
<h1>This page contains include action</h1>
<jsp:include page="test_include.html" />
<jsp:include page="test_jsp.jsp" />
</body>
</html>
test_include.html
<html>
<body>
Hello How are you?
</body>
</html>
Now the JSP page for displaying dynamic content is
test_jsp.jsp
<html>
<body>
<br>Time is <%= new java.util.Date().getHours()%>
: <%= new java.util.Date().getMinutes()%>
</body>
</html>
For getting the output, open the web browser and open our main JSP page
Include_action.jsp, it is as follows-
Forward action
Using forward action we can forward the current request to corresponding
JSP page or servlet.
Here is a simple demonstration in which we have created two web pages
the first one is a main JSP page named as first.jsp in which we are using JSP
action forward. And forwarding the current request to an HTML page
which is named as Second.html.
first.jsp
<html>
<head>
<title> Forward action Demo </title>
</head>
<body>
<h1>This page contains forward action</h1>
<jsp:forward page="Second.html" />
</body>
</html>
Second.html
<html>
<body>
<strong>You are forwarded to Second page!!</strong>
</body>
</html>
For getting the output open the web page and open the main JSP page that is first.jsp
and you will get the following output -
Output
useBean action
Java beans are reusable components. We can use simple Java bean in the JSP.
Beans are used in the JSP pages as the instance of class. We must specify the scope
of the bean in the JSP page. Here scope of the bean means the range time span of the
bean for its existence in JSP.
Bean is basically a Java class with get and set methods.
Let us understand the useBean action with illustrative example.
Example 4.3.5 Write a JSP document to display number of times user is visiting particular
page.
Solution :
Step 1 : Create a simple bean in which a variable count is maintained. This count can be
incremented using the JSP page.
CounterDemo.java
public class CounterDemo
{
public int count;
public CounterDemo()
{
count=0;
}
public int getCount()
{
return count;
}
public void setCount(int count)
{
this.count=count;
}
}
Step 2 : Now create a JSP page which make use of the bean created in step 1 in the
session scope.
beanJsp1.jsp
<html>
<head>
<title> Use of Bean with session scope </title>
</head>
<body>
<jsp:useBean id="bean_id" class="CounterDemo" scope="session" />
<%
bean_id.setCount(bean_id.getCount()+1);
%>
Your count is now <%= bean_id.getCount() %>
</body>
</html>
Step 3 : Open two different web browsers Mozilla Firefox and Internet Explorer and
open the same JSP page in both the browsers, repeatedly refresh the JSP page in
both the browsers and observe it.
Example 4.3.6 Write the differences between include action and include directive in JSP.
SPPU : Dec.-18, May-19, End Sem, Marks 5
Review Questions
The implicit objects are predefined variables used to access request and application
data. These objects are used by the scripting elements. Following is a list of implicit
objects.
Variable Class/Interface name Meaning Sample methods
name
setContentType()
getSession()
Review Questions
1. Create a simple JSP pages which will demonstrates use of implicit session objects in JSP.
SPPU : May-18, Dec.-18, Marks 5
2. List and elaborate any five JSP implicit objects.
SPPU : May-19, Marks 5
Java beans are reusable components. We can use simple Java bean in the JSP.
Beans are used in the JSP pages as the instance of class. We must specify the scope
of the bean in the JSP page. Here scope of the bean means the range time span of the
bean for its existence in JSP.
Bean is basically Java class with getXX and setXX methods.
JavaBean Properties
A JavaBean Property is a named attribute that can be accessed using the object.
The JavaBean properties can be accessed through two methods namely
1) getPropertyName() : This method is called accessor method. It returns the
property value. This method is written in some special way. For example - If the
property is rollNo then the method name for rollNo is getRollNo()
2) setPropertyName() : This is called mutator method. This method is generally
used to assign the value to the properties. This method is written in some special
way. For example - If the property is rollNo then method name will be
setRollNo()
The read-only attribute is for getPropertyName() method and write-only attribute is
for setPropertyName() method.
Example : Bean program using JSP for Employee Information.
Step 1 : Create a Bean program in some package. I have created a folder(as a package)
named BeanProg. The code for JavaBean class is written as follows -
Employee.java
package BeanProg;
public class Employee implements java.io.Serializable {
private String empName=null;
private int empNo=0;
public Employee() { //no argument constructor
}
public String getEmpName() {
return empName;
}
public int getEmpNo() {
return empNo;
}
public void setEmpName(String empName) {
this.empName=empName;
}
public void setEmpNo(int empNo) {
this.empNo=empNo;
}
}
Example 4.5.1 Write a client server JSP program to find the simple interest and display the
result in the client.
Input.html
<html>
<head><title>Input Form</title></head>
<body>
Enter following values:<br/>
<form method="post" action="interest.jsp">
Amount:<input type="text" name="amount" value="" size="10"/>
Period:<input type="text" name="period" value="" size="3"/>
Rate of Interest:<input type="text" name="rate" value="" size="3"/>
<input type="submit" value="Submit"/>
</form>
</body>
</html>
Step 2 : Create JSP page which acts as a client to receive the values for P,N and R.
These values will be sent to the server Java program for calculating the simple interest.
The calculated interest value is displayed by this same JSP page. The code for this is as
follows -
Interest.jsp
<html>
<head>
<title> Simple Interest Calculation Demo </title>
</head>
<body>
<jsp:useBean id="bean_id" class="interestcalcDemo.InterestDemo" scope="session" />
<% String s_p=request.getParameter("amount");
int p=Integer.parseInt(s_p);
bean_id.setP(p);
Calling server Java program for
String s_n=request.getParameter("period"); computing the simple interest.
int n=Integer.parseInt(s_n);
bean_id.setN(n);
Collecting values from input.html
String s_r=request.getParameter("rate");
created in Step 1 and sending them to
int r=Integer.parseInt(s_r);
bean_id.setR(r); sever program using method set
%>
</form>
Obtaining interest
Amount = <%= p%><br/>
Period = <%= n%><br/> value from server
Rate = <%= r%><br/>
<strong>Interest is now <%= bean_id.getI() %><br/></strong>
</body>
</html>
Step 3 : Following is a Java bean program which acts as a Server. It calculated the simple
interest using the formula (p*n*r)/100. This value is then returned to the client JSP
program created in Step 2. The code for server java program is as follows -
InterestDemo.java
package interestcalcDemo;
public class InterestDemo Output
{
public int p,n,r;
public InterestDemo()
{
p=0;n=0;r=0;
}
public int getI()
{
int i=(p*n*r)/100;
return i;
}
public void setP(int p)
{
this.p=p;
}
public int getP()
{
return p;
}
public void setN(int n)
{
this.n=n;
}
public int getN()
{
return n;
}
public void setR(int r)
{
this.r=r;
}
public int getR()
{
return r;
}
}
Review Question
1. What is the JSP action tags ? Discuss in details jsp:useBean action tag.
SPPU : May-18, Marks 5
According to the MVC design model, the model corresponds to business logic, view
corresponds to presentation and controller corresponds to request processing.
Advantages of using MVC design model
The use of MVC architecture allows the developer to keep the separation between
business logic, presentation and request processing.
Due to this separation it becomes easy to make changes in presentation without
disturbing the business logic. The changes in presentation are often required for
accommodating the new presentation interfaces.
Review Question
1. What is MVC ? Draw and explain MVC architecture for developing web applications.
SPPU : Dec.-18, Marks 6
Definition : The Web Services are the software systems that are displayed by the
web browser using the web protocol. These software systems are used by the some
software applications rather than by end-users directly.
At the lowest level of web services there are simply XML files that are for data level
description.
SOAP - Simple Object Access Protocol is a simple XML based protocol which
allows exchange of messaging over HTTP.
Typically web services make use of this protocol for exchange of information .
o The SOAP makes use of JAX-RPC component. These are JAVA API for XML
that makes use of Remote Procedure Calls.
o Basically SOAP defines message structure, encoding rules and conventions for
exchange of information in RPC programming model.
o The following table describes core JAX-RPC interfaces and classes.
Service Main client interface. Used for both static and dynamic
invocations.
At the higher level very important element of web service lies i.e. WSDL. The Web
Service Description Language is used for abstract description of web services. This
description is provided in XML document. When the client wants to make use of
web service, the users of the client make read this description file and understand
what input data is needed to perform the web service. Such a special file is called
WSDL i.e. Web Services Description Language.
UDDI i.e. Universal Description and Discovery Integration, provides a directory of
web services, so that client can easily discover the services of their choices. The
UDDI maintains a registry in which the web services are registered.
In this chapter we will learn how to develop a simple web service using JAX-RPC.
Further we will learn how to build a web client for using this service.
Review Questions
Prerequisite :
1) JDK must be installed.
2) Eclipse must be installed
3) Apache Server, Tomcat must be installed. Install the software package XAMPP
for this purpose.
Configuring Tomcat to Eclipse
Step A : To integrate Tomcat Server with your Eclipse, Select File->New->Other… from
Eclipse main menu.
Step B : Select Server->Server and click Next
Step 4 : Set the location of Axis2 folder with the help of Browse.. button. It is your
Webapps folder in Tomcat directory. On successful deploying of Axis2, we get “Axis2
runtime loaded successfully” message. Click Apply and then Ok button.
Following screenshot illustrates it.
Let us now discuss step by step - how to create a simple Web Service.
Example 4.8.1 Create a web service in java environment to return the sum of two integers with
necessary deployment procedures.
Solution :
Step 1 : Click on Eclipse icon. Click on File->New->Dynamic Web Project. Give the
suitable name to the project. I have given the project name as WebService. Set the Tomcat
Web Server and appropriate version number. Following screenshot illustrates this.
A New Class Window opens up. Give suitable Package name, Class name and
uncheck the check box for void main function. Then click Finish button. It is illustrated
by following screenshot.
return a+b;
}
}
Save the above code.
Step 4 : Now right click on src folder. Click New->other->Web Services->Web Service.
Then click Next button.
The Web Services window will appear. Write the name of service implementation and
click on Web service runtime:Apache Axis. Following screenshot shows this -
Click on Apache Axis2 and then click Ok button. Refer following screenshot.
Then click on Finish button. You will get the progress window as,
3. Now click on Services. Your Web Service name MyServer can be located on the
page.
4. Just click on MyServer link another web page will be opened up in the browser.
This is actually your WSDL file. Copy the full URL for WSDL file marked in screenshot
given below. Save this URL in some Notepad file. Note that: We need this URL during the
creation of Client.
Step 6 : Now go to File->New->Dynamic Web Project. Give suitable name for your
application. Here we are creating a client for the Web service created in above steps.
Hence I have given the name WebServiceClient. Then click Finish button.
Step 7 : Now under WebServiceClient, right click on src folder. Click on New->Other->
Web Services->Web Service Client
Click the Next button. Now on Web Services window. Copy the URL of WSDL which
you have copied in Step 5(4).
Then Select Web Service runtime:Apache Axis. Set it to Apache Axis2 click OK
button. Then Click on Finish button. You will get Progress Information and then two files
will get generated. These are as shown in following screenshot.
Step 8 : Now right click on src folder of WebServiceClient. Click on New->Class. The
New Java Class window will appear. Set appropriate package name, class name and
Check for void main method. Here is the screenshot.
Click on Finish button. You can now write the Java Client code for web service. The
code is as follows,
MyClient.java
package com.mypackage;
import com.mypackage.MyServerStub.Add;
import com.mypackage.MyServerStub.AddResponse;
Step 8 : Right click on MyClient.java file in Project Explorer. Click on Run As -> Java
Application
Troubleshooting :
We may get following error on running the above client
Exception in thread "main" org.apache.axis2.AxisFault:…
…
…
To overcome through this Exception, we need to make some changes in services.xml
file. It can be located in the Web Services folder. To locate this xml file, follow the path as
Web Content-> WEB-INF-> Services->MyServer->META-INF. Locate services.xml
Change following lines
<messageReceivermep=http://www.w3.org/2004/08/wsdl/in-only
class="org.apache.axis2.rpc.receivers.RPCInOnlyMessageReceiver" />
<messageReceivermep=http://www.w3.org/2004/08/wsdl/in-out
class="org.apache.axis2.rpc.receivers.RPCMessageReceiver"/>
To
<messageReceivermep=http://www.w3.org/ns/wsdl/in-only
class="org.apache.axis2.rpc.receivers.RPCInOnlyMessageReceiver"/>
<messageReceivermep=http://www.w3.org/ns/wsdl/in-out
class="org.apache.axis2.rpc.receivers.RPCMessageReceiver"/>
Stop the Apache Tomcat Server and start it again. Now Run your MyClient.java file as
Java Application and you will get the required output.
Elements Description
types It specifies the data types of the symbols used by the web service.
portType It specifies the name of the operation (function) defined by the web service
binding It specifies the name of the protocol of the web service, typically it is SOAP.
1) Types
If we declare and use some variable in the web service then their data types can be
specified.
For example -
<?xml version="1.0" encoding="UTF-8"?>
<definitions name="SimpleCalculator" targetNamespace="http://tempuri.org/wsdl" >
<types>
<schema targetNamespace="http://tempuri.org/types">
<import namespace="http://schemas.xmlsoap.org/soap/encoding/"/>
<complexType name="CalciClass">
<sequence>
<element name="operator1" type="double"/>
<element name="operator2" type="double"/>
<element name="operation" type="String"/>
</sequence>
</complexType>
</schema>
</types>
2) Messages
The messages define the part of the element along with the data types. The message
name specified the name of the function.
In following example the HelloFun is a name of the function which is declared in the
interface named MyInterface. The return parameter is specified by
name="MyInterface_HelloFunResponse".
For example -
<?xml version="1.0" encoding="UTF-8"?>
<definitions name="SimpleHelloMessage" targetNamespace="http://tempuri.org/wsdl" >
<types/>
<message name="MyInterface_HelloFun">
<part name="String_1" type="xsd:string"/>
</message>
<message name="MyInterface_HelloFunResponse">
<part name="result" type="xsd:string"/>
</message>
3) PortTypes
This is an important element of the WSDL file. It defined various operations that can
be performed by the web service.
one-way This operation will send the message but it will not get any response.
request-response This operation will send a message and will receive a response.
Solicit-response This operation will send a message and will wait for a response.
Notification This operation will send a message and will not wait for a response.
The messages in portTypes define the name of the operation along with the prefix tns
where tns stands for TypeNamespace.
4) Binding
The binding defines the message format and details of the protocol.
<?xml version="1.0" encoding="UTF-8"?>
<definitions name="SimpleHelloMessage" targetNamespace="http://tempuri.org/wsdl" >
<types/>
…
…
xmlns:soap="http://www.w3.org/2001/12/soap-envelope".
The encoding style is useful to define the data types used in the document. For
example the value of encoding can be given as -
soap:encodingStyle=“http://www.w3.org/2001/12/soap-encoding”
2) Header
The SOAP header field is optional. It contains the header information. The header
contains three attributes such as mustUnderstand, actor and encodingStyle
The mustUnderstand attribute specifies 0 or 1. If the value is 1 then it means that the
receiver should process the header.
Normally the SOAP message travels over a message path having the endpoints at the
two ends. The SOAP actor is used to specify the URI for this endpoint.
The encodingStyle is useful to define the data types used in the document
The SOAP header defines how the recipient should process the SOAP message.
3) Body
The required SOAP Body element contains the actual SOAP message intended for the
ultimate endpoint of the message.
4) Fault
This is optional element of the SOAP message. It is used to represent the error code. It
consists of elements such as faultcode which is a code for fault. The faultstring message
gives the details about the fault.
SOAP-ENV:encodingStyle="http://www.w3.org/2001/12/soap-encoding">
<SOAP-ENV:Body xmlns:m="http://www.mywebsite.com/mycreation">
<m:GetDetails>
<m:Name>ABCD</m:Name>
</m:GetDetails>
</SOAP-ENV:Body>
</SOAP-ENV:Envelope>
The SOAP response can be
HTTP/1.0 200 OK
Content-Type: text/xml; charset=utf-8
Content-Length: 500
<?xml version="1.0"?>
<SOAP-ENV:Envelope
xmlns:SOAP-ENV="http://www.w3.org/2001/12/soap-envelope"
SOAP-ENV:encodingStyle="http://www.w3.org/2001/12/soap-encoding">
<SOAP-ENV:Body xmlns:m="http://www.mywebsite.com/mycreation">
<m:GetDetailsResponse>
<m:ItemDetails>This is a my new creation</m:ItemDetails>
</m:GetDetailResponse>
</SOAP-ENV:Body>
</SOAP-ENV:Envelope>
For example - Following is a soap document sent by the client to display message web
service.
<?xml version=”1.0” encoding =”UTF-8”?>
<env:Envelop
xmlns:env=”http://schemas.xmlsoap.org/soap/envelop/”
xmlns:xsd=”http://www.w3.org/2001/XMLSchema”
xmlns:xsi=”http://www.w3.org/2001/XMLSchema-instance”
xmlns:enc=”http:// schemas.xmlsoap.org/soap/encoding/”
xmlns:ns0=”http://tempuri.org/wsdl”
xmlns:ns1=”http://tempuri.org/types”
env:encodingStyle=”http:// schemas.xmlsoap.org/soap/encoding/”>
<env:Body>
<ns0:HelloMsg> Call to procedure which is RPC
<msg_1 xsi: type=:xsd:string”>Welcome</msg_1>
</ns0:HelloMsg>
</env:Body>
</env:Envelop>
Struts is a framework software used for developing the Java Web Applications.
The struts framework was initially created by Craig McClanahan and donated to
Apache Software Foundation.
It is an open source product.
The latest commonly used release is struts 2.
Features
1. It is based on Model view Controller (MVC) architecture.
2. The action class is POJO (Plain Old Java Object) that means it is a simple Java
class.
3. Struts2 provides the support to AJAX technology. That means only required field
can be sent to the server and no need to send entire page. Due to this feature the
execution is fast.
4. The struts2 framework can be integrated with other applications like Hibernate,
Spring and so on.
5. Struts2 provides tag support such as UI tags, Data tags, control tags etc.
6. It provides support for views and templates.
7. Struts2 support multiple views for the same application.
Advantages of Struts
1. The complex web applications can be built using simple Model, View and
Controller components.
2. The designs made using struts are simpler, consistent and easy to maintain.
Review Question
The struts framework is based on Model, View and Controller architecture (MVC).
I. Normally when client wants any web page he demands it using get or post
request or by clicking Submit button, then a controller is invoked.
II. A Controller is nothing but a Java class in which business logic is written. The
job of Controller is to take user input and pass it to the Model. The controller in
turn invokes the Model.
III. Model stores the user's data may be in databases or so, and returns some result
to the Controller.
IV. Using this result, the Controller figures out user requirements and accordingly
forwards the result to the View page.
V. Finally required view can be obtained as a response (i.e. a display of required
web page is obtained) on the web browser. This can be diagrammatically shown
as below -
Fig. 4.12.1
In struts,
o Model components provide a model for "business logic" and data behind struts
program.
o View components in struts are those components that present the information
to the user or accept the user input. Typically these components are JSP or
HTML pages. View components are responsible for providing the display of
required information. Struts provide large number of JSP custom tags or struts
tags to simplify the development of view components.
o Controllers are the Java classes which allow developers to remove error
handling activities from JSP pages. These classes are typically referred as action
classes.
Review Question
1. Draw and explain neat diagram which depicts MVC to the struts architecture.
SPPU : May-18,19, Marks 6
Step 2 : Now copy the Jar files present in the c:\struts-2.2.34\lib folder to our
project's WEB-INF\lib folder. Following files need to be copied
commons-fileupload-1.3.2
commons-io-2.2
commons-lang-2.4
commons-lang3-3.2
commons-logging-1.1.3
freemarker-2.3.22
javassist-3.11.0.GA
ognl-3.0.21
struts2-core-2.3.34
xwork-core-2.3.34
Step 3 : Now create an action class which is a Java class. It should be created under
Java-Resourcs->src folder. Under src folder create a package with suitable
name. I have created package named myPkg and Java source class as
MyBigHello.java. The code for this is as follows -
MyBigHello.java
package myPkg;
public class MyBigHello {
private String name;
public String execute() throws Exception {
return "success";
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
The action class gets executed when user clicks the URL. Based on it, the JSP page will
be displayed.
Step 4 : Now we will create a view page. I have named it as MyHello.jsp. in the
WebContent folder in your eclipse project. To do this, right click on the
WebContent folder in the project explorer and select New >JSP File.
MyHello.jsp
<%@ page contentType = "text/html; charset = UTF-8" %>
<%@ taglib prefix = "s" uri = "/struts-tags" %>
<html>
<head>
<title>My First Struts Demo Application</title>
</head>
<body>
<h3>Welcome my friend, <s:property value = "name"/></h3>
</body>
</html>
In above code, the taglib directive tells us the Servlet container that this page is using
Struts 2 tag and the tags will be preceded by s.
The name property define in MyBigHello.java class will be returned by the function
getName() of MyBigHello class.
Step 5 : Now we will create the main page. In struts 2 the main page is denoted by
index.jsp in the WebContent folder. This file serves as the initial action
URL and calls the method defined in MyBigHello class, accordingly the
display of MyHello.jsp page will be updated.
index.jsp
<%@ page language = "java" contentType = "text/html; charset = ISO-8859-1"
pageEncoding = "ISO-8859-1"%>
<%@ taglib prefix = "s" uri = "/struts-tags"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>My First Struts Demo Application</title>
</head>
<body>
<h2>My Struts2 Application</h2>
<form action = "hello">
<label for = "name">Enter your name</label><br/>
<input type = "text" name = "name"/>
<input type = "submit" value = "Submit"/>
</form>
</body>
</html>
The hello action defined in the above view file will be mapped to the MyBigHello
class and its execute method using struts.xml file. When a user clicks on the Submit
button it will cause the Struts 2 framework to run the execute method defined in the
MyBigHello class and based on the returned value of the method, an appropriate view
will be selected and rendered as a response.
Step 6 : There is a file that ties MyBigHello class(model) with MyHello(view). This
file is struts.xml. This file must be present in the classes folder. Hence
under WebContent/WEB-INF, create a folder named classes and add new
file named struts.xml. The code for this file is
struts.xml
<?xml version = "1.0" encoding = "UTF-8"?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
"http://struts.apache.org/dtds/struts-2.0.dtd">
<struts>
<constant name = "struts.devMode" value = "true" />
<package name="default" extends="struts-default">
<action name = "hello"
class = "myPkg.MyBigHello"
method = "execute">
<result name = "success">/MyHello.jsp</result>
</action>
</package>
</struts>
Step 7 : Now create web.xml i.e. deployment descriptor file. This file acts as an
entry point for the request made by struts 2. The entry point will be filer
defined. Hence, we will define an entry of
org.apache.struts2.dispatcher.FilterDispatcher class in web.xml. The
web.xml file needs to be created under the WEB-INF folder under
WebContent. The web.xml generated by Eclipse can be modified as -
web.xml
<?xml version = "1.0" encoding = "UTF-8"?>
<web-app xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance"
xmlns = "http://java.sun.com/xml/ns/javaee"
xmlns:web = "http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
xsi:schemaLocation = "http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
id = "WebApp_ID" version = "3.0">
<display-name>Struts 2</display-name>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
<filter>
<filter-name>struts2</filter-name>
<filter-class>
org.apache.struts2.dispatcher.FilterDispatcher
</filter-class>
</filter>
<filter-mapping>
<filter-name>struts2</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
</web-app>
ii) Now run the Tomcat Web server. By selecting the Run configurations… from
the Menu bar of Eclipse. Select the Apache, under which select the Tomcat server
which is same as the Tomcat server which you have already installed on your
computer. I have selected Tomcat v7.0 as the version of my already installed
Tomcat. Then as a destination select the path of your tomcat directory. After
finishing this the Tomcat web server gets started.
The output can be displayed on the web browser as
There are two main configuration files used in struts and those are struts.xml and
web.xml.
There is struts.properties file is used to override the default values of default.xml file
provided by struts framework. So it is not mandatory.
struts.xml
The struts.xml file is used to initialize the resources such as inceptors, Actions classes.
This file is present inside the WEB-INF/classes folder.
The structure of this file is
<?xml version = "1.0" Encoding = "UTF-8"?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
"http://struts.apache.org/dtds/struts-2.0.dtd">
<struts>
<constant name = "struts.devMode" value = "true" />
<package name = "FirstStrutDemo" extends = "struts-default">
</package>
<-- more packages can be listed here -->
</struts>
1) Package Element
The package element specifies module or your project name.
It has following attributes -
i) name : The name must define the package
ii) namespace : This is optional attribute. If namespace is not present, / is assumed
as the default namespace.
iii) extends : The package element mostly extends the struts-default package where
interceptors and result types are defined.
2) Action Element
This element represents action. Various attributes of this element are -
i) name : This is any name with which the action is associated.
ii) class : The name of the action class is specified. This name must be accompanied
with the package name inside which the action class is defined.
iii) method : This is optional field. By default the execute method is associated with
this attribute.
iv) result name : The result name can be success, error and so on. In struts, on result
element the page to be displayed on success or error is specified.
web.xml
The web.xml is a configuration file which determines how elements of the HTTP
request are processed by the servlet container. It is not strictly a Struts2 configuration file,
but it is a file that needs to be configured for Struts2 to work.
The web.xml file needs to be created under the folder WebContent/WEB-INF.
This file contains the <welcome-file-list> tag using which the first file to be loaded on
execution of struts project is specified. For example
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
The simple meaning of above code is that as soon as you execute your struts
application, load the index.jsp file.
<filter-mapping>
<filter-name>struts2</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
The above code indicates that <url-pattern> is /* means that all urls will be parsed by
the struts filter.
Review Question
1. What are the different configuration files are require to develop any struts application ?
Explain each configuration file.
SPPU : Dec.-18, 19, Marks 6
Actions are important element of struts application. The actions are basically the
Java programs that contain the processing logic and satisfy the requests made by
the user.
Step 3 : Now create an action class which is a Java class. It should be created under
Java-Resourcs->src folder. Under src folder create a package with suitable
name. I have created package named myPkg and Java source class as
MyBigHello.java. The code for this is as follows -
MyBigHello.java
package myPkg;
public class MyBigHello {
private String name;
public String execute() throws Exception {
return "success";
}
index.jsp
<%@ page language = "java" contentType = "text/html; charset = ISO-8859-1"
pageEncoding = "ISO-8859-1"%>
<%@ taglib prefix = "s" uri = "/struts-tags"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>My First Struts Demo Application</title>
</head>
<body>
<h2>My Struts2 Application</h2>
<form action = "hello">
<label for = "name">Enter your name</label><br/>
<input type = "text" name = "name"/>
<input type = "submit" value = "Submit"/>
</form>
</body>
</html>
The hello action defined in the above view file will be mapped to the MyBigHello
class and it executes method using struts.xml file. When a user clicks on the Submit
button it will cause the Struts 2 framework to run the execute method defined in the
MyBigHello class and based on the returned value of the method, an appropriate view
will be selected and rendered as a response.
Step 5 : Create a file named struts.xml. This file must be present in the classes
folder. Hence under WebContent/WEB-INF, create a folder named classes
and add new file named struts.xml. The code for this file is
struts.xml
<?xml version = "1.0" encoding = "UTF-8"?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
"http://struts.apache.org/dtds/struts-2.0.dtd">
<struts>
<constant name = "struts.devMode" value = "false" />
<package name="default" extends="struts-default">
<action name = "hello"
class = "myPkg.MyBigHello"
method = "execute">
<result name = "success">/MyHello.jsp</result>
<result name = "error">/AccessDenied.jsp</result>
</action>
</package>
</struts>
The struts.xml is a file that ties MyBigHello class(model) with MyHello(view). This
MyHello.jsp file is basically a view file. It is created in next step.
Step 6 : We will create a view page. I have named it as MyHello.jsp. in the
WebContent folder in your eclipse project. To do this, right click on the
WebContent folder in the project explorer and select New >JSP File.
MyHello.jsp
<%@ page contentType = "text/html; charset = UTF-8" %>
<%@ taglib prefix = "s" uri = "/struts-tags" %>
<html>
<head>
<title>My First Struts Demo Application</title>
</head>
<body>
<h3>Welcome my friend, <s:property value = "name"/></h3>
</body>
</html>
The name property define in MyBigHello.java class will be returned by the function
getName() of MyBigHello class.
Step 7 : If we do not enter the name as "Admin" then the error page will be displayed as
AccessDenied.jsp
<%@ page contentType = "text/html; charset = UTF-8" %>
<%@ taglib prefix = "s" uri = "/struts-tags" %>
<html>
<head>
<title>Access Denied</title>
</head>
<body>
Error!!!You are not allowed to view this page
</body>
</html>
Step 8 : Now create web.xml i.e. deployment descriptor file. This file acts as an entry
point for the request made by struts 2. The entry point will be filer defined.
Hence, we will define an entry of
org.apache.struts2.dispatcher.FilterDispatcher class in web.xml. The
web.xml file needs to be created under the WEB-INF folder under
WebContent. The web.xml generated by Eclipse can be modified as -
web.xml
<?xml version = "1.0" encoding = "UTF-8"?>
<web-app xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance"
xmlns = "http://java.sun.com/xml/ns/javaee"
xmlns:web = "http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
xsi:schemaLocation = "http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
id = "WebApp_ID" version = "3.0">
<display-name>Struts 2</display-name>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
<filter>
<filter-name>struts2</filter-name>
<filter-class>
org.apache.struts2.dispatcher.FilterDispatcher
</filter-class>
</filter>
<filter-mapping>
<filter-name>struts2</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
</web-app>
For understanding the location of above files I am giving the following screen-shot.
Note that these files must be created in respective folders only -
If we enter other than Admin, here I have given the name as 'Parth' and then -
Review Question
1. Identify and explain data tags from struts2 which are used to manipulate data displayed on any
web application page.
SPPU : Dec.-18, May-19, Marks 6
Advantages of Interceptors
Step 3 : Inside the Java Resources-> src folder create a package(I have created
myPkg package). Inside that package create a Java class for inceptor named
MyInterceptor as follows -
MyInterceptor.java
package myPkg;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.AbstractInterceptor;
public class MyInterceptor extends AbstractInterceptor{
public String intercept(ActionInvocation invocation)throws Exception {
System.out.println("Before Execution");
String result = invocation.invoke(); Remember these interceptors will
System.out.println("After Execution");
shows the result in the console
return result;
} automatically
}
Step 4 : Now create the Java class as action class in which execute() method is
defined. Again this class is created inside the user defined package of src
folder. The code for this is as follows -
Test.java
package myPkg;
import com.opensymphony.xwork2.ActionSupport;
public class Test extends ActionSupport{
private String name;
public String execute() throws Exception {
System.out.println("Inside execute() method!!!");
return "success";
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
Step 5 : Now we will create a view page. I have named it as MyHello.jsp in the
WebContent folder in your eclipse project. To do this, right click on the
WebContent folder in the project explorer and select New >JSP File.
MyHello.jsp
<%@ page contentType = "text/html; charset = UTF-8" %>
<%@ taglib prefix = "s" uri = "/struts-tags" %>
<html>
<head>
index.jsp
<%@ page language = "java" contentType = "text/html; charset = ISO-8859-1"
pageEncoding = "ISO-8859-1"%>
<%@ taglib prefix = "s" uri = "/struts-tags"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>Struts Inceptor Demo Application</title>
</head>
<body>
<h2>My Struts2 Application</h2>
<form action = "hello">
<label for = "name">Enter your name</label><br/>
<input type = "text" name = "name"/>
<input type = "submit" value = "Submit"/>
</form>
</body>
</html>
Step 7 : Create the configuration file struts.xml as follows-
struts.xml
<?xml version = "1.0" encoding = "UTF-8"?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
"http://struts.apache.org/dtds/struts-2.0.dtd">
<struts>
<constant name = "struts.devMode" value = "true" />
<package name="default" extends="struts-default">
<interceptors>
<interceptor name = "myinterceptor"
Step 8 : The configuration file web.xml will invoke the index.jsp file. It is present
inside WEB-INF folder. Just modify the web.xml file as follows -
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
<display-name>InceptorDemo</display-name>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
<filter>
<filter-name>struts2</filter-name>
<filter-class>
org.apache.struts2.dispatcher.FilterDispatcher
</filter-class>
</filter>
<filter-mapping>
<filter-name>struts2</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
</web-app>
While creating this application in struts 2, please refer the following screen-shot of
Project Explorer to know the location of the above created files.
Step 9 : Export the WAR file and start Tomcat server. Run the program on Tomcat
server. The output will be obtained as follows -
Enter some name inside the text box and click the Submit button. You will
get the execution of interceptor as follows :
Review Question
1. How to use interceptors in Struts 2 ? List and describe important interceptors provided by
Struts 2 framework.
SPPU : May-18, Marks 6
The dispatcher result type is the default type, and is used if no other result type is
specified. It's used to forward to a servlet, JSP, HTML page, and so on, on the
server. It can be written as
<result name="success" type="dispatcher">
<param name="location">/Success.jsp</param>
</result>
Let us understand how to use result type with demonstration.
struts.xml
<?xml version = "1.0" encoding = "UTF-8"?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
"http://struts.apache.org/dtds/struts-2.0.dtd">
<struts>
<constant name = "struts.devMode" value = "false" />
NewLocation.jsp
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>My Result Type Struts Demo Application</title>
</head>
<body>
<h3>Ooops!! you are redirected to new page...</h3>
</body>
</html>
Step 4 : Now execute the above application and the output can be obtained as follows -
Click the submit button, and you will be redirected to a new page
4.18 Validations
In struts, validation framework help to perform validation before the action method
is executed.
You can validate data in action class also through validate() method.
In the validate() method we can validate the user name, password,age,email, phone
number and so on. If the validation fails an error is added using the addFieldError()
method.
LoginPg.jsp
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%@taglib uri="/struts-tags" prefix="s" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Login Page Demo</title>
<s:head />
</head>
<body>
<s:form action="Login">
<s:textfield name="userName" label="User Name" />
<s:submit value="Submit" />
</s:form>
</body>
</html>
Step 2 : Create one more JSP document under WebContent folder named
Welcome.jsp . This JSP file is for displaying welcome message for authentic
user. The code is
Welcome.jsp
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%@taglib uri="/struts-tags" prefix="s"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>login Page Demo</title>
</head>
<body>
<h1>Welcome, User <s:property value="userName"/> is authentic user!!!</h1>
</body>
</html>
Step 3 : Now we will write the Java File for validating the user name. Two
validations are used -
i) the user name must not be blank and ii) the user name must be root. For
validation purpose we will write one function named validate() in this Java
program. This method is written in action class, hence this program will be
created within package name myPkg under the src directory.
LoginProg.java
package myPkg;
import com.opensymphony.xwork2.ActionSupport;
public class LoginProg extends ActionSupport {
private String userName;
this.userName = userName;
}
public void validate() {
if (getUserName().length() == 0) {
addFieldError("userName", "UserName.required");
} else if (!getUserName().equals("root")) {
addFieldError("userName", "Invalid User");
}
}
}
Step 4 : Now we will write the configuration files. The struts.xml file under the
WEB-INF/classes folder will be -
struts.xml
<?xml version = "1.0" encoding = "UTF-8"?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
"http://struts.apache.org/dtds/struts-2.0.dtd">
<struts>
<constant name="struts.custom.i18n.resources" value="LoginProg" />
<package name="default" extends="struts-default" namespace="/">
<action name = "Login"
class = "myPkg.LoginProg"
method = "execute">
<result name = "success">/Welcome.jsp</result>
<result name = "input">/LoginPg.jsp</result>
</action>
</package>
</struts>
Step 5 : The web.xmlfile present inside the WEB-INF folder is modified as -
web.xml
<?xml version = "1.0" encoding = "UTF-8"?>
<web-app xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance"
xmlns = "http://java.sun.com/xml/ns/javaee"
xmlns:web = "http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
xsi:schemaLocation = "http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
id = "WebApp_ID" version = "3.0">
<display-name>Struts 2</display-name>
<welcome-file-list>
<welcome-file>LoginPg.jsp</welcome-file>
</welcome-file-list>
<filter>
<filter-name>struts2</filter-name>
<filter-class>
org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter
</filter-class>
</filter>
<filter-mapping>
<filter-name>struts2</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
</web-app>
The above file specifies the entry point for the project. It says that the first page to be
displayed is LoginPg.jsp.
Step 6 : Now deploy the WAR file to tomcat's webapps directory and run the above
application on Apache Tomcat server. The output will be
4.19 Localization
Internationalization is a process of translation or localization.
Internationalization is abbreviated i18n because the word starts with the letter "i"
and ends with "n", and there are 18 characters between the first i and the last n.
Internationalization (i18n) is the process of planning and implementing products
and services so that they can easily be adapted to specific local languages and
cultures, a process called localization.
The i18n interceptor provides multi-lingual support for your application.
It handles setting locale for the action. It can be used if user wants to set his/her
locale and get data according to the locale provided.
A locale is an identifier and represents the local details of the user to the application.
The locale can be created by java.util.Locale class. When a user session begins, the
Locale object is sent in the HTTP request as parameter.
The language_country represents the country locale. For example English United
States is represented as en_US, For Spanish it will be _es and so on. These properties file
can be named as
global.properties : This is a default file for the English language.
global_fr.properites : This file specifies the French locale.
global_cn.properties : It specifies the code in Chinese.
global_hi.properties : It specifies the code in Hindi
index.jsp
<%@ page language = "java" contentType = "text/html; charset = ISO-8859-1"
pageEncoding = "ISO-8859-1"%>
<%@ taglib prefix = "s" uri = "/struts-tags"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>Student Form with Multilingual Support</title>
</head>
<body>
<h1><s:text name = "global.heading"/></h1>
Welcome.jsp
<%@ page language = "java" contentType = "text/html; charset = ISO-8859-1"
pageEncoding = "ISO-8859-1"%>
<%@ taglib prefix = "s" uri = "/struts-tags"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>Success</title>
</head>
<body>
<s:property value = "getText('global.success')" />
</body>
</html>
In above code have used getText method to access the messages. To display i18n text,
use a call to getText in the property tag.
Step 3 : Now create the Java Class files inside the src folder. First create the package
with some suitable name under Java Resources/src. Here we will create two
Java Class files - first Java class file will take care of Locale and display the
index.jsp with different languages and second Java class file will handle the
form submission in which execute, getXX and setXX methods are defined.
The code for these Java files is as follows
StudLocale.java
package myPkg;
import com.opensymphony.xwork2.ActionSupport;
public class StudLocale extends ActionSupport {
public String execute() {
return SUCCESS;
}
}
TestAction.java
package myPkg;
import com.opensymphony.xwork2.ActionSupport;
public class TestAction extends ActionSupport {
private String name;
public String execute() {
return SUCCESS;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
Step 4 : Now we can create global.properties files. These files can be created for
different languages so that the web page can be displayed in those
corresponding languages. Here I will write the global file for displaying the
message English only. This file is created inside WEB-INF folder inside
which the classes folder is created. Save global.properties file inside this
classes folder.
global.properties
global.name = Name
global.submit = Submit
global.heading = Select desired Locale
global.success = You are authenticated user!!!
In this file,we will display the name of the fields and their corresponding values. For
instance for global.success the message "You are authenticated user!!!" message must be
displayed. For global.heading the "Select desired Locale" must be displayed.
Step 5 : Now create the configuration files. First create the struts.xml file inside
WEB-INF\classes folder. The code for this file would be as follows -
struts.xml
<?xml version = "1.0" encoding = "UTF-8"?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
"http://struts.apache.org/dtds/struts-2.0.dtd">
<struts>
<constant name = "struts.devMode" value = "false" />
<constant name = "struts.custom.i18n.resources" value = "global" />
<package name = "localizationdemo" extends = "struts-default" namespace="/">
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
<display-name>LocalizationDemo</display-name>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
<filter>
<filter-name>struts2</filter-name>
<filter-class>
org.apache.struts2.dispatcher.FilterDispatcher
</filter-class>
</filter>
<filter-mapping>
<filter-name>struts2</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
</web-app>
Here is the screen-shot for Project Explorer to understand the parent folders of above
created files -
Step 7 : Then right click on the project name and click Export-> WAR file for
exporting the war file in Tomcat directory. Then execute the above
application on Tomcat web server. The output will be
index.jsp
<%@ page language = "java" contentType = "text/html; charset = ISO-8859-1"
pageEncoding = "ISO-8859-1"%>
<%@ taglib prefix = "s" uri = "/struts-tags"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>My First Struts Demo Application</title>
</head>
<body>
<h2>My Struts2 Application</h2>
<form action = "hello">
<label for = "name">Enter your name</label><br/>
<input type = "text" name = "name"/>
<input type = "submit" value = "Submit"/>
</form>
</body>
</html>
Step 2 : Now create another JSP page to handle the successful submission of data.
This page will display the welcome message by user name. The JSP file is
created inside the WebContent folder. The code is very simple and it is -
MyHello.jsp
<%@ page contentType = "text/html; charset = UTF-8" %>
<%@ taglib prefix = "s" uri = "/struts-tags" %>
<html>
<head>
<title>Exception Demo Application</title>
</head>
<body>
<h3>Welcome my friend, <s:property value = "name"/></h3>
</body>
</html>
Step 3 : Now create the Java Class files inside the src folder. First create the package
with some suitable name under Java Resources/src. This Java class file will
handle the form submission in which execute, getXX and setXX methods are
defined. Note that purpose, inside the execute method I have created a null
string in variable str. Then trying to find the Uppercase string of this null
string. This action will cause the NullPointerAssignment problem. The code
for this Java file is as follows -
MyBigHello.java
package myPkg;
import com.opensymphony.xwork2.ActionSupport;
public class MyBigHello extends ActionSupport{
struts.xml
<?xml version = "1.0" encoding = "UTF-8"?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
"http://struts.apache.org/dtds/struts-2.0.dtd">
<struts>
<constant name = "struts.devMode" value = "false" />
<package name="default" extends="struts-default">
<action name = "hello"
class = "myPkg.MyBigHello"
method = "execute">
<result name = "success">/MyHello.jsp</result>
</action>
</package>
</struts>
Step 5 : Another configuration file web.xml is modified which is present inside the
WEB-INF folder.
web.xml
<?xml version = "1.0" encoding = "UTF-8"?>
<web-app xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance"
xmlns = "http://java.sun.com/xml/ns/javaee"
xmlns:web = "http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
xsi:schemaLocation = "http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
id = "WebApp_ID" version = "3.0">
<display-name>Struts 2</display-name>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
<filter>
<filter-name>struts2</filter-name>
<filter-class>
org.apache.struts2.dispatcher.FilterDispatcher
</filter-class>
</filter>
<filter-mapping>
<filter-name>struts2</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
</web-app>
Step 6 : Then right click on the project name and click Export-> WAR file for
exporting the war file in Tomcat directory. Then execute the above
application on Tomcat web server. The output will be
Step 7 : To overcome this problem we will create a dedicated JSP page to handle
exception. I have created a JSP page named ErrorHandle.jsp page as
follows -
ErrorHandle.jsp
<%@ page language = "java" contentType = "text/html; charset = ISO-8859-1"
pageEncoding = "ISO-8859-1"%>
<%@ taglib prefix = "s" uri = "/struts-tags"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title></title>
</head>
<body>
<h3>Some Error has occurred in your page!!!</h3>
</body>
</html>
Step 8 : Now in order to display the above created JSP page on exception we need to
modify our struts.xml file. The code will be
struts.xml
<?xml version = "1.0" encoding = "UTF-8"?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
"http://struts.apache.org/dtds/struts-2.0.dtd">
<struts>
4.21 Annotations
Java annotation is a tag used to represent the metadata. The metadata is a data
about classes, methods or fields.
Annotations in Java are used to provide some addition information. For instance - If
user is entering his age in the text field, then that age must not be negative or it
should not be blank - Such type of information can be provided to the user using
annotations.
Step 2 : Create the same project as discussed in section 4.18 for validation. The
LoginPg.jsp, Welcome.jsp will be as it is. The only change will be in the Java
file. In the Java file we introduce annotations. The code will be as follows -
LoginProg.java
package myPkg;
import com.opensymphony.xwork2.ActionSupport;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Result;
import org.apache.struts2.convention.annotation.Results;
import com.opensymphony.xwork2.validator.annotations.*;
@Results({
@Result(name = "success", location = "/Welcome.jsp"),
@Result(name = "input", location = "/LoginPg.jsp")
})
public class LoginProg extends ActionSupport {
private String userName;
@Action(value = "/Login")
public String execute() {
return SUCCESS;
}
@RequiredFieldValidator( message = "The user Name is required" )
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
}
Step 3 : Now we just do not require struts.xml file. The web.xml is the only configuration
file required. It will be as follow -
web.xml
<?xml version = "1.0" encoding = "UTF-8"?>
<web-app xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance"
xmlns = "http://java.sun.com/xml/ns/javaee"
xmlns:web = "http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
xsi:schemaLocation = "http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
id = "WebApp_ID" version = "3.0">
<display-name>Struts 2</display-name>
<welcome-file-list>
<welcome-file>LoginPg.jsp</welcome-file>
</welcome-file-list>
<filter>
<filter-name>struts2</filter-name>
<filter-class>
org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter
</filter-class>
<init-param>
<param-name>struts.devMode</param-name>
<param-value>true</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>struts2</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
</web-app>
Step 4 : Now Export-War file and execute the above application. If the name field is
kept empty and Submit button is clicked then "The user Name is required"
message will be displayed.
Q.14 What is the initial contact point for handling a web request in a Page-Centric
architecture ?
a A JSP page b A JavaBean.
c A servlet d A session manager.
Q.15 What is the key difference between using a <jsp:forward> and
HttpServletResponse.sendRedirect() ?
a Forward executes on the server while sendRedirect() executes on the client.
b Forward executes on the client while sendRedirect() executes on the server.
c The two methods perform identically.
d None of these
Q.16 In Struts2 Action classes are the components of ______.
a view b controller
c model d deployment
Q.17 In Struts2, What does validate() method of ActionForm returns ?
a ActionErrors b ActionForward
c ActionMapping d ActionError
Q.18 Which of the following methods is overridden by Action class ?
a run() b destroy()
c execute() d service()
Contents
5.1 Introduction to PHP
5.2 General Syntactic Characteristics
5.3 Primitives ............................................... May-18,19, ............................ Marks 4
5.9 Functions
5.14 Cookies
5.15 Session Tracking ............................................... Dec.-19,................................. Marks 8
(5 - 1)
Web Technology 5-2 Server Side Scripting Languages
5.17 WAP
5.18 WML
Part - I : PHP
5.1.2 Overview
PHP is a server side scripting language embedded in XHTML. It is an alternative to
CGI, ASP, ASP.NET and JSP.
The extensions to the PHP files are .php, .php3 or .phtml.
The php processor works in two modes. If the PHP processor finds XHTML tags in
the PHP script then the code is simply copied to the output file. But when the PHP
processor finds the PHP code in the script then that code is simply interpreted and
the output is copied to the output file.
If you click for view source on the web browser you can never see the PHP script
because the output of PHP script is send directly to the browser but you can see the
XHTML tags.
PHP makes use of dynamic typing that means there is no need to declare variables
in PHP. The type of variable gets set only when it is assigned with some value.
PHP has large number of library functions which makes it flexible to develop the
code in PHP.
WAMPP (the W stands for Windows OS). These packages support the Apache,
PHP, MYSQL, PERL.
I have installed the XAMPP package. The root directory can be accessed using the
http://localhost/\
xor
PHP Document[FirstCode.php]
<html>
<head>
<title> PHP Demo </title>
</head>
<body>
<?php
$i=10;
echo "<h3>Welcome to first PHP Document</h3>";
echo "The value of variable is = $i";
?>
</body>
</html>
Output
5.2.1 Variables
Variables are the entities that are used for storing the values.
PHP is a dynamically typed language. That is PHP has no type declaration.
The value can be assigned to the variable in following manner -
$variable_name=value
If the value is not assigned to the variable then by default the value is NULL. The
unsigned variables are called unbound variable.
If the unbound variable is used in the expression then its NULL value is converted
to the value 0.
Following are some rules that must be followed while using the variables -
1. The variable must start with letter or underscore _ , but it should not begin with
a number.
2. It consists of alphanumeric characters or underscore.
3. There should not be space in the name of the variable.
4. While assigning the values to the variable the variable must start with the $. For
example
$marks=100;
Using the function IsSet the value of the variable can be tested. That means if
IsSet($marks) function returns TRUE then that means some value is assigned to the
variable marks.
If the unbound variable gets referenced then the error reporting can be done with
the help of a function error_reporting(7). The default error reporting level is 7.
For example -
‘The total marks are= $marks’
will be typed as it is but
“The total marks are= $marks”
will display the value of $marks variable.
Review Question
1. Classify data types of PHP and describe various data types in each type.
SPPU : May-18,19, Marks 4
For example -
(int)$marks
2. The syntax is -
Conversion_function($variable_name)
For example -
Intval($marks)
3. The syntax is -
settype($variable_name,”datatype”)
For example -
settype($marks,”integer”);
The gettype function is useful to obtain the data type of the variable.
Function Purpose
floor The largest integer less than or equal to the parameter is returned.
For example floor(4.9) will return 4,
ceil The smallest integer greater than or equal to the parameter is returned.
For example ceil(4.9) will return 5,
Operator Meaning
&&
||
PHPScript[stringDemo1.php]
<?php
$s="I like PHP";
echo $s;
?>
Output
Note that the variable s is assigned with the string. The string is given in a double
quote. Then using the echo whatever string is stored in the variable s is displayed on the
console.
5.6 Output
The PHP is a server side scripting language and is used to submit the web page to
the client browser. Hence it is a standard method of embedding the PHP code
within the XHTML document. That means we can use the XHTML tags in PHP
while displaying the output.
The print function is used to create simple unformatted output. For example : The
string can be displayed as follows
print “I am proud of my <b>country</b>”
The numeric value can also be displayed using the print. For example -
print(100);
It will display the output as 100.
PHP also makes use of the printf function used in C. For example
printf(“The student %d has %f marks”,$roll_no,$marks);
Following is a simple PHP document which makes use of the statements for
displaying the output.
PHP Document[OutputDemo.php]
<html>
<head>
<title> Output Demo</title>
</head>
<body>
<?php
print "<h2>Welcome to my Website </h2>";
print "<hr/>";
$roll_no=1;
$name="AAA";
printf("<b>The roll number: %d</b>",$roll_no);
print "<br/><b>";
printf("The name: %s",$name);
print "</b>";
?>
</body>
</html>
Output
PHPDocument[selection.php]
<html>
<head>
<title>Selection Demo</title>
</head>
<body>
<?php
print "<h2>Selection Statement </h2>";
$a=10;
$b=20;
$c=30;
if($a>$b)
if($a>$c)
print "<b><I>a is the largest number </I></b>";
else
print "<b><I> c is the largest number</I></b>";
else
if($b>$c)
print "<b><I>b is the largest number</I></b>";
else
print "<b><I>c is the largest number</I></b>";
?>
</body>
</html>
Output
Similar to if statement the switch statement can also be used for selection.
Following is a simple PHP script for demonstrating switch statement -
PHPDocument[SwitchDemo.php]
<?php
$today = getdate();
switch($today['weekday'])
{
PHPDocument[LoopDemo1.php]
<?php
$i=1;
print "The numbers are ...";
print "<br/>";
while($i<=10)
{
print $i;
print "<br/>";
$i++;
}
?>
Output
Similarly we can modify the above script by using do-while and for loop as follows -
do …while for
<?php <?php
$i=1; print "The numbers are ...";
print "The numbers are ..."; print "<br/>";
print "<br/>"; for($i=1;$i<n)
do {
{ print $i;
print $i; print "<br/>";
print "<br/>"; $i++;
$i++; }
}while($i<=10); ?>
?>
Example 5.7.1 Write a PHP script to display the squares and cubes of 1 to 10 numbers.
Solution :
<html>
<head>
<title>Square and Cube Table </title>
</head>
<body>
<center>
<?php
print "<table border =1>";
print "<tr>";
print "<th>Number</th>";
print "<th>Square</th>";
print "<th>Cube</th>";
print "</tr>";
for($i=1;$i<=10;$i++)
{
print "<tr>";
print "<td>$i";
print "</td>";
print "<td>";
print $i*$i;
print "</td>";
print "<td>";
printpow($i,3);
print "</td>";
print "</tr>";
}
print "</table>";
?>
</center>
</body>
</html>
Output
Example 5.7.2 Write a PHP script to compute the sum and average of N numbers.
Solution :
<html>
<head>
<title> Sum and Average </title>
</head>
<body>
<center>
<?php
$sum=0;
for($i=1;$i<=10;$i++)
{
$sum+=$i;
}
$avg=$sum/10;
print "The Sum is: $sum";
print "<br/>";
print "the Average is: $avg";
?>
</center>
</body>
</html>
Output
An array is a collection of similar type of elements, but in PHP you can have the
elements of mixed type together in single array.
In each PHP, each element has two parts key and value.
The key represents the index at which the value of the element can be stored.
The keys are positive integers that are in ascending order.
<?php
$fruits = array("Mango", "Apple", "Banana","Grapes");
echo $fruits[0] . "," . $fruits[1] . "," . $fruits[2] . ",". $fruits[3];
?>
</body>
</html>
Output
<?php
$Student = array("AAA","BBB","CCC","DDD","EEE");
echo "<br/>Original Array<br/>";
print_r($Student);
echo "<br/>Deleting element at index 2<br/>";
unset($Student[2]);
print_r($Student);
echo "<br/>Adjusting gap<br/>";
$Student=array_values($Student);
print_r($Student);
?>
</body>
</html>
Output
Script Explanation :
1. In above script we have used unset function to create a gap at index 2.
2. Later on we have used array_values() to adjust this gap by subsequent element.
3. Using the print_r function the array can be displayed on the browser window.
Checking if value exists
PHP Document
<!DOCTYPE html>
<html>
<body>
<?php
$Student = array(1=>"AAA",2=>"BBB");
echo "<br/>Original Array<br/>";
print_r($Student);
if(isset($Student[0]))
echo "<br/>There is no value set at index 0<br/>";
if(isset($Student[1]))
echo "The value present at index 1 is: ".$Student[1];
?>
</body>
</html>
3. Multidimensional Arrays
(
array(10,"AAA"),
array(20,"BBB"),
array(30,"CCC"),
);
The complete PHP program in which the multidimensional array is created and
accessed is as follows -
PHP Document
<!DOCTYPE html>
<html>
<body>
<?php
$Student = array
(
array(10,"AAA"),
array(20,"BBB"),
array(30,"CCC"),
);
echo "The elements in Two dimensional array...<br/>";
for ($row = 0; $row < 3; $row++) {
for ($col = 0; $col < 2; $col++) {
echo " ".$Student[$row][$col];
}
echo "<br/>";
}
?>
</body>
</html>
Output
5.8.3 Extracting Data from Arrays, Implode, Explode and Flip Functions
i) The extract function :
Using the extract() function the array keys becomes the variable name and the array
values become the variable values.
Syntax :
int extract($input_array, $extract_rule, $prefix)
Where
$input_array : is the name of the array whose values need to be extracted. This is a
required parameter.
$extract_rule : This is an optional parameter. This parameter specifies how invalid
variable names will be treated.
$prefix : The prefix is automatically separated from the array key by an underscore
character. This is an optional parameter.
Example Program
<!DOCTYPE html>
<html>
<body>
<?php
$arr = array("a" => "Pune","b" => "Mumbai", "c" => "Chennai");
extract($arr);
echo "\$a = $a; \$b = $b; \$c = $c";
?>
</body>
</html>
Output
Example Program
<!DOCTYPE html>
<html>
<body>
<?php
$str="I Love my Country";
$arr=explode(" ",$str);
print_r($arr);
?>
</body>
</html>
Output
The array_flip() function is used to exchange the keys with their associated values in
array.
That means after applying the array_flip function we get keys from array become
values and values from array become keys.
Syntax :
array_flip(name_of_array)
Example Program
<!DOCTYPE html>
<html>
<body>
<?php
$arr=array("Red"=>10,"Green"=>20,"Blue"=>30,"Black"=>40);
$result=array_flip($arr);
print_r($result);
?>
</body>
</html>
Output
The array element reference start at the first element and array maintains an
internal pointer using which the next element can be easily accessible.
This helps to access the array elements in sequential manner.
The pointer current is used to point to the current element in the array. Using the
next function the next subsequent element can be accessed. Following PHP code
illustrates this idea -
PHP Document[ArrayFunDemo4.php]
<?php
$mylist = array("Hello", "PHP","You","Are","Wonderful!!!");
$myval=current($mylist);
print("The current value of the array is <b>$myval</b>");
print "<br/>";
$myval=next($mylist);
print("The next value of the array is <b>$myval</b>");
print "<br/>";
$myval=next($mylist);
print("The next value of the array is <b>$myval</b>");
print "<br/>";
$myval=next($mylist);
print("The next value of the array is <b>$myval</b>");
print "<br/>";
$myval=next($mylist);
print("The next value of the array is <b>$myval</b>");
?>
Output
Output
The foreach function is used to iterate through all the elements of the loop. The
syntax of foreach statement is as follows -
foreach($array as $value)
{
statements to be executed
}
The above code can be modified and written as follows -
PHP Document[ArrayFunDemo6.php]
<?php
$mylist = array("Hello", "PHP","You","Are","Wonderful!!!");
foreach($mylist as $value)
{
print("The current value of the array is <b>$value</b>");
print "<br/>";
}
?>
The output will be the same as above.
Review Questions
1. What is associative arrays in PHP ? Explain it with the help of simple PHP code.
SPPU : May-18,19, Marks 6
2. What is multi-dimensional arrays in PHP ? Explain it with simple PHP code.
SPPU : Dec.-18, Marks 6
5.9 Functions
The functions in PHP are very much similar to the functions in C. Let us discuss it in
detail.
PHPDocument[FunDemo1.php]
<?php
functionmyfun()
{
print "<i>This statement is in myfun()</i>";
}
print "<b>The Function Demo Program</b>";
print "<br/>";
myfun();
?>
Output
The return statement is used for returning some value from the function body.
Following PHP scripts shows this idea.
PHPDocument[FunDemo2.php]
<?php
function Addition()
{
$a=10;
$b=20;
$c=$a+$b;
return $c;
}
print "<b>The Function Demo Program with return statement</b>";
print "<br/>";
print "10+20= ".Addition();
?>
Output
5.9.2 Parameters
The parameter that we pass to the function during the call is called the actual
parameter. These parameters are generally the expressions.
The parameters that we pass to the function while defining it is called the formal
parameters. These are generally the variables. It is not necessary that the number of
actual parameters should match with the number of formal parameters.
If there are few actual parameter and more formal parameters then the value of
formal parameter will be some unbounded one.
If there are many actual parameters and few formal parameters then the excess of
actual parameters will be ignored.
The default parameter passing technique in PHP is pass by value. The parameter
passing by value means the values of actual parameters will be copied in the formal
parameters. But the values of formal parameters will not be copied to the actual
parameters.
Following PHP script illustrates the functions with parameters.
PHP Document[FunDemo3.php]
<?php
function Addition($a,$b)
{
$c=$a+$b;
return $c;
}
print "<b>The Function Demo Program with parameter passing and return
statement</b>";
print "<br/>";
$x=10;
$y=20;
print "10+20= ".Addition($x,$y);
?>
Output
Function Purpose
floor The largest integer less than or equal to the parameter is returned. For example -
floor(4.9) will return 4,
ceil The smallest integer greater than or equal to the parameter is returned. For example -
ceil(4.9) will return 5,
Solution : For this program we will apply various built in string manipulating functions to
the string. The PHP code is as follows -
<?php
$Str1="PHP is Fun";
$length = strlen($Str1);
echo "<b> Length:</b>The length of string: $Str1 is = $length";
echo "<br/><b>Position: </b>The position of word Fun in the $Str1 is ".strpos($Str1,'Fun');
$Str1="Hello";
$Str2="hello";
if(strcmp($Str1,$Str2))
echo "<br/><b>Comparison: </b> The two strings $Str1 and $Str2 are not equal";
else
echo "<br/><b>Comparision: </b> The two strings $Str1 and $Str2 are equal";
$Str1="HELLO";
echo "<br/><b>Changing Case: </b> The string $Str1 becomes ".strtolower($Str1);
echo "<br/><b>Reversing String: </b> The string $Str1 is reversed as ".strrev($Str1);
$Str1="Hello";
$Str2="Friend";
echo "<br/><b>Concatenating strings: </b> The string $Str1 and $Str2 are concatenated
".$Str1.$Str2;
echo "<br/><b>Replacing all instances of string: </b> The string tictactoe is now ";
echo str_replace("t","p","tictactoe");
$Str1="PHP is fun";
$newstring=substr_replace($Str1,"FUN",7,9);
echo "<br><b>Replacing substring: </b> $Str1 becomes $newstring";
?>
Output
Syntax :
Conversion_function($variable_name)
Example :
Intval($marks)
Syntax :
settype($variable_name,”datatype”)
Example :
settype($marks,”integer”);
The gettype function is useful to obtain the data type of the variable.
Function Purpose
array_search() Searches array for given value and returns the keys.
Example 5.11.1 Create HTML form with one textbox to get user's name. Also write PHP code
to show length of entered name when, the HTML form is submitted.
Example 5.11.2 Create HTML form to enter one number. Write PHP code to display the
message about number is odd or even.
Solution : Step 1 : The HTML form for accepting number is created as below -
<!DOCTYPE html>
<html >
<head><title> HTML-PHP DEMO</title>
</head>
<body>
<form method="post" action="http://localhost/getdata.php">
Enter Number: <input type="text" name="mynum" size="5"/>
<br/>
<input type="submit" name="submit" value="submit"/>
</form>
</body>
</html>
Step 2 : The PHP script deciding whether the number is even or odd is as given
below -
<?php
print "The number is: ";
print $_POST["mynum"];
$a= $_POST["mynum"];
if($a%2==1)
print "<br/> The number is odd ";
else
print "<br/> The number is even ";
?>
Output
Example 5.11.3 Create a form containing information sl.no, title of the book, publishers,
quantity, price read the data from the form and display it using PHP script.
Solution : Step 1 : Create an HTML page for inputting the data. Following is the code for
HTML script .
HTML Document[input.html]
<!doctype html>
<html>
<head>
<title> Book Order Form </title>
</head>
<body>
<h3> Enter the Book Data </h3>
<form method="post" action="http://localhost/php-examples/formdemo.php">
<table>
<tr>
<td>Sr.No.</td>
<td><input type="text" name="SLNo"></td>
</tr>
<tr>
<td>Book name</td>
<td><input type="text" name="BName"></td>
</tr>
<tr>
<td>Publisher</td>
<td><input type="text" name="PUBName"></td>
</tr>
<tr>
<td>Price</td>
<td><input type="text" name="Price"></td>
</tr>
<td>Quantity</td>
<td><input type="text" name="Qty"></td>
</tr>
<tr>
<td><input type="submit" value="Submit"></td>
<td><input type="submit" value="Clear"></td>
</tr>
</table>
</form>
</body>
</html>
Step 2 : Create a PHP script which will read out the data entered by the user using HTML
form. The code is as follows -
PHP Document[formdemo.php]
<html>
<head>
<title>Book Information</title>
</head>
<body>
<?php
$BName=$_POST["BName"];
$PUBName=$_POST["PUBName"];
$Price=$_POST["Price"];
$Qty=$_POST["Qty"];
?>
<center>
<h3> Book Data </h3>
<table border=1>
<tr>
<th>Book name</th>
<th>Publisher</th>
<th>Price</th>
<th>Quantity</th>
</tr>
<tr>
<td><?php print ("$BName"); ?></td>
<td><?php print ("$PUBName"); ?></td>
<td><?php printf("%3.2f",$Price); ?></td>
<td><?php printf("%d",$Qty); ?></td>
</tr>
</table>
</center>
</body>
</html>
Step 3 : Open some suitable web browser and enter the address for the HTML file
which you have created in step 1.
Now click on the Submit button and the PHP file will be invoked. The output will then
be as follows -
Example 5.11.4 Write a PHP program to accept a positive integer 'N' through a HTML form
and to display the sum of all the numbers from 1 to N.
Solution :
<html>
<head>
<title> PHP Demo </title>
</head>
<body>
<form method="post">
<input type="text" name="num"/>
<input type="submit" value="Submit"/>
</form>
</body>
</html>
<?php
//getting values from HTML form
$n = intval($_POST['num']);
$sum=0;
for($i=1;$i<=$n;$i++)
$sum=$sum+$i;
echo "The sum of all numbers from 1 to ".$n." is ".$sum;
?>
Output
The pattern matching technique which is used in PHP is of two types -The first one
is based on POSIX regular expression and the another is based on Perl regular
expression.
There is a preg_match function which is used to check the matching of the pattern
from the text. It takes two parameters the first parameter is the pattern to be
matched and the second parameter is the text against which the pattern is to be
matched.
The preg_split is the function that splits the string into the chunks.
PHP Document[PatternMatchDemo.php]
<?php
print "<h3>Use of preg_match function</h3>";
if (preg_match("/gram/", "I like Programming in PHP!"))
print "The pattern is matching <br />";
else
print "The pattern does not match <br />";
print "<h3>Use of preg_split function</h3>";
$text ="Hello:friends:how:are:you?";
print "The original string is<b> $text</b>";
print "<br/>";
print "The split is as follows ...<br/>";
$chunks=preg_split("/:/",$text);
while($myval=each($chunks))
{
$val=$myval["value"];
print("<b>$val</b>");
print "<br/>";
}
?>
Output
Example 5.12.1 Explain the string comparison capability of PHP using regular expression with
an example.
Solution : The preg_match function is used to compare two strings using regular
expression. The first parameter to this function is a regular expression and second
parameter is the string which is used for matching with the regular expression.
Following PHP program illustrates, the matching of date pattern using regular
expression.
Output
Example 5.12.2 Write a PHP program that tests whether an email address is input correctly.
Verify that the input begins with a series of characters followed by the @ character, another
series of characters, a period ‘.’ And a final series of characters. Test your program with both
valid and invalid email address.
Solution : Step 1 : The HTML form containing the text box for inputting the email address
is created as follows -
<html>
<head>
<title> Inserting Data into Database Table</title>
</head>
<body>
<form method = "post" action = "http://localhost/php-examples/ValidateEmail.php ">
<label>Email</label>
<input type="text" name="email" />
<br />
<input type="submit" value="Submit">
</form>
</body>
</html>
Step 2 : The PHP script that validates the given email address using regular
expression is as follows -
ValidateEmail.php
<?php
$reg = '/^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$/';
$email=$_POST["email"];
if (preg_match($reg, $email))
{
echo "Valid Email ID";
}
else
{
echo "Invalid Email ID.";
}
?>
Solution :
<?php
$to = "[email protected]";
$subject = "Hi!";
$body = "Hi,\n\nHow are you?";
if (mail($to, $subject, $body))
{
echo("<p>Email successfully sent!</p>");
}
else
{
echo("<p>Failure in Email delivery!!!</p>");
}
?>
PHP is known as a server-side scripting language. Hence file handling functions such
as create, read, write, append are some file related operations that are supported by PHP.
w Write only. Opens and clears the contents of file; or creates a new file if it is not
created
w+ Read/Write. Opens and clears the contents of file; or creates a new file if it is not
created.
a Append. Opens and writes to the end of the file or creates a new file if it is not
created.
For example :
$my_file = 'file.txt';
$file_handle = fopen($my_file, 'a') or die('Cannot open file: '.$my_file);
The fopen function returns TRUE if the required file is opened.
Example 5.13.1 Create a form containing information sl.no, title of the book, publishers,
quantity, price read the data from the form and write onto the file using PHP script.
Solution : Step 1 : We will create an input form for the user to enter the data. The HTML
code is as follows. (It is the same HTML form which we have discussed in the last section)
HTML Document[input.html]
<!doctype html public "-//w3c//dtd html 4.0 transitional//en">
<html>
<head>
<title> Book Order Form </title>
</head>
<body>
<h3> Enter the Book Data </h3>
<form method="post" action="http://localhost/php-examples/formdemo.php">
<table>
<tr>
<td>Sr.No.</td>
<td><input type="text" name="SLNo"></td>
</tr>
<tr>
<td>Book name</td>
<td><input type="text" name="BName"></td>
</tr>
<tr>
<td>Publisher</td>
<td><input type="text" name="PUBName"></td>
</tr>
<tr>
<td>Price</td>
<td><input type="text" name="Price"></td>
</tr>
<td>Quantity</td>
<td><input type="text" name="Qty"></td>
</tr>
<tr>
<td><input type="submit" value="Submit"></td>
<td><input type="submit" value="Clear"></td>
</tr>
</table>
</form>
</body>
</html>
Step 2 : Following is a simple PHP script which displays the data and then writes it to
the file.
PHP Document
<html>
<head>
<title>Book Information</title>
</head>
<body>
<?php
$BName=$_POST["BName"];
$PUBName=$_POST["PUBName"];
$Price=$_POST["Price"];
$Qty=$_POST["Qty"];
?>
<center>
<h3> Book Data </h3>
<table border=1>
<tr>
<th>Book name</th>
<th>Publisher</th>
<th>Price</th>
<th>Quantity</th>
</tr>
<tr>
<td><?php print ("$BName"); ?></td>
<td><?php print ("$PUBName"); ?></td>
<td><?php printf("%3.2f",$Price); ?></td>
<td><?php printf("%d",$Qty); ?></td>
</tr>
</table>
</center>
<?php
$my_file = 'file.txt';
$file_handle = fopen($my_file, 'a') or die('Cannot open file: '.$my_file);
fwrite($file_handle, $BName);
fwrite($file_handle, "\r\n");
fwrite($file_handle, $PUBName);
fwrite($file_handle, "\r\n");
fwrite($file_handle, $Price);
fwrite($file_handle, "\r\n");
fwrite($file_handle, $Qty);
fclose($file_handle);
?>
<p>The contents are written to the file <u>file.txt<u></p>
</body>
</html>
Step 3 : Now open the web browser and type the address of the html file which you
have created in step 1. On clicking the submit button on the this input form the data will
be displayed as follows -
Step 4 : Open the current directory folder (The folder in which your html and PHP
scripts are present). You will obtain a text file file.txt. Just Open the file and see the
contents. I have got the following contents -
Review Question
5.14 Cookies
In this section we will discuss how to create and read cookies.
Note that you have got the blank screen it indicates that the cookie is set. In above PHP
document we have set the PHP script for one month. Just observer the third parameter of
the setcookie function.
Now you can retrieve the cookie and read the value to ensure whether or the cookie is
set.
PHP Document[CookieReadDemo.php]
<html>
<head><title>Reading Cookies</title>
<body>
<?php
if (isset($_COOKIE["Myname"]))
echo "<h3>Welcome " . $_COOKIE["Myname"]."!!!</h3>";
else
echo "<h3>Welcome guest!</h3>";
?>
</body>
</html>
Output
Program Explanation
The isset function is used for checking whether or not the cookie is set. Then using the
$_COOKIE the value of the cookie can be retrieved.
When you open some application, use it for some time and then close it. This entire
scenario is named as session.
Session state is a server-based state mechanism that lets web applications store and
retrieve objects of any type for each unique user session. That is, each browser
session has its own session state stored as a serialized file on the server, which is
deserialized and loaded into memory as needed for each request. Refer Fig. 5.15.1.
Because server storage is a finite resource, objects loaded into memory are released
when the request completes, making room for other requests and their session
objects. This means there can be more active sessions on disk than in memory at any
one time.
Sometimes the information about the session is required by the server. This
information can be collected during the session. This process is called session
tracking.
In PHP, session state is available to the developer using the $_SESSION variable.
The unique ID for the sessions can be stored in superglobal array $_SESSION.
PHP keeps track of session by using a function called session_start(). Due to the call
to session_start() function the session ID is created and recorded.
Following is a simple PHP script in which the information about session is tracked.
PHP Document[SessionDemo.php]
<?php
session_start();
if(isset($_SESSION['pgvisit']))
{
$_SESSION['pgvisit']=$_SESSION['pgvisit']+1;
echo "<h3>You are visiting this page for <i>". $_SESSION['pgvisit']."</i> times</h3>";
}
else
{
$_SESSION['pgvisit']=1;
echo "<h3>You are visiting this page for the first time</h3>";
}
?>
Program Explanation :
Review Question
1. Explain how session and cookies are used for session management in PHP.
SPPU : Dec.-19, Marks 8
5.16 Using MySQL with PHP SPPU : May-18, Marks 6, Dec.-19, Marks 8
For example
<?php
// Make a MySQL Connection
$conn=mysql_connect("localhost:3306/mydb","root","mypassword");
if(!$conn)
{
die('error in connection'.mysql_error());
}
else
{
print"connected";
}
mysql_close($conn); //closing the database
?>
The database can be closed using the function mysql_close
For example -
<?php
// Make a MySQL Connection
$conn=mysql_connect("localhost ","root","mypassword");
if(!$conn)
{
die('error in connection'.mysql_error());
}
//Create a database
if(mysql_query("CREATE DATABASE mydb",$conn))
{
print "Database created";
}
else
{
print "Error creating database: " . mysql_error();
}
For example -
<?php
// Make a MySQL Connection
$conn=mysql_connect("localhost:3306/mydb ","root","mypassword");
if(!$conn)
{
die('error in connection'.mysql_error());
}
//Select a database
mysql_select_db("mydb", $conn);
mysql_close($conn); //closing the database
?>
For example -
<?php
// Make a MySQL Connection
$conn=mysql_connect("localhost:3306/mydb ","root","mypassword");
if(!$conn)
{
die('error in connection'.mysql_error());
}
//Show databases
$db_lists=mysql_list_db($conn)
while($i=$mysql_fetch_object($db_list))
{
echo $i->Database. “\n”; //Present Databases will be displayed
}
mysql_close($conn); //closing the database
?>
For example -
<?php
// Make a MySQL Connection
$conn=mysql_connect("localhost ","root","mypassword");
if(!$conn)
{
die('error in connection'.mysql_error());
}
$table_list=mysql_query("SHOW TABLES FROM mydb",$con)
if(!$table_list)
{
print "Error!!! " . mysql_error();
}
while($i=$mysql_fetch_row($table_list))
{
echo $i[0]. “\n”; //Listing the tables
}
mysql_close($conn); //closing the database
?>
//Create a database
if(mysql_query("CREATE DATABASE mydb",$con))
{
print "Database created";
}
else
{
For example -
<?php
// Make a MySQL Connection
$conn=mysql_connect("localhost","root","mypassword");
if(!$conn)
{
die('error in connection'.mysql_error());
}
mysql_select_db(“mydb”,$conn); //select the database
$query=” INSERT INTO my_table (id,name) VALUES(1,'SHILPA')”;
mysql_query($query,$conn);//Execution of Query
$query=” INSERT INTO my_table (id,name) VALUES(2,'MONIKA')”;
mysql_query($query,$conn);//Execution of Query
For example -
<?php
// Make a MySQL Connection
$conn=mysql_connect("localhost","root","mypassword");
if(!$conn)
{
die('error in connection'.mysql_error());
}
mysql_select_db(“mydb”,$conn); //select the database
$query=” DROP DATABASE mydb”;
mysql_query($query,$conn);//Execution of Query
mysql_close($conn); //closing the database
?>
Examples
Example 5.16.1 Write a PHP script to create a new database table with 4 fields of your choice
and perform following database operations.
1. Insert 2. Delete 3. Update 4. Display
Solution : We will create a table in the database test. The name of the table ismytable.
Then we will insert the record into the table using the INSERT command, update
particular field of the record using the command UPDATE and delete the record using
the command DELETE.
echo $row['phone'];
echo "</td><td>";
echo $row['emailId'];
echo "</td></tr>";
}
echo "</table>";
$result = mysql_query("UPDATE mytable SET phone='55555' WHERE phone='22222'")
or die(mysql_error());
print "<br/>";
echo "Data Updated!";
$result =mysql_query("SELECT * FROM mytable")
or die(mysql_error());
print "<br/>";
print "<b>User Database</b>";
echo "<table border='1'>";
echo "<tr><th>ID</th><th>Name</th><th>Phone</th><th>Email-ID</th>
</tr>";
while($row = mysql_fetch_array( $result ))
{
// Print out the contents of each row into a table
echo "<tr><td>";
echo $row['id'];
echo "</td><td>";
echo $row['name'];
echo "</td><td>";
echo $row['phone'];
echo "</td><td>";
echo $row['emailId'];
echo "</td></tr>";
}
echo "</table>";
$result = mysql_query("DELETE FROM mytable WHERE phone='33333'")
or die(mysql_error());
print "<br/>";
echo "Data Deleted!";
$result =mysql_query("SELECT * FROM mytable")
or die(mysql_error());
print "<br/>";
print "<b>User Database</b>";
echo "<table border='1'>";
echo "<tr><th>ID</th><th>Name</th><th>Phone</th><th>Email-ID</th>
</tr>";
while($row = mysql_fetch_array( $result ))
{
// Print out the contents of each row into a table
echo "<tr><td>";
echo $row['id'];
echo "</td><td>";
echo $row['name'];
echo "</td><td>";
echo $row['phone'];
echo "</td><td>";
echo $row['emailId'];
echo "</td></tr>";
}
echo "</table>";
?>
Output
Example 5.16.2 Create a HTML form "result.html" with a text box and a submit button to
accept registration number of the student. Write a "result.php" code to check the status of
the result from the table to display whether the student has "PASS" or "FAIL" status.
Assume that the MYSQL database "my_db" has the table "result_table" with two columns
REG_NO and STATUS.
Solution : Step 1 : Create a database named my_db. Create a table result_table for this
database and insert the values in this table. The table is created as follows -
1 101 PASS
2 102 FAIL
3 103 PASS
4 104 FAIL
5 105 PASS
Table 5.16.1
Step 2 : Create an HTML form to accept the registration number; the HTML document
is as follows -
result.html
<!DOCTYPE html>
<html>
<head>
<title> STUDENT RESULT </title>
</head>
<body>
<form name="myform" method="post" action="http://localhost/php-
examples/result.php">
<input type="text" name="reg_no"/>
<input type="submit" value="Submit"/>
</form>
</body>
</html>
Step 3 : Create a PHP script to accept the registration number. This php script will
connect to MYSQL database and the status (PASS or FAIL) of the corresponding
registration number will be displayed.
result.php
<?php
// Make a MySQL Connection
$conn=mysql_connect("localhost","root","");
if(!$conn)
{
die('error in connection'.mysql_error());
}
mysql_select_db("my_db",$conn); //select the database
//Execution of Query for displaying the data
$reg_no = intval($_POST['reg_no']);
Example 5.16.4 Write a user defined function 'CalculateInterest' using PHP to find the simple
interest to be paid for a loan amount. Read the loan amount, the number of years and rate of
interest from a database table called LOANDETAILS having three fields AMT, YEARS, and
RATE, and calculate the interest using the user defined function.
Solution : Step 1 : Create a database table named LOANDETAILS having three fields
AMT, YEARS and RATE. Insert the values in it. The sample table will be as follows -
10000 5 6.9
Table 5.16.2
Step 2 : The PHP code for calculating the simple interest the above values in a function
will be as follows -
Interest.php
<?php
function CalculateInterest()
{
// Make a MySQL Connection
$conn=mysql_connect("localhost","root","");
if(!$conn)
{
die('error in connection'.mysql_error());
}
mysql_select_db("my_db",$conn); //select the database
//Execution of Query for displaying the data
$result=mysql_query("SELECT * FROM LOANDETAILS");
$row = mysql_fetch_array($result);
$amount= $row['AMT'];
$rate= $row['RATE'];
$years= $row['YEARS'];
$interest=($amount * $rate *$years)/100;
mysql_close($conn); //closing the database
return $interest;
}
print "Simple Interest =".CalculateInterest();
?>
Output
Review Question
5.17 WAP
Wireless Application Protocol (WAP) is a set of standards designed to extend
Internet services to mobile phones and Personal Digital Assistants (PDA).
A WAP browser is a web browser for mobile devices such as mobile phones that
uses the protocol.
The mobile network gets connected to the Internet through WAP Gateway. The
function of WAP gateway is to convert the WAP request to a WEB request or a
WEB request to a WAP request.
The mobile phones act as a client when gets connected to the internet. The
demanded web pages can be displayed on the mobile phones if it is WAP enabled.
The Web pages are normally written in HTML language but the web pages written
in HTML gets loaded very slowly on the mobile phones. Hence the web pages for
mobile phones are written in the language called Wireless Markup Language
(WML)
The WAP model follows the OSI model and is represented by Fig. 5.17.1.
Application Layer
o The WAP’s application layer is the Wireless Application Environment (WAE).
o The WAE supports WAP application development using the Wireless Markup
Language (WML).
o The WAE also includes the Wireless Telephony Application Interface (WTA)
which provides the programming interface to telephones. This allows WAP
technology to support for sending messages, initiating calls and other
networking capability.
Session Layer
o The session layer makes use of Wireless Session Protocol (WSP).
o This protocol is similar to HTTP. But HTTP is not efficient for displaying the
web pages on mobile devices, WAP makes uses of WSP.
o The WSP conserves the bandwidth on the wireless links.
o The HTTP works with textual data whereas the WSP work with binary data.
o It supports for both connection-oriented and connectionless sessions.
Transaction, Security and Transport Layer
5.18 WML
The topmost layer in the WAP architecture is made up of WAE (Wireless
Application Environment), which consists of WML and WML scripting language.
WML stands for Wireless Markup Language.
The role of WML is the same as that of HTML in web applications. WAP sites are
written in WML, while web sites are written in HTML.
WML is basically the web language for making sites on mobile phones.
WML is an application of XML, which is defined in a document-type definition.
WML Document[FirstScript.wml]
<?xml version="1.0"?>
<!DOCTYPE wml PUBLIC "-//WAPFORUM//DTD WML 1.2//EN"
"http://www.wapforum.org/DTD/wml12.dtd">
<wml>
<card id="one" title="Welcome Card">
<p>
Hello, This is first card.
</p>
</card>
<card id="two" title="GoodBye Card">
<p>
Good bye, this is second card.
</p>
</card>
</wml>
Now open the WinWap browser and execute the above code. It will be as follows
Script Explanation :
1) The first line of the script says that it is XML document.
2) The second line indicates that document type definition (DTD). These are the
standard lines written in every WML script.
3) Then within <wml> …</wml> tag the entire code is written.
4) The two cards are created with their own ids. The title tag is used to display the
content on the title bard. Within the <p>…</p> i.e. paragraph tag the text which
is to be displayed on the browser window is displayed.
<p>
Hello, This is first card. For displaying on
</p> browser window for first
card
</card>
<p>
Good bye, this is second card. For displaying on browser
</p> window for second card
</card>
Instead of having pages, WAP sites have cards. These are what is displayed on the
screen at one time, just like a page. More than one card can be inserted in each WML
document. To declare a card, insert the following :
<card id="some id" title="some text">
Note that : Only one card will be displayed at a time on the web browser.
Closing Tag
Unlike HTML it is important to close every opened tag. Otherwise WML page will not
get executed. The card and wml tags are closed as follows
</card>
</wml>
5.18.3 Comments
Comments are placed inside <!-- --> in WML. This is the same as HTML. For example,
the following lines are comments. WAP browsers ignore all comments.
<!-- This is a comment in WML -->
<!-- This is a multi-line
comment -->
5.18.4 Paragraph
The <p> tag defines the paragraph of text. The paragraph in WML is always displayed
on a new line. The attributes of paragraph are as follows -
Attribute Value Purpose
align Left The text is displayed using left, right or center alignment.
right
center
Example
<?xml version="1.0"?>
<!DOCTYPE wml PUBLIC "-//WAPFORUM//DTD WML 1.2//EN"
"http://www.wapforum.org/DTD/wml12.dtd">
<wml>
<card id="one" title="Welcome Card">
<p align="left">
Hello, This is first card.
</p>
</card>
<card id="two" title="description Card">
<p align="center">
And, this is second card.
</p>
</card>
<card id="three" title="GoodBye Card">
<p align="right">
Good bye, this is third card.
</p>
</card>
</wml>
Example
<?xml version="1.0"?>
<!DOCTYPE wml PUBLIC "-//WAPFORUM//DTD WML 1.2//EN"
"http://www.wapforum.org/DTD/wml12.dtd">
<wml>
<card id="one" title="Welcome Card">
<p>
Hello, This is<br/> first card.
This is <br/> another line with line break
</p>
</card>
</wml>
Output
5.18.6 Table
The table tags are just similar to HTML tags. For example - using <table> … </table>
the table can be created. The <tr> </tr>tag is used for creating rows and <td> </td> is used
for creating columns. The <table> element is placed within <p> </p> tag.
Various attributes used along with the <table> tag are
Attribute Value Purpose
align L C or R The text is displayed using left (L), right (R) or center (C)
alignment. If we specify LCR then that means, first column is
left aligned, Second column is center aligned and third
column is right aligned.
WML Document[TableDemo.wml]
<?xml version="1.0"?>
<!DOCTYPE wml PUBLIC "-//WAPFORUM//DTD WML 1.2//EN"
"http://www.wapforum.org/DTD/wml12.dtd">
<wml>
<card title="Displaying Tables">
<p>
<table columns="3" align="LCR">
<tr>
<td>One</td>
<td>Two</td>
<td>Three</td>
</tr>
<tr>
<td>Four</td>
<td>Five</td>
<td>Six</td>
</tr>
</table>
</p>
</card>
</wml>
5.18.7 Image
The <img> element is used to include an image in a WAP card. WAP-enabled
wireless devices only supported the Wireless Bitmap (WBMP) image format.
WBMP images can only contain two colors : black and white.
The file extension of WBMP is ".wbmp"
There are free tools available on internet to convert the jpg or GIF images to .wbmp
format. For example Nokia Mobile Internet Toolkit, ImageMagic and so on. Hence
to display image on the browser using wml, we must convert our image file to
.wbmp format first.
Example
WML Document[ImageDemo.wml]
<?xml version="1.0"?>
<!DOCTYPE wml PUBLIC "-//WAPFORUM//DTD WML 1.2//EN"
"http://www.wapforum.org/DTD/wml12.dtd">
<wml>
<card title="Displaying Image">
<p>
Good Morning!!!
<img src="flower.wbmp" alt="flower image"/>
</p>
</card>
</wml>
align Top, middle or bottom Image is aligned at the top, middle or bottom.
alt Alternative text The alternative text will be displayed if the image is
not getting loaded on the page.
5.18.8 Hyperlinks
The hyperlink can be used in WML using the anchor tag.
In WML we can use <anchor>, <a> tag to create anchor link.
Various attributes of <a> tag are as given below.
href URL or address of the file The specified URL is linked with page and can be opened
up on clicking the link.
Example
WML Document[HyperlinkDemo1.wm]
<?xml version="1.0"?>
<!DOCTYPE wml PUBLIC "-//WAPFORUM//DTD WML 1.2//EN"
"http://www.wapforum.org/DTD/wml12.dtd">
<wml>
<card title="Displaying Hyperlink">
<p> This is hyperlink demo
<a href="test.wml">Clik here to navigate to next page</a>
</p>
</card>
</wml>
Output
Similarly we can use <anchor> tag for using hyperlink in WML document. This tag
is basically used along with <go/>, <refresh> or <prev/> tag.
Example
WML Document[HyperlinkDemo2.wml]
<?xml version="1.0"?>
<!DOCTYPE wml PUBLIC "-//WAPFORUM//DTD WML 1.2//EN"
"http://www.wapforum.org/DTD/wml12.dtd">
<wml>
<card title="Displaying Hyperlink">
<p> This is hyperlink demo
<anchor>
<go href="test.wml"/>
</anchor>
</p>
Using <prev/> tag we
<p>
can go to Back page
<anchor>
<prev/>
</anchor>
</card>
</wml>
5.18.9 Inputs
The <input/> tag allows the user to enter alphanumeric characters such as name, age,
address, phone number, email address and so on.
For example -
WML Document[InputDemo.wml]
<?xml version="1.0"?>
<!DOCTYPE wml PUBLIC "-//WAPFORUM//DTD WML 1.2//EN"
"http://www.wapforum.org/DTD/wml12.dtd">
<wml>
<card title="Displaying Input">
<p>
<h2>Student Information Form</h2>
Enter Name: <input name="name" size="20"/><br/><br/>
Enter Address: <input name="address" size="30"/><br/><br/>
Enter Email: <input name="email" size="20"/><br/>
</p>
</card>
</wml>
5.18.10 Select
The <select>...</select> WML elements are used to define a selection list and the
<option>...</option> tags are used to define an item in a selection list.
WML Document[Select.wml]
<?xml version="1.0"?>
<!DOCTYPE wml PUBLIC "-//WAPFORUM//DTD WML 1.2//EN"
"http://www.wapforum.org/DTD/wml12.dtd">
<wml>
<card title="Displaying List">
<p> Select the color :
<select>
<option value="red">Red</option>
<option value="blue">Blue</option>
<option value="yellow">Yellow</option>
</select>
</p>
</card>
</wml>
Output
You can select multiple value if the attribute “multiple” is set to true. For example
WML Document[SelectDemo.wml]
<?xml version="1.0"?>
<!DOCTYPE wml PUBLIC "-//WAPFORUM//DTD WML 1.2//EN"
"http://www.wapforum.org/DTD/wml12.dtd">
<wml>
<card title="Displaying List">
<p> Select the color :
<select multiple="true">
<option value="red">Red</option>
<option value="blue">Blue</option>
<option value="yellow">Yellow</option>
</select>
</p>
</card>
</wml>
Output
5.18.11 Event
The event is supported in WML using <onevent></onevent> tag. We can specify the
action to be taken whenever an event occurs.
There are four types of events that are supported in WML -
(1) ontimer : This event occurs when a timer expires.
(2) onenterbackward : This event occurs when a user goes back to a card through
the WAP browser's URL history.
(3) onenterforward : This event occurs when a user goes to a card in the forward
direction. For example, if a user goes to a card by entering its URL directly in the
WAP browser, the onenterforward event will be triggered.
(4) onpick : This event occurs when an item of a selection list is selected or
deselected.
The syntax of specifying the event tag is as follows -
<onevent type="event_type">
Task to be performed when event occurs
</onevent>
Example using ontimer Event :
Using ontimer event, we can load the specific web page after some desired amount of
time automatically. User need not have to click any hyper link in this case. Following
script loads the test.wml web page after 3 second. The timer value is specified using
value attribute and the time unit is 1/10 seconds.
WML Document[onTimerDemo.wml]
<?xml version="1.0"?>
<!DOCTYPE wml PUBLIC "-//WAPFORUM//DTD WML 1.3//EN"
"http://www.wapforum.org/DTD/wml12.dtd">
<wml>
<card id="card1" title="Timer Demo">
<onevent type="ontimer">
<go href="test.wml"/>
</onevent>
<timer value="30"/>
<p>
WML Timer Test
</p>
</card>
</wml>
Output
After 3 seconds
WML Document[onenterBackward.wml]
<?xml version="1.0"?>
<!DOCTYPE wml PUBLIC "-//WAPFORUM//DTD WML 1.3//EN"
"http://www.wapforum.org/DTD/wml12.dtd">
<wml>
<template>
<onevent type="onenterbackward">
<go href="#card1"/>
</onevent>
</template>
<card id="card2">
<p>
<anchor>
<prev/>
Welcome
</anchor>
</p>
</card>
<card id="card1">
<p>
Hello friends!!! How are you
</p>
</card>
</wml>
Output
WML Document[onForwardEvent.wml]
<?xml version="1.0"?>
<!DOCTYPE wml PUBLIC "-//WAPFORUM//DTD WML 1.2//EN"
"http://www.wapforum.org/DTD/wml12.dtd">
<wml>
Note that on clicking the link Go to card2 the control will move directly to card3,
because in card2 the onenterforward event will occur and control will be transferred
directly to card3.
WML Document[onPickEvent.wml]
<?xml version="1.0"?>
<!DOCTYPE wml PUBLIC "-//WAPFORUM//DTD WML 1.2//EN"
"http://www.wapforum.org/DTD/wml12.dtd">
<wml>
<card id="MainCard" title="Color Selection">
<p>
Select color :
<select>
<option onpick="#id1">Red</option>
<option onpick="#id2">Blue</option>
</select>
</p>
</card>
<card id="id1">
<p>
You have selected color RED!!!
</p>
</card>
<card id="id2">
<p>
You have selected color Blue!!!
</p>
</card>
</wml>
Output
Part - II : ASP.NET
Fig. 5.19.1
Just in Time (JIT) is a part of CLR. It converts the source code into native
intermediate code and then into machine instructions.
The CLR is also responsible for performing some other tasks such as exception
handling, memory management and garbage collection.
The important features of CLR are interoperability, security and portability.
2. Framework Class Library (FCL)
It is a standard library which is actually a collection of various classes, interfaces,
and namespaces that can be used to build the application.
It is the key component of .NET framework that provides the core functionalities of
.NET.
Most of the methods of classes are split either into System.* or Microsoft.*
namespaces. A namespace is a logical separation of methods.
3. Language
The .NET supports many languages. Developer can choose the desired language for
development of required application.
Following are the categories of various types of applications that can be developed
using .NET
o WinForms : This is useful for developing form based applications.
o ASP.NET : The web based applications can be developed using ASP.NET.
These applications will run on the web browsers such as Google Chrome,
Mozilla FireFox, Internet Explorer and so on. The IIS server is responsible for
executing the ASP.NET application which is a part of Microsoft component.
o ADO.NET : This technology is used to interact with the databases like
Microsoft SQL servers, Oracle and so on. The most commonly used languages
for this category is C# and VB.NET.
5.21 Overview of C#
The C# is a modern, object oriented programming language developed by
Microsoft.
C# was developed by Anders Hejlsberg during the development of .NET
framework.
Step 3 : Give any suitable name to your project. I have given the name as
MyFirstApplication.
Step 4 : The source code window will appear now. This window contains the default
C# code. We can write our first C# code as follows -
using System;
namespace MyFirstApplication
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Welcome User!!!!");
}
}
}
Step 5 : Click on
The console window will appear and display the output of the above program.
Program Explanation :
1. The first line of the program is using System; the word using is a keyword that
is used to include the System namespace in the program. The namespace is a
collection of classes.
2. On the next line the namespace is declared by the name of the program. This
namespace contains the class definition named Program in which the method
Method() is defined.
3. This is the only method defined in the class. This is the entry point for all C#
programs. The Main method states what the class will do when executed.
4. Inside the Main method we have written Console.writeln statement. The
Console is the class and we are invoking the writeln method of this class. By this
statement we can display the desired message on the output screen.
Comment Statement
The comments in C# are similar to C++ comment statements. The // and /* … */ are
used as comments in C#.
Points to Remember
1. C# is case sensitive
2. The execution of the program starts at Main method.
3. Every statement in C# must be terminated by semicolon.
4. The file name can be different from the class name.
5.21.3 Variables
Variables are used for storing values. The syntax for variables is as follows -
Data type variable = value
For example -
int age = 20;
char 1 byte
short 2 byte
int 4 byte
long 8 byte
float 4 byte
double 8 byte
decimal 16 byte
using System.Linq;
using System.Text;
namespace MyFirstApplication
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Enter your name: ");
String name = Console.ReadLine();
Console.WriteLine("You have entered..."+name);
Console.ReadKey();
}
}
}
Output
5.21.6 Operators
The operators are the symbols that are used to perform various operations.
Various operators that are used in Java are enlisted in following table -
Type Operator Meaning Example
* Multiplication c=a*b
/ Division c=a/b
% Mod c=a%b
== Equal to x==100
|| Or operator 0 ||1
Conditional operator
namespace MyFirstApplication
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Arithmetic Operations");
int a = 20;
int b = 10;
int c;
Console.WriteLine("a = " + a);
Console.WriteLine("b = " + b);
c = a + b;
Console.WriteLine("Addition of two numbers..."+c);
c = a - b;
Console.WriteLine("Subtraction of two numbers..." + c);
c = a * b;
Console.WriteLine("Multiplication of two numbers..." + c);
c = a / b;
Console.WriteLine("Division of two numbers..." + c);
Console.ReadKey();
}
}
}
Output
namespace MyFirstApplication
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("\n Performing Relational operations ");
int a = 10, b = 20, c = 10;
Console.WriteLine("a= " + a);
Console.WriteLine("b= " + b);
Console.WriteLine("c= " + c);
Console.WriteLine("\n The a<b is " + (a < b));
Console.WriteLine("\n The a>b is " + (a > b));
Console.WriteLine("\n The a==c is " + (a == c));
Console.WriteLine("\n The a<=b is " + (a <= b));
Console.WriteLine("\n The a>=c is " + (a >= c));
Console.WriteLine("\n The a!=b is " + (a != b));
Console.ReadKey();
}
}
}
Output
namespace MyFirstApplication
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("\n Performing Logical operations ");
Boolean oper1, oper2;
oper1 = true;
oper2 = false;
Boolean ans1, ans2;
ans1 = oper1 & oper2;
ans2 = oper1 | oper2;
Console.WriteLine("The oper1 is: " + oper1);
Console.WriteLine("The oper2 is: " + oper2);
Console.WriteLine("The oper1&oper2 is: " + ans1);
Console.WriteLine("The oper1|oper2 is: " + ans2);
Console.ReadKey();
}
}
}
Output
namespace MyFirstApplication
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("\n Performing Conditional operations ");
int a, b, c;
a = 10;
b = 20;
Console.WriteLine("a = " + a);
Console.WriteLine("b = " + b);
c = a > b ? a : b;
Console.WriteLine(c + " is greatest");
Console.ReadKey();
}
}
}
Output
Let us discuss these control structures with the help of simple examples.
1. If statement
There are two types of if statements - simple if statement and compound if
statement. The simple if statement is a kind of if statement which is followed by
single statement. The compound if statement is a kind of if statement for which a
group of statements are followed. These groups of statements are enclosed within
the curly brackets.
If statement can also be accompanied by the else part.
Following table illustrates various forms of if statement.
Type of Syntax Example
statement
2. while statement
The while statement is executing repeatedly until the condition is false. The while
statement can be simple while or compound while. Following table illustrates the forms
of while statements -
Type of statement Syntax Example
3. do..while
The do…while statement is used for repeated execution. The difference between do
while and while statement is that, in while statement the condition is checked
do…while do do
{ {
statement 1; Console.WriteLine(”a is less than b”);
… a++;
… } while(a<10);
}while(condition);
From multiple cases if only one case is to be executed at a time then switch case
statement is executed. Following table shows the use of switch case statements.
5. for loop
The for loop is a not statement it is a loop, using which the repeated execution of
statements occurs. Following table illustrates the use of for loop -
Break statement : The break statement is used to terminate the loops such as for, while,
do…while and switch.
Syntax :
break;
Example Program :
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace MyFirstApplication
{
class Program
{
static void Main(string[] args)
{
int i, count = 5;
for (i = 0; i < 10; i++)
{
if (i == count)
{
break;
}
Console.WriteLine("\n i = "+i);
}
Console.ReadKey();
}
}
}
Output
Continue statement : Sometime we need to skip certain test condition within a loop. At
that time continue statement is used.
Syntax :
continue;
Example Program
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace MyFirstApplication
{
class Program
{
static void Main(string[] args)
{
int i, count = 5;
for (i = 0; i < 10; i++)
{
if (i == count)
{
continue;
}
Console.WriteLine("\n i = " + i);
}
Console.ReadKey();
}
}
}
Output
namespace ConsoleApplication2
{
class Circle
{
double radius;
double pi=3.14;
double a;
public void getdata()
{
radius = 10;
}
public void area()
{
a = pi * radius * radius;
Console.WriteLine("Radius: {0}", radius);
Console.WriteLine("Area: {0}", a);
}
}
class Program
{ Note that while displaying the variables they
static void Main(string[] args) are displayed using the index{0},{1} and so
{ on.
Circle obj = new Circle(); These two statements can be combined into
obj.getdata(); one statement as follows -
obj.area(); Console.WriteLine("Radius: {0},Area: {1}",
Console.ReadKey();
radius, a);
}
}
}
Output
7. Unloading : The Unload event is raised after the page is fully rendered. At this
point, page properties such as Response and Request are unloaded and cleanup
is performed.
Page life cycle events
Within each stage of the life cycle of a page, the page raises events. The following table
lists the page life-cycle events that are used most commonly.
PreInit This event is raised after start stage is complete and before initialization
stage. It Checks the IsPostBack property to determine whether this is the
first time the page is being processed. It sets the Master page and theme
property dynamically.
Init This event is raised after all controls have been initialized.
Load The Page object calls the OnLoad method. This events is raised for the
page loading and then recursively for all the child controls.
LoadComplete It is raised at the end of the event-handling stage. This event can be
handled by overloading the OnLoadComplete method
PreRender When all the controls for the page are created then this event is raised.
The Page object raises the PreRender event on the Page object, and then
recursively does the same for each child control.
Render This is not an event; instead, at this stage of processing, the Page object
calls this method on each control that writes out the control's markup to
send to the browser
Unload Raised for each control and then for the page. During the unload stage,
the page and its controls have been rendered so further changes to
response stream can not be done.
Control Events These events are used to handle specific control events. For instance
Button control has click event.
Click on Next button. Give the suitable project name. I have given project name as
UserControlsDemo.
Step 3 : The default code for WebForm1.aspx will be displayed in the Source code
window. We can add the user controls using Toolbox.
If we double click on some control, then the code for the user control will appear in the
source code window. For instance if we want to insert a text box then,
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs"
Inherits="UserControlsDemo.WebForm1" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<b> User Name:</b>
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
</div>
</form>
</body>
</html>
Step 4 : The above web from can be executed on IIS Express server. Click on the IIS
Express option present below the menu bar.
The output of the web service will be displayed on the web browser as follows -
Step 5 : The default code for WebForm1.aspx is displayed in the Code window. Just
below that the Design, Split and Source options are located. Click on Design. The
form window will get opened up. Now we can select the controls from the ToolBox
under the Standard option. Click and drag the desired controls on the form. The most
commonly used controls are Button, TextBoxes, Labels, Checkboxes, ListBoxes and so
on.
Step 6 : Set the properties of the controls using the Properties Window. If you can
not locate this window just press F4. You can set the properties like ID, Text,
ForeColor, Font and so on.
Step 7 : A sample form is designed as follows by simply dragging the controls.
Automatically the code will get generated. This code can be viewed by clicking the
Source.
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs"
Inherits="WebApplication3.WebForm1" %>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
</div>
<p>
<asp:Label ID="Label2" runat="server" Text="Address:"></asp:Label>
<asp:TextBox ID="TextBox2" runat="server"></asp:TextBox>
</p>
<p>
<asp:Label ID="Label3" runat="server" Text="Phone:"></asp:Label>
<asp:TextBox ID="TextBox3" runat="server"></asp:TextBox>
</p>
<asp:Button ID="Button1" runat="server" Text="Click Me" />
</form>
</body>
</html>
In above code, on the Button click the function Button_Click is called. In this function
we are just assigning the Button clicked message as a Label control’s text.
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Label ID="Label1" runat="server" Text="Enter Some Text in the TextBox
"></asp:Label>
</div>
<div>
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
</div>
<div>
<asp:Button ID="Button1" runat="server" onclick="Button1_Click" Text="Click" />
</div>
</form>
</body>
</html>
Output
Just type some name in TextBox. And then click the button.
Example 5.24.3 Write ASP.NET code to demonstrate the CheckBox and ListBox control.
Solution :
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="ChkBoxFrm.aspx.cs"
Inherits="CheckBoxDemo.ChkBoxFrm" %>
<script runat="server">
void CheckBox1_CheckedChanged(object sender, EventArgs e)
{
if (CheckBox1 .Checked==true)
{
ListBox1.Items.Add(CheckBox1.Text);
}
else
{
ListBox1.Items.Remove(ListBox1.Items.FindByText(CheckBox1.Text));
}
}
void CheckBox2_CheckedChanged(object sender, EventArgs e)
{
if (CheckBox2.Checked == true)
{
ListBox1.Items.Add(CheckBox2.Text);
}
else
{
ListBox1.Items.Remove(ListBox1.Items.FindByText(CheckBox2.Text));
}
}
void CheckBox3_CheckedChanged(object sender, EventArgs e)
{
if (CheckBox3.Checked == true)
{
ListBox1.Items.Add(CheckBox3.Text);
}
else
{
ListBox1.Items.Remove(ListBox1.Items.FindByText(CheckBox3.Text));
}
}
</script>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:CheckBox ID="CheckBox1" runat="server" AutoPostBack="True"
oncheckedchanged="CheckBox1_CheckedChanged" Text="C++" />
</div>
<div>
<asp:CheckBox ID="CheckBox2" runat="server" AutoPostBack="True"
oncheckedchanged="CheckBox2_CheckedChanged" Text="Java" />
</div>
<div>
<asp:CheckBox ID="CheckBox3" runat="server" AutoPostBack="True"
oncheckedchanged="CheckBox3_CheckedChanged" Text="C#" />
</div>
<div>
<asp:ListBox ID="ListBox1" runat="server" Height="140px" Width="120px">
</asp:ListBox>
</div>
</form>
</body>
</html>
Output
Just check or uncheck the checkboxes to experience the effect of this control.
1) HTTP : The HTTP is a standard protocol which is widely used by the web
services to send and receive messages.
2) SOAP : The SOAP (Simple Object Access Protocol) provides the mechanism
between web services and applications. SOAP messages are in XML
format.
3) XML : XML is a scripting languages intended for describing the data.
4) WSDL : It stands for Web Services Description Language. It is basically XML
notation for describing the interface provided by web service
provider.
5) Extension .asmx : In .NET the web services have the extension ASMX.
Step 1 : Open Visual Studio. Click on Create a New Project. Select ASP.NET Web
Application (.NET Framework). Give the name of the application. I have given the name
as CalculatorWebService. Then select Empty project template.
Step 2 : In the Solution Explorer window locate the name of the project. Right click on
project name.
Step 3 : The source code window appears. Initially the default source code will be
present in the source code window. Inside the webservice class, there exists a default
[WebMethod]. Replace default WebMethod by any desired method for which you want
to develop a web service. I want to write a web service for displaying maximum number
out of two numbers. I have written a method with the name ShowMaxValue. To this
method two integer parameters are passed as arguments.
The code for this web service is as follows -
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
namespace CalculatorWebService
{
/// <summary>
/// Summary description for WebService1
/// </summary>
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.ComponentModel.ToolboxItem(false)]
// To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the
following line.
// [System.Web.Script.Services.ScriptService]
public class WebService1 : System.Web.Services.WebService
{
[WebMethod]
public int ShowMaxValue(int a,int b)
{
if (a > b)
return a;
else
return b;
}
}
}
Program Explanation :
The output of the web service will be displayed on the web browser as follows -
Step 5 : From above window, just click on Service Description link. In the address bar we
get the URL as https://localhost:44388/WebService1.asmx?WSDL. Just copy this link and
save it to notepad.
If we click on ShowMaxValue we get following screen.
The two different values can be entered in the text boxes. On hitting the Invoke
button, we get the result in the XML document. It is as follows. Note that the above layout
is a default layout provided by .NET framework.
The above created web service can be invoked using the proxy web client. In this
section we will create web service client by creating a HTML form. On the button
click event of the form, the above created web service method ShowMaxValue will
be invoked. The return value of this method is displayed as a result on the web
browser.
Step 1 : In above section we have created a web service for displaying the maximum out
of two numbers. Just right click on the name of the above web project which is displayed
in the solution explorer window. Select Add New Project->ASP.NET Empty Web Site.
Give suitable name to your web service client. I have given the name myWebClient.
Click OK button. Thus the web service reference by the namespace ServiceReference1
is created for the web service client.
Step 2 : In the solution explorer window, right click on myWebClient and add a form.
Write following HTML code for creating two text boxes for inputting two numbers,
one label for displaying the result and one button to invoke the web service for showing
the maximum out of two numbers.
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs"
Inherits="_Default" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<table>
<tr><td><b>Enter first Number:</b></td>
<td> <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox></td>
</tr>
<tr><td><b>Enter second Number:</b></td>
<td> <asp:TextBox ID="TextBox2" runat="server"></asp:TextBox></td>
</tr>
<tr><td><b>Maximum Number is:</b></td>
<td><asp:Label ID="LblResult" runat="server" Text=""></asp:Label> </td>
</tr>
<tr><td>
<asp:Button ID="btnResult" runat="server" Text="Click Me" OnClick="btn_Click"/>
</tr>
<tr><td colspan="2">
<td> </td>
</tr>
</table>
</form>
</body>
</html>
Script Explanation : In above given HTML document we have created two text boxes
for inputting two numbers. One label control for displaying the maximum of the two
numbers. On button click, the web service method ShowMaxValue is called.
Double click on ‘Click Me’ button. Write the code for button click event as follows –
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void btn_Click(object sender, EventArgs e)
{
LblResult.Text = result.ToString();
}
The Convert.ToInt32 method is
}
used to convert the textbox string
to numeric value.
Step 4 : Right click on web client project and click on ‘view in Browser’. The output will
be as follows -
Example 5.25.1 Write a web service and web client for implementing addition of two numbers
using .NET.
</tr>
<tr><td>
<asp:Button ID="btnResult" runat="server" Text="Click Me" OnClick="btn_Click"/>
</tr>
</table>
</form>
</body>
</html>
For executing the Node.js scripts we need to install it. We can get it downloaded
from https://nodejs.org/en.
The installation can be done on Linux or Windows OS. It has very simple
installation procedure.
After successful installation we can now execute the Node.js document.
The Node.js file has extension .js.
Step 1 : Open Notepad and type the following code. Save the file with some filename
having extension .js
Test.js
var http = require('http');
http.createServer(function (req, res) {
res.writeHead(200, {'Content-Type': 'text/html'});
res.end("Welcome to the Learn NodeJS!");
}).listen(8082);
console.log('Server is running at http://localhost:8082/');
Step 2 : Open command prompt window and type the command for executing above
script. The screen-shot for this execution is as follows -
Now open the web browser such as Mozilla Firefox or Chrome or Internet Explorer
and in the address bar type the URL http://localhost:8082/
Review Question
Q.5 The following mode opens the file for write only :
a w b r
c w+ d a+
Q.6 How do you get information from a form that is submitted using the “get” method ?
a $_GET[]; b Request.Form;
c Request.QueryString; d Request.GetQuery;
Q.7 Which superglobal variable holds information about header, paths and script, locations ?
a $_GLOBALS b $-SERVER
c $-SESSION d $_GET
Q.9 Which function sets the file filename’s last-modified and last-accessed times ?
a sets() b Set()
c touch() d touched()
Q.13 In ASP.NET application, the DLL files are stored in _______ folder.
a bin b App_data
c App_code d App_LocalResources
Q.14 Which of the following is the first event of ASP.NET page when the user requests a web
page ?
a Init b PreInit
c Render d Control Events
Q.15 Which of the following is the page life cycle event of ASP.NET page when the user makes
use of button control to invoke click events a web page ?
a Init b PreInit
c Render d Control Events
Q.17 Which of the following is a directory service where enterprises register and search for
web services ?
a WSDL b UDDI
c Supporting protocols of SOAP d None of the above
Syllabus
Introduction to Ruby : Origins & uses of Ruby, scalar types and their operations, simple input and
output, control statements, fundamentals of arrays, hashes, methods, classes, code blocks and
iterators, pattern matching. Introduction to Rails : Overview of Rails, Document Requests,
Processing Forms, Rails Applications and Databases, Layouts, Rails with Ajax. Introduction to EJB.
Contents
6.1 Origins & Uses of Ruby
6.2 Scalar Types and their Operations
6.3 Simple Input and Output
6.4 Control Statements
6.5 Fundamentals of Arrays
6.6 Hashes
6.7 Methods
6.8 Classes
6.9 Code Blocks and Iterators
6.10 Pattern Matching
6.11 Overview of Rails
6.12 Document Requests
6.13 Processing Forms
6.14 Rails Applications and Databases
6.15 Layouts
6.16 Rails with Ajax
6.17 Introduction to EJB ............................................... May-18, 19, Dec.-19, ............ Marks 8
6.18 Multiple Choice Questions
(6 - 1)
Web Technology 6-2 Ruby and Rails
Output
The value of pi variable is 3.14
The radius of the circle is 15
The area of the circle is 706.5
There is no need to declare the variable in Ruby.
In Ruby every data value is an object. Hence objects need references.
If a scalar variable is not assigned with a value then it is assigned with the value nil.
The constants in Ruby are declared with the first letter capital. A constant is created
when a variable is assigned with some value it becomes a constant variable.
There are special variables in variables which are called as implicit variables. The
scalar variables that are implicit variables begin with dollar sign while other type of
implicit variables can begin either by underscore _, carrot ^ or back slash \
The variables in Ruby are typeless. All that is assigned in an assignment statement
is address of an object.
There is a math module supported by Ruby. This module provides the methods for
basic trigonometric and mathematical functions. For instance the functions such as
cos, sin, tan, sqrt are supported by this module.
Along with the software package of Ruby an interactive interpreter is provided.
This interpreter is called Interactive Ruby. The acronym for this interpreter is irb.
The user can type the expression and get the answer of this expression immediately.
For that purpose, click on Start->All Programs->Ruby 1.9.2->Interactive Ruby.
Following is the illustration -
Every variable in Ruby refers to some memory location. If one variable is assigned
to another variable then that variable will refer to the same memory location. For
example :
For example : In above screen-shot you can see that the variable str1 contains the string
“MyRuby”. Another variable str2 is assigned with the value of str1. Hence on typing the
string str2 we get the same string i.e.”MyRuby”. Now the string str1 is assigned with
another string “Program”. Hence we get str1=”Program” but still the value of
str2=”MyRuby”.
Instead of directly assigning some string to str1, we can use the replace method for
assigning some new string.
For example: Instread of
str1=”Program”
we can write
str1.replace(“Program”);
Following are some methods that are used for various string operations -
Method/Operator Action Example
Capitalize This method converts the first letter to "india".capitalize => "India"
uppercase But
"11a".capitalize => "11a"
chop This method removes the last character. "Lucky".chop => "Luck"
chomp This method the newline from the right "Hello\n Friends\n".chomp
end, if there is one. => "Hello\n Friends"
equal The method equal is used to compare "Nisha".equal?("Nisha") => false
== two objects. because these are treated as two
The == equal to operator treats the string different objects
literally. "Nisha"=="Nisha" => true
because the string is compared
literally
upcase This method converts all the lower case "nisha".upcase => "NISHA"
letters to the object case.
downcase This method converts the upper case " NISHA ".upcase => "nisha”
letters of the string to lower case.
strip This method removes the space on both " India ".strip => "India"
ends.
lstrip This method removes the space from the " India ".lstrip => "India "
left end
rstrip This method removes the space from the " India ".strip => " India"
right end
swapcase This method converts the upper case to "NiSha".swapcase => "nIsHA"
lower case and lower case to upper case.
reverse It reverses the string. "Ruby".reverse => "ybuR"
The gets.to_i or the gets.to_f method is useful for obtaining the integer or the float
value. Following are the simple steps that can be followed for executing the ruby
program :
Step 1 : Open the suitable text-editor such as Notepad or Wordpad. Type the following code
and save this file using the extension .rb.
InputDemo.rb
puts "Enter the value of a"
a=gets.to_i
puts "Enter the value of b"
b=gets.to_i
c=a+b
puts "The addition of two numbers a and b is #{c}"
Step 2 : Now type the command at the command prompt for executing the ruby program as
Ruby InputDemo.rb
The associativity of the operators is as shown in the following table. The highest
precedence operators are listed first and then the lowest precedence operators.
** Exponentiation Right
The control statements are for controlling the flow of control of the program.
The if statement is of following form -
Ruby allows two kinds of multiple selection constructs. Both named case. The first
form of case statement is as follows -
The until statement is also used for looping. The body of until statement executes
when the condition is false.
Syntax
until conditional [do]
loop body statements
end
Ruby Script[UntilDemo.rb]
$i = 0;
$n = 3;
until $i > $n do
puts("Inside loop with i = #$i" );
$i +=1;
end
puts("Outside the loop with i=#$i")
Output
Inside loop with i = 0
Inside loop with i = 1
Inside loop with i = 2
Inside loop with i = 3
Outside the loop with i=4
The break statement is used to terminate the current execution. For example :
Ruby Script[BreakDemo.rb]
for count in 0..7
if count > 2*2 then
break
end
puts "count= #{count}"
end
Output
count= 0
count= 1
count= 2
count= 3
count= 4
Example 6.4.1 Write a Ruby program that inputs the list of numbers from keyboard and finds
the second smallest number in the list, along with its position in the list.
Solution :
Ruby Program[SecondDemo.rb]
i=0
arr=Array.new
puts "Enter the elements for the list. Press Cntrl+z for to terminate the list"
while(val=gets)
arr[i]=val
i+=1
end
first = arr[0]
second = arr[0]
i=0
for value in arr
if value < first
second = first
secondkey=i
first = value
elsif value < second
second = value
secondkey=i
end
i+=1
end
puts "The smallest element is #{second}and the position is #{secondkey}"
Output
The reverse method is used to reverse the contents of the array. For example :
irb(main):001:0> A=[10,20,30,40,50]
=> [10, 20, 30, 40, 50]
irb(main):002:0> A.reverse
=> [50, 40, 30, 20, 10]
irb(main):003:0> A
=> [10, 20, 30, 40, 50]
irb(main):004:0>
The sort method is used to sort the contents of the arrays. For example
irb(main):001:0> A=[30,10,20,50,40]
=> [30, 10, 20, 50, 40]
irb(main):002:0> A.sort
=> [10, 20, 30, 40, 50]
irb(main):003:0>
The include? is used to check whether the array contains particular element or not.
irb(main):001:0> A=[10,20,30,40]
=> [10, 20, 30, 40]
irb(main):002:0> A.include?(20)
=> true
irb(main):003:0> A.include?(99)
=> false
irb(main):004:0>
6.5.3 Examples
Following is a simple Ruby program that sorts the array and then searches the
desired element from the array.
Ruby Program
i=0
A=Array.new
puts "Enter the elements in the array"
while(i<5)
val=gets
A[i]=val
i+=1
end
A.sort!
puts "The sorted array is "
for val in A
puts val
end
puts "Serching the elements from an array"
puts "Enter the number to be searched"
key=gets
if A.include?(key)
puts "The element #{key} is present in the list"
else
puts "The element #{key} is not present in the list"
end
Output(Run1)
Enter the elements in the array
30
10
50
40
20
The sorted array is
10
20
30
40
50
Serching the elements from an array
Enter the number to be searched
40
The element 40
is present in the list
(Run1)
Enter the elements in the array
30
20
10
50
40
The sorted array is
10
20
30
40
50
Serching the elements from an array
6.6 Hashes
A hash is a collection of key-value pairs like this : "Roll" =>10
Hashes are also called as associative arrays.
The hashes are similar to arrays but the only difference between the two is that,
Hashes Arrays
The hash uses the string values as a The arrays use the integer values as a
subscript to address the elements. These subscript to address the element.
string values are basically the keys.
The elements in hash are not ordered. The elements in array are ordered by
The arrangement of elements in hash subscript. The arrangement of elements
resembles the set. in array resembles the list.
The hash can be created using either the new method or by assigning the key-value
pair. For example :
Ruby Program [HashDemo1.rb]
A = Hash.new( "one" )
puts "\tFirst Method of Hash Creation"
puts "#{A[0]}"
puts "#{A[3]}"
puts "#{A[5]}"
puts "\tSecond Method of Hash Creation"
B=Hash["AAA"=>100,"BBB"=>200,"CCC"=>300]
puts "#{B['AAA']}"
puts "#{B['BBB']}"
puts "#{B['CCC']}"
puts "\t Displaying the keys of the array"
keys=B.keys
puts "#{keys}"
Output
6.7 Methods
Methods in Ruby are similar to the functions.
When a block of statements that get repeated many times in the program then the
method is used.
The method is defined outside the class.
In this section we will discuss how to write the methods in Ruby and call them.
6.7.1 Fundamentals
The method definition includes method header and sequence of statements.
The method header consists of the reserved word def.
The method name must begin with lower case.
The syntax of method definition is as given below -
def method_name ( argument list )
method body
end
or
def method_name
method body
end
If the method has no parameter then the parenthesis can be omitted.
Ruby Program[MethodDemo.php]
def mymethod
puts " This is the method demo"
end
mymethod
Output
This is the method demo
Program Explanation :
In above, program, we have defined the method named mymethod. The method is
called only by its name. The keyword def is used to define the method.
Every method in Ruby returns something. The values can be returned using the
keyword return If there is no return statement then by default the last sentence of
the method is returned. For example :
def mymethod1
i=10
j=20
end
puts mymethod1
The above code will display the output as 20.
Local variables are the variables that are created inside the method.
The scope of the method during the definition of the method.
The advantage of local variables in the method is that if the name of the local
variable conflicts with the name of the global variable then the conflict gets resolved
automatically by using the local variable.
The name of the local variable must begin with either the lower case letter or by
underscore.
The lifetime of the local variable is the period of time over which it exists.
6.7.3 Parameters
There are two types of parameters - Actual parameter and the formal parameter.
For example :
Ruby Program[testmethod.rb]
def testmethod(arg1,arg2)
puts "The first parameter is #{arg1}"
puts "The second parameter is #{arg2}"
end
puts testmethod 10,20
Output
Variable number of parameters can be handled by the method using the asterisk *.
For example :
Ruby Program [testmethod1.rb]
def testmethod1(*arg)
puts "The total number of parameters are: #{arg.length}"
for i in 0...arg.length
puts "The parameters are #{arg[i]}"
end
end
testmethod1 10,20,30
testmethod1 11.1,12.2,13.3,14.4,15.5
Output
The total number of parameters are: 3
The parameters are 10
The parameters are 20
The parameters are 30
The total number of parameters are: 5
The parameters are 11.1
The parameters are 12.2
The parameters are 13.3
The parameters are 14.4
The parameters are 15.5
The call to the method must have same number of actual parameters as the number
of formal parameters.
6.8 Classes
Ruby is purely an object oriented programming language. Hence class is an
important factor of this programming language.
The objects are created from the classes. In other words we can say object is an
instance of a class.
o Class Variables : The class variables belongs to the class. They are used to
define the characteristics of the class. These are available across the objects. The
syntax of these variables is,
@@variable_name
Objects are the instances of the class and these can be created using the method
new.
For example :
Obj1= Myclass.new
There is a method named initialize is a constructor of the class which initializes the
values of the variables. Using the def and the end the method initialize can be
defined.
The name of the method must be starting with the lower case letter. It must be
ended by the keyword end.
Example : Create a class for obtaining the roll number,name and marks of the student. Display
the records.
class Student
@@TotalStudents=0 Class Variables
def initialize(roll, name, marks)
@stud_roll=roll
@stud_name=name
Instance Variables
@stud_marks=marks
end
def display()
puts "Roll Number: #@stud_roll"
puts "name: #@stud_name"
puts "Marks: #@stud_marks"
end
def total()
@@TotalStudents += 1
puts "\tTotal number of students: #@@TotalStudents"
end
end
S1=Student.new("1", "Shilpa", 97.11)
Output
F:\Ruby-Examples>Ruby classDemo.rb
Roll Number: 1
name: Shilpa
Marks: 97.11
Total number of students: 1
---------------------------------------------------
Roll Number: 2
name: Rashmi
Marks: 89.21
Total number of students: 2
There are three access control for the methods - Public, private and protected.
The default access control for the method is public.
The public access method means that the method can be called by any code.
The protected access means only objects of defining class and its subclasses may call
the method.
The private access means private methods of another object can not be accessed by
one object.
For example
Ruby Program [Test.rb]
class Test
def method1
puts "This is the first method"
end
private
def method2
puts "This is second method"
end
protected
def method3
6.8.3 Inheritance
Inheritance is the most important feature of any object oriented programming
language.
By inheritance the two classes are created one base class and another derived class.
Using the object of derived class one can access the methods of itself and the base
class both.
The syntax for declaring the derived class is,
class Derived_class_name < Base_class_name
For example :
Ruby Program [InheritanceDemo.rb]
class A
def method1
puts "I am in method1 of class A."
end
def method2
puts "I am in method2 of class A."
end
end
Note that in above code, using the object of derived class we can access the methods of
base class (i.e. method1 and method2) and the derived class (method3) as well.
A=[10,20,30,40]
A.each{|num| puts "The number is #{num}"}
Output
The number is 10
The number is 20
The number is 30
The number is 40
Using the iterator step the specific values can be displayed. For Example
Ruby Program [BlockDemo1.rb]
Output
The number is 10
The number is 12
The number is 14
The number is 16
The number is 18
The number is 20
A block is always invoked from a function. But the name of the function and the
name of the block must be the same in this case.
For example :
Ruby Program [BlockDemo1.rb]
def myfun
puts "This statement is in method" Block is called
yield
puts "Returning back to the method"
end Block is defined
Output
Open the Interactive Ruby interpreter and type the following commands and
observe the results.
irb(main):001:0> T="Success"
=> "Success"
irb(main):002:0> T=~/es/
=> 4
irb(main):003:0>
The split method is used to separate out the words from the given string. For
example following commands on Interactive Ruby interpreter will show how to
separate out the words from the string using split command.
Ruby allows to save the matched part of the pattern in the variable. Later on we can
use this variable to get the desired part of the pattern.
For example - Open the Interactive Ruby interpreter and type the following
command and observe the results -
irb(main):001:0> pattern="Anuradha-19999"
=> "Anuradha-19999"
irb(main):002:0> pattern=~ /(\w+)-(\d+)/
=> 0
irb(main):003:0> puts "First string is #{$1}"
First string is Anuradha
=> nil
irb(main):004:0> puts "Second string is #{$2}"
Second string is 19999
=> nil
irb(main):005:0>
In above example we have first stored the pattern in a variable say pattern. Then
this pattern is matched with the regular expression. The \w stands for matching the
words. The \d stands for matching the digits. Thus we get the groups of substrings
from the given pattern. Then using $1,$2,… we can retrieve particular part of the
regular expression. The $1 stands for the value of first matched substring, $2 stands
for the value of second matched string.
6.10.3 Substitutions
There are two methods sub and gsub which are for searching the desired pattern
and replacing them.
The sub method searches the first part of the pattern and replace it.
For example :
irb(main):001:0> mystr="PHP is a fun.Enjoy PHP"
=> "PHP is a fun.Enjoy PHP"
irb(main):002:0> mystr.sub(/PHP/,"Ruby")
=> "Ruby is fun.Enjoy PHP"
irb(main):003:0> Note that the first occurrence of PHP is replaced by the
word Ruby and the second occurrence remains
The gsub method is similar to sub but it replaces all the occurrences of matched
substring. For example :
irb(main):001:0> mystr="PHP is a fun.Enjoy PHP"
=> "PHP is a fun.Enjoy PHP" Note that the all the occurrences of
irb(main):002:0> mystr.gsub(/PHP/,"Ruby") PHP are replaced by the word Ruby
and the second occurrence remains
=> "Ruby is a fun.Enjoy Ruby"
unchanged.
irb(main):003:0>
Using sub or gsub have the mutator versions and those are sub! and gsub!. These
versions replace the original string also. For example :
irb(main):001:0> str="PHP is a fun. I like PHP"
=> "PHP is a fun. I like PHP"
irb(main):002:0> str.sub!(/PHP/,"Ruby")
=> "Ruby is a fun. I like PHP"
irb(main):003:0> str
=> "Ruby is a fun. I like PHP"
irb(main):004:0> str1="Java is OOP.I program in Java"
=> "Java is OOP.I program in Java"
irb(main):005:0> str1.gsub!(/Java/,"Ruby");
irb(main):006:0> str1
=>"Ruby is OOP.I program in Ruby"
The web application can be developed ten times faster with Rails than with a typical
Java framework.
Rails is based on MVC architecture - i.e. Model View Controller.
The MVC architecture clearly separates the logical and physical parts of the
applications in three parts - Model, View and Controller.
The Model part is for data and constraints on data. The View part prepares and
presents the result or output. The Controller controls the application.
The most significant characteristic of Rails is its approach to connecting object
oriented software with relational database. But both the object oriented software
and relational databases are not compatible to each other. Hence Rails make use of
Object-Relational Mapping (ORM) approach. By this each relational database
table is simply mapped to a class. For example if the database has a table named
Student then it will be mapped to class Student. Thus ORM maps tables to classes,
rows to objects and columns to field of objects. The ORM of rails is called
activeRecord.
The View and Controller part of MVC are supported by ActionPack components of
Rails. The view documents are generated for three categories of web documents
XHTML, XML and JavaScript and the Controller part of MVC interacts with data
model, user and the view.
Rails can be more commonly used with Ajax. It makes use of the JavaScript
framework named prototype to support Ajax and interaction with JavaScript
model.
Rails uses MVC architecture, consists of designing and building three parts of an
MVC system.
Step 1 : Go to the Projects directory within the Ruby Stack's directory. Create a folder of
any name for storing various applications. I have created a folder named MyProject1.
This is the base directory in which the developer can add new Rails applications. Now we
will create another subdirectory say test1 by issuing the following command
> rails new test1
Following screenshot illustrates it.
Rails respond to this command by generating number of files and directories. Out
of these directories the most important directory from the application point of view
is app. It has four subdirectories namely models, views, controllers and helpers.
The models, views and controllers are those directories that will support MVC of
Rails.
For the sake of understanding just look at the directory structure as given below -
Step 2 : This directory contains several important Ruby scripts that perform the services.
One of the service is generate. This service is used to create or generate the controller
methods. The two parameters are passed to this service - first is controller and second is
the name chosen for the controller. The controller indicates that we want the controller
class to be built. The command will be issued from the test1 directory. The command will
be as follows -
> rails generate controller first welcome
These Controllers are useful for producing the HTTP responses. To respond the
request there must be some actionmethod. This actionmethod simply indicate the
document as a response. The first_controller.rb will be as given below in appearance -
class FirstController < ApplicationController
def welcome
end
end
Step 3 : In above step the welcome is the action method name. It is the response to the
URL http://localhost:3000/first/welcome.
This is actually the view document. The view document is called as template. These
templates will be placed in app/views directory. The template will be written as an
XHTML file. The extension to this file will be .rhtml (or it can be html). The Ruby code
can be inserted in this file. Hence the extension is derived from the word Ruby HTML.
For our first application we can write the template as follows[Note that there is no Ruby
code embedded in the following rhtml file, it simply makes use of HTML tags].
welcome.rhtml
<html>
<head>
<title> FIRST RAILS PROGRAM</title>
</head>
<body>
<center>
<h1>Welcome!!!</h1>
<h3>This is my First Program using Rails </h3>
</center>
</body>
</html>
It can be illustrated as –
Step 4 : Now we will start the server for running the above created static document
application by issuing the following command
> rails server
The following screenshot illustrates this command.
Now open suitable web browser and type the URL http://localhost:3000/first/welcome
on the address bar. [Note that the URL specified during the installation is localhost and
port is 3000]
Dynamic document is a kind of web document in which the contents are changing
more often. For example if your web page is displaying the current date and time or
stack market position or Cricket match score then that document is said to be a
dynamic document.
In this section we will build an application in which the dynamic web document is
created for displaying the current date and time. The implementation of such web
document is possible by embedding some Ruby code within it.
The Ruby code can be embedded within the template file by using <% and %>
markers.
If the Ruby code produces some result then the result can be inserted within the
template document by <%= and %> marker.
Ruby's Time.now is used to display the current time. In earlier section we have seen
how to display the static web document. We will follow steps 1 and 2 from the
above section. The template document created in step 3 is slightly changed. It is as
follows -
welcome.html
<html>
<head>
<title> FIRST RAILS PROGRAM</title>
</head>
<body>
<center>
<h3>Current Date and Time … </h3>
<p> It is now <%= t = Time.now %> </p>
</center>
</body>
</html>
Now start the server by going into the test1 directory by the command -
>Rails server
Open the suitable web browser and get the output as follows -
Now the sampleForm will have all those necessary directories such as app, config,
script and so on generated within it.
Step 2 : Now go to the sampleForm directory and issue the following command on the
command prompt for generating controller.
>rails generate controller order orderform displayorder
Using the params symbol the parameters on the input rhtml file can be invoked.
The .to_i method is used to convert the string to integers.
The sprintf function of C can be used to format the numbers in two decimal places.
This is done for displaying the floating point data in formatted manner.
Save this file and close it. By the above code we have actually written the response
methods namely orderform and displayorder. The orderform.html and
displayorder.html files will be invoked as a response to these action methods. Out
of these the orderform.html is already created. Now we will created
displayorder.html web document.
Step 6 : Now open command prompt and start the server using the command.
>rails server
Then open the suitable web browser and type the following URL in the address bar.
http://localhost:3000/order/orderform
Enter the data and click the Submit button on that form. You will get following
output.
Step 2 : Now generate the controller by the following command in dbdemo directory
> rails generate controller mybook
Then create tables books and subject. Following screenshot illustrates the creation
commands.
Step 5 : Now we will generate the model files that are required for this application. Use
following command for this.
These command will generate the files namely book.rb and subject.rb in app/model
directory.
Open these files using the text editor and edit them as follows -
book.rb
class Book < ActiveRecord::Base
belongs_to :subject
end
subject.rb
class Subject < ActiveRecord::Base
has_many :books
end
The has_many and belongs_to are the relationships used in MySql for specifying the
classes associated with the database tables. When these relationships are provided then
Rails generate the capabilities to manipulate the given relationship.
Step 6 : Now insert the data into tables books and subject. Following commands
illustrates the insertion of data.
Step 7 : Now open the controller file which is present in the controller folder. Edit it as
follows -
mybook_controller.rb
class MybookController < ApplicationController
def welcome
end
def show
@titlename = params[:title]
@bookarr = book.find(:all, :conditions => ["title =?",@titlename])
@subarr = subject.find(:all)
end
<td><b>Publication</b></td>
<td><b>Subject</b></td>
</tr>
<% @bookarr.each do |b|
@accno=b.accNo
@title=b.tilte
@author=b.author
@edition=b.edition
@pub=b.publication
@subject_row=@subarr[b.title_id]
@subjectname=@subject_row. subject_name %>
<tr>
<td><b><%= accno %></b></td>
<td><b><%= title %></b></td>
<td><b><%= author %></b></td>
<td><b><%= edition %></b></td>
<td><b><%= pub %></b></td>
<td><b><%= subjectname %></b></td>
</tr>
<% end %>
</table>
</body>
<html>
6.15 Layouts
The app/View directory of each application has two directories, one is for the
controller and another is named as layouts.
A layout defines the surroundings of an HTML page. In layout directory you can
place a file for common look and feel of your final output. For that purpose layout
template is created.
Rails must be informed about the name of the layout document by placing the
layout command in the ApplicationController class of the application.
In the controller directory of app there is a file named application_controller.rb in
this file the following code can be placed -
class ApplicationController < ActionController::Base
layout "mainlayout"
end
Now if we add mainlayout.rhtml document to layout directory then the basic
layout of the application can be defined.
J2EE application container contains the components that can be used by the clients
for executing the business logic. These components are known as Enterprise Java
Beans (EJB).
EJB mainly contains the business logic and business data.
Using the technology like EJB the server side, distributed Java components can be
built.
EJBs provide a core set of system services to Java component. EJB components
always lie in some container which is called as EJB container.
EJB component is an EJB class. It is a Java class written by EJB developer and this
class implements business logic.
EJB component is similar to traditional Java beans but there are some difference
between the two. These differences are as given below -
The java bean components can be visible or The EJB components are always invisible to the
invisible to the user. user.
The Java beans normally run locally. EJB are distributed components and always
exist on the servers.
The Java beans can be used as Activex Control. EJBs can’t be used as Activex Control.
The Java beans can be described with EJBs can be described using
properties, BeanInfo classes and Customizers. DeploymentDescriptor.
Entity Bean
Entity beans are used for modelling the business concepts. Therefore entity beans
represent the data. For example entity bean can represent the bank account or a
customer. The nouns that are used in the problem description refer to the entity
beans. Basically the entity beans represent the real world objects.
Such beans then act as a persistent record in the database.
Session Bean
Session beans are used for managing processes or tasks. For example Compute net
profit or transaction or browsing for some information on the web browser. Hence session
beans are used for managing activities. Basically session beans represent the
activities. Hence session beans are transient, because activities generally exist for a
short period. Session bean does not represent anything in the database but it can
access the database. Session beans are client specific.
What are the differences between entity bean and session bean ?
2. It refers to the records in the database. These refers to the activities for the database.
3. These can survive on server crash. Session objects generally cannot survive on
(After server gets online these can be server crashes.
reconstructed from the underlying
data).
Stateless
Stateless bean is designed for simple and lightweight components.
This brings the scalability in server performance. As no state is maintained in this
type of bean it is called stateless bean.
The stateless beans are not tied to any specific client. Hence any available instance
of stateless session bean can be used to service a client.
Stateful
The stateful bean is used to store the internal states of the EJB.
There is only one stateful session bean per EJB client.
These types of beans can be saved across client sessions. And we can restore them
back.
Message driven Bean
Message driven is similar to the session bean but it gets activated only when
asynchronous message arrives.
A message-driven bean's instances retain no data or state for a specific client.
A single message-driven bean can process messages from multiple clients.
When a message arrives then the EJB container calls the message driven bean’s
onMessage method to process the method.
6.17.3 Architecture
Components of EJB
The EJB container provides following services to EJB component -
o Security
o Transactions
o Messaging
o Persistence
o Distributions
o Connectivity
The idea behind developing EJB is to provide a framework for the components that
can be plugged into a server. This ultimately helps to increase the functionality of
the server.
EJB is a managed component that can be created, controlled and managed by its
container J2EE.
There can be multiple EJBs in the container J2EE. The container J2EE provides the
resources (such as memory and database connections) required by the EJB.
Thus J2EE maintains a pool of EJB instances. These instances can be assigned to the
clients.
Client makes use of these EJB components and when it is no longer required by the
client, these instances can be returned to the pool so that other clients can used
these instances. The client who is using the EJB instance does not need to know
about its container.
Fig. 6.17.2
EJB has a technique that keeps business logic separate from the database. In other
words, the business logic can deal with business data without caring about how
data is stored in database.
There are two main purposes of the container firstly control the EJB it contains and
secondly provide the services to the EJB that are currently present in the container.
The EJBs are typically one part of a three tier architecture as shown below.
Now as I want GlassFish server for supporting my EJB app, I will choose
Java EE bundle for downloading. Here is the screenshot of download page
of NetBeans -
Step 2 : The exe file will start downloading on your machine. After getting the exe
file, click on it and start running the installer.
As shown in above screen-shot, Just check for GlassFish Server option. The GlassFish
is an Open Source server project started by Sun-Microsystems. It supports the
implementation of Enterprise Java Beans, JSF, RMI, JSP and Servlets.
Step 3 : Just go on installing the software by clicking Next button. Just uncheck for
Updates if you do not want any updates for NetBeans. Finally uncheck for
“Contribute to the NetBeans project by providing … “ and click Finish button.
Here completes the installation of your NetBeans software.
Step 1 : Select File->New Project->Java EE-> EJB Module and Click Next Button.
Give the Suitable Name to the project. Here I am giving “MyAddApp”. Click Next
Button.
Select the server as GlassFish.
Select the J2EE version what ever is installed on your machine and then click Finish
button.
Step 2 : Create a new Java Package called myPkg (I have given this name to my package.
You can give any suitable name) under the Source Package Folder.
Then create an interface called “MyInterface” under myPkg package and add
following code.
MyInterface.java
packagemyPkg;
import javax.ejb.Remote;
@Remote
public interface MyInterface {
The glassfish-ejb-jar.xml file will be created under the Configuration Files Folder.
Set the JNDI Name for the MyClass Bean by editing the file or by clicking the TAB
"EJB" and giving jndi name as "aaa". The edited xml file is as shown below -
Glassfish-ejb-jar.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE glassfish-ejb-jar PUBLIC "-//GlassFish.org//DTD GlassFish Application Server 3.1
EJB 3.1//EN" "http://glassfish.org/dtds/glassfish-ejb-jar_3_1-1.dtd">
<glassfish-ejb-jar>
<enterprise-beans>
<ejb>
<ejb-name>MyClass</ejb-name>
<jndi-name>aaa</jndi-name>
</ejb>
</enterprise-beans>
</glassfish-ejb-jar>
Step 5 : Right click on Project node(MyAddApp) and select Clean and Build.
After clean and Build again right click and click on project node and select deploy
For both these actions “BUILD SUCCESSFUL” message will be displayed in the
console output. Thus the JNDI name “aaa” is successfully deployed with our EJB bean
MyClass.
Step 6 : Now it’s the time to create the driver class which will call the method add which
we have defined in our bean program MyClass.java(Refer step 3). For that
purpose, again right click on the myPkg and create a Java Class. I have named it
as DriverClass . This program will contain the JNDI name and call to the method
add inside the public void main function. The code is as follows -
DriverClass.java
package myPkg;
import java.util.Properties;
import javax.naming.InitialContext;
public class DriverClass {
public static void main(String arg[])throws Exception
{
Properties p=new Properties();
InitialContext c=new InitialContext();
Object obj=c.lookup("aaa");
MyInterface inter=(MyInterface)obj;
System.out.println("The additon of two numbers is = "+inter.add(10,20));
}
}
To let you know, the locations of these files I am giving the screen-shot of Project
explorer window for MyAddApp project.
Step 7 : Right click on DriverClass.java click on Run File option and you will get the
output on console window. Here is the output screenshot.
Step 1 : Click File-> New Project -> Java-> Java Class Library.
Click Next button. Add name to the Project. I have given the name as
MyWebAppInterface and click Finish button.
Step 3 : Now click on MyWebApp-War node, then click on Web-Pages folder, locate the
index.html file. Double click this file and edit it as follows -
index.html
<html>
<head>
<title>Web Application For Bank Transactions</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<form action="Main">
Enter Amount: <input type="text" name="amt_txt">
<br/><br/>
Select Operation:
<br/><br/>
<select name="operation">
<option value="deposit">Deposit</option>
<option value="withdraw">Withdraw</option>
<option value="balance">Balance</option>
</select>
<br/><br/>
<input type="Submit" value="Submit">
</form>
</body>
</html>
Now give suitable name to your bean. Create this bean inside some package. I have
created a bean named MyBean inside the package named mypkg.
Since this is a stateful EJB application, Select the option Stateful. Here I have created
a Local interface. For that purpose, check for Local interface option. Finally click Finish
button. Edit the bean file as follows.
While inserting the code we can right click inside the class MyBean and add business
methods as -
MyBean.java
package myPkg;
import javax.ejb.Stateful;
@Stateful
public class MyBean implements MyBeanLocal {
int balance=0;
@Override
public void deposit(int amount) {
balance=balance+amount;
}
@Override
public boolean withdraw(int amount) {
if(amount<=balance)
{
balance=balance-amount;
return true;
}
return false;
}
@Override
public int getBalance() {
return balance;
}
}
Step 5 : Right click MyWebApp-ejb node and click Run. The GlassFish Server will start
running and you will get BUILD SUCCESSFUL message in console window at
the bottom of your NetBean IDE.
Step 6 : Now , inside the MyWebApp-War node there is a Source Packages , right click it
and create Servlet. I have named this as Main. Click the next button and Check
“Add information to deployment…” as shown -
Now using the instance myBean we can invoke the methods defined in our Java Bean.
Note that this Java bean we have created in step 4.
The edited code for servlet is as follows -
Main.java
import java.io.IOException;
import java.io.PrintWriter;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import myPkg.MyBeanLocal;
public class Main extends HttpServlet {
MyBeanLocal myBean = lookupMyBeanLocal();
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
try (PrintWriter out = response.getWriter()) {
String choice=request.getParameter("operation");
int amount=Integer.parseInt(request.getParameter("amt_txt"));
if(choice.equals("deposit"))
{
myBean.deposit(amount);
out.println("The amount is deposited successfully!!!");
}
if(choice.equals("withdraw"))
{
if(myBean.withdraw(amount))
{
out.println("The amount is wihdrawn successfully!!!");
}
Else
out.println("Sorry, Balance insufficient!!!");
}
if(choice.equals("balance"))
{
out.println("The total balance is = "+myBean.getBalance());
}
}
}
…
….
private MyBeanLocal lookupMyBeanLocal() {
try {
Context c = new InitialContext();
return (MyBeanLocal) c.lookup("java:global/MyWebApp/MyWebApp-
ejb/MyBean!myPkg.MyBeanLocal");
} catch (NamingException ne) {
Logger.getLogger(getClass().getName()).log(Level.SEVERE, "exception caught", ne);
throw new RuntimeException(ne);
}
}
}
Step 7 : Now right click the MyWebApp-ejb and deploy it. Again click on the node
MyWebApp and Run. The browser window will execute the application as
follows -
Declarative Transactions
Transaction management is complex if multiple data access components or multiple
data sources are involved. The EJB provides the transaction management service in
such a way that the complex transaction can be managed without any coding.
The Java API - Java Transaction API (JTA) provides standard interface between
transaction manager, application server and component. There is another Java API
Java Transaction Service (JTS) which is directly used by the application
programmer.
Declarative Security
It is most essential to have security for data and business logic functionality.
Usually application developers provide security using servlets or JSP pages. But
this is complex and error prone task. The EJB uses the simplified security model
due to which EJB resources can be protected from unauthorized access. The EJB
developer rely on security provided at the web level.
Error Handling
The EJB offers clear and consistent error handling framework. The EJB specification
defines how errors affect transactions, client results, server logging and recovery of
components.
Scalability
Using EJB specification rules it is possible for the application server to manage large
number of simultaneous clients. EJB specification is useful to satisfy the multiple
demands for business logic components and data access components.
Portability
EJB’s are written to an industry standard API. Hence they can be run on any new
J2EE compliant application server. There is no need to modify the EJB components
for running them on application servers.
Manageability
EJB container provides the facility to manage access, add or remove users from
appropriate role. Using EJB it is possible to manage secure access to every user
interface that provides the functionality of accessing the users.
In EJB, the client can access the session bean using the business interface.
Depending upon the location of client, there are two types of interfaces used -
1) Remote Interface : The remote interface is used by client that may be running on
different machine than the bean. Using Remote Method Interface (RMI) the
access to the bean can be made.
2) Local Interface : The local interface can be used by the client which is running on
the same machine where the bean is residing.
Various aspects while deciding between local and remote interface are represented in
the following table -
Type of client If the clients are application If the clients are either web components or
clients, web components or EJBs EJBs executing on the same machine.
executing on different machine.
Protocol used If the RMI used for If the local function calls are used for
communication. communication.
Component If the component in the If the components are located on the same
distribution application are distributed, that machine where bean is present.
means present on different
machines.
Loose or tight If the client and bean are coupled If there is a requirement of tight coupling
coupling loosely. between EJB components.
Performance Slow performance due to RMI Better performance due to local calls.
calls.
Location If the client need not know the If the client wants to know that the current
transparency location of EJB and access it machine is the location of EJB.
transparently.
Communication If multiple objects are passed by If objects are passed by reference and the
value so that client and bean can client or bean can change the value of the
operate on different copies of the same object.
object.
Serialization If the serialized objects are passed. If the objects are not serialized.
Review Questions
1. Decide and explain various aspects while deciding between local and remote interface can be
considered. SPPU : May-18, Marks 8
2. What is enterprise Java Bean ? Draw and explain main components of EJB architecture.
SPPU : May-18, Marks 8
3. Draw and explain the role of EJB container in enterprise applications.
SPPU : May-18, Marks 6
4. Draw and explain scenario of client accessing remote EJB. List some of the EJB clients.
SPPU : Dec.-18, May-19, Marks 8
5. Draw and explain each tier of three tiers architecture using EJB.
SPPU : May-19, Marks 8
Q.3 ___ method in ruby is used to insert the element from the end.
a Insert b Push
c Put d None of these
Q.4 What is the extension used for saving the ruby file ?
a .ruby b .rb
c .ry d None of these
Q.5 Which of the following is valid conditional statement in ruby ?
a elseif b elsif
c else if d elseiff
Q.6 What will any variable evaluate to if it is of Boolean data type ?
a True b NULL
c False d Either True or False
Q.7 Which services are provided to EJB components by the EJB container ?
a Transaction support b Persistence support
c Naming support d All mentioned above
Q.8 Session beans don't have _____.
a ejbCreate() method b ejbStore() method
c ejbRemove() method d none of these
Q.9 An entity bean's local interface MUST extend the ________ interface.
a javax.ejb.EJBLocalObject b javax.ejb.EJBObject
c javax.ejb.RemoteObject d none of the above
Q.10 What executes EJB components ?
a A web server b An application server
c An EJB container d A database server
Q.11 What represents a persistent global data from the database ?
a Entity bean b Session bean
c Both A & B d None of the above
Notes
(L - 1)
Web Technology L-2 Web Technology Laboratory
Experiment 1 : Design the XML document to store the information of the employees
of any business organization and demonstrate the use of :
a) DTD
b) XML Schema
And display the content in (e.g., tabular format) by using CSS/XSL.
Employee.dtd
<!DOCTYPE Person[
<!ELEMENT Person (Employee+)>
<!ELEMENT Employee (EmpId,EmpName,Department)>
<!ELEMENT EmpId (#PCDATA)>
<!ELEMENT EmpName (#PCDATA)>
<!ELEMENT Department (#PCDATA)>
]>
</Employee>
<Employee>
<EmpId>222</EmpId>
<EmpName>Rashmi</EmpName>
<Department>Purchase</Department>
</Employee>
<Employee>
<EmpId>333</EmpId>
<EmpName>Sheetal</EmpName>
<Department>Sales</Department>
</Employee>
<Employee>
<EmpId>444</EmpId>
<EmpName>Aniket</EmpName>
<Department>Marketing</Department>
</Employee>
</Person>
Step 2 : Display of information using xsl is done using following .xsl document.
Employeeschema.xsl
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="/">
<html>
<body>
<center>
<h2>Employee Information</h2>
<table border="1">
<tr bgcolor="gray">
<th>EmpId</th>
<th>EmpName</th>
<th>Department</th>
</tr>
<xsl:for-each select="Person/Employee">
<tr>
<td bgcolor="green"><xsl:value-of select="EmpId"/></td>
<td bgcolor="red"><b><xsl:value-of
select="translate(EmpName,'abcdefghijklmnopqrstuvwxyz','ABCDEFGHIJKLMNOPQRSTUVWXYZ')"/>
</b></td>
<td bgcolor="cyan"><xsl:value-of select="Department"/></td>
</tr>
</xsl:for-each>
</table>
</center>
</body>
</html>
</xsl:template>
</xsl:stylesheet>
Solution :
calci.html
<!DOCTYPE html>
<html>
<head>
<title> JavaScript and CSS Calculator </title>
<style>
.form_style
{
width: 300px;
height: 580px;
margin: auto;
border: 5px solid blue;
border-radius: 5px;
padding: 20px;
}
input
{
width: 20px;
background-color: grey;
color: white;
border: 3px solid black;
border-radius: 5px;
padding: 28px;
margin: 5px;
font-weight:bold;
font-size: 15px;
}
#calculate
{
width: 250px;
background-color: khaki;
color:black;
<input type = "button" value = "=" onclick = "result() " id= "equal_to" >
</form>
</div>
<script>
function display(val)
{
myform.answer.value +=val
}
function clear_all()
{
alert("You have clicked clear all button")
myform.answer.value = ' '
}
function square_val()
{
num=myform.answer.value
myform.answer.value = num*num
}
function result()
{
ans = eval(myform.answer.value)
if(ans==Infinity)
{
alert("divide by Zero")
myform.answer.value=' '
}
if(ans==undefined)
{
alert("Enter some input")
myform.answer.value=' '
}
else
myform.answer.value = ans
}
</script>
</body>
</html>
Output
Experiment 4 : Implement the program demonstrating the use of JSP. e.g., Create a
database table students_info (stud_id, stud_name, class, division,
city) using database like Oracle/MySQL etc. and display (use SQL
select query) the table content using JSP.
Solution :
Step 2 : The JSP page containing the input entry form is as given below. On this JSP page
itself we are retrieving the values from the database by connection to it.
Registration_Form.jsp
<%@ page language="java" import="java.sql.*" %>
<%@ page import="java.io.*" %>
<%
Connection conn=null;
ResultSet rs=null;
Statement stmt=null;
Class.forName("com.mysql.jdbc.Driver").newInstance();
conn=DriverManager.getConnection("jdbc:mysql://localhost:3306/registration_DB",
"root","system");
out.write("Connected to mysql!!!");
stmt=conn.createStatement();
if(request.getParameter("action") != null)
{
String Studname=request.getParameter("Studname");
String Studemail=request.getParameter("Studemail");
String Studphone=request.getParameter("Studphone");
stmt.executeUpdate("insert into registration_table(name,email,phone) values(' "+Studname+"
',' "+Studemail+" ',' "+Studphone+" ')" );
rs=stmt.executeQuery("select * from registration_table");
%>
<html>
<body>
<center>
<h2>Student List</h2>
if((Form_obj.Studphone.value.length==0)||
(Form_obj.Studphone.value.length>10))
{
alert("Invalid Phone number Entry, fill up once again!!");
Form_obj.Studphone.focus();
return false;
}
return true;
}
</script>
</head>
<body>
<center>
<form action="Registration_Form.jsp" method="post"
name="entry" onSubmit="return validation(this)">
<input type="hidden" value="list" name="action">
<table border="3" cellpadding="0" cellspacing="0">
<tr>
<td>
<table>
<tr>
<td colspan="2" align="center">
<h2>Student Entry Form</h2></td>
</tr>
<tr>
<td colspan="2"> </td>
</tr>
<tr>
<td>Student Name:</td>
<td><input name="Studname" type= "text" size="50"></td>
</tr>
<tr>
<td>Student Password:</td>
<td><input name="Studpass" type= "password" size="50"></td>
</tr>
<tr>
<td>E-Mail:</td>
<td><input name="Studemail" type="text" size="50"></td>
</tr>
<td>Phone:</td>
<td><input name="Studphone" type="text" size="15"></td>
</tr>
<tr>
<td colspan="2" align="center">
<input type="submit" value="Submit"></td>
</tr>
</table>
</td>
</tr>
</table>
</form>
</center>
</body>
</html>
<%}%>
Experiment 6 : Design a login page with entries for name, mobile number email id
and login button. Use struts and performs following validations
a. Validation for correct names
b. Validation for mobile numbers
c. Validation for email id
d. Validation if no entered any value
e. Re-display for wrongly entered values with message
f. Congratulations and welcome page upon successful entries
Solution : In this web application using struts2 we will create two JSP files and one Java
action file. Moreover, we will create two configuration files named struts.xml and
web.xml. For understanding the locations of these files refer the following screenshot.
Following are the steps to be followed to build the login validation web application.
Sep 1 : Start Eclipse. Create Dynamic Web Project. Copy the required jar files to WEB-
INF/lib folder.
Now Create a Login Page using JSP. This file is created in WebContent or webapp.
This page displays the login form with the textfields such as name, mobile number and
email-id. The code for this JSP script is as follows -
LoginPg.jsp
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%@taglib uri="/struts-tags" prefix="s" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Login Page Demo</title>
<s:head />
</head>
<body>
<s:form action="Login" validate="true">
<s:textfield name="userName" label="User Name" />
<s:textfield name="mobileNum" label="Mobile Number" />
<s:textfield name="email" label="Email ID" />
Step 2 : Create one more JSP document under WebContent or webapp folder named
Welcome.jsp. This JSP file is for displaying welcome message for authentic user. The
code is
Welcome.jsp
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%@taglib uri="/struts-tags" prefix="s"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>login Page Demo</title>
</head>
<body>
<h1>Congratulations!!! </h1>
<h2>Welcome, User <s:property value="userName"/>!!!</h2>
</body>
</html>
Step 3 : Now we will write the Java File for validating the user name, mobile number and
email-id.
The validation for empty fields, or incorrect values is done in this program. If user
enters incorrect values then the error message is displayed with the incorrect values
which user has entered. If user does not enter the values and press the login button, then
error message is displayed for the corresponding fields. If the user enters correct user
name, correct mobile number and correct email-id then only he/she is redirected to
welcome page. This validation is done inside validate() function
The code for this Java program is as follows -
LoginProg.java
package myPkg;
import com.opensymphony.xwork2.ActionSupport;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
Step 4 : Now we will write the configuration files. The struts.xml file under the WEB-
INF/classes folder will be -
Struts.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
"http://struts.apache.org/dtds/struts-2.0.dtd">
<struts>
<constant name="struts.custom.i18n.resources" value="LoginProg" />
<package name="default" extends="struts-default" namespace="/">
<action name = "Login"
class = "myPkg.LoginProg"
method = "execute">
<result name = "success">/Welcome.jsp</result>
<result name = "input">/LoginPg.jsp</result>
</action>
</package>
</struts>
Step 5 : The web.xml file present inside the WEB-INF folder is modified as -
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-
app_3_1.xsd"
id="WebApp_ID" version="3.1">
<display-name>Struts2</display-name>
<welcome-file-list>
<welcome-file>LoginPg.jsp</welcome-file>
<welcome-file>Welcome.jsp</welcome-file>
</welcome-file-list>
<filter>
<filter-name>struts2</filter-name>
<filter-class>
org.apache.struts2.dispatcher.FilterDispatcher
</filter-class>
</filter>
<filter-mapping>
<filter-name>struts2</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
</web-app>
Step 6 : For executing the above application right-click on project name(here it is test) in
the Project Explorer window, click on Run As->Run Configuration. Set the tomcat(under
Apache) which is available on your machine.
Then right click on the project name and click Export > WAR File to create a War file.
Then deploy this WAR in the Tomcat's webapps directory. For a destination click the
Browse button and select the path c:/your_tomcat_directory/webapps folder by accepting
the default name of the war file. Normally "your_project_name.war" file gets generated.
Here we get test.war in the c:/tomcat_directory/webapps. The output can be viewed on a
browser window by typing the URL for localhost. Note that as my tomcat is running on
port 8082(default is 8080 port, but you can change the port number if you want), I am
giving the URL with localhost:8082
We will first check various invalid entries. Refer following screenshots -
Now we will enter all the authentic and valid entries and get the welcome page
Solution :
Step 1 : Create a javascript(.js) that defines the configurations and controllers written
using AngularJS. This file directs to respective homepage, registration or login page,
when the link for homepage, registration page or login page is clicked.
appDemo.js
var app = angular.module('myApp', ['ngRoute']);
app.config(function($routeProvider) {
$routeProvider
.when('/', {
templateUrl : 'home.html',
controller : 'HomeController'
})
.when('/registration', {
templateUrl : 'registration.html',
controller : 'RegistrationController'
})
.when('/login', {
templateUrl : 'login.html',
controller : 'LoginController'
})
.otherwise({redirectTo: '/'});
});
app.controller('HomeController', function($scope) {
$scope.message = 'Welcome to a home page';
});
app.controller('RegistrationController', function($scope) {
$scope.message = 'Please fill up the Registration form(New User)';
});
app.controller('LoginController', function($scope) {
$scope.message = 'Please fill up the Login form(Existing User)';
});
appDemo.html
<!DOCTYPE html>
<html ng-app="myApp">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet"
href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.7/angular.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.7/angular-route.min.js"></script>
</head>
<body ng-app="myApp">
<div class = "row">
<div class = "col-sm-12 well">
<center><h1>OUR WEB SITE</h1></center>
</div>
</div>
<div class="row">
<div class ="col-sm-4 well" style = "background-color:pink;height:500px">
<ul>
<li><a href="#/">Home</a></li>
<li><a href="#/registration">Registration</a></li>
<li><a href="#/login">Login</a></li>
</ul>
</div>
<div class ="col-sm-8 well" style="background-color:aqua;height:500px">
<div ng-view></div>
</div>
</div>
<script src="appDemo.js"></script>
</body>
</html>
Step 3 : Now the HTML documents for home page, registration page and login page is as
follows.
home.html
<div>
<center><h3>{{message}}</h3></center> Message for home page
</div>
<div>
<center>
<img src="welcome.jfif"> Displaying image on welcome page
</center>
</div>
registration.html
<html>
<head>
<title>
Registration Form
</title>
</head>
<body>
<h3>{{message}}</h3>
<form>
<p>First Name:<input type="text" name="fname"></p>
<p>Last Name:<input type="text" name="lname"></p>
<p>User Name:<input type="text" name="username"></p>
<p>Password:<input type="password" name="password"></p>
<p><input type="submit" value="submit"></p>
</form>
</body>
</html>
login.html
<html>
<head>
<title>
Login Form
</title>
</head>
<body>
<h3>{{message}}</h3>
<form>
<p>User Name:<input type="text" name="username"></p>
<p>Password:<input type="password" name="password"></p>
<p><input type="submit" value="submit"></p>
</form>
</body>
</html>
Step 4 : Make a separate directory and store above files (from step 1 to step 3) in it. It is
preferable to store this folder in your Apache’s htdocs folder. Open the web browser and
give the URL for appDemo.html document. The output can be viewed as follows -
If we click on Registration link on the left panel we get following registration form.
If we click on Login link present in the left pane then we get following login form.
Q.1 a) List and discuss any four HTTP commands. (Refer example 1.4.1) [4]
b) Define the terms - i) Web site ii) Web server iii) URL. (Refer example 1.7.1) [3]
Q.2 a) What is the difference between HTML and HTML5 ? (Refer section 1.19.2) [5]
b) How will you create a password field in HTML form ? (Refer example 1.18.1) [4]
c) How to you create a multi colour text on a web page using CSS ?
(Refer example 1.26.1) [6]
Q.3 a) Explain data types used in JavaScript. (Refer section 2.5) [4]
c) Write JavaScript to validate a for consisting of Name, Age, Address, EmailID, hobby
(check box), Gender(radio box), country(Drop down menu).
(Refer example 2.24.2) [8]
OR
Q.4 a) Demonstrate the use of load() method using jQuery. (Refer section 2.25.3) [3]
b) When to use jQuery ? What are the advantages and disadvantages of jQuery ?
(Refer section 2.25) [5]
c) Write a AngularJS document for creating a table. (Refer section 2.26.6) [7]
1
Time : 2 Hours] [Total Marks : 70
2
N. B. :
i) Attempt Q.1 or Q.2, Q.3 or Q.4, Q.5 or Q.6, Q.7 or Q.8.
ii) Neat diagrams must be drawn wherever necessary.
ii) Figures to the right side indicate full marks.
iv) Assume suitable data, if necessary.
Q.1 a) What is the difference between server side scripting language and client side scripting
language. (Refer section 3.1) [5]
b) Write a Java servlet program which will display “welcome servlet” message.
(Refer section 3.3) [8]
c) Write HTML form to read user name and password. This data is sent to the servlet. If
the correct user name and password is given then welcome him/her by his/her name
otherwise display the message for invalid user. (Refer example 3.7.2) [5]
OR
Q.2 a) Enlist the steps for connectivity between servlet and database.
(Refer section 3.14.3) [5]
b) What are the strengths of XML technology ? Also list the limitations of XML.
(Refer section 3.15) [5]
c) Write AJAX script to obtain the student information stored in XML document. The
information should be displayed on clicking the button. It should be displayed in
tabular form. (Refer example 3.26.1) [8]
Q.3 a) Write advantages of JSP over servlets. Also explain the life cycle of JSP.
(Refer section 4.2) [5]
c) What is MVC ? Draw and explain MVC architecture for developing web applications.
(Refer section 4.6) [7]
OR
b) Draw and explain neat diagram which depicts MVC to struts architecture.
(Refer section 4.12) [5]
c) Write a client server JSP program to find the simple interest and display the result in
the client. (Refer example 4.5.1) [7]
Q.5 a) Classify data types of PHP and describe various data types. (Refer section 5.3) [4]
b) Explain how session and cookies are used for session management in PHP.
(Refer sections 5.14 and 5.15) [8]
c) What is associative arrays in PHP ? Explain it with the help of simple PHP code.
(Refer section 5.8) [6]
OR
Q.6 a) Identify and explain steps involved in connecting to MySQL with PHP.
(Refer section 5.16) [8]
c) Explain the life cycle of ASP.NET application. (Refer section 5.22.1) [5]
Q.7 a) Explain the scalar types and their operations in ruby. (Refer section 6.2) [6]
b) Write a program in rails for displaying the current date and time.
(Refer section 6.12.2) [6]
c) Write a ruby program to add two numbers. (Refer section 6.3.2) [5]
OR
Q.8 a) Write a ruby program that sorts the array and searches the desired element from
array. (Refer section 6.5.3) [8]
b) Explain how to write a student class in ruby program. (Refer section 6.8.1) [9]