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

Website Tech

Ceramic capacitors Ceramic capacitors refer to a wide range of capacitors available as disc capacitors, MLC (Multi-Layer Ceramic) capacitors, and SMD capacitors. The composition of these capacitors varies with the manufacturers. Some of the commonly used materials in the construction of ceramic capacitors include strontium titanate, titanium oxide, barium titanate, etc. Electrolytic capacitors Electrolytic Capacitors are polarized capacitors that offer high capacitance per unit volum

Uploaded by

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

Website Tech

Ceramic capacitors Ceramic capacitors refer to a wide range of capacitors available as disc capacitors, MLC (Multi-Layer Ceramic) capacitors, and SMD capacitors. The composition of these capacitors varies with the manufacturers. Some of the commonly used materials in the construction of ceramic capacitors include strontium titanate, titanium oxide, barium titanate, etc. Electrolytic capacitors Electrolytic Capacitors are polarized capacitors that offer high capacitance per unit volum

Uploaded by

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

STUDY MATERIAL

ON
ADVANCED WEB TECHNOLOGY
BCA-SE-4034

PREPARED BY
KABYASHREE HAZARIKA
ASSISTANT PROFESSOR
ICON COMMERCE COLLEGE
UNIT 1: Web Development Techniques

WWW:

WWW is stands for World Wide Web introduced in 1990 by Tim Berners- Lee. The World Wide Web (WWW)
is a global information medium which users can read and write via computer connected to the internet. The
Web, or World Wide Web, is basically a system of Internet servers that support specially formatted
documents. The documents are formatted in a markup language called HTML (Hypertext Markup Language)
that supports links to other documents, as well as graphics, audio, and video files. Web pages are primarily
text documents formatted and annotated with Hypertext Markup Language (HTML). In addition to formatted
text, web pages may contain images, video, and software components that are rendered in the user's web
browser as coherent pages of multimedia content.

The Web uses the HTTP protocol, only one of the languages spoken over the Internet, to transmit data. The
Web also utilizes browsers, such as Internet Explorer or Firefox, to access Web documents called Web pages
that are linked to each other via hyperlinks. Web documents also contain graphics, sounds, text and video.

The Internet, linking your computer to other computers around the world, is a way of transporting content.
The Web is software that lets you use that content…or contribute your own. The Web, running on the mostly
invisible Internet, is what you see and click on in your computer’s browser.

Internet:

The Internet is a huge collection of computers across the world connected through a communication network.
Generally each computer in the internet will not be connected to one another known as a Local Area Network
(LAN) and one of the computers in the LAN will be connected to the outside world. So, Internet can also be
described as a network of networks. The interface between various computers in the Internet for
communicating with one another is a low level protocol known as the TCP/IP. In order to communicate with
one another each device in the Internet should be assigned an address which is known as the IP address.
Widely used IP address format is IPV4 which contains 32 bits. An IP address contains 4 octets. A new
standard known as IPV6 has been approved in 1998 which contains 128 bits. As it is quite difficult to
remember the numerical IP addresses, they ar3e converted to names using the DNS (Domain Name System),
which are easy to remember. Names and IP addresses are analogous to variable names and memory
addresses in programming. The name server, is a software which implements the DNS, used to convert a
name (domain name) to its corresponding IP address.

TCP/IP:
TCP/IP stands for Transmission Control Protocol/Internet Protocol and is a suite of communication protocols
used to interconnect network devices on the internet. TCP/IP is also used as a communications protocol in a
private computer network (an intranet or extranet). The TCP/IP protocol suite functions as an abstraction
layer between internet applications and the routing and switching fabric .

TCP/IP specifies how data is exchanged over the internet by providing end-to-end communications that

identify how it should be broken into packets, addressed, transmitted, routed and received at the destination.

TCP/IP requires little central management and is designed to make networks reliable with the ability to recover

automatically from the failure of any device on the network.


The two main protocols in the IP suite serve specific functions. TCP defines how applications can create

channels of communication across a network. It also manages how a message is assembled into smaller packets

before they are then transmitted over the internet and reassembled in the right order at the destination

address.

IP defines how to address and route each packet to make sure it reaches the right destination. Each gateway

computer on the network checks this IP address to determine where to forward the message.

A subnet mask tells a computer, or other network device, what portion of the IP address is used to represent

the network and what part is used to represent hosts, or other computers, on the network.

Network address translation (NAT) is the virtualization of IP addresses. NAT helps improve security and

decrease the number of IP addresses an organization needs.

Common TCP/IP protocols include the following:

• Hypertext Transfer Protocol (HTTP) handles the communication between a web server and a web

browser.

• HTTP Secure handles secure communication between a web server and a web browser.

• File Transfer Protocol handles transmission of files between computers.

How does TCP/IP work?

TCP/IP uses the client-server model of communication in which a user or machine (a client) is provided a

service, like sending a webpage, by another computer (a server) in the network. Collectively, the TCP/IP suite

of protocols is classified as stateless, which means each client request is considered new because it is

unrelated to previous requests. Being stateless frees up network paths so they can be used continuously. The

transport layer itself, however, is stateful. It transmits a single message, and its connection remains in place

until all the packets in a message have been received and reassembled at the destination. The TCP/IP model

differs slightly from the seven-layer Open Systems Interconnection (OSI) networking model designed after it.

The OSI reference model defines how applications can communicate over a network.
Why is TCP/IP important?

TCP/IP is nonproprietary and, as a result, is not controlled by any single company. Therefore, the IP suite can

be modified easily. It is compatible with all operating systems (OSes), so it can communicate with any other

system. The IP suite is also compatible with all types of computer hardware and networks. TCP/IP is highly

scalable and, as a routable protocol, can determine the most efficient path through the network. It is widely

used in current internet architecture.

The 4 layers of the TCP/IP model

TCP/IP functionality is divided into four layers, each of which includes specific protocols:

1. The application layer provides applications with standardized data exchange. Its protocols include HTTP,

FTP, Post Office Protocol 3, Simple Mail Transfer Protocol and Simple Network Management Protocol. At

the application layer, the payload is the actual application data.

2. The transport layer is responsible for maintaining end-to-end communications across the network. TCP

handles communications between hosts and provides flow control, multiplexing and reliability. The

transport protocols include TCP and User Datagram Protocol, which is sometimes used instead of TCP for

special purposes.

3. The network layer, also called the internet layer, deals with packets and connects independent networks

to transport the packets across network boundaries. The network layer protocols are IP and Internet

Control Message Protocol, which is used for error reporting.

4. The physical layer, also known as the network interface layer or data link layer, consists of protocols that

operate only on a link -- the network component that interconnects nodes or hosts in the network. The

protocols in this lowest layer include Ethernet for local area networks and Address Resolution Protocol.
IP:

IP is a low-level internet protocol that facilitates data communications over the internet. Its purpose is to

deliver packets of data that consist of a header, which contains routing information, such as source and

destination of the data, and the data payload itself. IP is limited by the amount of data that it can send. The

maximum size of a single IP data packet, which contains both the header and the data, is between 20 and 24

bytes long. This means that longer strings of data must be broken into multiple data packets that must be

independently sent and then reorganized into the correct order after they are sent.

Since IP is strictly a data send/receive protocol, there is no built-in checking that verifies whether the data

packets sent were actually received. In contrast to IP, TCP/IP is a higher-level smart communications protocol

that can do more things. TCP/IP still uses IP as a means of transporting data packets, but it also connects

computers, applications, webpages and web servers. TCP understands holistically the entire streams of data

that these assets require in order to operate, and it makes sure the entire volume of data needed is sent the

first time. TCP also runs checks that ensure the data is delivered. As it does its work, TCP can also control the

size and flow rate of data. It ensures that networks are free of any congestion that could block the receipt of

data.

An example is an application that wants to send a large amount of data over the internet. If the application

only used IP, the data would have to be broken into multiple IP packets. This would require multiple requests

to send and receive data, since IP requests are issued per packet.

With TCP, only a single request to send an entire data stream is needed; TCP handles the rest. Unlike IP, TCP

can detect problems that arise in IP and request retransmission of any data packets that were lost. TCP can

also reorganize packets so they get transmitted in the proper order -- and it can minimize network

congestion. TCP/IP makes data transfers over the internet easier.

TELNET:

Telnet stands for TErminaL NETwork. It is a type of protocol that enables one computer to connect to local
computer. It is a used as a standard TCP/IP protocol for virtual terminal service which is given by ISO. The
computer which starts a connection known as the local computer. Computer which is being connected to
i.e. which accepts the connection known as remote computer. When the connection is established between
local and remote computer. During telnet operation whatever that is being performed on the remote
computer will be displayed by local computer. Telnet operates on client/server principle. Local computer
uses telnet client program and the remote computers uses telnet server program.
FTP:

FTP stands for File transfer protocol. FTP is a standard internet protocol provided by TCP/IP used for
transmitting the files from one host to another. It is mainly used for transferring the web page files from their
creator to the computer that acts as a server for other computers on the internet. It is also used for
downloading the files to computer from other servers.

Objectives of FTP

1. It provides the sharing of files.


2. It is used to encourage the use of remote computers.
3. It transfers the data more reliably and efficiently.

Why FTP?

Although transferring files from one system to another is very simple and straightforward, but sometimes it
can cause problems. For example, two systems may have different file conventions. Two systems may have
different ways to represent text and data. Two systems may have different directory structures. FTP protocol
overcomes these problems by establishing two connections between hosts. One connection is used for data
transfer, and another connection is used for the control connection.

There are two types of connections in FTP:

1. Control Connection: The control connection uses very simple rules for communication. Through
control connection, we can transfer a line of command or line of response at a time. The control
connection is made between the control processes. The control connection remains connected during
the entire interactive FTP session.
2. Data Connection: The Data Connection uses very complex rules as data types may vary. The data
connection is made between data transfer processes. The data connection opens when a command
comes for transferring the files and closes when the file is transferred.

DNS

An application layer protocol defines how the application processes running on different systems, pass the
messages to each other. DNS stands for Domain Name System. DNS is a directory service that provides a
mapping between the name of a host on the network and its numerical address. DNS is required for the
functioning of the internet. Each node in a tree has a domain name, and a full domain name is a sequence of
symbols specified by dots. DNS is a service that translates the domain name into IP addresses. This allows the
users of networks to utilize user-friendly names when looking for other hosts instead of remembering the IP
addresses.For example, suppose the FTP site at EduSoft had an IP address of 132.147.165.50, most people
would reach this site by specifying ftp.EduSoft.com. Therefore, the domain name is more reliable than IP
address. DNS is a TCP/IP protocol used on different platforms. The domain name space is divided into three
different sections: generic domains, country domains, and inverse domain.
Working of DNS

o DNS is a client/server network communication protocol. DNS clients send requests to the. server while
DNS servers send responses to the client.
o Client requests contain a name which is converted into an IP address known as a forward DNS lookups
while requests containing an IP address which is converted into a name known as reverse DNS
lookups.
o DNS implements a distributed database to store the name of all the hosts available on the internet.
o If a client like a web browser sends a request containing a hostname, then a piece of software such
as DNS resolver sends a request to the DNS server to obtain the IP address of a hostname. If DNS
server does not contain the IP address associated with a hostname, then it forwards the request to
another DNS server. If IP address has arrived at the resolver, which in turn completes the request over
the internet protocol.

SMTP:
SMTP stands for Simple Mail Transfer Protocol. SMTP is a set of communication guidelines that allow software
to transmit an electronic mail over the internet is called Simple Mail Transfer Protocol. It is a program used
for sending messages to other computer users based on e-mail addresses. It provides a mail exchange between
users on the same or different computers, and it also supports. It can send a single message to one or more
recipients. Sending message can include text, voice, video or graphics. It can also send the messages on
networks outside the internet.

The main purpose of SMTP is used to set up communication rules between servers. The servers have a way of
identifying themselves and announcing what kind of communication they are trying to perform. They also have
a way of handling the errors such as incorrect email address. For example, if the recipient address is wrong,
then receiving server reply with an error message of some kind.

Working of SMTP

1. Composition of Mail: A user sends an e-mail by composing an electronic mail message using a Mail
User Agent (MUA). Mail User Agent is a program which is used to send and receive mail. The message
contains two parts: body and header. The body is the main part of the message while the header
includes information such as the sender and recipient address. The header also includes descriptive
information such as the subject of the message. In this case, the message body is like a letter and header
is like an envelope that contains the recipient's address.
2. Submission of Mail: After composing an email, the mail client then submits the completed e-mail to
the SMTP server by using SMTP on TCP port 25.
3. Delivery of Mail: E-mail addresses contain two parts: username of the recipient and domain name.
For example, [email protected], where "vivek" is the username of the recipient and "gmail.com" is the
domain name. If the domain name of the recipient's email address is different from the sender's
domain name, then MSA will send the mail to the Mail Transfer Agent (MTA). To relay the email, the
MTA will find the target domain. It checks the MX record from Domain Name System to obtain the
target domain. The MX record contains the domain name and IP address of the recipient's domain.
Once the record is located, MTA connects to the exchange server to relay the message.
4. Receipt and Processing of Mail: Once the incoming message is received, the exchange server delivers
it to the incoming server (Mail Delivery Agent) which stores the e-mail where it waits for the user to
retrieve it.
5. Access and Retrieval of Mail: The stored email in MDA can be retrieved by using MUA (Mail User
Agent). MUA can be accessed by using login and password.

SNMP:
SNMP stands for Simple Network Management Protocol. SNMP is a framework used for managing devices
on the internet. It provides a set of operations for monitoring and managing the internet.

SNMP has two components Manager and agent. The manager is a host that controls and monitors a set of agents
such as routers. It is an application layer protocol in which a few manager stations can handle a set of agents.
The protocol designed at the application level can monitor the devices made by different manufacturers and
installed on different physical networks. It is used in a heterogeneous network made of different LANs and
WANs connected by routers or gateways.

Difference between Internet and WWW:

The Web is a Portion of The Internet. The Web is just one of the ways that information can be disseminated
over the Internet. The Internet, not the Web, is also used for email, which relies on SMTP, Usenet news
groups, instant messaging and FTP. So the Web is just a portion of the Internet.

Web Browser and Web Server:


Web server and web browser are the terms which are commonly used for website. The basic purpose of both
is to develop a platform for internet web directory. So that any users can anytime access any kind of websites.
Major difference between them is on their function and how they perform their functions.
Web browser is a client, program, software or tool through which we sent HTTP request to web server. The
main purpose of web browser is to locate the content on the World Wide Web and display in the shape of web
page, image, audio or video form. We can also call it a client server because it contacts the web server for desired
information. If the requested data is available in the web server data then it will send back the requested
information again via web browser. Microsoft Internet Explorer, Mozilla Firefox, Safari, Opera and Google
Chrome are examples of web browser and they are more advanced than earlier web browser because they are
capable to understand the HTML, JavaScript, AJAX, etc. Now days, web browser for mobiles are also available,
which are called micro browser.
WEB HTTP REQUEST WEB

BROWSER SERVER
HTTP RESPONSE

Fig1. Communication between Web browser and Web server

Web server is a computer system, which provides the web pages via HTTP (Hypertext Transfer Protocol). IP
address and a domain name is essential for every web server. Whenever, you insert a URL or web address into
your web browser, this sends request to the web address where domain name of your URL is already saved.
Then this server collects the all information of your web page and sends to browser, which you see in form of
web page on your browser. Lot of web server software is available in the market in shape of NCSA, Apache,
Microsoft and Netscape. Storing, processing and delivering web pages to clients are its main function. All the
communication between client (web browser) and server takes place via HTTP.
Uniform Resource Locator (URL):
The resources provided by the web servers are identified through Uniform Resource Locators (URLs). A
resource can be identified through HTTP protocol which is used to request and send XHTML (extensible HTML)
pages. The default port for HTTP is 80. If the web server uses any other port, it should be appended at the end
of the domain name. Like http, we have file scheme which denotes that the resource is available on the local
host or system.
URLs are of two types, first one is absolute URL, where the entire path including the domain name is specified.
Second one is relative URL, where the domain name is skipped and the rest of the path is specified.

HTTP Protocol: Request and Response:

HTTP stands for Hypertext Transfer Protocol. HTTP is based on the client-server architecture model and a
stateless request/response protocol that operates by exchanging messages across a reliable TCP/IP
connection. An HTTP "client" is a program (Web browser) that establishes a connection to a server for the
purpose of sending one or more HTTP request messages. An HTTP "server" is a program (generally a web
server like Apache Web Server) that accepts connections in order to serve HTTP requests by sending HTTP
response messages. Errors on the Internet can be quite frustrating — especially if you do not know the
difference between a 404 error and a 502 error. These error messages, also called HTTP status codes are
response codes given by Web servers and help identify the cause of the problem. HTTP is a stateless protocol
means the HTTP Server doesn't maintain the contextual information about the clients communicating with it
and hence we need to maintain sessions in case we need that feature for our Web-applications HTTP header
fields provide required information about the request or response, or about the object sent in the message
body. There are four types of HTTP message headers:

1. General-header: These header fields have general applicability for both request and response
messages.
2. Request-header: These header fields have applicability only for request messages.
3. Response-header: These header fields have applicability only for response messages.
4. Entity-header: These header fields define Meta information about the entity-body.

According to HTTP, there are several request methods, among which some important methods are listed below:
Method Description
GET Retrieves the content of the required resource
POST Executes the specified resource, using the enclosed data
HEAD Same as GET but only retrieves the header without the body
PUT Replaces the specified resource with the enclosed resource
DELETE Deletes the specified resource

Web 2.0 is term that was introduced in 2004 and refers to the second generation of the World Wide Web. The
term "2.0" comes from the software industry, where new versions of software programs are labeled with an
incremental version number. Some examples of features considered to be part of Web 2.0 are listed below:
1. Blogs : It also known as Web logs, these allow users to post thoughts and updates about their life on
the Web.
2. Wikis: Wikis - sites like Wikipedia and others enable users from around the world to add and update
online content.
3. Social Networking: Sites like Facebook and MySpace allow users to build and customize their own
profile sand communicate with friends.
4. Web Application: Web application is a broad range of new applications make it possible for users to
run programs directly in a Web browser.as Web logs, these allow users to post thoughts and updates
about their life on the Web.
5. User Participation: In traditional web the contents are solely provider by the web site owner or
company, but in web 2.0 the users participate in content sourcing. This is also known as Crowd
sourcing. Examples: Wikipedia & You Tube.
6. Long Tail: The traditional web was like a retail business the product is sold directly to user and the
revenue generated. But in web 2.0 the niche product is not sold directly but offered as a service on
demand basis and income is generated as monthly fee and pay per consumption.
7. Rich User Experience : Traditional web are built with HTML and CSS CGI and had been offered as a
static page. On the other hand Web 2.0 uses AjaxAsynchronous JavaScript + XML) presenting dynamic,
rich user experience to users.
Example: Google Provided Google Maps and Google Suggest
Web 2.0 technologies provide a level user interaction that was not available before. Websites have become
much more dynamic and interconnected, producing "online communities" and making it even easier to share
information on the Web. Because most Web 2.0 features are offered as free services, sites like Wikipedia and
Facebook have grown at amazingly fast rates.
Web Development and Designs:
Web development refers to the building, creating, and maintaining of websites. It includes aspects such as web
design, web publishing, web programming, and database management. It is the creation of an application that
works over the internet i.e. websites. Web Development can be classified into two ways: Frontend Development
and Backend Development.
Frontend Development: The part of a website that the user interacts directly is termed as front end. It is also
referred to as the ‘client side’ of the application.
HTML: HTML stands for Hypertext Markup Language. It is used to design the front end portion of web pages
using markup language. It acts as a skeleton for a website since it is used to make the structure of a website.

CSS: Cascading Style Sheets referred to as CSS is a simply designed language intended to simplify the process
of making web pages presentable. It is used to style and layout our website.

JavaScript: JavaScript is a scripting language commonly used as a part of web pages. It allows client-side script
to interact with the user and to provide dynamic pages.

Bootstrap: Bootstrap is a free and open-source tool collection for creating responsive websites and web
applications. It is the most popular CSS framework for developing responsive, mobile-first websites. Nowadays,
the websites are perfect for all the browsers (Firefox and Chrome) and for all sizes of screens (Desktop, Tablets,
and Phones).
Backend development: Backend is the server side of a website. It is the part of the website that users cannot
see and interact. It is the portion of software that does not come in direct contact with the users. It is used to store
and arrange data.

PHP: The PHP Hypertext Preprocessor (PHP) is a programming language that allows web developers to create
dynamic content that interacts with databases. PHP is basically used for developing web based software
applications. PHP is a server-side scripting language designed specifically for web development.

Java: Java is an object-oriented programming language that produces software for multiple platforms.

Python: Python is a programming language that lets us work quickly and integrate systems more efficiently.

Node.js: Node.js is an open source and cross-platform runtime environment for executing JavaScript code
outside a browser.

DBMS: It is a set of prewritten programs that are used to store, update and retrieve a database. It is a well
organized set of data. It acts as the interface between the data stored on the disk and its user. Database is the
base for data i.e. an assembled group of data.

SQL: SQL stands for Structured Query Language is a standard language for storing, manipulating and
retrieving data in database.

HTML:

HTML stands for Hypertext Markup Language. It is a markup language used to describe the content in a web
document. It was defined using SGML (Standard Generalized Markup Language) which is an ISO
(International Organization for Standardization) standard for describing text-formatting languages. A file
with HTML code is saved with .html extension. Moreover, one thing you should remember that HTML is not a
programming language. We can apply this markup language to your pages to display text, images, sound and
movie files, and almost any other type of electronic information. We use the language to format documents
and link them together, regardless of the type of computer with which the file was originally created.

The initial version of HTML was designed by Tim Berners-Lee along with the Web in the initial 90s. The first
major standardized version of HTML was released in 1995 i.e. HTML 2.0. HTML 4.0 was released in late 1997,
which offers three variations: Strict, Transitional and Frameset.

The basic syntactic units in any HTML document are: Tags, Elements and Attributes. HTML describes
information in a web document with the help of tags, which provide a way for marking the text. An element
consists of three basic parts: an opening tag, the element's content, and finally, a closing tag. The syntax of a
tag is shown below:

<tag-name>

In HTML, the collection of content and the enclosing tags is known as an element. In general, all tags in HTML
support attributes using which additional information is specified to the browser to render the content of the
element. Every (web) page requires four critical elements: the html, head, title, and body elements.

Elements:

1. <html> Element...</html>
• <html> begins and ends each and every web page, that is the root tag for each HTML
document.
• Its purpose is to encapsulate all the HTML code and describe the HTML document to the web
browser.
<html>…..</html>
2. <head> Element
• The <head> element specifies the head section in a web document which usually contains
metadata. It is "next" as they say. As long as it falls somewhere between your tag and your
web page content.
• The head functions "behind the scenes." Tags placed within the head element are not directly
displayed by web browsers.
• We will be placing the <title> element here.
• Other elements used for scripting (JavaScript) and formatting (CSS) will eventually be
introduced and you will have to place them within your head element.
<html>
<head>
</head>
</html>
3. <title> Element
• <title> specifies the title of the web document to be displayed on the browser’s title bar.
• Place the <title> tag within the <head> element to title your page.
• The words you write between the opening and closing <title></title> tags will be displayed
at the top of a viewer’s browser.
<html>
<head> <title> My WebPage. </title>
</head>
</html>
4. <body> Element
• It specifies the body section which contains the actual content of a web document.
• The <body> element is where all content is placed. (Paragraphs, pictures, tables, etc).
• The body element will encapsulate all of your webpage's viewable content.
<html>
<head><title>My WebPage</title> </head>
<body> Hello World. Welcome to my Page. </body>
</html>
Tags:
A web browser reads an HTML document top to bottom, left to right. Each time the browser finds a tag, it is
displayed accordingly (paragraphs look like paragraphs, tables look like tables, etc). Tags have 3 major parts:
opening tag(s), content(s), and closing tag(s). Recall that a completed tag is termed an element.
1. Paragraph Tag <p>:
The <p> tag defines a paragraph. Using this tag places a blank line above and below the text of the
paragraph.

<p>Hello Everyone</p>

<p> I am a student of ICON Commerce College. </p>

2. HTML – Headings 1 to 6:
A heading in HTML is just what we might expect, a title or subtitle. By placing text inside of <h1>
(heading) tags, the text displays bold and the size of the text depends on the number of heading (1-6).
Headings are numbered 1-6, with 1 being the largest heading and 6 being the smallest.
<html><body>
<h1> This is heading 1<h1> <h2> This is heading 2</h2> <h3>This is heading 3</h3>
<h4> This is heading 4</h4><h5>This is heading 5<h5><h6>This is heading 6</h6>
</body> </html>
3. Line Breaks: Line breaks are different then most of the tags we have seen so far. A line break ends the
line you are currently on and resumes on the next line.
<p> Welcome <br>
To <br> ICON Commerce College</p>
Block Elements: The block elements are displayed like blocks of text. Browser renders the block elements as
text followed with a line break and some padding automatically. Some of the well known block elements are:
quotes(<blockquote>), pre formatted text (<pre>), lists(<ul>, <ol> and <dl>), divisions (<div>).
1. HTML Ordered Lists <ol>:
• Use the <ol> tag to begin an ordered list. Place <li> (list item) tag between your opening <ol>
and closing </ol> tags to create list items.
• Ordered simply means numbered, as the list below demonstrates.
<ol>
<li> BCA</li>
<li> BBA</li>
</ol>
• Start your ordered list on any number besides 1 using the start attribute.
<ol start=”4”>
<li> BCA</li>
<li> BBA</li>
</ol>
• There are 4 other types of ordered lists. Instead of generic numbers you can replace them
with Roman numerals or letters, both capital and lower-case. Use the type attribute to
change the numbering.
<ol type=”a”>
<ol type=”A”>
<ol type=”i”>
<ol type=”I”>
</ol>
2. HTML Unordered Lists:
• Create a bulleted list with the <ul> tag. The bullet itself comes in three subtypes: squares,
discs, and circles.
• The default bullet displayed by most web browsers is the traditional full disc.
<ul>
<li> Milk</li>
<li>Chocolate</li>
</ul>
• There are 3 other types of unordered lists.
<ol type= “square”>
<ol type= “disc”>
<ol type= “circle”>
</ol>

3. HTML Definition Term Lists:


• Make definition lists as seen in dictionaries using the <dl> tag. These lists displace the term
word just above the definition itself for a unique look. It's wise to bold the terms to displace
them further.
▪ <dl> - defines the start of the list
▪ <dt> - definition term
▪ <dd> - defining definition
<dl>
<dt><b> Fromage </b></dt>
<dd> French word for cheese.</dd>
<dt><b> Voiture</b></dt>
<dd> French word for car.</dd>
</dl>
4. HTML Nested Lists:
• You can also nest one list within another, so you could make an unordered list inside a
numbered one:
<html>
<ol>
<li>Clear out garage</li>
<ul>
<li> Tomatoes</li>
</ul>
<li> Repair fence</li>
</ol>
</html>
HTML – Formatting Elements:
Several tags exist to further amplify text elements. These formatting tags can make text bold, italic,
sub/superscripted, and more.
Tag Description Example
<b> This tag specifies bold text. <b> Bold Text </b>
<i> This tag specifies italic text. <i> Italic Text</i>
<em> This tag specifies emphasis text. <em> Emphasized Text</em>
<sup> This tag defines superscript text. <sup>b2</sup>
<sub> This tag defines subscript text. <sub>b2</sub>
<tt> This tag defines teletype text. <p><tt> This text is teletype
text.</tt></p>
<blink> This tag is used for blinking the text. <blink> Blinking text tag </blink>
HTML Color Coding System – Color Names:
There are 3 different methods to set color.
1. We can set color using three methods.
• Using color name
<body bgcolor = “red”>
<font color=”red”>
• Using RGB (Red, Green, Blue) value
<body bgcolor=”rgb(72,0,0)”>
<font color=”rgb(72,0,0)”>
• Using hexadecimal value
<body bgcolor=”#ffff00”>
<font color=”#ffff00”>
HTML – Font and Basefont:
1. The <font> tag is used to add style, size, and color to the text on your site. Use the size, color, and face
attributes to customize your fonts.
2. Use a <basefont> tag to set all of your text to the same size, face, and color.
• Font Size: Set the size of your font with size. The range of accepted values is from 1(smallest)
to 7(largest).The default size of a font is 3.
<p><font size =”5”> Here is a size 5 font </font></p>
• Font Color: Set the color of your font with color.
<font color =”#990000”> This text is hexcolor #990000 </font></br>
<font color =”red”> This text is red </font>
• Font Face: Choose a different font face using any font you have installed.
<p><font face=” Web Technology, A developer’s perspective, N.P. Gopalan, J.
Akilandweswari”> This paragraph has had its font…</font></p>
• Basefont – Set a Solid Base: With the basefont tag you will be able to set the default font for
your web page.
<basefont size=”2” color=”green”><p>This Paragraph has had its font…</p> </basefont>
HTML- Hypertext Reference (href) or Hyperlinks:
The href attribute defines reference that the link refers to. Basically this is where the user will be taken if they
wish to click this link. Use the <a></a> tags to define the start and ending of an anchor. Decide what type of
href attribute you need and place this attribute into the opening tag. The text you place between the opening
and closing tags will be shown as the link on a page. Use the demonstration below as a reference. Hypertext
references can be Internal, Local, or Global. For example,
Internal - href="#anchorname"
Local - href="../pics/picturefile.jpg"
Global - href=http://www.xyz.com/
<a href=http://www.google.com/target=”_blank”>Google Home</a>
Link Targets: The target attribute defines whether to open the page in a separate window, or to open the link
in the current browser window.
• target=”_blank” : opens new page in a new browser window
• target=”_self” : loads the new page in current window
• target=”_parent” : loads new page into a frame that is superior to where the link lies
• target=”_top” : loads new page into the current browser window, cancelling all frames
Anchors: To link to sections of your existing page a name must be given to the anchor. By placing blank
anchors just after each heading, and naming them, we can then create reference links to those sections on this
page. For example,
<a href=”#top”> Go to the Top</a>
<a href=”#text”> Learn about Text Links</a>
<a href=”#email”> Learn about Email Links</a>
HTML – Images:
Use the <img/> tag to place an image on your web page.
<img src=”sunset.gif”/>
• Image src: src stands for source, the source of the image or more appropriately, where the picture file
is located. There are two ways to define the source of an image. First you may use a standard URL. As
your second choice, you may copy or upload the file onto your web server and access it locally using
standard directory three methods. The location of this picture file is in relation to your location of
your .html file.
<src=”sunset.gif”>
• Alternative Attribute: The alt attribute specifies alternate text to be displayed if for some reason the
browser cannot find the image, or if a user has image files disabled.
<img src=http://example.com/brokenlink/sunset.gif alt=”Beautiful Sunset”/>
• Image Height and Width: To define the height and width of the image, rather than letting the browser
compute the size, use the height and width attributes.
<img src=”sunset.gif” height=”50” width=”100”>
• Vertically and Horizontally Align Images: Use the align and valign attributes to place images within
your body, tables, or sections.
1. Align(horizontal) – right, left, center
2. Valign (vertical) – top, bottom, center
<p><img src=”sunset.gif” align=”right”> The image will appear along the… isn’t it? </p>
• Images as Links: Images are very useful for links and can be created with the HTML below.
<a href=http://www.xyz.com/><img src=”sunset.gif”></a>
HTML Forms:

A form will take input from the viewer and depending on your needs, you may store that data into a file, place
an order, gather user statistics, register the person to your web forum, or maybe subscribe them to your
weekly newsletter.

Making a Form: <form> is main tag to build a form. It has a few optional attributes too. For example,

<form action=”processform.php” method=”post”> </form>


The action attribute tells the HTML where to send the collected information, while the method attribute
describes the way to send it.

Type of Input:

The main tag for collecting information from the user is <input>. The tag itself contains a name attribute, so
that we can refer to the input by a name, and the size of the entry box in characters. There are quite few
different types of input to choose from:

• <input type=”text”/> This is the default input type and accepts characters and numbers into a text
box. It can also have a value attribute attached to it, which will give it an initial value.
• <input type=”password”/> This is similar to the above text box but anything that is typed cannot be
seen; instead an asterisk is printed to cover up the entry. As the name suggests, this is used for
password entry.
• <input type=”checkbox”/> This gives a box that can be toggled between checked and unchecked. It
can initially be set to one or the other with checked=”checked”.
• <input type=”radio”/> This is similar to checkbox but in group of radio buttons only one can be
selected at a time. This can also have an initial checked state on one of the radio buttons.
• <input type=”file”/> This will give a box to allow you to choose a file similar to when you open or
save files usually on your machine. It can be used to select a file on the local machine for upload to a
server.
• <input type=”submit”/> This allows a form to be submitted. When pressed, the information will be
passed on for processing, usually to a script mentioned in the action attribute option of the form.
• <input type=”image”/> This will also submit the form when selected and, like the img tag, requires
the src attribute to specify an associated image.
• <input type=”button”/> This makes a button available.
• <input type=”reset”/> This will reset the form to its initial state when selected.
• <input type=”hidden”/> This allows hidden data to be passed along with the form.

HTML Text Fields:

The <input> has a few attributes that you should be aware of:

• Type- determines what kind of input field it will be. Possible choices are text, submit, and password.
• Name- assigns a name to the given field so that you may reference it later.
• Size- sets the horizontal width of the field. The unit of measurement is in blank spaces.
• Maxlength- dictates the maximum number of characters that can be entered.
<form method=”post” action=”[email protected]”>
Name: <input type=”text” size=”10” maxlength=”40”name=”name”><br/>
Password: <input type=”password” size=”10” maxlength=”10” name=”password”>

HTML Radio Buttons:

Radio buttons are a popular form of interaction. You may have seen them on quizzes, questionnaires, and
other web sites that give the user a multiple choice question that relate to the radio button.

<form method=”post” action=”[email protected]”> What is your name? <br/>

Shade: <input type=”radio” name=”shade” value=”dark”> Dark


<input type =”radio” name=”shade” value=”light”> Light<br/> </form>

HTML Check Boxes:

Check boxes allow for multiple items to be selected for a certain group of choices. The check box's name and
value attributes behave the same as a radio button.

<form method=”post” action=”[email protected]”> Select your favorite cartoon characters.

<input type=”checkbox” name=”toon” value=”Goofy”>Goofy

<input type=”checkbox” name=”toon” value=”Donald”>Donald

</form>

HTML Drop Down List:

Drop down menus are created with the <select> and <option> tags. <select> is the list itself and each
<option> is an available choice for the user.

<form method=”post” action=”[email protected]”>

College Degree?

<select name= “degree”>

<option> Choose One</option>

<option> Bachelor of Computer Applications</option>

<option> Bachelor of Chemistry</option>

</select>

</form>

HTML Selection List:

Yet another type of form, a highlighted selection list. This form will post what the user highlights. Basically
just another type of way to get input from the user. The size attribute selects how many options will be shown
at once before needing to scroll, and the selected option tells the browser which choice to select by default.

<form method=”post” action=”[email protected]”>

Musical Taste

<select multiple name=”music” size=”4”>

<option value=”emo” selected>Emo</option>

<option value=”metal”>Metal</option>
<option value=”hiphop”>Hip Hop</option>

<option value=”jazz”>Jazz</option>

</form>

HTML Text Areas:

Text areas serve as an input field for viewers to place their own comments onto forums and the like use text
areas to post what you type onto their site using scripts. For this form, the text area is used as a way to write
comments to somebody. Rows and columns need to be specified as attributes to the <textarea> tag. Another
attribute to be aware of is the wrap. Wrap has 3 values.

<form method=”post” action=”[email protected]>

<textarea rows=”5” cols=”20” name=”comments”> Enter Comments Here</textarea>

</form>

HTML Tables:

The <table> tag is used to begin a table. Within a table element are the <tr> (table rows) and <td> (table
counting) tags.

<table border=”1”>

<tr><td>Row 1 Cell 1</td><td> Row 1 Cell2</td></tr>

<tr><td>Row 2 cell 1</td><td> Row 2 Cell 2</td></tr>

</table>

Output:

Row 1 Cell 1 Row 1 Cell 2


Row 2 Cell 1 Row 2 Cell 2
Content is placed within tables cells. A table cell is defined by <td> and </td>. The border attribute defines how
wide the table’s border will be.

1. Spanning Multiple Rows and Cells


Use rowspan to span multiple rows and colspan to span multiple columns. Point to be noted that if you
would like to place headers at the top of your columns, use the <th> tag as shown below. By default
these headers are bold to set them apart from the rest of your table's content.
<table border=”1”><tr><th>Column 1</th><th> Column 2</th><th>Column 3</th></tr>
<tr><td rowspan=”2”>Row 1 Cell 1</td></td>Row 1 Cell 2</td><td>Row 1 Cell 3</td></tr>
<tr><td>Row 2 Cell 2</td><td>Row 2 Cell3</td></tr>
<tr><td colspan=”3”>Row 3 Cell 1</td></tr>
</table>
Output:
Colum 1 Column 2 Column 3
Row 1 Cell 1 Row 1 Cell 2 Row 1 Cell 3
Row 2 Cell 2 Row 2 Cell 3
Row 3 Cell 1
2. Cell Padding and Spacing:
With the cellpadding and cellspacing attributes you will be able to adjust the white space on your
tables. Spacing defines the width of the border, while padding represents the distance between cell
borders and the content within. Color has been added to the table to emphasize these attributes.
<table border=”1” cellspacing=”10” bgcolor=”rgb(0,255,0)”>
<tr><th>Column 1</th><th>Column 2</th></tr>
<tr><td>Row 1 Cell 1</td><td>Row 1 Cell 2</td></tr>
<tr><td>Row 2 Cell 1</td><td>Row 2 Cell 2</td></tr>
</table>
Output:
Column 1 Column 2

Row 1 Cell 1 Row 1 Cell 2


Row 2 Cell 1 Row 2 Cell 2
And we can also change the cellpadding of the table and removing the cellspacing from the example.
HTML <!—Comments-->:
A comment is a way for you as the web page developer to control what lines of code are to be ignored
by the web browser. Comment syntax may be a little complicated, there is an opening and a closing
much like tags.
1. <!—Opening Comment
2. --> Closing Comment

<!—Note to self: This is my banner image! Don’t forget -->

<img src=”http://www.website.com/pics/anyimage.jpg” height=”100” width=”200”/>

HTML Form and different form attributes:

Form is a data collection mechanism within HTML that allows the design of various styles of input to suit most
types of information. An input element can vary in many ways, depending on the type attribute. An input
element can be of type textfield, checkbox, password, radiobutton, submit button, and more. Following are
attributes of <form>:

1. Name: The name attribute specifies the name of a form which is used to reference elements in a
JavaScript.
<form action=”URL” Value: URL
Description: Where to send the form data.
2. Action: The required action attribute specifies where to send the form‐data when a form is submitted.
<form action=”URL”> Value: URL
Description: Where to send the form data.
3. Method: The method attribute specifies how to send form‐data (the form‐data is sent to the page
specified in the action attribute).
<form method=”get|post”>
Value: get
Description: Default. Appends the form-data to the URL in name/value pairs:
URL?name= value&name=value
Value: post
Description: Sends the form-data as an HTTP post transaction.
4. Target: The target attribute specifies a name or a keyword that indicates where to display the response
that is received after submitting the form.
<form target=”_blank|_self|_parent|_top|framename”>
Value Description
_blank The response is displayed in a new window or tab
_self The response is displayed in the same frame (this is default)
_parent The response is displayed in the parent frame
_top The response is displayed in the full body of the window
framename The response is displayed in a named frame
<optgroup>: The <optgroup> is used to group related options in a drop‐down list. If you have a long list of
options, groups of related options are easier to handle for a user.

<select>

<optgroup label=”Swedish Cars”>

<option value=”volvo”>Volvo </option>

<option value=”saab”>Saab </option>

</optgroup>

<optgroup label=”German Cars”>

<option value=”mercedes”>Mercedes</option>

<option value=”audi”>Audi</option>

</optgroup>

</select>

<span>: The <span> tag is used to group inline‐elements in a document. It provides no visual change by itself
and a way to add a hook to a part of a text or a part of a document. When the text is hooked in a <span> element
you can add styles to the content, or manipulate the content with for example JavaScript.

<p>My mother has <span style=” color: lightblue”> lightblue</span>eyes.</p>

eXtensible HyperText Markup Language (XHTML):

The direct descendents of SGML are HTML, XML, WML etc. XHTML is an implementation of XML (eXtensible
Markup Language) in which the syntax rules are stringent. Difference between HTML and XHTML are:

1. HTML is an implementation of SGML, whereas XHTML is an implementation of XML.


2. HTML syntax is non-rigid, whereas XHTML’s syntax is rigid.
3. In HTML, tags and attribute names are case insensitive, whereas in XHTML, they are case sensitive.
4. Unlike HTML, every opening tag should have corresponding closing tag in XHTML.
5. Unlike HTML, all attribute values must be enclosed in double quotes.
6. Unlike HTML, all attribute values must be mentioned explicitly. In HTML, it is valid to write border,
checked, multiple and selected attributes without any values, whereas in XHTML it is invalid.
7. For nesting elements,
• Text cannot be directly nested in body or form elements.
• Block elements cannot be nested in inline elements.
• If an element appears inside another element, the closing tag of the inner element must occur
before the closing tag of outer element.
• Anchor element cannot be nested in another anchor element.
• List element cannot be directly nested in another list element.

HTML doesn’t enforce the above rules, where XHTML does.

HTML5:

1. The DOCTYPE declaration for HTML5 is very simple: <!DOCTYPE html>


2. The character encoding (charset) declaration is also very simple: <meta charset=”UTF-8”>
3. New HTML5 Elements:
• New semantic elements like <header>,<footer> ,<article> , and <section>.
• New form control attributes like number, date, time, calendar, and range.
• New graphic elements: <svg> and <canvas>.
• New multimedia elements: <audio> and <video>
• Elements Removed in HTML5: <acronym>, <applet>,<basefont>, <big>, <center>,
<dir>, <font>, <frame>, <frameset>,<noframes>, <strike>, <tt>

CSS (Cascading Style Sheets):

Although HTML or XHTML tags can specify basic presentation details by adding different attributes, they are
all deprecated in favour of CSS. All the presentation details (like layout, font, colour etc…) of a web document
are specified in a style sheet. With a style sheet we can have more control on how the content in a web document
is presented to the user. Style information can be specified at three levels and this information will be cascaded
to get the end presentation details. Hence the name Cascading Style Sheets (CSS). A style sheet created with
CSS is saved with .css extension.

CSS was developed by Wium Lie and Bert Bos and the first version CSS1 was released in 1996 as
recommendation by W3C (World Wide Web Consortium). Next version CSS2 was published in 1998. In 2011,
a revision of CSS2 was published as CSS2.1. After CSS2, different features in CSS2 were divided into documents
called modules and work on CSS level 3 started separately for each module.

CSS Syntax: A CSS rule is made of two main elements: a selector and one or more declarations enclosed in braces
({}): The syntax for a CSS rule is shown below:

selector {

declaration 1;

declaration 2;

The selector specifies the HTML element to which the presentation effects should be applied and the
declaration contains two parts: property-name and property-value. A HTML element can have several
presentational properties and corresponding property values. An example for applying green colour to a
paragraph element is shoen below:

p{

color: green;

CSS Levels:

Based on where you are writing the style information, there are three levels of CSS: inline, external and internal.

• Inline Style Sheet:


It is possible to place CSS right in your HTML code, and this method of CSS usage is referred to as Inline
CSS. Inline CSS has the highest priority out of external, internal, and inline CSS. This means that you
can override styles that are defined in external or internal by using inline CSS. If you want to add a style
inside an HTML element all you have to do is specify the desired CSS properties with the style HTML
attribute.
<html><head>
<link rel=”stylesheet” type=”text/css” href=”test.css”/></head>
<body>
<p style=”background: blue; color:white;”> A new background and font color with inline CSS</p>
</body>
</html>
• External Style Sheet:
When using CSS it is preferable to keep the CSS separate from your HTML. Placing CSS in a separate
file allows the web designer to completely differentiate between content (HTML) and design (CSS).
External CSS is a file that contains only CSS code and issaved with a ".css" file extension. This CSS file
is then referenced in your HTML using the <link> instead of <style>.
File Creation: Open up notepad.exe, or any other plain text editor and type the following CSS code.
body{ background-color: gray;}p{color:blue;}h3{color:white;}
Save the file as a CSS (.css) file. Name the file "test.css" (without the quotes). Now create a new HTML
file and fill it with the following code.
<html><head>
<link rel=”stylesheet” type=”text/css” href=”test.css” /></head>
<body><h3> A White Header</h3>
<p> This paragraph has a blue font. The background color of this page is gray because we changed it
with CSS! </p>
</body></html>
External CSS keeps your website design and content separate. It's much easier to reuse your CSS code
if you have it in a separate file. Instead of typing the same CSS code on every web page you have, simply
have many pages refer to a single CSS file with the "link" tag. You can make drastic changes to your
web pages with just a few changes in a single CSS file.
3. Internal /Embedded CSS:
This type of CSS is only for Single Page. The embedded CSS also known as document level CSS, allows
us to specify style information within the document in the head section. When using internal CSS, we
must add a new tag, <style>, inside the <head> tag. The HTML code below contains an example of
<style>’s usage.
<html><head>
<style type=”text/css”>
p {color: white;}
body {background-color: black;}
</style><?head><body>
<p>White text on a black background! </p></body> </html>

CSS Background with all its attributes:

CSS background properties are used to define the background effects of an element. They are:

1. CSS Background Color: The background-color property specifies the background color of an element.
The background color of a page is defined in the body selector. Below is example of CSS backgrounds:
body {background-color:#b0c4de;}
2. CSS Background Image: The background-image property specifies an image to use as the background
of an element.
body {background-image:url(‘paper.gif’);}
3. Background Image Repeat: You can have a background image repeat vertically (y-axis), horizontally
(x-axis), in both directions, or in neither direction.
p {background-image: url(icc.jpg); background-repeat: repeat;}
h4 {background-image: url(icc.jpg); background-repeat: repeat-y;}
ol {background-image: url(icc.jpg); background-repeat: repeat-x;}
ul {background-image: url(icc.jpg); background-repeat: no-repeat;}
4. CSS Fixed Background Image: The background-attachment property sets whether a background image
is fixed or scrolls with the rest of the page.
textarea.noScroll { background-image: url(icc.jpg); background-attachment: fixed;}
textarea {
background-image: url(icc.jpg);
background-attachment: scroll; }
5. CSS Background Image Positioning: The background-position property sets the starting position of a
background image.
p {background-image: url(icc.jpg); background-position: 20px 10px;}
h4 {background-image: url(icc.jpg); background-position: 30% 30%;}
ol {background-image: url(icc.jpg); background-position: top center;}

CSS Font with all its attributes:

CSS font properties define the font family, boldness, size, and the style of a text. They are:

1. CSS Font Color: Set the text-color for different elements:


h4 { color: red; }
h5 { color: #9000A1; }
h6 { color: rgb(0, 220, 98); }
2. CSS Font Family: The font family of a text is set with the font-family property.
h4 { font-family: sans-serif; }h5 { font-family: serif; }
h6 { font-family: arial; }
3. CSS Font Size: The font-size property sets the size of the text.
p { font-size: 120%; } ol{ font-size: 10px; } ul{ font-size: x-large; }
4. CSS Font Style: The font-style property is mostly used to specify italic text. This property has three
values:
• normal – The text is shown normally
• italic - The text is shown in italics
• oblique - The text is "leaning" (oblique is very similar to italic, but less supported)

p { font-style: italic; }h4{ font-style: oblique; }

5. CSS Font Weight: The font-weight property sets how thick or thin characters in text should be
displayed.
p { font-weight: 100; } ul{ font-weight: bolder; }
6. CSS Font Variant: The font-variant property specifies whether or not a text should be displayed in a
smallcaps font.
p { font-variant: small-caps; }

CSS Text with all its attributes:

While CSS Font covers most of the traditional ways to format your text, CSS Text allows you to control the
spacing, decoration, and alignment of your text.

1. Text Decoration: The text-decoration property is used to set or remove decorations from text. The text-
decoration property is mostly used to remove underlines from links for design purposes.
h4{ text-decoration: line-through; }
h5{ text-decoration: overline; }
h6{ text-decoration: underline; }
a { text-decoration: none; }
2. Text Indent: The text-indentation property is used to specify the indentation of the first line of a text.
p { text-indent: 20px; } h5 { text-indent: 30%; }
3. Text Align: The text-align property is used to set the horizontal alignment of a text.
p { text-align: right; } h5{ text-align: justify; }
4. Text Transform: The text-transform property is used to specify uppercase and lowercase letters in a
text.
p{ text-transform: capitalize; } h5{ text-transform: uppercase; }
5. CSS White Space: The white-space attribute allows you to prevent text from wrapping until you place
a break </br> into your text.
p { white-space: nowrap; }
6. CSS Word Spacing: With the CSS attribute word-spacing you are able to specify the exact value of the
spacing between your words. Word-spacing should be defined with exact values.
p { word-spacing: 10px; }
7. CSS Letter Spacing: With the CSS attribute letter-spacing you are able to specify the exact value of the
spacing between your letters. Letter-spacing should be defined with exact values.
p { letter-spacing: 3px; }

CSS BOX MODEL:

All HTML elements can be considered as boxes. In CSS, the term "box model" is used when talking about design
and layout. The CSS box model is essentially a box that wraps around HTML elements, and it consists of:
margins, borders, padding, and the actual content. The box model allows us to place a border around elements
and space elements in relation to other elements. The image below illustrates the box model:

Explanation of the different parts:

• Margin - Clears an area around the border. The margin does not have a background color, it is completely
transparent. To specify margin only on individual sides we have properties: margin-top, margin-right,
margin-bottom and margin-left.
p {margin: 10px 20px 10px 20px;} specifies individual margin on all sides in order of top, right,
bottom and left.

• Border - A border that goes around the padding and content. The border is affected by the background
color of the box.
table {
border-style: solid;
border-width: 3px;
border-color: grey;
}
Above example demonstrates different border properties for a table element.
• Padding - Clears an area around the content. The padding is affected by the background color of the box.
To specify padding only on individual sides we have the following properties: padding-top, padding-
bottom, padding-left and padding-right.
p { padding: 10px 20px 10px 20px;} specifies a padding on all sides in order of top, right, bottom
and left.
• Content - The content of the box, where text and images appear.

JAVACRIPT:

JavaScript primarily known as LiveScript was developed by Brendan Eich of Netscape Corporation. It was
developed and released to the public in1995. Due to wide spread adaption of JavaScript, Microsoft developed
their own implementation of JavaScript known as Jscript in 1996. JavaScript was standardized by
ECMA(European Computer Manufacturers Association) and the first standardized version is released in 1997,
namely ECMAScript.

JavaScript is a general purpose programming language which supports multiple programming paradigms like
object-orientation, imperative and functional. HTML and CSS concentrate on a static rendering of a page; things
do not change on the page over time, or because of events. To do these things, we use scripting languages, which
allow content to change dynamically. Not only this, but it is possible to interact with the user beyond what is
possible with HTML. Scripts are programs just like any other programming language; they can execute on the
client side or the server. JavaScript is often written in another file which is saved with .js extension.

Uses of JavaScript:

1. JavaScript is used for validating user input on client-side.


2. JavaScript is used for file handling and database connectivity on the server-side.
3. JavaScript can be used as an alternative to applets.
4. JavaScript is used to implement programming on client-side web documents.
5. JavaScript can be used to implement event driven programming.
6. Along with DOM, JavaScript can be used to develop DHTML (Dynamic HTML).

Syntax of Embedded JavaScript, it is embedded in an HTML document using the <script> tags as shown below:

<script type=”text/javascript”>

---JavaScript Code here---

</script>

The script tag has effect of the stopping the JavaScript being printed out as well as indentifying the code
enclosed. The JavaScript can be placed in the head section of your HTML or the body.

<html>

<body>

<script type=”text/javascript”>

document.write(“<h1>This is heading</h1>”);

</script></body>

</html>

The Scripts placed in the body section are executed as the page loads and can be used to generate the content
of the page. As well as the body section, JavaScript can also be placed in the head part. The advantages of putting
a script in there are that it loads before the main body.

If you want to use the same script on several pages it could be a good idea to place the code in a separate file,
rather than writing it on each. That way if you want to update the code, or change it, you only need to do it once.
Simply take the code you want in a separate file out of your program and save it with the extension .js. Syntax
of External JavaScript is shown below:

<html>
<body>

<script src=”myScripts.js”></script>

</body></html>

JavaScript Variables:

Variables in JavaScript behave the same as variables in most popular programming languages (C, C++, etc) do,
but in JavaScript you don't have to declare variables before you use them. A variable's purpose is to store
information so that it can be used later. A variable is a symbolic name that represents some data that you set.
When using a variable for the first time it is not necessary to use "var" before the variable name. Variable names
must begin with a letter. Variable names are case sensitive (y and Y are different variables).

var x=5; var y=6; varz=x+y;

You can declare many variables in one statement. Just start the statement with var and separate the variables
by comma:

var name="Doe", age=30, job="carpenter";

var name="Doe",

age=30,

job="carpenter";

Variable declared without a value will have the value undefined. If you re-declare a JavaScript variable, it will
not lose its value. The value of the variable carname will still have the value "Volvo" after the execution of the
following two statements.

varcarname="Volvo"; varcarname;

JavaScript Operators:

Operators in JavaScript are very similar to operators that appear in other programming languages. The
definition of an operator is a symbol that is used to perform an operation. Most often these operations are
arithmetic (addition, subtraction, etc), but not always.

Operator Name
+ Addition
- Subtraction
* Multiplication
/ Division
% Modulus
= Assignment
JavaScript Array:

An array is a special variable, which can hold more than one value at a time. The Array object is used to store
multiple values in a single variable. An array can be created in three ways. The following code creates an Array
object called myCars.

1. Regular:
varmyCars=new Array();
myCars[0]="Saab";
myCars[1]="Volvo";
myCars[2]="BMW";
2. Condensed:
varmyCars=new Array("Saab","Volvo","BMW");
3. Literal:
varmyCars=["Saab","Volvo","BMW"];

Access an Array: You refer to an element in an array by referring to the index number. This statement access
the value of the first element in myCars. var name=myCars[0];

This statement modifies the first element in myCars: myCars[0]="Opel";

JavaScript Functions:

A function is a section of code that is separate from the main program. It is defined once but can be invoked
many times. A function can be passed as parameters so that they can be used and a value can be returned back.
There are some functions already built in to JavaScript, such as the Math.cos() function, which calculates the
cosine of an angle. An example function could be:

<html><body>

<script type=”text/javascript”>

var z=multXbyY(5,10);

document.write(“The result is” +z);

functionmultXbyY(x,y) {

document.write(“x is “ +x);

document.write(“y is “ +y);

return x*y;

</script>

</body></html>

JavaScript Conditions:

Conditional statements are used to perform different actions based on different conditions. In JavaScript we
have the following conditional statements:

• if statement - use this statement to execute some code only if a specified condition is true.
if (condition)
{ code to be executed if condition is true }
• if...else statement - use this statement to execute some code if the condition is true and another code if
the condition is false.
if (condition)
{ code to be executed if condition is true }
else {
code to be executed if condition is not true}
• if...else if ...else statement - use this statement to select one of many blocks of code to be executed.
if (condition1)
{ code to be executed if condition1 is true }
else if (condition2)
{ code to be executed if condition2 is true }
else {
code to be executed if neither condition1 nor condition2 is true }
• switch statement - use this statement to select one of many blocks of code to be executed.
switch(n) {
case 1:
execute code block 1
break;
case 2:
execute code block 2
break;
default:
code to be executed if n is different from case 1 and 2
}

Conditional Operator: JavaScript also contains a conditional operator that assigns a value to a variable based
on some condition.

variablename=(condition)?value1:value2

voteable=(age<18)?”Too Young”:”Old Enough”;

JavaScript Loops and Repetition:

Loops can execute a block of code a number of times. Loops are handy, if you want to run the same code over
and over again, each time with a different value. JavaScript supports different kinds of loops:

• for - loops through a block of code a number of times


for (statement 1; statement 2; statement 3) {
the code block to be executed }
i) Statement 1 is executed before the loop (the code block) starts.
ii) Statement 2 defines the condition for running the loop (the code block).
iii) Statement 3 is executed each time after the loop (the code block) has been executed.

for (var i=0; i<5 ; i++) {

x=x + "The number is " + i + “<br>"; }

• for/in- loops through the properties of an object


var person={fname:"John",lname:"Doe",age:25};
for (x in person) {
txt=txt + person[x];
}
• while - loops through a block of code while a specified condition is true
while (condition) {
code block to be executed }
• do/while - also loops through a block of code while a specified condition is true
do {
code block to be executed }
while (condition);

JavaScript Objects:

JavaScript has several built-in objects, like String, Date, Array, and more. An object is just a special kind of data,
with properties and methods.

Accessing Object Properties: Properties are the values associated with an object. The syntax for accessing the
property of an object is: objectName.propertyName

Accessing Objects Methods: Methods are the actions that can be performed on objects. You can call a method
with the following syntax: objectName.methodName()

Creating JavaScript Objects:

With JavaScript you can define and create your own objects. There are 2 different ways to create a new object:

1) Define and create a direct instance of an object.


This example creates a new instance of an object, and adds four properties to it:
person=new Object();
person.firstname="Narendra";
person.lastname="Modi";
person.age=24; person.eyecolor="blue";
2) Use a function to define an object, then create new object instances.
JavaScript allows you to create your own objects. The first step is to use the new operator.
VarmyObj= new Object();
This creates an empty object. This can then be used to start a new object that you can then give new
properties and methods. In object- oriented programming such a new object is usually given a constructor
to initialize values when it is first created. However, it is also possible to assign values when it is made
with literal values.
<!DOCTYPE html>
<html>
<body>
<script language=”JavaScript” type=”text/JavaScript”>
person={
firstname: "Ketan",
lastname: "Chavda",
age: 24,
eyecolor: "blue"
}
document.write(person.firstname + " is " + person.age + " years old.");
</script></body></html>

How a constructor can be used to populate data in the object?

A constructor is pre defined method that will initialize your object. To do this in JavaScript a function is used
that is invoked through the new operator. Any properties inside the newly created object are assigned using
this keyword, referring to the current object being created.

<!DOCTYPE html>
<html>
<body>
<script> function person(firstname, lastname, age)
{
this.firstname = firstname;
this.lastname = lastname;
this.age = age;
}
var person1=new person("Narendra","Modi",24);
document.write(person1.firstname + “ ”+ person1.lastname +” “+ person1.age);
</script>
</body></html>
In above the function person becomes the constructor invoked through the new keyword on assignment
to the person1 variable. Here the values are passed as parameters to the constructor. Inside the constructor
the this keyword takes on the value of the newly created object and therefore applies properties to it.

Event Handling in JavaScript:

Event handlers are attributes that force an element to "listen" for a specific event to occur. Event handlers all
begin with the letters "on". There are two types of events in Javascript:

1. Interactive i.g. onClick (a pointer button was clicked)


2. Non-interactive i.g. onLoad (All frames or document have been loaded)

Document object in JavaScript:

There are lots of objects that descend from the document object forming a large sub-tree known as the
Document Object Model (DOM), which has become standardized. The document object represents the HTML
displayed in window. Using this object it is possible to access information about the document itself and also
about the information content. Using this object it is possible to control certain parameters of the current
document like background, foreground and link colors.

VarmyObj= new Object();

document.bgColor = “#9F2020”;

documet.fgcolor = “#FAF519”;

It is possible to access any form information in document by using the form[] array. This contains all the form
objects that are in the document. Below example shows the use of document object.
<html><head>

<title>Document Object Example</title>

<script type=”text/javascript”>

functionincrementCurrent() {

current = parseInt(document.forms["noteForm"].total.value);

document.forms["noteForm"].total.value = current + 1;

</script>

</head><body>

<div id=”mainDiv”>

<h1> Document Object Example</h1>

<form id=”noteForm”>

Current number of notes:

<input type="text" name="total" value="0" size="3"/>

<input type="button" value="Add a new note" onclick= “incrementCurrent()”/>

</form></div>

</body></html>

Why do you need validation? Show the use of regular expression in JavaScript to validate the email address
with example:

The idea behind JavaScript form validation is to provide a method to check the user entered nformation before
they can even submit it. JavaScript also lets you display helpful alerts to inform the user what information they
have entered incorrectly and how they can fix it.

JavaScript Email Address validation using Regular Expression:

<html>

<head>

<title> JavaScript Forms</title></head>

<body>

<form. method=”post” name=”getinfo” onSubmit=”return processForm()”>

<input type=”text” name=”email”/>


<input type=”submit” value=”log in” name=”Login”/>

</form>

<script language=”JavaScript” type=”text/JavaScript”>

functionprocessForm() { varmyform= document.getinfo;

var check= myform.email.value; D

ocument.write(testEmail(check));

Function testEmail(chkMail) {

varemailpattern = “^*\\w-_\.]*[\\w-_\.]\@[\\w]\.+[\\w]+[\\w+$”;

var regex = new RegExp(emailpattern);

returnregex.test(chkMail);}

</script>

</body></html>

This will check for a valid email as describe. The testEmail() function returns true or false. The way it
determines this end result is built on the template/pattern in the string emailpattern. This is used to work out
the order of expected characters, how many times they repeat and specially occurring punctuation. The string
in this case that is used as template is:

“^*\\w-_\.]*[\\w-_\.]\@[\\w]\.+[\\w]+[\\w+$”

In this program after the string is declared, a regular expression object is created with the pattern:

var regex = new RegExp(emailpattern);

The pattern can then be tested against the incoming parameter with object’s test method:

returnregex.test(chkMail);

This will return true or false depending on whether there is a match or not.

List the important inbuilt objects:

1. JS String
2. JS Date
3. JS Array
4. JS Boolean
5. JS Math
6. JS RegExp
Math Object Properties:

Property Description
E Returns Euler’s number
LN2 Returns the natural logarithm of 2
LN10 Returns the natural logarithm of 10
LOG2E Returns the base-2 logarithm of E
PI Returns PI
SQRT1_2 Returns the square root of 1/2
SQRT2 Returns the square root of 2
Maths Object Methods:

Method Description
abs(x) Returns the absolute value of x
acos(x) Returns the arccosine of x, in radians
asin(x) Returns the arcsine of x, in radians
atan(x) Returns the arctangent of x as a numeric value between‐PI/2 and PI/2radians
atan2(y,x) Returns the arctangent of the quotient of its arguments
ceil(x) Returns x, rounded upwards to the nearest integer
cos(x) Returns the cosine of x (x is in radians)
exp(x) Returns the value of Ex
floor(x) Returns x, rounded downwards to the nearest integer
log(x) Returns the natural logarithm(base E) of x
max(x,y,z,...,n) Returns the number with the highest value
random() Returns a random number between 0 and 1

Differentiate between server side and client side scripting languages:

Client-side scripting languages:

1. The client-side environment used to run scripts is usually a browser.


2. The processing takes place on the end users computer.
3. The source code is transferred from the web server to the user’s computer over the internet and run
directly in the browser.
4. The scripting language needs to be enabled on the client computer.
5. Sometimes if a user is conscious of security risks they may switch the scripting facility off.
6. When this is the case a message usually pops up to alert the user when script is attempting to run.

Server-side scripting languages:

1. The server-side environment that runs a scripting language is a web server.


2. A user's request is fulfilled by running a script directly on the web server to generate dynamic HTML
pages.
3. This HTML is then sent to the client browser.
4. It is usually used to provide interactive web sites that interface to databases or other data stores on
the server.
5. This is different from client-side scripting where scripts are run by the viewing web browser, usually
in JavaScript.
6. The primary advantage to server-side scripting is the ability to highly customize the response based
on the user's requirements, access rights, or queries into data stores.
Advantages of client side scripting:

1. The web browser uses its own resources, and eases the burden on the server.
2. It has fewer features than server side scripting.
3. It saves network bandwidth.

Disadvantages of client side scripting:

1. Code is usually visible.


2. Code is probably modifiable.
3. Local files and databases cannot be accessed
4. User is able to disable client side scripting.

Advantages of server side scripting:

1. Allows running programs in programming languages that aren’t supported by the browser.
2. Enables you to program dynamic web applications browser- independently,
3. Client-side programming features such as Java applets, Dynamic Html, and ActiveX controls, all of
which are
browsed specifically.
4. Can provide the client (browser) with data that does not reside at the client.
5. Provides improved security measures, since you can write code that can never be viewed from the
browser.
Disadvantages of server side scripting:

1. Increases the workload of the server.


2. Slower than client side scripting because it requires user request.
What is difference between Java script and JAVA?

1. Java is a statically typed language; JavaScript is dynamic.


2. Java is class-based; JavaScript is prototype-based.
3. Java constructors are special functions that can only be called at object creation; JavaScript
"constructors" are just standard functions.
4. Java requires all non-block statements to end with a semicolon; JavaScript inserts semicolons at the
ends of certain lines.
5. Java uses block-based scoping; JavaScript uses function-based scoping.
6. Java has an implicit this scope for non-static methods, and implicit class scope; JavaScript has implicit
global scope.

XML

XML is a meta-language, which can be used to store data & act as a mechanism to transfer information
between dissimilar systems. XML stands for EXtensible Markup Language. XML is a markup language much
like HTML. XML was designed to describe data. XML tags are not predefined in XML. You must define your
own tags. XML is self describing. XML uses a DTD (Document Type Definition) to formally describe the data.

<?xml version=”1.0”?>

<Person>
< Firstname>Ralph< /Firstname>

<Lastname>Mosely</Lastname>

</Person>

Difference between XML and HTML:

1. XML was designed to store data and transfer the data. While HTML was designed to display data.
2. XML focuses on what data is. Whereas HTML focus on how data looks.
3. In XML you can design your own tag. HTML has predefined tags.
4. XML uses parser to check & read xml files eg. DOM, SAX. HTML don’t use any kind of parser.

Use of XML:

1. Used to exchange data between dissimilar systems.


2. Used to describe content of document.
3. XML can be used as database to store data.

Features of XML: XML has its own tag so it’s self describing. Any language is able to read & write XML. XML
can be work on any platform i.e. OS independent. It’s a plain text file in user readable format so you can edit
or view in simple editor. It has hierarchical structure which is powerful to express complex data and simple
to understand.

XML Key Component:

1. XML Root Element: XML must have root element. The first element after xml version declaration in
file is a root element.
< bookstore>
< book category="CHILDREN">
<title>Harry Potter</title>
< author>J K. Rowling</author>
<year> 2005</year>
< price>29.99</price>
</book>
</bookstore>
In above example is root element.
2. XML Element: An XML element is everything from (including) the element's start tag to (including)
the element's end tag. An element can contain other elements, text, attributes, or a mix of all of the
above. n above example <title>,< author>, < year> and <price> are elements.
3. XML Attribute: Attributes provide additional information about an element. Attributes often provide
information that is not a part of the data. In the example below, the file type is irrelevant to the data,
but can be important to the software that wants to manipulate the element.
< file type="gif">computer.gif</file>
XML Attributes must be quoted. Attribute values must always be quoted. Either single or double
quotes can be used. For a person's sex, the person element can be written like this:
< person sex="male"> or< person sex='female'>
4. XML Namespace: The XML namespace is a special type of reserved XML attribute that you place in an
XML tag. The reserved attribute is actually more like a prefix that you attach to any namespace you
create. This attribute prefix is "xmlns:” which stands for XML Namespace. The colon is used to
separate the prefix from your namespace that you are creating. “xmlns” must have a unique value
that no other namespace in the document has. That is commonly used is the URI (Uniform Resource
Identifier) or the more commonly used URL.
Xmlns=”http://www.mydomian.com/ns/animals/1.1 “

Create a XML file that contains Book Information:

< xml version=”1.0”?>

<bookstore>
<book>
<title>Learning XML</title>
<author>Erik T. Ray</author>
<year>2003</year>
<price>39.95</price>
</book>
<book>
<title>WAD</title>
<author>Ralph Mosely</author>
<year>2001</year>
<price>395</price>
</book>
</bookstore>

DTD (Document Type Definition):

The purpose of a DTD is to define the legal building blocks of an XML document. It defines the document
structure with a list of legal elements. A DTD can be declared inline in your XML document, or as an external
reference.

Internal DTD: This is an XML document with a Document Type Definition

<?xml version=”1.0”?>

<!DOCTYPE note [

<!ELEMENT note (to,from,heading,body)>

<!ELEMENT to (#PCDATA)>

<!ELEMENT from (#PCDATA)>

<!ELEMENT heading (#PCDATA)>

<!ELEMENT body (#PCDATA)>

]>

<note>

<to>Ravi</to>
<from>Ketan</from>

<heading>Reminder</heading>

<body>Don't forget me this weekend!</body>

</note>

The DTD is interpreted like this:

1. !ELEMENT note (in line 2) defines the element "note" as having four elements:
"to,from,heading,body".
2. !ELEMENT to (in line 3) defines the "to" element to be of the type "CDATA".
3. !ELEMENT from (in line 4) defines the "from" element to be of the type "CDATA"

External DTD: This is the same XML document with an external DTD

<?xml version=”1.0”?>

<!DOCTYPE note SYSTEM “note.dtd”>

<note>

<to>Ravi</to>

<from>Krissh</from>

<heading>Reminder</heading>

<body>Don't forget me this weekend!</body>

</note>

This is a copy of the file "note.dtd" containing the Document Type Definition:

<?xml version=”1.0”?>

<!ELEMENT note (to,from,heading,body)>

<!ELEMENT to (#PCDATA)>

<!ELEMENT from (#PCDATA)>

<!ELEMENT heading (#PCDATA)>

<!ELEMENT body (#PCDATA)>

DTD – Elements: In the DTD, XML elements are declared with an element declaration. An element declaration
has the following syntax: <!ELEMENT element-name (element-content)>

• Empty elements: Empty elements are declared with the keyword EMPTY inside the parentheses:
<!ELEMENT img (EMPTY)>
• Elements with data: Elements with data are declared with the data type inside parentheses:
<!ELEMENT element-name(#PCDATA)> or <!ELEMENT element-name(#CDATA)> or
<!ELEMENT element-name(#ANY)>
#CDATA means the element contains character data that is not supposed to be parsed by a parser.
#PCDATA means that the element contains data that IS going to be parsed by a parser. The keyword
ANY declares an element with any content. If a #PCDATA section contains elements, these elements
must also be declared.
• Elements with children (sequences): Elements with one or more children are defined with the name
of the children elements inside the parentheses:
<!ELEMENT element-name (child-element-name,child-element-name,. ... )> or
<!ELEMENT element-name (child-element-name)>
When children are declared in a sequence separated by commas, the children must appear in the
same sequence in the document. In a full declaration, the children must also be declared, and the
children can also have children.
• Wrapping: If the DTD is to be included in your XML source file, it should be wrapped in a DOCTYPE
definition with the following syntax:
<!DOCTYPE root-element [element-declarations]>
• Declaring only one occurrence of the same element: <!ELEMENT element-name (child-name)>
• Declaring minimum one occurrence of the same element:<!ELEMENT element-name (child-name+)>
The + sign in the example above declares that the child element message must occur oneor more
times inside the note element.
• Declaring zero or more occurrences of the same element: <!ELEMENT element-name (child-name*)>
The * sign in the example above declares that the child element message can occur zero or more
times inside the note element.
• Declaring zero or one occurrences of the same element: <!ELEMENT element-name (child-name?)>
The ? Sign in the example above declares that the child element message can occur zero or one times
inside the note element.

DTD – Attributes:

Attributes provide extra information about elements. Attributes are placed inside the start tag of an element.
In the DTD, XML element attributes are declared with an ATTLIST declaration. An attribute declaration has
the following syntax:

<!ATTLIST element-name attribute-name attribute-type default-value>

As you can see from the syntax above, the ATTLIST declaration defines the element which can have the
attribute, the name of the attribute, the type of the attribute, and the default attribute value. The attribute-
type can have the following values:

Value Explanation
CDATA The value is character data
(eval|eval|..) The value must be an enumerated value
ID The value is an unique id
NMTOKEN The value is a valid XML name
ENTITY The value is an entity
NOTATION The value is a name of a notation
xml: The value is predefined
The attribute-default-value can have the following values:

Value Explanation
#DEFAULT value The attribute has a default value
#REQUIRED The attribute value must be included in the element
#IMPLIED The attribute does not have to be included
#FIXED value The attribute value is fixed
XML Schema:

An XML Schema describes the structure of an XML document. XML Schema is an XML-based alternative to
DTD. The XML Schema language is also referred to as XML Schema Definition (XSD). XML Schema is a W3C
Recommendation.

XSD Elements:

XML Schemas define the elements of your XML files. It’s of two types: Simple and Complex type.

XSD Simple Elements:

A simple element is an XML element that can contain only text. It cannot contain any other elements or
attributes. The syntax for defining a simple element is: <xs:element name="aaa" type="bbb"/>

where aaa is the name of the element and bbb is the data type of the element.

XML Schema has a lot of built-in data types. The most common types are: xs:string, xs:decimal, xs:integer,
xs:Boolean, xs:date, xs:time. The corresponding simple element definitions:

<xs:element name="lastname" type="xs:string"/>

<xs:element name="age" type="xs:integer"/>

<xs:element name="dateborn" type="xs:date"/>

XSD Complex Elements:

A complex element is an XML element that contains other elements and/or attributes. There are four kinds of
complex elements: empty elements, elements that contain only other elements, elements that contain only
text, elements that contain both other elements and text. A complex XML element, "product", which is empty:
<product pid="1345"/>

XSD Attributes:

Simple elements cannot have attributes. If an element has attributes, it is considered to be of a complex type.
But the attribute itself is always declared as a simple type. The syntax for defining an attribute is:

<xs:attribute name="aaa" type="bbb"/> Where aaa is the name of the attribute and bbb specifies the data
type of the attribute.

Attributes may have a default value OR a fixed value specified. o A default value is automatically assigned to
the attribute when no other value is specified. o In the following example the default value is "EN":
<xs:attribute name="lang" type="xs:string" default="EN"/>

A fixed value is also automatically assigned to the attribute, and you cannot specifyanother value. o In the
following example the fixed value is "EN": <xs:attribute name="lang" type="xs:string" fixed="EN"/>

Optional and Required Attributes:


Attributes are optional by default. To specify that the attribute is required, use the "use"attribute:

<xs:attribute name="lang" type="xs:string" use="required"/>

Difference between DTD and XML Schema:

XML Schema DTD


Markup Any global element can be root. No Can specify only the root element in the
validation ambiguous content support. document. No content support.
Namespace Declarations only where multiple No namespaces are being used.
support namespaces are used
Code reuse Can reuse definitions using named types. Poorly supported. Can use parameter
entities.
Data type Provides flexible set of data types. No real data type support.
Validation Provides multi-field key cross references.
No co-occurrence constraints.
XSL:

XSL stands for EXtensible Stylesheet Language. Here XSL is the Style Sheets for XML. XSL describes how the
XML document should be displayed. Actually XSL is more than a Style Sheet Language. XSL consists of three
parts:

• XSLT‐a language for transforming XML documents.


• XPath‐a language for navigating in XML documents.
• XSL‐FO‐a language for formatting XML documents.

XSLT: XSLT stands for XSL Transformations. XSLT is the most important part of XSL. XSLT transforms an XML
document into another XML document. XSLT uses XPath to navigate in XML documents.

XSL Transformation and XSL Elements: The style sheet provides the template that transforms the document
from one structure to another. In this case <xsl:template> starts the definition of the actual template, as the
root of the source XML document. The match = “/” attribute makes sure this begins applying the template to
the root of the source XML document. The style sheet is linked into the XML by adding the connecting statement
to the XML document: <? xml‐stylesheet type=”text/xsl” href=”libstyle.xsl” ?>

XSL Transformations: XSLT is used to transform an XML document into another XML document, or another
type of document that is recognized by a browser, like HTML and XHTML. Normally XSLT does this by
transforming each XML element into an (X)HTML element. With XSLT you can add/remove elements and
attributes to or from the output file. You can also rearrange and sort elements, perform tests and make
decisions about which elements to hide and display, and a lot more. A common way to describe the
transformation process is to say that XSLT transforms an XML source‐tree in to an XML result‐tree.

XSLT uses XPath to find information in an XML document. XPath is used to navigate through elements and
attributes in XML documents. In the transformation process, XSLT uses XPath to define parts of the source
document that should match one or more predefined templates. When a match is found, XSLT will transform
the matching part of the source document into the result document.

XSL Elements: XSL contains many elements that can be used to manipulate, iterate and select XML, for output.
Some of the elements are:
• <xsl:for-each> Element: The XSL <xsl:for‐each> element can be used to select every XML element of a
specified node‐set.
• < xsl:if> Element: To put a conditional if test against the content of the XML file, add an element to the
XSL document. Syntax:
< xsl:if test="expression"> …some output if true </xsl:if>
• <xsl:sort> Element: The <xsl:sort> element is used to sort the output.
< xsl:sort select="artist"/>
The select attribute indicates what XML element to sort on.
• <xsl:choose> Element: The <xsl:choose> element is used in conjunction with and to express multiple
conditional tests. Syntax:
<xsl:choose>
<xsl:when test="expression">…some output…
</ xsl:when>
<xsl:otherwise/> …some output…
</xsl:otherwise>
</xsl:choose>
• <xsl:apply-templates> Element: This element applies a template to the current element or to the
current element's child nodes. If we add a select attribute to the <xsl:apply-templates> element it will
process only the child element that matches the value of the attribute. We can use the select attribute
to specify the order in which the child nodes are processed.
< xsl:template match="cd">
<p> <xsl:apply-templates select="title"/>
<xsl:apply-templates select="artist"/> </p>
</xsl:template>

Transforming with XSLT:

It is possible to convert an XML document to XHTML using the browser’s own parser. However, this is not
always possible:

1. The browser at the client end may not be suitable or equipped to do the transformation.
2. It may not be a good idea to include the reference to the style sheet or even have the style sheet
available.

The answer to this process the document and style sheet outside of the browser’s own mechanism for
doing this task. This task can be done either on the client side or the server side.

Open Source:

In general, open source refers to any program whose source code is made available for use or modification.
Open source software is usually developed as a public collaboration and made freely available. It means can be
used without purchasing any license. Open Source is a certification mark owned by the Open Source Initiative
(OSI). Developers of software that is intended to be freely shared and possibly improved and redistributed by
others can use the Open Source trademark if their distribution terms conform to the OSI's Open Source
Definition. To summarize, the Definition model of distribution terms require that:

• The software being distributed must be redistributed to anyone else without any restriction.
• The source code must be made available (so that the receiving party will be able to improve or modify
it).
Example of Open Source: Linux, Apache, MySQL, PHP.

PHP:

PHP is a general‐purpose server‐side scripting language originally designed for web development to produce
dynamic websites. PHP scripts execute on web server and serve WebPages to user on request. PHP was
originally created by Rasmus Lerdorf in 1994. Programmer Rasmus Lerdorf initially created a set of C scripts
he called "Personal Home Page Tools" to maintain his personal homepage. The scripts performed tasks such as
displaying his résumé and recording his web‐page traffic. These were released and extended to include a
package called the Form Interpreter (PHP/FI). While PHP originally stood for "Personal Home Page", it is now
said to stand for "PHP: Hypertext Preprocessor", a recursive acronym.

PHP code is embedded into the HTML source document and interpreted by a web server with a PHP processor
module, which generates the web page document. It also has evolved to include a command‐line interface
capability and can be used in standalone graphical applications.PHP can be deployed on most web servers and
as a standalone interpreter, on almost every operating system and platform free of charge.

In 1997 Zeev Suraski and Andi Gutmans along with Rasmus rewrite PHP and released PHP version 3.0 in June
1998.After this release PHP becomes so much popular. The PHP version 4.0 was launched in May 2000.This
version includes session handling, output buffering, a richer cire language and support for wide variety of web
server platforms. The PHP 5.0 version released in 2004 with object oriented programming concept.

Apache Web Server:

The Apache web Server, commonly referred to as Apache is web server software notable for playing a key
role in the initial growth of the World Wide Web. The first version of Apache, based on the NCSA http Web
server, was developed in 1995. The Apache server has been developed by an open source community ‐
Apache Software Foundation, whose members are constantly adding new useful functionalities, with the sole
purpose of providing a secure and extensible server platform that ensures HTTP service delivery in
accordance with the current HTTP standards. The original version of Apache was written for UNIX, but there
are now versions that run under OS/2, Windows and other platforms. The Apache Server provides full range
of Web Server features, including CGI, SSL and virtual domains. Apache also supports plug‐in modules for
extensibility. It was called Apache because it was developed from existing NCSA code plus various patches,
hence the name a patchy server, or Apache server. Apache is open source free software distributed by the
Apache Software Foundation. Apache is reliable, free and relatively easy to configure.

MySQL:

MySQL is a relational database management system (RDBMS) that runs as a server providing multi‐user
access to a number of databases. It is named after developer Michael Widenius' daughter, My. The SQL
phrase stands for Structured Query Language. The data in MySQL is stored in database objects called tables.
A table is a collection of related data entries and it consists of columns and rows. The MySQL development
project has made its source code available under the terms of the License. The license can require improved
versions of the software to carry a different name or version from the original software. First released in
January,1998, MySQL was owned and sponsored by the Swedish company MySQL AB, now owned by Oracle
Corporation. MySQL is fully multithreaded using kernel threads, and provides application programming
interfaces (APIs) for many programming languages, including C,C++, Java, Perl, PHP, Python. MySQL is used
in a wide range of applications, including data warehousing, e‐commerce, Web databases, logging
applications and distributed applications.
Relationship between Apache, MySQL and PHP (AMP Module):

• AMP stands for Apache MySQL PHP

PHP is a server side scripting that was designed for creating dynamic websites. It slots into your Apache web
server and processes instructions contained in a web page before that page is sent through to your web
browser. PHP is a powerful scripting language that can be run in the command line of any computer with
PHP installed. However, PHP alone isn't enough in order to build dynamic web sites.

To use PHP on a web site, you need a server that can process PHP scripts. Apache is a free web Server that,
once installed on a computer, allows developers to test PHP scripts locally; this makes it an invaluable piece
of your local development environment. Like all web servers, Apache accepts an HTTP request and serves an
HTTP response.

Additionally, dynamic websites are dependent on stored information that can be modified quickly and easily;
this is the main difference between a dynamic site and a static HTML site. However, PHP doesn’t provide a
simple, efficient way to store data. This is where a relational database management system like MySQL comes
into play. PHP provides native support for it and the database is free, open‐source project. MySQL is a
relational database management system (DBMS). Essentially, this means that MySQL allows users to store
information in a table‐based structure, using rows and columns to organize different pieces of data.

Creating and Running a PHP Script:

PHP scripts can be embedded in a XHTML document or written separately without any XHTML markup. In
both cases, the file must be saved with the extension .php.

Creating a PHP Script: Any PHP script (code) must be enclosed within the PHP tags which are represented
using <?php and ?> , for example., save the below written program as hello.php

<?php

print “Hello World”; ?>

Running a PHP Script: To run a PHP Script, a web server must be installed and started. Then place the PHP file
hello.php in the web server’s root directory and start the server. Now open the web browser and type the
URL in the address bar: http://localhost/hello.php

General Syntactic Features: In PHP, all variable names begin with a dollar ($) sign. Rules for variable names
are as in other programming languages. PHP variable names are case-sensitive. Unlike variable names,
reserved words and function names are case-insensitive. Some of the reserved words in PHP are listed below:

and, else, global, virtual, break, elseif, if, return, case, extends, include, static, while, class, false, list, etc…

Variables:

A variable is a named location in memory to store data temporarily. PHP is dynamically typed language. So,
there is no need for monitoring the data type of a variable. The type will be detected automatically based on
the value assigned to the variable. A variable can be created as: $var1=10;

A variable which is not assigned a value contains NULL. In expressions containing numbers, NULL will be
coerced to 0 and in case of strings, NULL will be coerced to an empty string. A string can be printed as:
print(“Value of var1 is: $var1”);
A variable can be checked if it contains a value other than NULL by using the function IsSet. This function
returns TRUE if the variable contains a non-NULL value and FALSE if it contains a NULL value.

Constants:

Constants are identifiers which are used to store values that cannot be changed once initialized. A constant
doesn’t begin with a dollar ($) sign. The convention for constant is, the name of a constant should always be
written in uppercase. We use the function define to create constants. Below example demonstrates and using
constants in PHP:

<?php

define(“PI”, 3.14);

print(PI);

$area= PI*10*10; //Let radius be 10

print(“<br/> Area of Circle is: $area”);

?>

Data Types:

PHP provides four scalar types namely Boolean, integer, double and string and two compound types namely
array and object and two special types namely resource and NULL. PHP has a single integer type, named
integer. This type is same as long type in C. The size of an integer type is generally the size of word in the
machine. In most of the machines that size will be 32 bits.

PHP’s double type corresponds to the double type in C and its successors. Double literals can contain a
decimal point, an exponent or both. An exponent is represented using E or e followed by a signed integer
literal. Digits before and after the decimal point are optional. So, both .12 and 12. are valid double literals.

String is a collection of characters. There is no special type for characters in PHP. A character is considered as
a string with length 1. String literals are represented with single quotes or double quotes. In a string literal
enclosed in single quotes, escape sequences and variables are not recognized and no substitution occurs. Such
substitution is known as interpolation. In string literals enclosed in double quotes, escape sequence and
variables are recognized and corresponding action is taken.

The only two possible values for a Boolean type are TRUE and FALSE both of which are case-insensitive.
Integer value 0 is equal to Boolean FALSE and anything other than 0 is equal to TRUE. An empty string and
string “0” are equal to Boolean FALSE and remaining other strings are equal to TRUE. Only double value equal
to Boolean FALSE is 0.0.

Operators:

Operators are used in expressions to perform operations on operands. There are several operators supported
by PHP which are categorized into following categories:

1. Arithmetic operators: PHP arithmetic operators are used along with numbers to perform operations
like addition, subtraction, multiplication etc. Below is a list of arithmetic operators:
Operator Name Example Description
+ Addition $x+$y Sum of x and y
- Subtraction $x-$y Difference of x and y
* Multiplication $x*$y Product of x and y
/ Division $x/$y Quotient of x divided by y
% Modulus $x%$y Remainder of x divided by y
** Exponentiation $x**$y Result of x raised to the power of y
2. Assignment Operators:
PHP assignment operators are used in assignment expressions to store the value of expression in to a
variable. Below is a list of assignment operators:
Assignment Same as Description
x=y x=y Assigning value of y to x
x +=y x= x+y Adding x and y and store the result in x
x-=y x= x-y Subtracting y from x and store the result in x
x*=y x=x*y Multiplying x and y and store the result in x
x/=y x=x/y Dividing x by y and store the result in x
x%=y x=x % y Dividing x by y store the remainder in x
3. Increment/ Decrement Operators:
The increment/ decrement operators are used to increment the value of variable by 1 or decrement
the value of variable by 1. The increment operator is ++ and decrement operator is --.
4. Relational or Comparison Operators:
PHP comparison operators are used to compare two values and are frequently seen in Boolean
expressions. Below is a list of comparison operators:
Operator Name Example Description
== Equal $x==$y Returns true if x and y are equal
=== Identical $x===$y Returns true if x and y are equal and
of same type
!= Not equal $x!=$y Returns true if x and y are not equal
!== Not identical $x!==$y Returns true if x and y are not equal
and of same type
< Less than $x<$y Returns true if x is less than y
<= Less than or equal to $x<=$y Returns true if x is less than or equal
to y
> Greater than $x>$y Returns true if x is greater than y
>= Greater than or equal to $x>=$y Returns true if x is greater than or
equal to y
<> Not equal $x<>$y Returns true if x and y are not equal
5. Logical Operators:
PHP logical operators are used find the Boolean value of multiple conditional expressions. Below is a
list of logical operators:

Operator Name Example Description


and And $x and $y Returns true when both x and y are true
or Or $x or $y Returns true when either x or y or both of
them are true
xor Xor $x xor $y Returns true when either x or y is true
&& And $x && $y Returns true when both x and y are true
|| Or $x || $y Returns true when either x or y or both of
them are true
! Not !$x Returns true when x is false and vice versa
6. String Operators:
PHP provides two operators which are used with strings only. They are listed below:
Operator Name Example Description
. Concatenation $str1.$str2 str1 and str2 are concatenated
.= Concatenation Assignment $str1.=$str2 str1 is appended to str1
Strings can be treated as arrays i.e. individual characters can be accessed using the index values. The
index value begins with zero. A character at index I can be retrieved as $str[i].
<?php
$str1=”master”;
print($str1[2]);
?>
The print statement in the above prints ‘s’.
echo($str1[2]);
We can also echo statement to get the output.
There are several predefined functions to manipulate strings, some are listed below:
Function name Parameters Description
strlen One string Returns number of characters in the string
strcmp Two strings Returns zero if both strings are equal, a –ve number
if the first string occurs before second string or a
+ve number if the first string occurs after the
second string
substr One string and one Returns the substring from the specified string
integer from the position specified as an integer. If a third
integer value is specified, it represents the length of
the substring to be retrieved.
strrev One string Returns the reverse of the given string
trim One string Returns the string with all white spaces removed
on both sides
7. Array Operators:

Operator Name Example Description


== Equality $x==$y Returns true if x and y have the same key-value pairs
=== Identify $x===$y Returns true if x and y have the same key-value pairs in
same order and are of same type
!= Inequality $x!=$y Returns true if x and y are not equal
!== Non-Identity $x!==$y Returns true if x and y are not identical
<> Inequality $x!==$y Returns true if x and y are not equal
+ Union $x+$y Returns union of x and y
Array is a group of variable that can store multiple values under a single name. In PHP, there are three types
of array: numeric array, associative array and multidimensional array.

Numeric Array: In numeric array each element having numeric key associated with it that is starting from 0.
You can use array() function to create array. The general syntax is given below:

$array_name=array ( value1, value2 …valueN);

An example of numeric array is:

<?php

$myarray=array(‘A’,’B’,’C’);

print_r($myarray);
?>

Output: Array([0]=>A[1]=>B[2]=>C)

You can refer to individual element of an array in PHP script using its key value as shown below:

<?php

$myarray=array(‘A’,’B’,’C’);

echo $myarray[1];

?>

Output: B

In Numeric Array you can use for, while or do while loop to iterate through each element in array because in
numeric array key values are consecutive.

<?php

$myarray=array(“Apache”, “MySQL”, “PHP”);

for($i=0;$i<3;$i++) {

echo $myarray*$i+.”<br>”; }

?>

Output: Apache

MySQL

PHP

Associative Array:

The associative part means that arrays store element values in association with key values rather than in a
strict linear index order. If you store an element in an array, in association with a key, all you need to retrieve
it later from that array is the key value. Key may be either numeric or string. You can use array() function to
create associative array. The general syntax is given below:

$array_name=array(key1=>value1,key1=>value1,…keyN=>valueN);

An example is given below:

<?php

$myarray=array(“Name”=>”James” , “Age”= >25, “Gender”= >”Male” );

?>

Output: Array([Name]=>James [Age]= >25 [Gender]=>Male)


You can refer to individual element of an array in PHP using its key value. For example,

<?php

$myarray=array(“Name”=>”James” , “Age”= >25, “Gender”=> ”Male” );

echo “Name:”.$myarray*‘Name’+;

?>

Output: Name:James

In associative array you cannot use for, while r do..while loop to iterate through each element in array
because in Associative array key value are not consecutive. So you have to use for each loop. For example,

<?php

$myarray=array(“Name”=>”James” , “Age”=> 25, “Gender”=>”Male” );

foreach($myarray as $item) {

echo $item; }

?>

Output: James 25 Male

Multidimensional Array:

PHP can easily support multidimensional arrays, with arbitrary numbers of key. And just as in one
dimensional arrays, there is no need to declare out intentions in advance. Assignment can be like:

$multi_array*0+*1+*2+*3+=”Good Morning”;

That is four dimensional arrays with numerical index. The values those are stored in array can themselves be
arrays, just as legitimately as they can be string or numbers. For example:

$multi_level_array*0+=”a simple string”;

$multi_level_array*1+*‘contains’+=”a string stored deeper”;

The integer key of 0 stores a string, and the key 1 stores an array that, in turn, has a string in it. Creating array
within another array using array() construct is as follows:

$basket=array( ‘fruit’ => array(‘red’ =>‘apple’, ‘yellow’ => ‘banana’, ‘black’ => ‘grapes’),

‘flower’ =>array(‘red’ => ‘rose’, ‘yellow’ => ‘sunflower’, ‘purple’ => ‘iris’)

);

It is simply an array with two values stored in association with keys. Each of them values is an array itself.

How to integrate PHP in HTML and vice-versa?


When it comes to using PHP in HTML, there are two different approaches. The first is to embed the PHP code
in your HTML file itself with the .html extension. The other option, the preferred way, is to combine PHP and
HTML tags in .php files. Since PHP is a server-side scripting language, the code is interpreted and run on the
server side. For example, if you add the following code in your index.html file:

<!DOCTYPE html>
<html>
<head>
<title>Embed PHP in a .html File</title>
</head>
<body>
<h1><?php echo "Hello World" ?></h1>
</body>
</html>
Output: <?php echo "Hello World" ?>

By default, PHP tags in your .html document are not detected, and they're just considered plain text, outputting
without parsing. That's because the server is usually configured to run PHP only for files with
the .php extension.

If you want to run your HTML files as PHP, you can tell the server to run your .html files as PHP files, but it's a
much better idea to put your mixed PHP and HTML code into a file with the .php extension.

How to Add PHP Tags in Your HTML Page:

When it comes to integrating PHP code with HTML content, you need to enclose the PHP code with the PHP
start tag <?php and the PHP end tag ?>. The code wrapped between these two tags is considered to be PHP
code, and thus it'll be executed on the server side before the requested file is sent to the client browser. For
example,

<!DOCTYPE html>
<html>
<head>
<title>How to put PHP in HTML - Simple Example</title>
</head>
<body>
<h1><?php echo "This message is from server side." ?></h1>
</body>
</html>

Output: This message is from the server side.

To look at the current date and time, the following codes are used:

<!DOCTYPE html>
<html>
<head>
<title>How to put PHP in HTML- Date Example</title>
</head>
<body>
<div>This is pure HTML message.</div>
<div>Next, we’ll display today’s date and day by PHP!</div>
<div>
Today’s date is <b><?php echo date('Y/m/d') ?></b> and it’s a <b><?php echo date(‘l’) ?></b> today!
</div>
<div>Again, this is static HTML content.</div>
</body>
</html>
Output:
This is pure HTML message.
Next, we’ll display today’s date and day by PHP!
Today’s date is 2022/07/30 and it’s a Saturday today!
Again, this is static HTML content.

How to Use PHP Loops in Your HTML Page:


Iterating through the arrays to produce HTML content is one of the most common tasks you'll encounter
while writing PHP scripts. In most cases, you’ll need to display array content which you’ve populated from the
database or some other sources. An example to initialize the array:

<!DOCTYPE html>
<html>
<head>
<title>How to put PHP in HTML - foreach Example</title>
</head>
<body>
<?php
$employees = array(‘John’, ‘Michelle’, ‘Mari’, ‘Luke’, ‘Nellie’);
?>
<h1>List of Employees</h1>
<ul>
<?php foreach ($employees as $employee) { ?>
<li><?php echo $employee ?></li>
<?php } ?>
</ul>
</body>
</html>
Output: List of Employees
• John
• Michelle
• Mari
• Luke
• Nellie

Here firstly, we’ve initialized the array at the beginning of our script. Next, we’ve used the foreach construct to
iterate through the array values. And finally, we’ve used the echo construct to display the array element value.

If we write the same example with a while loop:

<!DOCTYPE html>
<html>
<head>
<title>How to put PHP in HTML - foreach Example</title>
</head>
<body>
<?php
$employees = array(‘John’, ‘Michelle’, ‘Mari’, ‘Luke’, ‘Nellie’);
$total = count($employees);
?>
<h1>List of Employees</h1>
<ul>
<?php
$i = 0;
?>
<?php while ($i < $total) { ?>
<li><?php echo $employees[$i] ?></li>
<?php ++$i ?>
<?php } ?>
</ul>
</body>
</html>
Magic constants: Magic constants are the predefined constants in PHP which is used on the basis of their
use. These constants are created by various extensions. There are nine magic constant in the PHP and all of
the constant resolved at the compile-time, not like the regular constant which is resolved at run time.
There are eight magic constants that start and end with double underscores (__).

All the constants are listed below with the example code:

1. __line__: This magic constant return the current line number of the file. If you use this magic constant
in your program file somewhere then this constant will display the line number during compile time.
For example,

<?php echo "The Line number is : ". __line__; ?>

Output: The Line number is: 3

2. __file__: This magic constant return the full path of the executed file with the name of the file.
Syntax:
<?php

echo "The file name is : ". __file__;

?>
Output: The file name is : /home/shsa.php
3. __dir__: This magic constant return the directory of the executed file.
Syntax:

<?php

echo "The directory is : ". __dir__;

?>
Output: The directory is: /home
4. __function__: This magic constant return the name of the function where this magic constant is
included.
Syntax:
<?php
function F(){
echo "The function name is : ". __function__;
}
F();
?>
Output: The function name is : F
5. __class__: This magic constant return the name of the class where this magic constant is included.
Syntax:
<?php
class F
{
public function getClassName(){
return __class__;
}
}
$obj = new F();
echo $obj->getClassName();
?>
Output: F
6. __method__: This magic constant return the method name where this magic constant is included.
Syntax:
<?php
class Company
{
public function XYZ(){
return __method__;
}
}
$obj = new Company();
echo $obj->XYZ();
?>
Output: XYZ
7. __namespace__: This magic constant return the current namespace where this magic constant is
included.
Syntax:
<?php
namespace ABC;

class Company {
public function abc() {
return __namespace__;
}
}

$obj = new Company();


echo $obj->abc();

?>
Output: ABC
8. __trait__: This magic constant return the trait name where this magic constant is included.
Syntax:

<?php

trait BAC{

function z(){

echo __trait__;

class Company{

use BAC;

$a = new Company;

$a->z();

?>
Output: BAC
9. ClassName::class: This magic constant return the fully qualified class name.
Syntax:
<?php

namespace Computer_Applications;
class Classroom{ }

echo Classroom::class;//Classname::class

?>
Output: Computer Applications

Working with PHP Superglobals: These are specially-defined array variables in PHP that make it easy for
you to get information about a request or its context. The superglobals are available throughout your script.
These variables can be accessed from any function, class or any file without doing any special task such as
declaring any global variable etc. They are mainly used to store and get information from one page to another
etc in an application.

Below is the list of superglobal variables available in PHP:


1. $GLOBALS
2. $_SERVER
3. $_REQUEST
4. $_GET
5. $_POST
6. $_SESSION
7. $_COOKIE
8. $_FILES
9. $_ENV

$GLOBALS : It is a superglobal variable which is used to access global variables from anywhere in the PHP
script. PHP stores all the global variables in array $GLOBALS[] where index holds the global variable name,
which can be accessed.
Below program illustrates the use of $GLOBALS in PHP:

<?php

$x = 300;

$y = 200;

function multiplication(){

$GLOBALS['z'] = $GLOBALS['x'] * $GLOBALS['y'];

multiplication();

echo $z;

?>

Ouput: 60000

$_SERVER : It is a PHP super global variable that stores the information about headers, paths and script
locations. Some of these elements are used to get the information from the superglobal variable $_SERVER.
Below program illustrates the use of $_SERVER in PHP:

<?php

echo $_SERVER['PHP_SELF'];

echo "<br>";

echo $_SERVER['SERVER_NAME'];

echo "<br>";

echo $_SERVER['HTTP_HOST'];

echo "<br>";

echo $_SERVER['HTTP_USER_AGENT'];
echo "<br>";

echo $_SERVER['SCRIPT_NAME'];

echo "<br>"

?>

Output: /abc/index.php

localhost

localhost: 81

Mozilla/5.0

$_REQUEST : It is a superglobal variable which is used to collect the data after submitting a HTML form.
$_REQUEST is not used mostly, because $_POST and $_GET perform the same task and are wide ly used.
Below is the HTML and PHP code to explain how $_REQUEST works:
<!DOCTYPE html>
<html>
<body>

<form method="post" action="<?php echo $_SERVER['PHP_SELF'];?>">


NAME: <input type="text" name="fname">
<button type="submit">SUBMIT</button>
</form>
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$name = htmlspecialchars($_REQUEST['fname']);
if(empty($name)){
echo "Name is empty";
} else {
echo $name;
}
}
?>
</body>
</html>
Output: Name: Computer Applications Submit
\
Computer Applications

$_POST : It is a super global variable used to collect data from the HTML form after submitting it. When
form uses method post to transfer data, the data is not visible in the query string, because of which security
levels are maintained in this method.
Below is the HTML and PHP code to explain how $_POST works:

<!DOCTYPE html>
<html>

<body>

<form method="post" action="<?php echo $_SERVER['PHP_SELF'];?>">

<label for="name">Please enter your name: </label>

<input name="name" type="text"><br>

<label for="age">Please enter your age: </label>

<input name="age" type="text"><br>

<input type="submit" value="Submit">

<button type="submit">SUBMIT</button>

</form>

<?php

$nm=$_POST['name'];

$age=$_POST['age'];

echo "<strong>".$nm." is $age years old.</strong>";

?>

</body>

</html>

Output:

Please enter your name: Computer Applications

Please enter your age: 24

Submit
$_GET : $_GET is a super global variable used to collect data from the HTML form after submitting it. When
form uses method get to transfer data, the data is visible in the query string, therefore the values are not
hidden. $_GET super global array variable stores the values that come in the URL.
Below is the HTML and PHP code to explain how $_GET works:
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body bgcolor="cyan">
<?php
$name = $_GET['name'];
$city = $_GET['city'];
echo "<h1>This is ".$name." of ".$city."</h1><br>";
?>
<img src = "2.jpg" alt = "nanilake" height = "400" width="500" />
</body>
</html>
Output:
Name= “Kolkata Diaries”
city =” Kolkata”

How do you create session & cookie in PHP? Give difference between session and cookie with
example. (OR) What are cookies? Explain the cookies handling in PHP with proper example.

PHP Sessions: A PHP session variable is used to store information about, or change settings for a user session.
Session variables hold information about one single user, and are available to all pages in one application.

creates unique
Client 1 request session id session id

Container

Client 2 creates unique session


request
session id id
PHP Session Variables: When you are working with an application, you open it, do some changes and then you
close it. This is much like a Session. The computer knows who you are. It knows when you start the
application and when you end. But on the internet there is one problem: the web server does not know who
you are and what you do because the HTTP address doesn't maintain state. A PHP session solves this problem
by allowing you to store user information on the server for later use (i.e. username, shopping items, etc).
However, session information is temporary and will be deleted after the user has left the website. If you need
a permanent storage you may want to store the data in a database. Sessions work by creating a unique id
(UID) for each visitor and store variables based on this UID. The UID is either stored in a cookie or is
propagated in the URL.

Starting a PHP Session:


Before you can store user information in your PHP session, you must first start up the session. The
session_start() function must appear BEFORE the <html> tag:

<?php session_start(); ?>

<html><body> ………</body></html>

The code above will register the user's session with the server, allow you to start saving user information, and
assign a UID for that user's session.

Storing a Session Variable: The correct way to store and retrieve session variables is to use the PHP
$_SESSION variable:

<?php session_start(); // store session data

$_SESSION['views']=1; ?>

<html>

<body><?php //retrieve data

echo “Pageviews=”.$_SESSION[‘views’];

?>

</body></html>

Output: Pageviews =1

The isset() function checks if the "views" variable has already been set. If "views" has been set, we can
increment our counter. If "views" doesn't exist, we create a "views" variable, and set it to 1:

<?php

session_start();

if(isset($_SESSION['views']))
$_SESSION['views']=$_SESSION['views']+1;

else $_SESSION['views']=1;

echo "Views=". $_SESSION['views'];

?>

Destroying a Session: If you wish to delete some session data, you can use the unset() or the session_destroy()
function. The unset() function is used to free the specified session variable:

<?php

unset($_SESSION['views']);

?>

You can also completely destroy the session by calling the session_destroy() function:

<?php

session_destroy();

?>

Note:session_destroy() will reset your session and you will lose all your stored session data.

PHP Cookie:

A cookie is often used to identify a user. A cookie is a small file that the server embeds on the user's computer.
Each time the same computer requests a page with a browser, it will send the cookie too. With PHP, you can
both create and retrieve cookie values.
Request + Cookie

Request + Cookie
Browser Server

Request + Cookie
How to Create a Cookie?

The setcookie() function is used to set a cookie. The setcookie() function must appear BEFORE the <html>
tag.

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

In the example below, we will create a cookie named "user" and assign the value "Alex Porter" to it. We also
specify that the cookie should expire after one hour:

<?php

setcookie("user", "Alex Porter", time()+3600);

?>

<html> ….

The value of the cookie is automatically URL encoded when sending the cookie, and automatically decoded
when received (to prevent URL encoding, use setrawcookie() instead). You can also set the expiration time of
the cookie in another way. It may be easier than using seconds.

<?php

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

setcookie("user", "Alex Porter", $expire);

?>

<html>…

How to Retrieve a Cookie Value?

The PHP $_COOKIE variable is used to retrieve a cookie value. In the example below, we retrieve the value of
the cookie named "user" and display it on a page:
<?php

// Print a cookie

echo $_COOKIE["user"];

// A way to view all cookies

print_r($_COOKIE);

?>

In the following example we use the isset() function to find out if a cookie has been set:

<html>

<body>

<?php

if (isset($_COOKIE["user"]))

echo "Welcome " . $_COOKIE["user"] ."!</br>";

else

echo "Welcome guest!</br>";

?>

</body></html>

How to Delete a Cookie?

When deleting a cookie you should assure that the expiration date is in the past.
<?php

// set the expiration date to one hour ago

setcookie("user", "", time()-3600);

?>

What if a Browser Does NOT Support Cookies?

If your application deals with browsers that do not support cookies, you will have to use other methods to
pass information from one page to another in your application. One method is to pass the data through forms
(forms and user input are described earlier in this tutorial). The form below passes the user input to
"welcome.php" when the user clicks on the "Submit" button:

<html>

<body>

<form action="welcome.php" method="post"> Name: <input type=”text” name=”name”/>

Age: <input type=”text” name=”age”/>

<input type=”submit”/>

</form>

</body>

</html>

Retrieve the values in the "welcome.php" file:

<html>

<body>
Welcome <?php echo $_POST[“name”;?> <br/>

You are <?php echo $_POST[“age”];?>years old.

</body>

</html>

Creating a simple HTML Form:

All the form controls given above is designed by using the input tag based on the type attribute of the tag.
In the below script, when the form is submitted, no event handling mechanism is done. Event handling
refers to the process done while the form is submitted. These event handling mechanisms can be done by
using javaScript or PHP. However, JavaScript provides only client-side validation. Hence, we can use PHP
for form processing.

<!DOCTYPE html>

<html>

<head>

<title>Simple Form Processing</title>

</head>

<body>

<form id="form1" method="post">

FirstName:

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

<br>

<br>

LastName

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

<br>
<br>

Address

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

<br>

<br>

Email Address:

<input type="email" name="emailaddress" required/>

<br>

<br>

Password:

<input type="password" name="password" required/>

<br>

<br>

<input type="submit" value="Submit”/>

</form>

</body>

</html>

PHP- HTML form handling:

Form Validation: Form validation is done to ensure that the user has provided the relevant information.
Basic validation can be done using HTML elements. For example, in the above script, the email address text
box is having a type value as “email”, which prevents the user from entering the incorrect value for an
email. Every form field in the above script is followed by a required attribute, which will intimate the user
not to leave any field empty before submitting the form. PHP methods and arrays used in form processing
are:

• isset(): This function is used to determine whether the variable or a form control is having a value or
not.
• $_GET[]: It is used the retrieve the information from the form control through the parameters sent in
the URL. It takes the attribute given in the url as the parameter.
• $_POST[]: It is used the retrieve the information from the form control through the HTTP POST method.
IT takes name attribute of corresponding form control as the parameter.
• $_REQUEST[]: It is used to retrieve an information while using a database.

Form Processing using PHP: Above HTML script is rewritten using the above mentioned functions and
array. The rewritten script validates all the form fields and if there are no errors, it displays the received
information in a tabular form.

<?php

if (isset($_POST['submit']))

if ((!isset($_POST['firstname'])) || (!isset($_POST['lastname'])) ||

(!isset($_POST['address'])) || (!isset($_POST['emailaddress'])) ||

(!isset($_POST['password'])) || (!isset($_POST['gender'])))

$error = "*" . "Please fill all the required fields";

else

$firstname = $_POST['firstname'];

$lastname = $_POST['lastname'];

$address = $_POST['address'];

$emailaddress = $_POST['emailaddress'];

$password = $_POST['password'];

$gender = $_POST['gender'];

?>

Note: When the PHP and HTML are coded in a single file, the file should be saved as PHP. In the form, the
value for the action parameter should be a file name.
<html>

<head>

<title>Simple Form Processing</title>

</head>

<body>

<h1>Form Processing using PHP</h1>

<fieldset>

<form id="form1" method="post" action="form.php">

<?php

if (isset($_POST['submit']))

if (isset($error))

echo "<p style='color:red;'>"

. $error . "</p>";

?>

FirstName:

<input type="text" name="firstname"/>

<span style="color:red;">*</span>

<br>

<br>

Last Name:

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


<span style="color:red;">*</span>

<br>

<br>

Address:

<input type="text" name="address"/>

<span style="color:red;">*</span>

<br>

<br>

Email:

<input type="email" name="emailaddress"/>

<span style="color:red;">*</span>

<br>

<br>

Password:

<input type="password" name="password"/>

<span style="color:red;">*</span>

<br>

<br>

Gender:

<input type="radio"

value="Male"

name="gender"> Male

<input type="radio"

value="Female"

name="gender">Female
<br>

<br>

<input type="submit" value="Submit" name="submit" />

</form>

</fieldset>

<?php

if(isset($_POST['submit']))

if(!isset($error))

echo"<h1>INPUT RECEIVED</h1><br>";

echo "<table border='1'>";

echo "<thead>";

echo "<th>Parameter</th>";

echo "<th>Value</th>";

echo "</thead>";

echo "<tr>";

echo "<td>First Name</td>";

echo "<td>".$firstname."</td>";

echo "</tr>";

echo "<tr>";

echo "<td>Last Name</td>";

echo "<td>".$lastname."</td>";

echo "</tr>";

echo "<tr>";
echo "<td>Address</td>";

echo "<td>".$address."</td>";

echo "</tr>";

echo "<tr>";

echo "<td>Email Address</td>";

echo "<td>" .$emailaddress."</td>";

echo "</tr>";

echo "<tr>";

echo "<td>Password</td>";

echo "<td>".$password."</td>";

echo "</tr>";

echo "<tr>";

echo "<td>Gender</td>";

echo "<td>".$gender."</td>";

echo "</tr>";

echo "</table>";

?>

</body>

</html>

PHP File Handling

PHP File System allows us to create file, read file line by line, read file character by character, write file, append
file, delete file and close file.
PHP Open File –fopen(): It is used to open a file or URL and returns resource. The fopen() function accepts two
arguments: $filename and $mode. The $filename represents the file to be opended and $mode represents the
file mode for example read-only, read-write, write-only etc. Syntax:

resource fopen ( string $filename , string $mode [, bool $use_include_path = false [, resource $context ]] )

Example,
<?php
$handle = fopen("c:\\folder\\file.txt", "r");
?>

PHP Close File - fclose(): The PHP fclose() function is used to close an open file pointer.

Syntax: ool fclose ( resource $handle )


Example,
<?php
fclose($handle);
?>

PHP Read File - fread(): PHP provides various functions to read data from file. The PHP fread() function is used
to read the content of the file. It accepts two arguments: resource and file size.

Syntax: string fread ( resource $handle , int $length )


Example,
<?php
$filename = "c:\\myfile.txt";
$handle = fopen($filename, "r"); //open file in read mode
$contents = fread($handle, filesize($filename)); //read file
echo $contents; //printing data of file
fclose($handle); //close file
?>

PHP Write File - fwrite(): PHP fwrite() and fputs() functions are used to write data into file. The PHP fwrite()
function is used to write content of the string into file.

Syntax: int fwrite ( resource $handle , string $string [, int $length ] )

Example,

<?php
$fp = fopen('data.txt', 'w');//open file in write mode
fwrite($fp, 'hello ');
fwrite($fp, 'php file');
fclose($fp);
echo "File written successfully";
?>

PHP Delete File - unlink(): The PHP unlink() function is used to delete file. PHP unlink() generates E_WARNING
level error if file is not deleted. It returns TRUE if file is deleted successfully otherwise FALSE. Syntax:

bool unlink ( string $filename [, resource $context ] )

Example,

<?php
unlink('data.txt');
echo "File deleted successfully";
?>

Connection of PHP to MySQL:

MySQL is an open-source relational database management system (RDBMS). It is the most popular database
system used with PHP. SQL stands for Structured Query Language. The data in a MySQL database are stored
in tables that consist of columns and rows. MySQL is a database system that runs on a server. MySQL is ideal
for both small and large applications. MySQL is a very fast, reliable, and easy-to-use database system. It uses
standard SQL. MySQL compiles on a number of platforms.

How we can connect PHP to MySQL?

PHP can work with a MySQL database using: MySQLi extension (the ‘i’ is abbreviation for improved) and
PDO (PHP Data Objects). Both MySQLi and PDO have their recompenses:
• PDO will work with 12 different database systems, whereas MySQLi will only work with MySQL
databases.
• So, if you have to shift your project to use alternative database, PDO makes the process easy. You only
have to change the connection string and a few queries. With MySQLi, you will need to rewrite the
complete code — queries included.
• Both are object-oriented, but MySQLi also offers a procedural API.
Connection to MySQL using MySQLi:
PHP provides mysql_connect() function to open a database connection.This function takes a single
parameter, which is a connection returned by the mysql_connect() function. You can disconnect from the
MySQL database anytime using another PHP function mysql_close(). There is also a procedural approach of
MySQLi to establish a connection to MySQL database from a PHP script. It can be done in two ways :
1. MySQLi Object-Oriented:
Example,
<?php
$servername = "localhost";
$username = "username";
$password = "password";

// Connection
$conn = new mysqli($servername, $username, $password);
// For checking if connection is
// successful or not
if ($conn->connect_error) {
die("Connection failed: "
. $conn->connect_error);
}
echo "Connected successfully";
?>
2. MySQLi Procedural: PHP mysqli_connect() function is used to connect with MySQL database. It
returns resource if connection is established or null. Syntax:
resource mysqli_connect (server, username, password)
Example,
<?php
$servername = "localhost";
$username = "username";
$password = "password";

// Connection
$conn = mysqli_connect($servername,
$username, $password);

// Check if connection is
// Successful or not
if (!$conn) {
die("Connection failed: "
. mysqli_connect_error()); }
echo "Connected successfully";
?>

PHP mysqli_close(): PHP mysqli_close() function is used to disconnect with MySQL database. It returns true if
connection is closed or false. Syntax: bool mysqli_close(resource $resource_link)

Connection to MySQL using PDO:


<?php

$servername = "localhost";
$username = "username";
$password = "password";

try {
$conn = new PDO(
"mysql:host=$servername;dbname=myDB",
$username, $password);

// Set the PDO error mode


// to exception
$conn->setAttribute(PDO::ATTR_ERRMODE,
PDO::ERRMODE_EXCEPTION);
echo "Connected successfully";
} catch(PDOException $e) {
echo "Connection failed: "
. $e->getMessage();
}
?>

PHP CRUD operation with MySQL Database(DB):

CRUD is an acronym for Create, Read, Update, and Delete. CRUD operations are basic data manipulation for
database.

PHP MySQLi Create Database Example:

<?php
$host = 'localhost:3306';
$user = '';
$pass = '';
$conn = mysqli_connect($host, $user, $pass);
if(! $conn )
{
die('Could not connect: ' . mysqli_connect_error());
}
echo 'Connected successfully<br/>';
$sql = 'CREATE Database mydb';
if(mysqli_query( $conn,$sql)){
echo "Database mydb created successfully.";
}else{
echo "Sorry, database creation failed ".mysqli_error($conn);
}
mysqli_close($conn);
?>

PHP MySQLi Create Table Example:

<?php
$host = 'localhost:3306';
$user = '';
$pass = '';
$dbname = 'test';
$conn = mysqli_connect($host, $user, $pass,$dbname);
if(!$conn){
die('Could not connect: '.mysqli_connect_error());
}
echo 'Connected successfully<br/>';
$sql = "create table emp5(id INT AUTO_INCREMENT,name VARCHAR(20) NOT NULL,
emp_salary INT NOT NULL,primary key (id))";
if(mysqli_query($conn, $sql)){
echo "Table emp5 created successfully";
}else{
echo "Could not create table: ". mysqli_error($conn);
}
mysqli_close($conn);
?>

PHP MySQLi Insert Record Example:

<?php
$host = 'localhost:3306';
$user = '';
$pass = '';
$dbname = 'test';
$conn = mysqli_connect($host, $user, $pass,$dbname);
if(!$conn){
die('Could not connect: '.mysqli_connect_error());
}
echo 'Connected successfully<br/>';
$sql = 'INSERT INTO emp4(name,salary) VALUES ("sonoo", 9000)';
if(mysqli_query($conn, $sql)){
echo "Record inserted successfully";
}else{
echo "Could not insert record: ". mysqli_error($conn);
}
mysqli_close($conn);
?>

PHP MySQLi Delete Record Example:

<?php
$host = 'localhost:3306';
$user = '';
$pass = '';
$dbname = 'test';
$conn = mysqli_connect($host, $user, $pass,$dbname);
if(!$conn){
die('Could not connect: '.mysqli_connect_error());
}
echo 'Connected successfully<br/>';
$id=2;
$sql = "delete from emp4 where id=$id";
if(mysqli_query($conn, $sql)){
echo "Record deleted successfully";
}else{
echo "Could not deleted record: ". mysqli_error($conn);
}
mysqli_close($conn);
?>

PHP MySQL Select Query:

PHP mysql_query() function is used to execute select query. There are two other MySQLi functions used in
select query.

• mysqli_num_rows(mysqli_result $result): returns number of rows.


• mysqli_fetch_assoc(mysqli_result $result): returns row as an associative array. Each key of the array
represents the column name of the table. It return NULL if there are no more rows.

Example,

<?php
$host = 'localhost:3306';
$user = '';
$pass = '';
$dbname = 'test';
$conn = mysqli_connect($host, $user, $pass,$dbname);
if(!$conn){
die('Could not connect: '.mysqli_connect_error());
}
echo 'Connected successfully<br/>';
$sql = 'SELECT * FROM emp4';
$retval=mysqli_query($conn, $sql);
if(mysqli_num_rows($retval) > 0){
while($row = mysqli_fetch_assoc($retval)){
echo "EMP ID :{$row['id']} <br> ".
"EMP NAME : {$row['name']} <br> ".
"EMP SALARY : {$row['salary']} <br> ".
"--------------------------------<br>";
} //end of while
}else{
echo "0 results";
}
mysqli_close($conn);
?>
PHP MySQL Order By:

PHP mysql_query() function is used to execute select query with order by clause. The order by clause is used
to fetch data in ascending order or descending order on the basis of column.

Example,

<?php
$host = 'localhost:3306';
$user = '';
$pass = '';
$dbname = 'test';
$conn = mysqli_connect($host, $user, $pass,$dbname);
if(!$conn){
die('Could not connect: '.mysqli_connect_error());
}
echo 'Connected successfully<br/>';
$sql = 'SELECT * FROM emp4 order by name';
$retval=mysqli_query($conn, $sql);
if(mysqli_num_rows($retval) > 0){
while($row = mysqli_fetch_assoc($retval)){
echo "EMP ID :{$row['id']} <br> ".
"EMP NAME : {$row['name']} <br> ".
"EMP SALARY : {$row['salary']} <br> ".
"--------------------------------<br>";
} //end of while
}else{
echo "0 results";
}
mysqli_close($conn);
?>
PHP JSON

PHP allows us to encode and decode JSON by the help of json_encode() and json_decode functions.

1) PHP json_encode
The json_encode() function returns the JSON representation of a value. In other words, it converts PHP variable
(containing array) into JSON. Syntax:

string json_encode ( mixed $value [, int $options = 0 [, int $depth = 512 ]] )

PHP json_encode example


<?php
$arr = array('a' => 1, 'b' => 2, 'c' => 3, 'd' => 4, 'e' => 5);
echo json_encode($arr);
?>

2) PHP json_decode

The json_decode() function decodes the JSON string. In other words, it converts JSON string into a PHP variable.
Syntax:

mixed json_decode ( string $json [, bool $assoc = false [, int $depth = 512 [, int $options = 0 ]]] )

PHP json_decode example,

<?php
$json = '{"a":1,"b":2,"c":3,"d":4,"e":5}';
var_dump(json_decode($json, true));//true means returned object will be converted into associative array
?>

Servlet

Servlet technology is used to create a web application (resides at server side and generates a dynamic web
page). Servlet technology is robust and scalable because of java language. Before Servlet, CGI (Common
Gateway Interface) scripting language was common as a server-side programming language. However, there
were many disadvantages to this technology. There are many interfaces and classes in the Servlet API such as
Servlet, GenericServlet, HttpServlet, ServletRequest, ServletResponse, etc.

What is Servlet?

Servlet can be described in many ways, depending on the context. Servlet is a technology which is used to
create a web application. Servlet is an API that provides many interfaces and classes including
documentation. Servlet is an interface that must be implemented for creating any Servlet. Servlet is a class
that extends the capabilities of the servers and responds to the incoming requests. It can respond to any
requests. Servlet is a web component that is deployed on the server to create a dynamic web page.

request Server
Client

response is generated at runtime


response is sent to
the client
CGI (Common Gateway Interface):

CGI technology enables the web server to call an external program and pass HTTP request information to the
external program to process the request. For each request, it starts a new process.

There are many problems in CGI technology:

1. If the number of clients increases, it takes more time for sending the response.

2. For each request, it starts a process, and the web server is limited to start processes.

3. It uses platform dependent language e.g. C, C++, perl.

Advantages of Servlet over CGI:

There are many advantages of Servlet over CGI. The web container creates threads for handling the multiple
requests to the Servlet. Threads have many benefits over the Processes such as they share a common memory
area, lightweight, cost of communication between the threads are low.

The advantages of Servlet are as follows:

1. Better performance: because it creates a thread for each request, not process.

2. Portability: because it uses Java language.

3. Robust: JVM manages Servlets, so we don't need to worry about the memory leak, garbage collection, etc. 4.
Secure: because it uses java language.

Servlet Terminology Description


Website: static vs dynamic It is a collection of related web pages that may contain text, images,
audio and video.
HTTP It is the data communication protocol used to establish
communication between client and server.
HTTP Requests It is the request send by the computer to a web server that contains
all sorts of potentially interesting information.
Get vs Post It gives the difference between GET and POST request.
Container It is used in java for dynamically generating the web pages on the
server side.
Server: Web vs Application It is used to manage the network resources and for running the
program or software that provides services.
Content Type It is HTTP header that provides the description about what are you
sending to the browser.

Servlet API: Servlet API consists of two important packages that encapsulates all the important classes and
interface, namely : javax.servlet & javax.servlet.http

Some Important Classes and Interfaces of javax.servlet are:


• Servlet(interfaces)- ServletInputStream(class)
• ServletContext(Interface)- ServletOutputStream (class)
• ServletConfig(Interface) – ServletRequestWrapper(class), etc

Servlet Interface provides five methods. Out of these five methods, three methods are Servlet life cycle
methods and rest two are non life cycle methods. Life cycle methods are

• service(ServletRequest, ServletResponse)
• init (ServletConfig)
• destroy()

Non life cycle methods are:

• getServletConfig()
• getServletInfo()

GenericServlet Class: GenericServlet is an abstract class that provides implementation of most of the basic
servlet methods. This is a very important class. Methods of GenericServlet class:

• public void init(ServletConfig)


• public abstract void service(ServletRequest request,ServletResposne response)
• public void destroy()
• public ServletConfig getServletConfig()
• public String getServletInfo()
• public ServletContext getServletContext()
• public String getInitParameter(String name)
• public Enumeration getInitParameterNames()
• public String getServletName()
• public void log(String msg)
• public void log(String msg, Throwable t)

HttpServlet class: HttpServlet is also an abstract class. This class gives implementation of various service()
methods of Servlet interface. To create a servlet, we should create a class that extends HttpServlet abstract
class. The Servlet class that we will create, must not override service() method. Our servlet class will override
only the doGet() and/or doPost() methods. The service() method of HttpServlet class listens to the Http
methods (GET, POST etc) from request stream and invokes doGet() or doPost() methods based on Http
Method type.

<interface> <interface> <interface>


ServletRequest Servlet ServletResponse

<interface> <interface>
HttpServlet
HttpServletRequest HttpServletResponse

getHeader(name)
getHeadersNames()
getIntHeader()
getDataHeader()
service() setHeader()
doGet() setDateHeaders()
doPost() setIntHeader()

My Servlet
implements extends class

How a Servlet Application works:

1. User sends request for a servlet by clicking a link that has URL to a servlet.
2. The container finds the servlet using deployment descriptor and creates two objects:
a. HttpServletRequest b. HttpServletResponse
3. Then the container creates or allocates a thread for that request and calls the Servlet's service()
method and passes the request, response objects as arguments.
4. The service() method, then decides which servlet method, doGet() or doPost() to call, based on HTTP
Request Method(Get, Post etc) sent by the client. Suppose the client sent an HTTP GET request, so the
service() will call Servlet's doGet() method.
5. Then the Servlet uses response object to write the response back to the client.
6. After the service() method is completed the thread dies. And the request and response objects are
ready for garbage collection.

Tomcat: Apache Tomcat (called "Tomcat" for short) is a free and open-source implementation of the Jakarta
Servlet, Jakarta Expression Language, and Web Socket technologies. Tomcat provides a "pure Java" HTTP web
server environment in which Java code can run. Tomcat is developed and maintained in 1998 by an open
community of developers under the auspices of the Apache Software Foundation, released under the Apache
License 2.0 license.
Apache Tomcat is a web container. It allows the users to run Servlet and JAVA Server Pages that are
based on the web-applications. It can be used as the HTTP server. The performance of the Tomcat server
is not as good as the designated web server. It can be used as separate product with its own internal Web-
server. It can also be used as mutually with the others Web-servers which include Apache, Microsoft
Internet Information Server, and Microsoft Personal Web-server.

Difference between the Apache Tomcat server and Apache web server:

Apac he Tomcat Server Apache Web Server


1. This server is a JSP/Servlet container. 1. This server is a HTTP server. It serves the
files through the HTTP protocol.
2. We can use it to host code based on Java. 2. We can use it to host applications written in
any programming language.
3. Apache tomcat server can be used to 3. It can be used to handle static pages.
handle both static and dynamic pages. Dynamic pages coded in Ruby, PHP, or
Pages generated using HTML are static other languages can also be handled by an
pages, and the pages generated using apache web server via add-on modules
Servlet and JSP are dynamic pages. offered by Apache or any other client.
4. It is not more configurable and robust. 4. It is more configurable and robust.
5. It is written in Java. 5. It is written in the C programming
language.
6. When it comes to serving static content, it 6. When it comes to serving static content, it
is slower. is faster.
Servlet Life Cycle:

1. Load Servlet Class

2. Create Servlet Instance 3.


READY
Call init() method 5. Call the
destroy() method

4. Call the Service() method

1. Loading Servlet Class : A Servlet class is loaded when first request for the servlet is received by
the Web Container.
2. Servlet instance creation : After the Servlet class is loaded, Web Container creates the instance of
it. Servlet instance is created only once in the life cycle.
3. Call to the init() method : init() method is called by the Web Container on servlet instance to
initialize the servlet.
4. Call to the service() method : The containers call the service() method each time the request for
servlet is received. The service() method will then call the doGet() or doPost() methos based ont
eh type of the HTTP request, as explained in previous lessons.
5. Call to destroy() method: The Web Container call the destroy() method before removing servlet
instance, giving it a chance for cleanup activity.

JAVA

Overview of Java:

Java is a programming language and a platform. Java is a high level, robust, object-oriented and secure
programming language. Java was developed by Sun Microsystems in the year 1995. James Gosling is known as
the father of Java. Before Java, its name was Oak. A general-purpose programming language made for
developers to write once run anywhere that is compiled Java code can run on all platforms that support
Java. Java applications are compiled to byte code that can run on any Java Virtual Machine.

History: Java is a programming language created in 1991. James Gosling, Mike Sheridan, and Patrick
Naughton, a team of Sun engineers known as the Green team initiated the Java language in 1991. Sun
Microsystems released its first public implementation in 1996 as Java 1.0. It provides no-cost -run-times on
popular platforms. Java1.0 compiler was re-written in Java by Arthur Van Hoff to strictly comply with its
specifications. With the arrival of Java 2, new versions had multiple configurations built for different types
of platforms.
Terms related to JAVA:
1. Java Virtual Machine(JVM): This is generally referred to as JVM. There are three execution phases
of a program. They are written, compile and run the program.
• Writing a program is done by a java programmer like you and me.
• The compilation is done by the JAVAC compiler which is a primary Java compiler included in the Java
development kit (JDK). It takes the Java program as input and generates bytecode as output.
• In the Running phase of a program, JVM executes the bytecode generated by the compiler.
Every Operating System has a different JVM but the output they produce after the execution of bytecode is
the same across all the operating systems. This is why Java is known as a platform-independent language.
2. Bytecode in the Development process: As discussed, the Javac compiler of JDK compiles the java
source code into bytecode so that it can be executed by JVM. It is saved as .class file by the compiler.
To view the bytecode, a disassembler like javap can be used.
3. Java Development Kit(JDK): While we were using the term JDK when we learn about bytecode and
JVM. So, as the name suggests, it is a complete Java development kit that includes everything
including compiler, Java Runtime Environment (JRE), java debuggers, java docs, etc. For the program
to execute in java, we need to install JDK on our computer in order to create, compile and run the
java program.
4. Java Runtime Environment (JRE): JDK includes JRE. JRE installation on our computers allows the
java program to run, however, we cannot compile it. JRE includes a browser, JVM, applet supports,
and plugins. For running the java program, a computer needs JRE.
5. Garbage Collector: In Java, programmers can’t delete the objects. To delete or recollect that memory
JVM has a program called Garbage Collector. Garbage Collectors can recollect the objects that are not
referenced. So Java makes the life of a programmer easy by handling memory management.
However, programmers should be careful about their code whether they are using objects that have
been used for a long time. Because Garbage cannot recover the memory of objects being referenced.
6. ClassPath: The classpath is the file path where the java runtime and Java compiler look for .class files
to load. By default, JDK provides many libraries. If you want to include external libraries they should
be added to the classpath.

Main Features of: Java

1. Platform Independent: Compiler converts source code to bytecode and then the JVM executes the
bytecode generated by the compiler. This bytecode can run on any platform. Each operating system
has a different JVM, but the output produced by all the OS is the same after the execution of bytecode.
That is why we call java a platform-independent language.

2. Object-Oriented Programming Language: Organizing the program in the terms of collection of


objects is a way of object-oriented programming, each of which represents an instance of the class.
The four main concepts of Object-Oriented programming are:
• Abstraction
• Encapsulation
• Inheritance
• Polymorphism
3. Simple: Java is one of the simple languages as it does not have complex features like pointers, operator
overloading, multiple inheritances, and Explicit memory allocation.
4. Robust: Java language is robust which means reliable. It is developed in such a way that it puts a lot of
effort into checking errors as early as possible, that is why the java compiler is able to detect even those
errors that are not easy to detect by another programming language. The main features of java that make
it robust are garbage collection, Exception Handling, and memory allocation.
5. Secure: In java, we don’t have pointers, so we cannot access out-of-bound arrays. That’s why several
security flaws like stack corruption or buffer overflow are impossible to exploit in Java. Also java programs
run in an environment that is independent of the os(operating system) environment which makes java
programs more secure .
6. Distributed: We can create distributed applications using the java programming language. Remote
Method Invocation and Enterprise Java Beans are used for creating distributed applications in java. The
java programs can be easily distributed on one or more systems that are connected to each other through
an internet connection.
7. Multithreading: Java supports multithreading. It is a Java feature that allows concurrent execution
of two or more parts of a program for maximum utilization of the CPU.
8. Portable: The platform-independent feature of java in which its platform-independent bytecode can
be taken to any platform for execution makes java portable.
9. High Performance: Java architecture is defined in such a way that it reduces overhead during the
runtime and at some time java uses Just In Time (JIT) compiler where the compiler compiles code
on-demand basics where it only compiles those methods that are called making applications to
execute faster.
10. Dynamic flexibility: Java being completely object-oriented gives us the flexibility to add classes, new
methods to existing classes and even create new classes through sub-classes.
11. Sandbox Execution: Java programs run in a separate space that allows user to execute their
applications without affecting the underlying system with help of a bytecode verif ier. Bytecode
verifier also provides additional security as its role is to check the code for any violation of access.
12. Write Once Run Anywhere: Java provides ease t architecture-neutral ease as bytecode is not
dependent on any machine architecture. It is the primary reason java is used in the enterprising IT
industry globally worldwide.
13. Power of compilation and interpretation: Most languages are designed with purpose either they are
compiled language or they are interpreted language. But java integrates arising enormous power as
Java compiler compiles the source code to bytecode and JVM executes this bytecode to machine OS -
dependent executable code.

How Java works:

The Java codes are first compiled into byte code (machine-independent code). Then the byte code runs
on Java Virtual Machine (JVM) regardless of the underlying architecture. Java’s byte-code can run on any
device with the JVM that is why Java is known as ‘write once, run anywhere’. Java does not provide low-level
programming functionalities like pointers. Also, Java codes are always written in the form of classes and
objects. When compared with C++, Java codes are generally more maintainable because Java does not allow
many things which may lead to bad/inefficient programming if used incorrectly.
Example 1:
// Importing classes from packages
import java.io.*;

// Main class
public class GFG {

// Main driver method


public static void main(String[] args)
{

// Print statement
System.out.println("Welcome to GeeksforGeeks");
}
}
This example represents:
1. Comments: Comments are used for explaining code and are used in a similar manner in Java or C
or C++. Compilers ignore the comment entries and do not execute them. Comments can be of a
single line or multiple lines.
Single line Comments:
Syntax: // Single line comment
Multi-line comments:
Syntax: /* Multi line comments*/
2. import java.io.*: This means all the classes of io package can be imported. Java io package provides
a set of input and output streams for reading and writing data to files or other input or output
sources.
3. class: The class contains the data and methods to be used in the program. Methods define the
behavior of the class. Class GFG has only one method Main in JAVA.
4. static void Main(): static keyword tells us that this method is accessible without instantiating the
class.
5. void: keywords tell that this method will not return anything. The main() method is the entry point
of our application.
6. System.in: This is the standard input stream that is used to read characters from the keyboard or
any other standard input device.
7. System.out: This is the standard output stream that is used to produce the result of a program on an
output device like the computer screen.
8. println(): This method in Java is also used to display text on the console. It prints the text on the
console and the cursor moves to the start of the next line at the console. The next printing takes
place from the next line.
9. String []args: This is the argument passed to the main function which is an array of strings with the
array name args. One can choose their own flexible name but this name is used by many developers.
Everything in java , is represented in Class as an object including the main function.
Example 2:

// A Java program to print "Hello World"

// This is a simple Java program.


// FileName : "HelloWorld.java".

class HelloWorld
{
// Your program begins with a call to main().
// Prints "Hello, World" to the terminal window.
public static void main(String args[])
{
System.out.println("Hello, World");
}
}
Output: Hello, World
The “Hello World!” program consists of three primary components: the HelloWorld class definition, the main
method, and source code comments. The following explanation will provide you with a basic understanding
of the code:
1. Class definition: This line uses the keyword class to declare that a new class is being defined.
class HelloWorld {
//
//Statements
}
2. HelloWorld : It is an identifier that is the name of the class. The entire class definition, including all
of its members, will be between the opening curly brace “{” and the closing curly brace “}“.
3. main method: In the Java programming language, every application must contain a main method.
The main function(method) is the entry point of your Java application, and it’s mandatory in a Java
program. whose signature in Java is:
public static void main(String[] args)
• public: So that JVM can execute the method from anywhere.
• static: The main method is to be called without an object. The modifiers public and static can be written
in either order.
• void: The main method doesn’t return anything.
• main(): Name configured in the JVM. The main method must be inside the class definition. The compiler
executes the codes starting always from the main function.
• String[]: The main method accepts a single argument, i.e., an array of elements of type String.
System.out.println("Hello, World");
This line outputs the string “Hello, World” followed by a new line on the screen. Output is accomplished by
the built-in println( ) method. The System is a predefined class that provides access to the system,
and out is the variable of type output stream connected to the console.
JSP

Introduction to JSP:
JSP stands for Java Server Pages, is a server side technology. JSP technology is used to create dynamic web
applications. JSP pages are easier to maintain then a Servlet. JSP pages are opposite of Servlets as a servlet
adds HTML code inside Java code, while JSP adds Java code inside HTML using JSP tags. Everything a Servlet
can do, a JSP page can also do it. JSP enables us to write HTML pages containing tags, inside which we can
include powerful Java programs. Using JSP, one can easily separate Presentation and Business logic as a web
designer can design and update JSP pages creating the presentation layer and java developer can write server
side complex computational code without concerning the web design. And both the layers can easily interact
over HTTP requests.
JSP pages are more advantageous than Servlet:

• They are easy to maintain.


• No recompilation or redeployment is required.
• JSP has access to entire API of JAVA .
• JSP are extended version of Servlet.
Features of JSP:
• Coding in JSP is easy :- As it is just adding JAVA code to HTML/XML.
• Reduction in the length of Code :- In JSP we use action tags, custom tags etc.
• Connection to Database is easier :-It is easier to connect website to database and allows to read or write
data easily to the database.
• Make Interactive websites :- In this we can create dynamic web pages which helps user to interact in
real time environment.
• Portable, Powerful, flexible and easy to maintain :- as these are browser and server independent.
• No Redeployment and No Re-Compilation :- It is dynamic, secure and platform independent so no need
to re-compilation.
• Extension to Servlet :- as it has all features of servlets, implicit objects and custom tags.
JSP syntax:
Syntax available in JSP are following
1. Declaration Tag :- A declaration declares one or more variables or methods that you can use in Java
code later in the JSP file. You must declare the variable or method before you use it in the JSP file.
Syntax:- <%! declaration; [ declaration; ]+ ... %>
Example:-
<%! int i = 0; %>
<%! int a, b, c; %>
<%! Circle a = new Circle(2.0); %>

2. Scriplets :- A scriptlet can contain any number of JAVA language statements, variable or method
declarations, or expressions that are valid in the page scripting language. It allows us to add any
number of JAVA code, variables and expressions.
Syntax:-
<% java code %>
Example:
<html>
<head><title>Hello World</title></head>

<body>
Hello World!<br/>
<%
out.println("Your IP address is " + request.getRemoteAddr());
%>
</body>
</html>

3. JSP Expression :- A JSP expression element contains a scripting language expression that is evaluated,
converted to a String, and inserted where the expression appears in the JSP file. Because the value of an
expression is converted to a String, you can use an expression within a line of text, whether or not it is
tagged with HTML, in a JSP file. The expression element can contain any expression that is valid
according to the Java Language Specification but you cannot use a semicolon to end an expression.
Syntax:-
<%= expression %>
Example:-
<html>
<head><title>A Comment Test</title></head>

<body>
<p>Today's date: <%= (new java.util.Date()).toLocaleString()%></p>
</body>
</html>
4. JAVA Comments :- JSP comment marks text or statements that the JSP container should ignore. A JSP
comment is useful when you want to hide or "comment out", a part of your JSP page.
Syntax:-
<% -- JSP Comments %>
Example:
<html>
<head><title>A Comment Test</title></head>

<body>
<h2>A Test of Comments</h2>
<%-- This comment will not be visible in the page source --%>
</body>
</html>

There are a small number of special constructs you can use in various cases to insert comments or characters
that would otherwise be treated specially. Some of them are listed below:
• <%-- comment --%> : A JSP comment, ignored by the JSP engine.
• <!-- comment --> : An HTML comment. Ignored by the browser.
• <\% :Represents static <% literal.
• %\> :Represents static %> literal.
• \' : A single quote in an attribute that uses single quotes.
• \" : A double quote in an attribute that uses double quotes.
There are also three types of directive tags:
• <%@ page ... %> :Defines page-dependent attributes, such as scripting language, error page, and
buffering requirements.
• <%@ include ... %> :Includes a file during the translation phase.
• <%@ taglib ... %> : Declares a tag library, containing custom actions, used in the page
JSP Actions:
JSP actions use constructs in XML syntax to control the behavior of the servlet engine. You can dynamically
insert a file, reuse JavaBeans components, forward the user to another page, or generate HTML for the Java
plugin. There is only one syntax for the Action element, as it conforms to the XML standard:
<jsp:action_name attribute="value" />
Action elements are basically predefined functions. Following is list of the available JSP Actions:
• jsp:include :Includes a file at the time the page is requested.
• jsp:useBean :Finds or instantiates a JavaBean.
• jsp:setProperty :Sets the property of a JavaBean.
• jsp:getProperty :Inserts the property of a JavaBean into the output.
• jsp:forward :Forwards the requester to a new page.
• jsp:plugin :Generates browser-specific code that makes an OBJECT or EMBED tag for the Java plugin.
• jsp:element :Defines XML elements dynamically.
• jsp:attribute :Defines dynamically-defined XML element's attribute.
• jsp:body :Defines dynamically-defined XML element's body.
• jsp:text :Used to write template text in JSP pages and documents.
JSP Implicit Objects
JSP supports nine automatically defined variables, which are also called implicit objects. These variables are −
• request :This is the HttpServletRequest object associated with the request.
• response :This is the HttpServletResponse object associated with the response to the client.
• out :This is the PrintWriter object used to send output to the client.
• session :This is the HttpSession object associated with the request.
• application :This is the ServletContext object associated with the application context.
• config :This is the ServletConfig object associated with the page.
• pageContext :This encapsulates use of server-specific features like higher performance JspWriters.
• page :This is simply a synonym for this, and is used to call the methods defined by the translated servlet
class.
• Exception :The Exception object allows the exception data to be accessed by designated JSP.
Control-Flow Statements
You can use all the APIs and building blocks of Java in your JSP programming including decision-making
statements, loops, etc.
Decision-Making Statements
The if...else block starts out like an ordinary Scriptlet, but the Scriptlet is closed at each line with HTML text
included between the Scriptlet tags.

<%! int day = 3; %>


<html>
<head><title>IF...ELSE Example</title></head>

<body>
<% if (day == 1 || day == 7) { %>
<p> Today is weekend</p>
<% } else { %>
<p> Today is not weekend</p>
<% } %>
</body>
</html>
The following shows the switch...case block which has been written a bit differently using out.println() and
inside Scriptlet as

<%! int day = 3; %>


<html>
<head><title>SWITCH...CASE Example</title></head>

<body>
<%
switch(day) {
case 0:
out.println("It\'s Sunday.");
break;
case 1:
out.println("It\'s Monday.");
break;
case 2:
out.println("It\'s Tuesday.");
break;
case 3:
out.println("It\'s Wednesday.");
break;
case 4:
out.println("It\'s Thursday.");
break;
case 5:
out.println("It\'s Friday.");
break;
default:
out.println("It's Saturday.");
}
%>
</body>
</html>

Loop Statements
You can also use three basic types of looping blocks in Java: for, while, and do…while blocks in your JSP
programming.
The following is a for loop example:

<%! int fontSize; %>


<html>
<head><title>FOR LOOP Example</title></head>

<body>
<%for ( fontSize = 1; fontSize <= 3; fontSize++){ %>
<font color = "green" size = "<%= fontSize %>">
JSP Tutorial
</font><br />
<%}%>
</body>
</html>

An example of using the while loop as follows :

<%! int fontSize; %>


<html>
<head><title>WHILE LOOP Example</title></head>

<body>
<%while ( fontSize <= 3){ %>
<font color = "green" size = "<%= fontSize %>">
JSP Tutorial
</font><br />
<%fontSize++;%>
<%}%>
</body>
</html>
JSP Operators
JSP supports all the logical and arithmetic operators supported by Java. Following table lists out all the
operators with the highest precedence appear at the top of the table, those with the lowest appear at the
bottom. Within an expression, higher precedence operators will be evaluated first.

Category Operator Associativity

Postfix () [] . (dot operator) Left to right

Unary ++ - - ! ~ Right to left


Multiplicative */% Left to right

Additive +- Left to right

Shift >> >>> << Left to right

Relational > >= < <= Left to right

Equality == != Left to right

Bitwise AND & Left to right

Bitwise XOR ^ Left to right

Bitwise OR | Left to right

Logical AND && Left to right

Logical OR || Left to right

Conditional ?:`` Right to left

Assignment = += -= *= /= %= >>= <<= &= ^= |= Right to left

Comma , Left to right


JSP Literals
The JSP expression language defines the following literals −
• Boolean − true and false
• Integer − as in Java
• Floating point − as in Java
• String − with single and double quotes; " is escaped as \", ' is escaped as \', and \ is escaped as \\.
• Null − null
Advantages of using JSP:
• It does not require advanced knowledge of JAVA
• It is capable of handling exceptions
• Easy to use and learn
• It can tags which are easy to use and understand
• Implicit objects are there which reduces the length of code
• It is suitable for both JAVA and non JAVA programmer

Disadvantages of using JSP:


• Difficult to debug for errors.
• First time access leads to wastage of time
• It’s output is HTML which lacks features.
An example of JSP Hello World program
demo.jsp
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Hello World - JSP tutorial</title>
</head>
<body>
<%= "Hello World!" %>
</body>
</html>

JSP Architecture:
JSP architecture gives a high-level view of the working of JSP. JSP architecture is a 3 tier architecture. It has
a Client, Web Server, and Database. The client is the web browser or application on the user side. Web
Server uses a JSP Engine i.e; a container that processes JSP. For example, Apache Tomcat has a built -in JSP
Engine. JSP Engine intercepts the request for JSP and provides the runtime environment for the
understanding and processing of JSP files. It reads, parses, build Java Servlet, Compiles and Executes Java
code, and returns the HTML page to the client. The webserver has access to the Database. The following
diagram shows the architecture of JSP.

In this JSP tags are used to insert JAVA code into HTML pages. It is an advanced version of Servlet
Technology. It is a Web-based technology that helps us to create dynamic and platform-independent web
pages. In this, Java code can be inserted in HTML/ XML pages or both. JSP is first converted into a servlet by
JSP container before processing the client’s request.JSP Processing is illustrated and discussed in
sequential steps prior to which a pictorial media is provided as a handful pick to understand the JSP
processing better which is as follows:
Step 1: The client navigates to a file ending with the .jsp extension and the browser initiates an HTTP
request to the webserver. For example, the user enters the login details and submits the button. The
browser requests a status.jsp page from the webserver.
Step 2: If the compiled version of JSP exists in the web server, it returns the file. Otherwise, the request is
forwarded to the JSP Engine. This is done by recognizing the URL ending with .jsp extension.
Step 3: The JSP Engine loads the JSP file and translates the JSP to Servlet(Java code). This is done by
converting all the template text into println() statements and JSP elements to Java code. This process is
called translation.
Step 4: The JSP engine compiles the Servlet to an executable .class file. It is forwarded to the Servlet engine.
This process is called compilation or request processing phase.
Step 5: The .class file is executed by the Servlet engine which is a part of the Web Server. The output is an
HTML file. The Servlet engine passes the output as an HTTP response to the webserver.
Step 6: The web server forwards the HTML file to the client’s browser.
Life cycle of JSP:
A Java Server Page life cycle is defined as the process that started with its creation which la ter translated to
a servlet and afterward servlet lifecycle comes into play. This is how the process goes on until its
destruction.
Following steps are involved in the JSP life cycle:

• Translation of JSP page to Servlet: This is the first step of the JSP life cycle. This translation phase deals
with the Syntactic correctness of JSP. Here test.jsp file is translated to test.java.
• Compilation of JSP page(Compilation of JSP into test.java): Here the generated java servlet file
(test.java) is compiled to a class file (test.class).
• Classloading (test.java to test.class): Servlet class which has been loaded from the JSP source is now
loaded into the container.
• Instantiation(Object of the generated Servlet is created): Here an instance of the class is generated. The
container manages one or more instances by providing responses to requests.
• Initialization(jspInit() method is invoked by the container): jspInit() method is called only once during
the life cycle immediately after the generation of Servlet instance from JSP.
• Request processing(_jspService()is invoked by the container): jspService() method is used to serve the
raised requests by JSP. It takes request and response objects as parameters. This method cannot be
overridden.
• JSP Cleanup (jspDestroy() method is invoked by the container): In order to remove the JSP from the use
by the container or to destroy the method for servlets jspDestroy()method is used. This method is
called once, if you need to perform any cleanup task like closing open files, releasing database
connections jspDestroy() can be overridden.

What happens to a JSP when it is translated into Servlet?

Let's see what really happens to JSP code when it is translated into Servlet. The code written inside <% %> is
JSP code.

<html>

<head><title>My First JSP Page</title></head>

<%

int count = 0;
%>

<body>

Page Count is: <% out.println (++ count); %>

</body>

</html>

The above JSP page(hello.jsp) becomes this Servlet,

public class hello_jsp extends HttpServlet

{ public void _jspService(HttpServletRequest request, HttpServletResponse response) throws


IOException,ServletException

{ PrintWriter out = response.getWriter();

response.setContenType("text/html");

out.write(“<html><body>”);

int count=0;

out.write("Page count is:"); out.print(++count);

out.write(“</body></html”>);

Creating a JSP Page: A jsp page looks similar to an html page, but a jsp page also has java code in it. We can put
any regular java code in a jsp file using a scriplet tag which start with <% and ends with %>.
JSP – Debugging:
It is always difficult testing/debugging a JSP and servlets. JSP and Servlets tend to involve a large amount of
client/server interaction, making errors likely but hard to reproduce.
The following are a few hints and suggestions that may aid you in your debugging.
• Using System.out.println(): System.out.println() is easy to use as a marker to test whether a certain piece
of code is being executed or not. We can print out variable values as well. Since the System object is part
of the core Java objects, it can be used everywhere without the need to install any extra classes. This
includes Servlets, JSP, RMI, EJB's, ordinary Beans and classes, and standalone applications. Compared to
stopping at breakpoints, writing to System.out doesn't interfere much with the normal execution flow of
the application, which makes it very valuable when the aiming is crucial. Syntax:
System.out.println("Debugging message");
An example to show how to use System.out.println():
< %@taglib prefix = "c" uri = "http://java.sun.com/jsp/jstl/core" % >
<html>
<head><title>System.out.println</title></head>
<body>
<c:forEach var = "counter" begin = "1" end = "10" step = "1" >

<c:out value = "${counter-5}"/></br>


<% System.out.println( "counter = " + pageContext.findAttribute("counter") ); %>
</c:forEach>

</body>
</html>

• Using the JDB Logger: The J2SE logging framework is designed to provide logging services for any
class running in the JVM. We can make use of this framework to log any information.

An example using JDK logger API:

<%@taglib prefix = "c" uri = "http://java.sun.com/jsp/jstl/core" %>


<%@page import = "java.util.logging.Logger" %>

<html>
<head><title>Logger.info</title></head>

<body>
<% Logger logger = Logger.getLogger(this.getClass().getName());%>

<c:forEach var = "counter" begin = "1" end = "10" step = "1" >
<c:set var = "myCount" value = "${counter-5}" />
<c:out value = "${myCount}"/></br>
<% String message = "counter = "
+ pageContext.findAttribute("counter") + "myCount = "
+ pageContext.findAttribute("myCount");
logger.info( message );
%>
</c:forEach>

</body>
</html>
Messages can be sent at various levels by using the convenience functions severe(), warning(), info(), config(),
fine(), finer(), and finest(). Here finest() method can be used to log finest information and the severe()
method can be used to log severe information.

Debugging Tools

NetBeans is a free and open-source Java Integrated Development Environment that supports the
development of standalone Java applications and Web applications supporting the JSP and servlet
specifications and includes a JSP debugger as well. NetBeans supports the following basic debugging
functionalities :

• Breakpoints
• Stepping through code
• Watchpoints
• Using JDB Debugger: You can debug JSP and servlets with the same jdb commands you use to debug
an applet or an application. To debug a JSP or servlet, you can debug sun.servlet.http.HttpServer, then
observe as HttpServer executes the JSP/servlets in response to HTTP requests we make from a
browser. This is very similar to how applets are debugged. You need to help your debugger by
considering the following −
Set your debugger's classpath. This helps you find sun.servlet.http.Http-Server and the associated

classes.
▪ Set your debugger's classpath. This helps you find your JSP and support classes,
typically ROOT\WEB-INF\classes.
Once you have set the proper classpath, start debugging sun.servlet.http.HttpServer. You can set breakpoints
in whatever JSP you're interested in debugging, then use a web browser to make a request to the HttpServer
for the given JSP. The execution here stops at breakpoints.
• Using Comments: Comments in your code can help the debugging process in various ways. Comments can
be used in lots of other ways in the debugging process. The JSP uses Java comments and single line (//
...) and multiple line (/* ... */) comments can be used to temporarily remove parts of your Java code. If the
bug disappears, take a closer look at the code you just commented and find out the problem.
JSP - Form Processing

The Methods in Form Processing

1.
GET method : The GET method sends the encoded user information appended to the page request.
The page and the encoded information are separated by the ? character as follows −
http://www.test.com/hello?key1=value1&key2=value2
The GET method is the default method to pass information from the browser to the web server and it produces
a long string that appears in your browser's Location:box. It is recommended that the GET method is better not
used. if you have password or other sensitive information to pass to the server.
The GET method has size limitation: only 1024 characters can be in a request string.
This information is passed using QUERY_STRING header and will be accessible through QUERY_STRING
environment variable which can be handled using getQueryString() and getParameter() methods of request
object.
2. POST method : A generally more reliable method of passing information to a backend program is the
POST method. This method packages the information in exactly the same way as the GET method, but
instead of sending it as a text string after a ? in the URL it sends it as a separate message. This message
comes to the backend program in the form of the standard input which you can parse and use for your
processing.
JSP handles this type of requests using getParameter() method to read simple parameters
and getInputStream() method to read binary data stream coming from the client.

Reading Form Data using JSP

JSP handles form data parsing automatically using the following methods depending on the situation −
• getParameter() − You call request.getParameter() method to get the value of a form parameter.
• getParameterValues() − Call this method if the parameter appears more than once and returns
multiple values, for example checkbox.
• getParameterNames() − Call this method if you want a complete list of all parameters in the current
request.
• getInputStream() − Call this method to read binary data stream coming from the client.

GET Method Example Using URL:

<html>
<head>
<title>Using GET Method to Read Form Data</title>
</head>

<body>
<h1>Using GET Method to Read Form Data</h1>
<ul>
<li><p><b>First Name:</b>
<%= request.getParameter("first_name")%>
</p></li>
<li><p><b>Last Name:</b>
<%= request.getParameter("last_name")%>
</p></li>
</ul>

</body>
</html>

GET Method Example Using Form:

Following is an example that passes two values using the HTML FORM and the submit button.

<html>
<body>

<form action = "main.jsp" method = "GET">


First Name: <input type = "text" name = "first_name">
<br />
Last Name: <input type = "text" name = "last_name" />
<input type = "submit" value = "Submit" />
</form>

</body>
</html>

POST Method Example Using Form:

Below is the JSP program to handle the input given by web browser using the GET or the POST methods. Infact
there is no change in the above JSP because the only way of passing parameters is changed and no binary data
is being passed to the JSP program. File handling related concepts will be explained in separate chapter where
we need to read the binary data stream.

<html>
<head>
<title>Using GET and POST Method to Read Form Data</title>
</head>

<body>
<center>
<h1>Using POST Method to Read Form Data</h1>

<ul>
<li><p><b>First Name:</b>
<%= request.getParameter("first_name")%>
</p></li>
<li><p><b>Last Name:</b>
<%= request.getParameter("last_name")%>
</p></li>
</ul>

</body>
</html>

Passing Checkbox Data to JSP Program:

Checkboxes are used when more than one option is required to be selected. Following is an example,

<html>
<body>

<form action = "main.jsp" method = "POST" target = "_blank">


<input type = "checkbox" name = "maths" checked = "checked" /> Maths
<input type = "checkbox" name = "physics" /> Physics
<input type = "checkbox" name = "chemistry" checked = "checked" /> Chemistry
<input type = "submit" value = "Select Subject" />
</form>

</body>
</html>

Following is main.jsp JSP program to handle the input given by the web browser for the checkbox button.
<html>
<head>
<title>Reading Checkbox Data</title>
</head>

<body>
<h1>Reading Checkbox Data</h1>

<ul>
<li><p><b>Maths Flag:</b>
<%= request.getParameter("maths")%>
</p></li>
<li><p><b>Physics Flag:</b>
<%= request.getParameter("physics")%>
</p></li>
<li><p><b>Chemistry Flag:</b>
<%= request.getParameter("chemistry")%>
</p></li>
</ul>

</body>
</html>

Reading All Form Parameters:

Following is a generic example which uses getParameterNames() method of HttpServletRequest to read all
the available form parameters. This method returns an Enumeration that contains the parameter names in an
unspecified order.

<%@ page import = "java.io.*,java.util.*" %>


<html>
<head>
<title>HTTP Header Request Example</title>
</head>
<body>
<center>
<h2>HTTP Header Request Example</h2>
<table width = "100%" border = "1" align = "center">
<tr bgcolor = "#949494">
<th>Param Name</th>
<th>Param Value(s)</th>
</tr>
<%
Enumeration paramNames = request.getParameterNames();
while(paramNames.hasMoreElements()) {
String paramName = (String)paramNames.nextElement();
out.print("<tr><td>" + paramName + "</td>\n");
String paramValue = request.getHeader(paramName);
out.println("<td> " + paramValue + "</td></tr>\n");
}
%>
</table>
</center>
</body>
</html>

Cookies Handling in JSP: Cookies are text files stored on the client computer and they are kept for various
information tracking purposes. JSP transparently supports HTTP cookies using underlying servlet technology.
There are three steps involved in identifying and returning users −
• Server script sends a set of cookies to the browser. For example, name, age, or identification number, etc.
• Browser stores this information on the local machine for future use.
• When the next time the browser sends any request to the web server then it sends those cookies
information to the server and server uses that information to identify the user or may be for some other
purpose as well.

Cookies are usually set in an HTTP header (although JavaScript can also set a cookie directly on a browser). A
JSP that sets a cookie might send headers in this way:

HTTP/1.1 200 OK
Date: Fri, 04 Aug 2022 21:03:38 GMT
Server: Apache/1.3.9 (UNIX) PHP/4.0b3
Set-Cookie: name = xyz; expires = Friday, 04-Aug -22 22:03:38 GMT;
path = /; domain = tutorialspoint.com
Connection: close
Content-Type: text/html
The Set-Cookie header contains a name value pair, a GMT date, a path and a domain. The name and value will be
URL encoded. The expires field is an instruction to the browser to "forget" the cookie after the given time and
date.
If the browser is configured to store cookies, it will then keep this information until the expiry date. If the user
points the browser at any page that matches the path and domain of the cookie, it will resend the cookie to the
server. A JSP script will then have access to the cookies through the request method request.getCookies() which
returns an array of Cookie objects.

Servlet Cookies Methods:

Following table lists out the useful methods associated with the Cookie object which you can use while
manipulating cookies in JSP −
• public void setDomain(String pattern) :This method sets the domain to which the cookie applies; for
example, tutorialspoint.com.
• public String getDomain() :This method gets the domain to which the cookie applies; for example,
tutorialspoint.com.
• public void setMaxAge(int expiry) :This method sets how much time (in seconds) should elapse before
the cookie expires. If you don't set this, the cookie will last only for the current session.
• public int getMaxAge() :This method returns the maximum age of the cookie, specified in seconds, By
default, -1 indicating the cookie will persist until the browser shutdown.
• public String getName(): This method returns the name of the cookie. The name cannot be changed after
the creation.
• public void setValue(String newValue) :This method sets the value associated with the cookie.
• public String getValue(): This method gets the value associated with the cookie.
• public void setPath(String uri): This method sets the path to which this cookie applies. If you don't
specify a path, the cookie is returned for all URLs in the same directory as the current page as well as all
subdirectories
• public String getPath(): This method gets the path to which this cookie applies.
• public void setSecure(boolean flag) : This method sets the boolean value indicating whether the cookie
should only be sent over encrypted (i.e, SSL) connections.
• public void setComment(String purpose): This method specifies a comment that describes a cookie's
purpose. The comment is useful if the browser presents the cookie to the user.
• public String getComment(): This method returns the comment describing the purpose of this cookie, or
null if the cookie has no comment.

Setting Cookies with JSP: Setting cookies with JSP involves three steps −

Step 1: Creating a Cookie object


You call the Cookie constructor with a cookie name and a cookie value, both of which are strings.
Cookie cookie = new Cookie("key","value");
Step 2: Setting the maximum age
You use setMaxAge to specify how long (in seconds) the cookie should be valid. The following code will set up
a cookie for 24 hours.
cookie.setMaxAge(60*60*24);
Step 3: Sending the Cookie into the HTTP response headers
You use response.addCookie to add cookies in the HTTP response header as follows
response.addCookie(cookie);

Form Example to set the cookies for the first and the last name:

<%
// Create cookies for first and last names.
Cookie firstName = new Cookie("first_name", request.getParameter("first_name"));
Cookie lastName = new Cookie("last_name", request.getParameter("last_name"));

// Set expiry date after 24 Hrs for both the cookies.


firstName.setMaxAge(60*60*24);
lastName.setMaxAge(60*60*24);

// Add both the cookies in the response header.


response.addCookie( firstName );
response.addCookie( lastName );
%>

<html>
<head>
<title>Setting Cookies</title>
</head>
<body>
<center>
<h1>Setting Cookies</h1>
</center>
<ul>
<li><p><b>First Name:</b>
<%= request.getParameter("first_name")%>
</p></li>
<li><p><b>Last Name:</b>
<%= request.getParameter("last_name")%>
</p></li>
</ul>

</body>
</html>

Reading Cookies with JSP:

To read cookies, you need to create an array of javax.servlet.http.Cookie objects by calling the getCookies(
) method of HttpServletRequest. Then cycle through the array, and use getName() and getValue() methods to
access each cookie and associated value.

<html>
<head>
<title>Reading Cookies</title>
</head>

<body>
<center>
<h1>Reading Cookies</h1>
</center>
<%
Cookie cookie = null;
Cookie[] cookies = null;

// Get an array of Cookies associated with the this domain


cookies = request.getCookies();

if( cookies != null ) {


out.println("<h2> Found Cookies Name and Value</h2>");

for (int i = 0; i < cookies.length; i++) {


cookie = cookies[i];
out.print("Name : " + cookie.getName( ) + ", ");
out.print("Value: " + cookie.getValue( )+" <br/>");
}
} else {
out.println("<h2>No cookies founds</h2>");
}
%>
</body>
</html>
Delete Cookies with JSP

To delete cookies is very simple. If you want to delete a cookie, then you simply need to follow these three steps

• Read an already existing cookie and store it in Cookie object.
• Set cookie age as zero using the setMaxAge() method to delete an existing cookie.
• Add this cookie back into the response header.
Following example will show you how to delete an existing cookie named "first_name" and when you run
main.jsp JSP next time, it will return null value for first_name.

<html>
<head>
<title>Reading Cookies</title>
</head>

<body>
<center>
<h1>Reading Cookies</h1>
</center>
<%
Cookie cookie = null;
Cookie[] cookies = null;

// Get an array of Cookies associated with the this domain


cookies = request.getCookies();

if( cookies != null ) {


out.println("<h2> Found Cookies Name and Value</h2>");

for (int i = 0; i < cookies.length; i++) {


cookie = cookies[i];

if((cookie.getName( )).compareTo("first_name") == 0 ) {
cookie.setMaxAge(0);
response.addCookie(cookie);
out.print("Deleted cookie: " +
cookie.getName( ) + "<br/>");
}
out.print("Name : " + cookie.getName( ) + ", ");
out.print("Value: " + cookie.getValue( )+" <br/>");
}
} else {
out.println(
"<h2>No cookies founds</h2>");
}
%>
</body>
</html>
A webserver can assign a unique session ID as a cookie to each web client and for subsequent requests from
the client they can be recognized using the received cookie.
This may not be an effective way as the browser at times does not support a cookie. It is not recommended to
use this procedure to maintain the sessions.
Hidden Form Fields: A web server can send a hidden HTML form field along with a unique session ID as
follows −
<input type = "hidden" name = "sessionid" value = "12345">
This entry means that, when the form is submitted, the specified name and value are automatically included in
the GET or the POST data. Each time the web browser sends the request back, the session_id value can be used
to keep the track of different web browsers.
URL Rewriting: You can append some extra data at the end of each URL. This data identifies the session; the
server can associate that session identifier with the data it has stored about that session. URL rewriting is a
better way to maintain sessions and works for the browsers when they don't support cookies. The drawback
here is that you will have to generate every URL dynamically to assign a session ID though page is a simple
static HTML page.

The session Object:

Apart from the above mentioned options, JSP makes use of the servlet provided HttpSession Interface. This
interface provides a way to identify a user across.

• a one page request or


• visit to a website or
• store information about that user
By default, JSPs have session tracking enabled and a new HttpSession object is instantiated for each new client
automatically. Disabling session tracking requires explicitly turning it off by setting the page directive session
attribute to false as follows –
<%@ page session = "false" %>
The JSP engine exposes the HttpSession object to the JSP author through the implicit session object.
Since session object is already provided to the JSP programmer, the programmer can immediately begin
storing and retrieving data from the object without any initialization or getSession().

Important methods available through the session object –


1. public Object getAttribute(String name): This method returns the object bound with the
specified name in this session, or null if no object is bound under the name.
2. public Enumeration getAttributeNames(): This method returns an Enumeration of String
objects containing the names of all the objects bound to this session.
3. public long getCreationTime(): This method returns the time when this session was created,
measured in milliseconds since midnight January 1, 1970 GMT.
4. public String getId(): This method returns a string containing the unique identifier assigned to
this session.
5. public long getLastAccessedTime(): This method returns the last time the client sent a request
associated with the this session, as the number of milliseconds since midnight January 1, 1970
GMT.
6. public int getMaxInactiveInterval(): This method returns the maximum time interval, in
seconds, that the servlet container will keep this session open between client accesses.
7. public void invalidate(): This method invalidates this session and unbinds any objects bound to
it.
8. public boolean isNew(): This method returns true if the client does not yet know about the
session or if the client chooses not to join the session.
9. public void removeAttribute(String name): This method removes the object bound with the
specified name from this session.
10. public void setAttribute(String name, Object value): This method binds an object to this
session, using the name specified
11. public void setMaxInactiveInterval(int interval): This method specifies the time, in seconds,
between client requests before the servlet container will invalidate this session.
Session Tracking Example:
<%@ page import = "java.io.*,java.util.*" %>
<%
// Get session creation time.
Date createTime = new Date(session.getCreationTime());

// Get last access time of this Webpage.


Date lastAccessTime = new Date(session.getLastAccessedTime());

String title = "Welcome Back to my website";


Integer visitCount = new Integer(0);
String visitCountKey = new String("visitCount");
String userIDKey = new String("userID");
String userID = new String("ABCD");

// Check if this is new comer on your Webpage.


if (session.isNew() ){
title = "Welcome to my website";
session.setAttribute(userIDKey, userID);
session.setAttribute(visitCountKey, visitCount);
}
visitCount = (Integer)session.getAttribute(visitCountKey);
visitCount = visitCount + 1;
userID = (String)session.getAttribute(userIDKey);
session.setAttribute(visitCountKey, visitCount);
%>

<html>
<head>
<title>Session Tracking</title>
</head>
<body>
<center>
<h1>Session Tracking</h1>
</center>
<table border = "1" align = "center">
<tr bgcolor = "#949494">
<th>Session info</th>
<th>Value</th>
</tr>
<tr>
<td>id</td>
<td><% out.print( session.getId()); %></td>
</tr>
<tr>
<td>Creation Time</td>
<td><% out.print(createTime); %></td>
</tr>
<tr>
<td>Time of Last Access</td>
<td><% out.print(lastAccessTime); %></td>
</tr>
<tr>
<td>User ID</td>
<td><% out.print(userID); %></td>
</tr>
<tr>
<td>Number of visits</td>
<td><% out.print(visitCount); %></td>
</tr>
</table>
</body>
</html>
This example describes how to use the HttpSession object to find out the creation time and the last-accessed
time for a session. We would associate a new session with the request if one does not already exist.

Deleting Session Data:

When you are done with a user's session data, you have several options −
• Remove a particular attribute − You can call the public void removeAttribute(String name) method
to delete the value associated with the a particular key.
• Delete the whole session − You can call the public void invalidate() method to discard an entire
session.
• Setting Session timeout − You can call the public void setMaxInactiveInterval(int interval) method
to set the timeout for a session individually.
• Log the user out − The servers that support servlets 2.4, you can call logout to log the client out of the
Web server and invalidate all sessions belonging to all the users.
• web.xml Configuration − If you are using Tomcat, apart from the above mentioned methods, you can
configure the session time out in web.xml file as follows.
Working with JDBC:
JDBC or Java Database Connectivity is a Java API to connect and execute the query with the database. It is a
specification from Sun microsystems that provides a standard abstraction(API or Protocol) for java
applications to communicate with various databases. It provides the language with java database connectivity
standards. It is used to write programs required to access databases. JDBC, along with the database driver,
can access databases and spreadsheets. The enterprise data stored in a relational database (RDB) can be
accessed with the help of JDBC APIs.
Purpose of JDBC :
Interacting with a database requires efficient database connectivity, which can be achieved by using the ODBC
(Open database connectivity) driver. This driver is used with JDBC to interact or communicate with various
kinds of databases such as Oracle, MS Access, Mysql, and SQL server database.
ODBC: ODBC stands for Open Database Connectivity.
It is an open standard Application Programming Interface also known as API which is used for accessing a
database. First ODBC driver was build in 1992 when Microsoft partners with Simba named SIMBA.DLL.
With the help of ODBC statement in a program. We can access different files in a number of a different or
common database.
First ODBC standard was introduced in 1992 by Microsoft. This driver was a standard model that is
basically designed to unify access to different SQL databases.
Components of JDBC:
There are generally four main components of JDBC through which it can interact with a database. They are as
mentioned below:
1. JDBC API: It provides various methods and interfaces for easy communication with the database. It
provides two packages as follows, which contain the java SE and Java EE platforms to exhibit
WORA(write once run everywhere) capabilities.
2. It also provides a standard to connect a database to a client application.
3. JDBC Driver manager: It loads a database-specific driver in an application to establish a connection
with a database. It is used to make a database-specific call to the database to process the user
request.
4. JDBC Test suite: It is used to test the operation (such as insertion, deletion, updation) being
performed by JDBC Drivers.
5. JDBC-ODBC Bridge Drivers: It connects database drivers to the database. This bridge translates the
JDBC method call to the ODBC function call. It makes use of the sun.jdbc.odbc package which includes
a native library to access ODBC characteristics.
Architecture of JDBC:
• Application: It is a java applet or a servlet that communicates with a data source.
• The JDBC API: The JDBC API allows Java programs to execute SQL statements and retrieve results.
• Driver Manager: It plays an important role in the JDBC architecture. It uses some database-specific
drivers to effectively connect enterprise applications to databases.
• JDBC drivers: To communicate with a data source through JDBC, you need a JDBC driver that
intelligently communicates with the respective data source.
Both ODBC and JDBC are the programming interface that is required by the applications at the client side to
access the database at server side. Basically both are known as drivers to get connected with a database and
are provided by the vendors of RDBMS.
Difference between ODBC and JDBC:
ODBC JDBC
1. ODBC stands for Open Database Connectivity 1. JDBC Stands for Java database connectivity i.e
which literally means that it is compatible with all only compatible with java language.
types of languages such as C, C++, Java, etc.
2. ODBC was introduced by Microsoft prior to JDBC 2. JDBC was introduced by SUN MicroSystems after
in 1992. ODBC in 1998.
3. ODBC is platform dependent as we can use ODBC 3. On the other hand, JDBC is platform-independent
only for windows platform. and can be used for any platform.
4. ODBC can be considered as a type of procedural 4. On the other hand, JDBC is a purely object-
as most of these drivers are developed in a native oriented type driver.
languages like C and C++ which are the procedural
types of language.
5. The performance of ODBC is faster as compared 5. On the other hand performance of JDBC is slower
to JDBC as data imports and exports are faster and than native ODBC but its platform independence
memory-intensive. allowing to work with any operating system
(including Mac and Linux), driver version, or
bitness (32-bit or 64-bit)

JDBC Drivers: JDBC drivers are client-side adapters (installed on the client machine, not on the server) that
convert requests from Java programs to a protocol that the DBMS can understand. There are 4 types of JDBC
drivers:
1. Type-1 driver or JDBC-ODBC bridge driver
2. Type-2 driver or Native-API driver
3. Type-3 driver or Network Protocol driver
4. Type-4 driver or Thin driver
Types of JDBC Architecture(2-tier and 3-tier): The JDBC architecture consists of two-tier and three-tier
processing models to access a database. They are as described below:
• Two-tier model: A java application communicates directly to the data source. The JDBC driver
enables the communication between the application and the data source. When a user sends a query
to the data source, the answers for those queries are sent back to the user in the form of results. The
data source can be located on a different machine on a network to which a user is connected. This is
known as a client/server configuration, where the user’s machine acts as a client, and the machine
has the data source running acts as the server.
• Three-tier model: In this, the user’s queries are sent to middle-tier services, from which the
commands are again sent to the data source. The results are sent back to the middle tier, and from
there to the user. This type of model is found very useful by management information system
directors.
Interfaces of JDBC API: A list of popular interfaces of JDBC API is given below:
• Driver interface
• Connection interface
• Statement interface
• PreparedStatement interface
• CallableStatement interface
• ResultSet interface
• ResultSetMetaData interface
• DatabaseMetaData interface
• RowSet interface
Classes of JDBC API: A list of popular classes of JDBC API is given below:
• DriverManager class
• Blob class
• Clob class
• Types class
Working of JDBC:
Java application that needs to communicate with the database has to be programmed using JDBC API. JDBC
Driver supporting data sources such as Oracle and SQL server has to be added in java application for JDBC
support which can be done dynamically at run time. This JDBC driver intelligently communicates the
respective data source.
Creating a simple JDBC application:
package com.vinayak.jdbc;
import java.sql.*;
public class JDBCDemo {
public static void main(String args[])
throws SQLException, ClassNotFoundException {
String driverClassName = "sun.jdbc.odbc.JdbcOdbcDriver";
String url = "jdbc:odbc:XE";
String username = "scott";
String password = "tiger";
String query = "insert into students values(109, 'bhatt')";
// Load driver class
Class.forName(driverClassName);
// Obtain a connection
Connection con = DriverManager.getConnection( url, username, password);
// Obtain a statement
Statement st = con.createStatement();
// Execute the query
int count = st.executeUpdate(query);
System.out.println( "number of rows affected by this query= " + count);
// Closing the connection as per the requirement with connection is completed
con.close();
}
} // class
The above example demonstrates the basic steps to access a database using JDBC. The application uses the
JDBC-ODBC bridge driver to connect to the database. You must import java.sql package to provide basic SQL
functionality and use the classes of the package.
Java Beans:
A JavaBean is a specially constructed Java class written in the Java and coded according to the JavaBeans API
specifications. In computing based on the Java Platform, JavaBeans is a technology developed by Sun
Microsystems and released in 1996, as part of JDK 1.1. The 'beans' of JavaBeans are classes that encapsulate
one or more objects into a single standardized object (the bean).
Advantages of JavaBeans from other Java classes:
1. It provides a default, no-argument constructor.
2. It should be serializable and that which can implement the Serializable interface.
3. It may have a number of properties which can be read or written.
4. It may have a number of "getter" and "setter" methods for the properties.
// Java program to illustrate the
// structure of JavaBean class
public class TestBean {
private String name;
public void setName(String name)
{
this.name = name;
}
public String getName()
{
return name;
}
}
JavaBeans Properties:
A JavaBean property is a named attribute that can be accessed by the user of the object. The attribute can be
of any Java data type, including the classes that you define. A JavaBean property may be read, write, read only,
or write only. JavaBean properties are accessed through two methods in the JavaBean's implementation class:
1. getPropertyName(): For example, if property name is firstName, your method name would be
getFirstName() to read that property. This method is called accessor.
2. setPropertyName(): For example, if property name is firstName, your method name would be
setFirstName() to write that property. This method is called mutator.
A read-only attribute will have only a getPropertyName() method, and a write-only attribute will have only a
setPropertyName() method. An example to illustrate JavaBean student class with few properties:
package com.tutorialspoint;
public class StudentsBean implements
java.io.Serializable {
private String firstName = null;
private String lastName = null;
private int age = 0;
public StudentsBean() { …. }
public String getFirstName(){
return firstName; }
public String getLastName(){
return lastName; }
public int getAge(){
return age; }
public void setFirstName(String firstName){
this.firstName = firstName; }
public void setLastName(String lastName){
this.lastName = lastName; }
public void setAge(Integer age){
this.age = age; }
}

Accessing JavaBeans:
The useBean action declares a JavaBean for use in a JSP. Once declared, the bean becomes a scripting variable
that can be accessed by both scripting elements and other custom tags used in the JSP. The full syntax for the
useBean tag is as follows –
<jsp: useBean id = "bean's name" scope = "bean's scope" typeSpec/>
Here values for the scope attribute can be a page, request, session or application based on your requirement.
The value of the id attribute may be any value as a long as it is a unique name among other useBean
declarations in the same JSP.
An example shows how to use the useBean action –
<html>
<head><title>useBean Example</title></head>
<body>
<jsp: useBean id = "date" class = "java.util.Date" />
<p>The date/time is <%= date %>
</body>
</html>
Accessing JavaBeans Properties:
Along with <jsp:useBean...> action, you can use the <jsp:getProperty/> action to access the get methods and the
<jsp:setProperty/> action to access the set methods. Here is the full syntax:

<jsp: useBean id = "id" class = "bean's class" scope = "bean's scope">


<jsp: setProperty name = "bean's id" property = "property name" value = "value"/>
<jsp: getProperty name = "bean's id" property = "property name"/>
……….
</jsp:useBean>

The name attribute references the id of a JavaBean previously introduced to the JSP by the useBean action.
The property attribute is the name of the get or the set methods that should be invoked. Following example
shows how to access the data using the above syntax

<html>

<head><title>get and set properties Example</title></head>

<body>

<jsp:useBean id = "students" class = "com.tutorialspoint.StudentsBean">

<jsp:setProperty name = "students" property = "firstName" value = "Zara"/>

<jsp:setProperty name = "students" property = "lastName" value = "Ali"/>

<jsp:setProperty name = "students" property = "age" value = "10"/>

<jsp:useBean>

<p>Student First Name: <jsp: getProperty name = "students" property = "firstName"/> </p>

<p>Student Last Name: <jsp: getProperty name = "students" property = "lastName"/></p>

<p>Student Age: <jsp: getProperty name = "students" property = "age"/></p>


</body>

</html>

Intermediate Web Development Techniques


AJAX:
Ajax is an acronym for Asynchronous Javascript and XML. It is used to communicate with the server without
refreshing the web page and thus increasing the user experience and better performance.
How does it work?
Ajax allows web pages to be updated asynchronously by exchanging small amounts of data with the server
behind the scenes.For implementing Ajax, only be aware of XMLHttpRequest object.It is an object used to
exchange data with the server behind the scenes. The paradigm of OOP which says that object communicates
through calling methods (or in general sense message passing). The same case applied here as well. Usually,
create this object and use it to call the methods which result in effective communication. All modern browsers
support the XMLHttpRequest object.
The syntax of creating the object is given below:
req = new XMLHttpRequest();
There are two types of methods open() and send(). Uses of these methods:
req.open("GET", "abc.php", true);
req.send();
In the above code, req stands for the request, it is basically a reference variable. The GET parameter is as
usual one of two types of methods to send the request. Use POST as well depending upon whether send the
data through POST or GET method. The second parameter is being the name of the file which actually handles
the requests and processes them. The third parameter is true, it tells that whether the requests are processed
asynchronously or synchronously. It is by default true which means that requests are asynchronous. The
open() method prepares the request before sending it to the server. The send method is used to send the
request to the server. Sending the parameter through Getting or POST request. The syntax is given below:
req.open("GET", "abc.php?x=25", true);
req.send();
In the above lines of code, the specified query in the form of URL followed by ? which is further followed by
the name of the variable then = and then the corresponding value. If sending two or more variables use
ampersand(&) sign between the two variables. The above method as shown applies for GET request. Sending
the data through the POST, then send it in the send method as shown below:
req.send("name=johndoe&marks=99");
Use of setRequestHeader() method as shown below:
req.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
Events and handling mechanism: Any action performs on the clicking button, hovering over elements, page
loading etc all are termed as events. Also aware of fact that javascript can detect events. So bind the code of
specific event with its action which can be implemented by javascript. These are basically event handlers.
Implementing event handlers which actually hold the events. Events handlers are basically functions written
in javascript which act on or set into action when an event is fired by the user. When sending the request
through send method usually get the response from the server later. But getting of response time is not
known. So need to track it. Therefore to keep a track of the response onreadystatechange event which is
binding with the event handler(function) which will get executed when a response comes.
When a request to the server is sending perform actions based on the response. The onreadystatechange
event is triggered every time the readyState changes. So what actually a ready state is and when will the
onreadystate event actually occur and how many times it will occur between the request and response? The
XMLHttpRequest object has a property called as readyState whose value changes in the complete request-
response journey i.e when a request is prepared, sent, resolves, processed and when the response comes.
That’s why it is called os onreadystatechange.
The onreadystatechange stores a function (or the name of the function)to be called automatically each time
the readyState property changes. The readyState holds different values ranging from 0 to 4.
• request not initialized
• server connection established
• request received
• processing request
• request finished and response is ready
XMLHttpRequest also has a property named as status. The status has following values
• 200: “OK”
• 404: “Page not found"
The whole thing described above is implemented in coding as given below:
<p id=”dis”></p>

req.onreadystatechange = function(){

if(req.readyState == 4 && req.status == 200){

document.getElementById("dis").innerHTML = req.responseText; }

Advantages:

1. .Speed is enhanced as there is no need to reload the page again.


2. AJAX make asynchronous calls to a web server, this means client browsers avoid waiting for all the
data to arrive before starting of rendering.
3. Form validation can be done successfully through it.
4. Bandwidth utilization – It saves memory when the data is fetched from the same page. More
interactive.

Disadvantages:

1. Ajax is dependent on Javascript. If there is some Javascript problem with the browser or in the OS,
Ajax will not support.
2. Ajax can be problematic in Search engines as it uses Javascript for most of its parts.
3. Source code written in AJAX is easily human readable. There will be some security issues in Ajax.
4. Debugging is difficult.
5. Problem with browser back button when using AJAX enabled pages.

How to Create an PHP Ajax application: We will create a simple application that allows users to search for
popular PHP MVC frameworks. Our application will have a text box that users will type in the names of the
framework. We will then use mvc AJAX to search for a match then display the framework’s complete name
just below the search form.

The steps involved are as follows:

1. Creating the index page:


<html>

<head>

<title>PHP MVC Frameworks - Search Engine</title>

<script type="text/javascript" src="auto_complete.js"></script>


</head>

<body>

<h2>PHP MVC Frameworks - Search Engine</h2>

<p><b>Type the first letter of the PHP MVC Framework</b></p>

<form method="POST" action="index.php">

<p><input type="text" size="40" id="txtHint" onkeyup="showName(this.value)"></p>

</form>

<p>Matches: <span id="txtName"></span></p>


</body>
</html>
Here,

• “onkeyup=”showName(this.value)”” executes the JavaScript function showName everytime a key is


typed in the textbox. This feature is called auto complete

2. Creating the frameworks page:


<?php

$frameworks = array("CodeIgniter","Zend Framework","Cake PHP","Kohana") ;

$name = $_GET["name"];

if (strlen($name) > 0) {

$match = "";

for ($i = 0; $i < count($frameworks); $i++) {

if (strtolower($name) == strtolower(substr($frameworks[$i], 0, strlen($name)))) {

if ($match == "") {

$match = $frameworks[$i];

} else {
$match = $match . " , " . $frameworks[$i];

echo ($match == "") ? 'no match found' : $match;


?>

3. Creating the JS script


function showName(str){

if (str.length == 0){ //exit function if nothing has been typed in the


textbox

document.getElementById("txtName").innerHTML=""; //clear previous


results

return;

if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera,


Safari

xmlhttp=new XMLHttpRequest();

} else {// code for IE6, IE5

xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");

xmlhttp.onreadystatechange=function() {

if (xmlhttp.readyState == 4 && xmlhttp.status == 200){

document.getElementById("txtName").innerHTML=xmlhttp.responseText;

xmlhttp.open("GET","frameworks.php?name="+str,true);

xmlhttp.send();

}
HERE,

• “if (str.length == 0)” check the length of the string. If it is 0, then the rest of the script is not executed.
• “if (window.XMLHttpRequest)…” Internet Explorer versions 5 and 6 use ActiveXObject for AJAX
implementation. Other versions and browsers such as Chrome, FireFox use XMLHttpRequest. This
code will ensure that our application works in both IE 5 & 6 and other high versions of IE and
browsers.
• “xmlhttp.onreadystatechange=function…” checks if the AJAX interaction is complete and the status is
200 then updates the txtName span with the returned results.
4. Testing our PHP Ajax application
Assuming you have saved the file index.php In phututs/ajax, browse to the URL
http://localhost/phptuts/ajax/index.php

Working with XML Documents using PHP and JSP:

Working with XML Documents using PHP:

Read XML using PHP: The code that will read the employees XML document and display the results in a web
browser is Index.php

<?php

$xml = simplexml_load_file('employees.xml');

echo '<h2>Employees Listing</h2>';

$list = $xml->record;

for ($i = 0; $i < count($list); $i++) {

echo '<b>Man no:</b> ' . $list[$i]->attributes()->man_no . '<br>';

echo 'Name: ' . $list[$i]->name . '<br>';

echo 'Position: ' . $list[$i]->position . '<br><br>';

?>

Here,

• “$xml = simplexml_load_file(’employees.xml’);” uses the simplexml_load_file function to load the file


name employees.xml and assign the contents to the array variable $xml.
• “$list = $xml->record;” gets the contents of the record node.
• “for ($i = 0; $i < count(…)…” is the for loop that reads the numeric array and outputs the results
• “$list[$i]->attributes()->man_no;” reads the man_no attribute of the element
• “$list[$i]->name;” reads the value of the name child element
• “$list[$i]->position;” reads the value of the position child element

Create an XML using PHP:

The following code uses the PHP built in class DOMDocument to create an XML document.

<?php

$dom = new DOMDocument();


$dom->encoding = 'utf-8';

$dom->xmlVersion = '1.0';

$dom->formatOutput = true;

$xml_file_name = 'movies_list.xml';

$root = $dom->createElement('Movies');

$movie_node = $dom->createElement('movie');

$attr_movie_id = new DOMAttr('movie_id', '5467');

$movie_node->setAttributeNode($attr_movie_id);

$child_node_title = $dom->createElement('Title', 'The Campaign');

$movie_node->appendChild($child_node_title);

$child_node_year = $dom->createElement('Year', 2012);

$movie_node->appendChild($child_node_year);

$child_node_genre = $dom->createElement('Genre', 'The Campaign');

$movie_node->appendChild($child_node_genre);

$child_node_ratings = $dom->createElement('Ratings', 6.2);

$movie_node->appendChild($child_node_ratings);

$root->appendChild($movie_node);

$dom->appendChild($root);

$dom->save($xml_file_name);

echo "$xml_file_name has been successfully created";


?>
Here,

• “$dom = new DOMDocument();” creates an instance of DOMDocument class.


• “$dom->encoding = ‘utf-8’;” sets the document encoding to utf-8
• “$dom->xmlVersion = ‘1.0’;” specifies the version number 1.0
• “$dom->formatOutput = true;” ensures that the output is well formatted
• “$root = $dom->createElement(‘Movies’);” creates the root node named Movies
• “$attr_movie_id = new DOMAttr(‘movie_id’, ‘5467’);” defines the movie id attribute of Movies node
• “$child_node_element_name = $dom->createElement(‘ElementName’, ‘ElementValue’)” creates the
child node of Movies node. ElementName specifies the name of the element e.g. Title. ElementValue
sets the child node value e.g. The Campaign.
• “$root->appendChild($movie_node);” appends the movie_node elements to the root node Movies
• “$dom->appendChild($root);” appends the root node to the XML document.
• “$dom->save($xml_file_name);” saves the XML file in the root directory of the web server.
• “echo ‘<a href= “‘.$xml_file_name.'”>’ . $xml_file_name . ‘</a> has been successfully created’;” creates
the link to the XML file.

Working With XML Documents using JSP:

You can send the XML content using JSPs the same way you send HTML. The only difference is that you must
set the content type of your page to text/xml. To set the content type, use the <%@page%> tag, like this −
<%@ page contentType = "text/xml" %>
%> tag, like this −
<%@ page contentType = "text/xml" %>
<books>
<book>
<name>Padam History</name>
<author>ZARA</author>
<price>100</price>
</book>
</books>
Before you proceed with XML processing using JSP, you will need to copy the following two XML and XPath
related libraries into your <Tomcat Installation Directory>\lib −
• XercesImpl.jar − Download it from https://www.apache.org/dist/xerces/j/
• xalan.jar − Download it from https://xml.apache.org/xalan-j/index.html
<%@ taglib prefix = "c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix = "x" uri="http://java.sun.com/jsp/jstl/xml" %>

<html>
<head>
<title>JSTL x:parse Tags</title>
</head>

<body>
<h3>Books Info:</h3>
<c:import var = "bookInfo" url="http://localhost:8080/books.xml"/>

<x:parse xml = "${bookInfo}" var = "output"/>


<b>The title of the first book is</b>:
<x:out select = "$output/books/book[1]/name" />
<br>

<b>The price of the second book</b>:


<x:out select = "$output/books/book[2]/price" />
</body>
</html>

To Format XML with JSP it will be like-

• Consider the following XSLT stylesheet style.xsl −

<?xml version = "1.0"?>


<xsl:stylesheet xmlns:xsl = "http://www.w3.org/1999/XSL/Transform"
version = "1.0">

<xsl:output method = "html" indent = "yes"/>


<xsl:template match = "/">
<html>
<body>
<xsl:apply-templates/>
</body>
</html>
</xsl:template>

<xsl:template match = "books">


<table border = "1" width = "100%">
<xsl:for-each select = "book">
<tr>
<td>
<i><xsl:value-of select = "name"/></i>
</td>

<td>
<xsl:value-of select = "author"/>
</td>

<td>
<xsl:value-of select = "price"/>
</td>
</tr>
</xsl:for-each>
</table>

</xsl:template>
</xsl:stylesheet>

• Now consider the following JSP file:

<%@ taglib prefix = "c" uri = "http://java.sun.com/jsp/jstl/core" %>


<%@ taglib prefix = "x" uri = "http://java.sun.com/jsp/jstl/xml" %>

<html>
<head>
<title>JSTL x:transform Tags</title>
</head>

<body>
<h3>Books Info:</h3>
<c:set var = "xmltext">
<books>
<book>
<name>Padam History</name>
<author>ZARA</author>
<price>100</price>
</book>
<book>
<name>Great Mistry</name>
<author>NUHA</author>
<price>2000</price>
</book>
</books>
</c:set>
<c:import url = "http://localhost:8080/style.xsl" var = "xslt"/>
JSON:
JSON or JavaScript Object Notation is a lightweight text-based open standard designed for human-readable data
interchange. Conventions used by JSON are known to programmers, which include C, C++, Java, Python, Perl,
etc.
JSON stands for JavaScript Object Notation. The format was specified by Douglas Crockford. It was designed for
human-readable data interchange. It has been extended from the JavaScript scripting language. The filename
extension is .json. JSON Internet Media type is application/json.The Uniform Type Identifier is public.json.
JSON supports the following two data structures −
• Collection of name/value pairs − This Data Structure is supported by different programming
languages.
• Ordered list of values − It includes array, list, vector or sequence etc.

Uses of JSON

• It is used while writing JavaScript based applications that includes browser extensions and websites.
• JSON format is used for serializing and transmitting structured data over network connection.
• It is primarily used to transmit data between a server and web applications.
• Web services and APIs use JSON format to provide public data.
• It can be used with modern programming languages.

Characteristics of JSON

• JSON is easy to read and write.


• It is a lightweight text-based interchange format.
• JSON is language independent.

JSON format supports the following data types –


1. Number: double- precision floating-point format in JavaScript
2. String: double-quoted Unicode with backslash escaping
3. Boolean: true or false
4. Array: an ordered sequence of values
5. Value: it can be a string, a number, true or false, null etc
6. Object: an unordered collection of key:value pairs
7. Whitespace: can be used between any pair of tokens
8. null: empty

Number
1. It is a double precision floating-point format in JavaScript and it depends on implementation.
2. Octal and hexadecimal formats are not used.
3. No NaN or Infinity is used in Number.
The types of number and its description:
• Integer: Digits 1-9, 0 and positive or negative
• Fraction: Fractions like .3, .9
• Exponent: Exponent like e, e+, e-, E, E+, E-
Syntax: var json-object-name = { string : number_value, .......}

String

1. It is a sequence of zero or more double quoted Unicode characters with backslash escaping.
2. Character is a single character string i.e. a string with length 1.
Various special characters that you can use in strings of a JSON document –
• " - double quotation
• \ - backslash
• / - forward slash
• b - backspace
• f - form feed
• n - new line
• r-carriage return
• t - horizontal tab

• u - four hexadecimal digits


Syntan: var json-object-name = { string : "string value", .......}

Boolean : It includes true or false values.

Syntax : var json-object-name = { string : true/false, .......}

Array

1. It is an ordered collection of values.


2. These are enclosed in square brackets which means that array begins with .[. and ends with .]..
3. The values are separated by , (comma).
4. Array indexing can be started at 0 or 1.
5. Arrays should be used when the key names are sequential integers.
Syntax: [ value, .......]

Object

• It is an unordered set of name/value pairs.


• Objects are enclosed in curly braces that is, it starts with '{' and ends with '}'.
• Each name is followed by ':'(colon) and the key/value pairs are separated by , (comma).
• The keys must be strings and should be different from each other.
• Objects should be used when the key names are arbitrary strings.
Syntax : { string : value, .......}

Whitespace : It can be inserted between any pair of tokens. It can be added to make a code more readable.
Example shows declaration with and without whitespace −

Syntax : {string:" ",....}

null : It means empty type.

Syntax: null

JSON parsing and serialization using PHP, JSP and JavaScript:

Parsing, on the other hand, takes a stream of (structured) data and then does something based on the contents
of that stream, usually either creating an in-memory structure based on it, or executing a sequence of
operations based on it. Compiling source code is also a type of parsing (together with then serializing the result
of the parsing as machine code or assembly), as is linting or formatting code, doing static analysis of it, and

many other things you would do to it using tools.

Serialization is the process of converting a data structure into a format that it can be safely stored or
transmitted and the recreated from the stored or transmitted format. It's usually used to refer to applying this
process to complex data structures like trees, objects, or graphs, as they don't inherently lend themselves to
being transmitted as a simple string of binary data. Converting an in-memory object to JSON or XML is an
example of serialization.

Deserialization (the reverse process of serialization) is a particular type of parsing, it takes serialized data
and recreates the original data structure from it.

JSON with PHP: The JSON extension is bundled and compiled into PHP by default. PHP json_encode() function
is used for encoding JSON in PHP. This function returns the JSON representation of a value on success or
FALSE on failure.

Syntax : string json_encode ( $value [, $options = 0 ] )


Parameters
• value − The value being encoded. This function only works with UTF-8 encoded data.
• options − This optional value is a bitmask consisting of JSON_HEX_QUOT, JSON_HEX_TAG,
JSON_HEX_AMP, JSON_HEX_APOS, JSON_NUMERIC_CHECK, JSON_PRETTY_PRINT,
JSON_UNESCAPED_SLASHES, JSON_FORCE_OBJECT.
Example: The following example shows how to convert an array into JSON with PHP −
<?php
$arr = array('a' => 1, 'b' => 2, 'c' => 3, 'd' => 4, 'e' => 5);
echo json_encode($arr);
?>
While executing, this will produce the following result: {"a":1,"b":2,"c":3,"d":4,"e":5}

The following example shows how the PHP objects can be converted into JSON –
<?php
class Emp {
public $name = "";
public $hobbies = "";
public $birthdate = "";
}

$e = new Emp();
$e->name = "sachin";
$e->hobbies = "sports";
$e->birthdate = date('m/d/Y h:i:s a', "8/5/1974 12:20:03 p");
$e->birthdate = date('m/d/Y h:i:s a', strtotime("8/5/1974 12:20:03"));

echo json_encode($e);
?>
While executing, this will produce the following result −
{"name":"sachin","hobbies":"sports","birthdate":"08\/05\/1974 12:20:03 pm"}

Decoding JSON in PHP (json_decode)

PHP json_decode() function is used for decoding JSON in PHP. This function returns the value decoded from
json to appropriate PHP type.
Syntax: mixed json_decode ($json [,$assoc = false [, $depth = 512 [, $options = 0 ]]])
Paramaters
• json_string − It is an encoded string which must be UTF-8 encoded data.
• assoc − It is a boolean type parameter, when set to TRUE, returned objects will be converted into
associative arrays.
• depth − It is an integer type parameter which specifies recursion depth
• options − It is an integer type bitmask of JSON decode, JSON_BIGINT_AS_STRING is supported.
The following example shows how PHP can be used to decode JSON objects –

<?php
$json = '{"a":1,"b":2,"c":3,"d":4,"e":5}';
var_dump(json_decode($json));
var_dump(json_decode($json, true));
?>
While executing, it will produce the following result −
object(stdClass)#1 (5) {
["a"] => int(1)
["b"] => int(2)
["c"] => int(3)
["d"] => int(4)
["e"] => int(5)
}
array(5) {
["a"] => int(1)
["b"] => int(2)
["c"] => int(3)
["d"] => int(4)
["e"] => int(5)
}

JSON parsing and serialization with JavaScript:


JSON parsing is the process of converting a JSON object in text format to a JavaScript object that can be used
inside a program. In JavaScript, the standard way to do this is by using the method JSON.parse(), as
the JavaScript standard specifies.
Using JSON.parse()
Javascript programs can read JSON objects from a variety of sources, but the most common sources are
databases or REST APIs. A JSON object read from these sources enters a Javascript program in a “flat”
string format that contains the object’s key-value pairs.

JSON.parse() requires one parameter: the flat JSON string to be converted into a JSON
object. JSON.parse() takes the flat JSON string directly or as a Javascript variable. Passing variables is easier
and more readable than passing in a long flat JSON string.

JSON.parse('{"a", "b", "c", 1}');


let flatJSON2 = '{"a": "b", "c": 1, "d": {"e": 2}}';
JSON.parse(flatJSON2);

JSON.parse() takes an optional second parameter which is called a “reviver.” A reviver is a function that
converts the JSON data that JSON.parse() cannot process by itself. This reviver function example handles
undefined values:

let flatJSON3 = ‘{“a”: “b”, “c”: 1, “d”: {“e”: 2}}’;


let reviver = function(key, value) {
if(typeof value === 'undefined') { return null; }
;

let parsed = JSON.parse(flatJSON3, reviver);


Revivers convert empty values and complex objects into valid Javascript objects.
Handling JSON.parse() Special Cases with Revivers Error Handling:
Improperly-formatted data passed to JSON.parse() raises an error, stops processing, and returns no
processed data, even if the rest of the JSON is correct. If an error occurs, never assume
that JSON.parse() returns a specific value.
Depending on how you write your program, an error could stop the rest of your Javascript code from
executing. Wrap calls to JSON.parse() in a try catch statement so you can explicitly specify what happens if
parsing fails.
try {
JSON.parse(input);
} catch (e) {
return undefined; // Or whatever action you want here
}

Wrap JSON.parse() in a function to cover its limits, handing special cases appropriate to your needs.
Include a reviver function in a closure to handle common data conversion needs.
When you need more specialized data conversion than your default reviver function can handle, add a
second reviver function as a parameter to your safe parsing function. Call the second reviver function at the
end of the default reviver function.
Putting all of this together with previous code examples, here’s a simple safe JSON parsing function:
function safeJsonParse(json, reviver) {
function defaultReviver(key, value) {
if (value.match(/^[0-9]{4}-[0-9]{2}-[0-9]{2}$/)) {
return new Date(value);
}
if(typeof value === 'undefined') { return null; }
if(reviver !== undefined) { reviver(); }
}
try {
let json = JSON.parse(json, defaultReviver);
} catch(e) {
return null;
}
}

Here is the full example code for Parsing a message in JavaScript with JSON as follows:

<html>
<head>
<title>Parsing Message using JSON in JavaScript</title>
<script language="javascript" src="json2.js"></script>
<script language="javascript" >
var students = {
"Maths" : [
{ "Name" : "Amit", // First element
"Marks" : 67,
"age" : 23 },
{
"Name" : "Sandeep", // Second element
"Marks" : 65,
"age" : 21 }
]
}
// Printing Maths array values in the alert message
var i=0
var arrayObject = new Array();
for(i=0;i<students.Maths.length;i++)
{
arrayObject.push(students.Maths[i].Name);
arrayObject.push(students.Maths[i].Marks);
arrayObject.push(students.Maths[i].age);
}
alert("Parsing JSON Message Example ");
alert(arrayObject.toJSONString().parseJSON());
</script>
</head>
<body>
Parsing Message using JSON in JavaScript
</body>
</html>
The following example shows how to use JSON to store information related to books based on their topic and
edition.
{
"book": [

{
"id":"01",
"language": "Java",
"edition": "third",
"author": "Herbert Schildt"
},

{
"id":"07",
"language": "C++",
"edition": "second",
"author": "E.Balagurusamy"
}
]
}
Another example of JSON:
<html>
<head>
<title>JSON example</title>
<script language = "javascript" >
var object1 = { "language" : "Java", "author" : "herbert schildt" };
document.write("<h1>JSON with JavaScript example</h1>");
document.write("<br>");
document.write("<h3>Language = " + object1.language+"</h3>");
document.write("<h3>Author = " + object1.author+"</h3>");

var object2 = { "language" : "C++", "author" : "E-Balagurusamy" };


document.write("<br>");
document.write("<h3>Language = " + object2.language+"</h3>");
document.write("<h3>Author = " + object2.author+"</h3>");
document.write("<hr />");
document.write(object2.language + " programming language can be studied " + "from book written by " +
object2.author);
document.write("<hr />");
</script>
</head>

<body>
</body>
</html>
If you open the above code (json.htm) using IE or any other javascript enabled browser that produces the
following result :
JSON parsing and serialization with JSP:

Creating JSON data in JSP:

JSON has provided libraries to create/parse JSON data through Java code. These libraries can be used in any
Java/J2EE project including Servlet, Struts, JSF, JSP etc and JSON data can be created. A JSONObject is an
unordered collection of name/value pairs. Its external form is a string wrapped in curly braces with colons
between the names and values, and commas between the values and names. The internal form is an object
having get() and opt() methods for accessing the values by name, and put() methods for adding or replacing
values by name. The values can be any of these types: Boolean, JSONArray, JSONObject, Number, and String,
or the JSONObject.NULL object.

import org.json.JSONObject;

….

JSONObject json = new JSONObject();

json.put (“city”,”Mumbai”);

json.put(“country”,”India”);

String output = json.toString();


By using toString() method you can get the output in JSON format.

JSON Array in JSP:

A JSONArray is an ordered sequence of values. Its external text form is a string wrapped in square brackets
with commas separating the values. The internal form is an object having get and opt methods for accessing
the values by index, and put methods for adding or replacing values. The values can be any of these types:
Boolean, JSONArray, JSONObject, Number, String, or the JSONObject.NULL object. The constructor can convert
a JSON text into a Java object. The toString method converts to JSON text. JSONArray class can also be used to
convert a collection of Java beans into JSON data. Similar to JSONObject, JSONArray has a put() method that
can be used to put a collection into JSON object. Thus by using JSONArray you can handle any type of data and
convert corresponding JSON output.

Using json-lib library


JSON-lib is a java library for transforming beans, maps, collections, java arrays and XML to JSON and back
again to beans and DynaBeans. Json-lib comes in two flavors, depending on the jdk compatibility. json-lib-x.x-
jdk13 is compatible with JDK 1.3.1 and upwards. json-lib-x.x-jdk15 is compatible with JDK 1.5, includes
support for Enums in JSONArray and JSONObject. Download: json-lib.jar Json-lib requires (at least) the
following dependencies in your classpath:

1. jakarta commons-lang 2.5


2. jakarta commons-beanutils 1.8.0
3. jakarta commons-collections 3.2.1
4. jakarta commons-logging 1.1.1
5. ezmorph 1.0.6

An example is shown below:

package nwet.viralpatel.java;

import java.util.ArrayLiat;

import java.util.HashMap;

import java.util.List;

import java.util.Map;

import net.sf.json.JSONObject;

public class JsonMain{

public static void main(string[] args){


Map<String, Long> map = new HashMap<String, Long>();

map.put(“A”, 10L):

map.put(“B”, 20L):

map.put(“C”, 30L):

JSONObject json= new JSONObject();

json.accumulateAll(map);

System.out.println(json.toString());

List<String> list= new ArrayList<String>();

list.add(“Sunday”);

list.add(“Monday”);

list.add(“Tuesday”);

json.accumulate(“weekdays”, list);

System.out.printlin(json.toString());

Using Google Gson library

Gson is a Java library that can be used to convert Java Objects into their JSON representation. It can also be
used to convert a JSON string to an equivalent Java object. Gson can work with arbitrary Java objects including
pre-existing objects that you do not have source-code of. There are a few open-source projects that can
convert Java objects to JSON.
Gson Goals
▪ Provide simple toJson() and fromJson() methods to convert Java objects to JSON and vice-versa
▪ Allow pre-existing unmodifiable objects to be converted to and from JSON
▪ Extensive support of Java Generics
▪ Allow custom representations for objects
▪ Support arbitrarily complex objects (with deep inheritance hierarchies and extensive use of generic
types)

UNIT – 2

Current Trends in Web Technology Lectures

Architecture Paradigms:

Object-oriented architecture (OOA), component-based architecture (CBA), and service-based architecture


(SBA) represent three technical architecture paradigms in current software systems. Object, component, and
service are three key concepts in distributed software systems. From implementation point of view, a service
is implemented by one or more components, which in turn are often implemented in object-oriented
programming languages like C+ + and Java. Distributed component-based software systems can be structured
in any of the architecture paradigms, some have more advantages than others depending on business
requirements.

MVC:

The Model-View-Controller (MVC) is an architectural pattern that separates an application into three main
logical components: the model, the view, and the controller. Each of these components are built to handle
specific development aspects of an application. MVC is one of the most frequently used industry-standard
web development framework to create scalable and extensible projects.

Trygve Reenskaug invented MVC. The first reports on MVC were written when he was visiting a scientist at

Xerox Palo Alto Research Laboratory (PARC) in 1978/79. At first, MVC was called “Thing Model View Editor”

but rapidly changed it to “ Model View Controller”.

The goal of Tygrve was to solve the problem of users controlling a large and complex data set. The practice of

MVC has changed over the years. Since the MVC pattern was invented before web browsers, initially was used

as an architectural pattern for graphical user interfaces(GUI).

The components of MVC :


Model: The Model component corresponds to all the data-related logic that the user works with. This can
represent either the data that is being transferred between the View and Controller components or any other
business logic-related data. For example, a Customer object will retrieve the customer information from the
database, manipulate it and update it data back to the database or use it to render data.
View: The View component is used for all the UI logic of the application. For example, the Customer view will
include all the UI components such as text boxes, dropdowns, etc. that the final user interacts with.
Controller: Controllers act as an interface between Model and View components to process all the business
logic and incoming requests, manipulate data using the Model component and interact with the Views to
render the final output. For example, the Customer controller will handle all the interactions and inputs from
the Customer View and update the database using the Customer Model. The same controller will be used to
view the Customer data.

An example is given to show MVC Design Pattern.

class Student

private String rollNo;

private String name;

public String getRollNo()

return rollNo;

public void setRollNo(String rollNo)


{

this.rollNo = rollNo;

public String getName()

return name;

public void setName(String name)

this.name = name;

class StudentView

public void printStudentDetails(String studentName, String studentRollNo)

System.out.println("Student: ");

System.out.println("Name: " + studentName);

System.out.println("Roll No: " + studentRollNo);

class StudentController

private Student model;

private StudentView view;


public StudentController(Student model, StudentView view)

this.model = model;

this.view = view;

public void setStudentName(String name)

model.setName(name);

public String getStudentName()

return model.getName();

public void setStudentRollNo(String rollNo)

model.setRollNo(rollNo);

public String getStudentRollNo()

return model.getRollNo();

public void updateView()

view.printStudentDetails(model.getName(), model.getRollNo());

}
}

class MVCPattern

public static void main(String[] args)

Student model = retriveStudentFromDatabase();

StudentView view = new StudentView();

StudentController controller = new StudentController(model, view);

controller.updateView();

controller.setStudentName("Vikram Sharma");

controller.updateView();

private static Student retriveStudentFromDatabase()

Student student = new Student();

student.setName("Lokesh Sharma");

student.setRollNo("15UCS157");

return student;

Output:

Student:
Name: Lokesh Sharma
Roll No: 15UCS157
Student:
Name: Vikram Sharma
Roll No: 15UCS157
Advantages
• Multiple developers can work simultaneously on the model, controller and views.
• MVC enables logical grouping of related actions on a controller together. The views for a specific model
are also grouped together.
• Models can have multiple views.
Disadvantages
• The framework navigation can be complex because it introduces new layers of abstraction and requir es
users to adapt to the decomposition criteria of MVC.
• Knowledge on multiple technologies becomes the norm. Developers using MVC need to be skilled in
multiple technologies.

ASP.NET MVC

ASP.NET supports three major development models: Web Pages, Web Forms and MVC (Model View Controller).
ASP.NET MVC framework is a lightweight, highly testable presentation framework that is integrated with the
existing ASP.NET features, such as master pages, authentication, etc. Within .NET, this framework is defined in
the System.Web.Mvc assembly. The latest version of the MVC Framework is 5.0. We use Visual Studio to create
ASP.NET MVC applications which can be added as a template in Visual Studio.
ASP.NET MVC Features
ASP.NET MVC provides the following features −
• Ideal for developing complex but lightweight applications.
• Provides an extensible and pluggable framework, which can be easily replaced and customized. For
example, if you do not wish to use the in-built Razor or ASPX View Engine, then you can use any other
third-party view engines or even customize the existing ones.
• Utilizes the component-based design of the application by logically dividing it into Model, View, and
Controller components. This enables the developers to manage the complexity of large-scale projects
and work on individual components.
• MVC structure enhances the test-driven development and testability of the application, since all the
components can be designed interface-based and tested using mock objects. Hence, ASP.NET MVC
Framework is ideal for projects with large team of web developers.
• Supports all the existing vast ASP.NET functionalities, such as Authorization and Authentication,
Master Pages, Data Binding, User Controls, Memberships, ASP.NET Routing, etc.
• Does not use the concept of View State (which is present in ASP.NET). This helps in building
applications, which are lightweight and gives full control to the developers.
PHP based Content Management Systems:
Content management systems aka CMS have changed the definition of websites in last decade. These powerful
tool help anyone setup a fully customizable and highly scalable websites in matter of minutes. The real beauty
lies in plugins which essentially are core feature enhancements for these frameworks.
Top 12 PHP based content management systems (CMS) listed in order or popularity:
1. WordPress: WordPress is most popular free open source blogging tool as well as a content
management system based on PHP. It is one of the most user friendly CMS in the market and offers
simple flow to integrate themes,widgets and plugins.
2. Joomla: Joomla is an open source content management system to build powerful websites and on-
line template based applications. It also offers themes and other templates for user friendly actions.
3. Drupal: The open source content management system distributed under the General Public License. It
is use to build very flexible eCommerce websites and web based applications.
4. ModX: The CMS is a web application framework for publishing content on the world wide
web. MODx frontend and backed is very easy to set-up and use.
5. Concrete5: Concrete5 is the Next generation Content Management System available with wide range
of themes,plugins and add-ons. It is well designed to publish content on the internet and truly delivers
the best.
6. MotoCMS: The Next generation Content Management is one of the advanced Flash based CMS, allow to
create stunning Flash Websites without and programming skills and flash knowledge.
7. Contao: Conato is the free CMS is mostly used for medium to large websites and allow the pages to
generate under the guidelines W3C/WAI and as per XHTML, HTML5 and CSS standards.
8. Frog CMS: Frog CMS is the small and fast content management system software developed in PHP5
with MySQL database. It offers simple hierarchical structured page creation and navigation.
9. TextPattern: Textpattern CMS is very flexible, elegant and easy-to-use Content Management System
and allows easily create, edit and publish content over the world wide web.
10. ExpressionEngine: ExpressionEngine CMS is one of the incredible open-source PHP framework multi-
purpose content management system. It offers powerful list of features and best for e-commerce.
11. SilverStripe: SilverStripe is open source content management system (CMS) software for building,
editing and maintaining websites. Its design works on smartphones, tablets, and desktop computers
and offers extensible web application interface.
12. CMS Made Simple: CMS Made Simple is free open source platform for content management system
to provide developers, programmers and site owners a web-based development and administration
area.
MVC paradigm using PHP Framework:
What is PHP MVC framework?
PHP MVC is an application design pattern that separates the application data and business logic (model) from
the presentation (view). MVC stands for Model, View & Controller. The controller mediates between the
models and views. For example, think of the MVC design pattern as a car and the driver. The car has the
windscreens (view) which the driver (controller) uses to monitor traffic ahead then speed or brake (model)
depending on what he sees ahead.

Why use PHP MVC Framework?

PHP MVC Frameworks simplify working with complex technologies by;

• Hiding all the complex implementation details


• Providing standard methods that we can use to build our applications.
• Increased developer productivity, this is because the base implementation of activities such as
connecting to the database, sanitizing user input etc. are already partially implemented.
• Adherence to professional coding standards

PHP MVC Design Pattern:

We know that the components of the MVC design pattern are model, controller and views. Model is
concerned with the business logic and the application data. It can be used to perform data validations, process
data and store it. The data can come from; flat file, database, XML document and other valid data sources.
Controller is the part deals with the users’ requests for resources from the server. Views deals with
presenting the data to the user. This is usually in form of HTML pages.

Types of PHP MVC framework:

Selecting the best PHP framework is a challenge. You don’t have to write your own framework to benefit from
the advantages of MVC. You should only attempt to create your own MVC related application design for
understanding how MVC frameworks work. Once you are comfortable with the way MVC frameworks work,
you should move on to the mature and already tested frameworks. Some of the important PHP frameworks
are discussed above. Symfony and Laravel are also PHP frameworks, we will how they works.
Laravel:

Laravel is a PHP-based web framework that is largely based on the MVC architecture. Laravel was created
to make it easier for developers to get started on PHP projects. With Laravel, you think less about the
setup, architecture, and dependencies of a project and go straight into the meat of the project.

When you create a new Laravel project, (you can create one by running the command laravel new project-
name), a drop-down list is opened. There is a file in the routes/ directory called web.php. That file is where
you handle the requests when users visit your app. The file looks like this:

<?php

/*
|----------------------------------------- ---------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| [...]
|
*/

Route::get('/', function () {
return view('welcome');
});

To create a new Laravel project run the command in your terminal:

$ laravel new product-store


To see the starter app at work, update the APP_URL in your .env file to http://localhost:8000 then run the
following command in your terminal: $ php artisan serve
All artisan commands for a Laravel project have to be run inside the root of the Laravel project so you ha
ve to cd there first before running the command. This will run your app and you can visit it on 127.0.0.1:8
000/. You should see a welcome view in your browser. To stop the server press ctrl + c on your keyboard
for Windows, Mac, and Linux.

Models: creating our product model: In Laravel, the Model is usually a class with properties that match
the columns in the database.

In our database, a product will have the following properties:

• Name (name) – Name of product.


• Short Description (description) – Short description of a product.
• Count (count) – The number of products available.
• Unit Price (price) – How much a single product costs.

To create a model in Laravel, run the command in your terminal:

$ php artisan make:model Product

When you run this command, Laravel will create a Product.php file in the app directory. This will be a PHP
class with the name Product and it will be the model for our products table in the database.
In the Product model, add the $fillable property as shown below:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Product extends Model {

protected $fillable = [
'name',
'count',
'price',
'description',
];

}
The fillable property is used to represent mass assignable attributes for our model.

Migration lets developers make and undo changes to a project’s database. Migrations can be used to make
managing databases easy and predictable. To create a migration, run the following in your terminal:

$ php artisan make:migration create_products_table

When the command is executed, we should see a new *_create_products_table.php file in


the database/migrations directory and we can edit it to have our products table schema like this:

<?php

[...]

class CreateProductsTable extends Migration


{
public function up()
{
Schema::create('products', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->text('description');
$table->integer('count');
$table->integer('price');
$table->softDeletes();
$table->timestamps();
});
}

public function down()


{
Schema::dropIfExists('products');
}
}
Next copy the .env.example file in the root of your project to .env and then in the copied file, replace the
following lines:

DB_CONNECTION=mysql
DB_DATABASE=homestead
DB_USERNAME=username
DB_PASSWORD=password

with

DB_CONNECTION=sqlite
DB_DATABASE=/full/path/to/database.sqlite

That is all for our database setup. Now to run the migrations, run the command below in your terminal:

$ php artisan migrate

Before running the command, you need to have set up your database and set the connection details in
your .env file in the root of the project.

Controllers - creating our controller: For our make-believe project, we are going to use Resource
Controllers. Laravel resource routing assigns the typical “CRUD” routes to a controller with a single line
of code.

To create a resource controller in Laravel, run the following command:

$ php artisan make:controller ProductController -r

The -r flag makes it a resource controller and thus creates all the methods required for CRUD operation.
When the command is run, Laravel will create a new file in the app/Http/Controllers directory
called ProductController.php. Before we start adding logic to the controller, go to the routes/web.php file
and add the following route:

Route::resource('/products', 'ProductController');

You can see the list of routes by running the command php artisan route:list in your terminal.

1. The create method:

public function create()


{
return view('createproduct');
}

The controller loads a view (V in MVC) called create product and serves that as the response for anytime
someone visits the route /products/create with a GET HTTP method.

2. The store method:

public function store(Request $request) {


\App\Product::create([
'name' => $request->get('name'),
'description' => $request->get('description'),
'price' => $request->get('price'),
'count' => $request->get('count'),
]);

return redirect('/products');
}

The store method is called when a user sends a POST HTTP request to the /products endpoint. This logic
above gets the data from the request and stores it in the database using the Product model.

3. The index method:

public function index()


{
$products = \App\Product::all();

return view('viewproducts', ['allProducts' => $products]);


}

The index method is called when the /products route is loaded with a GET HTTP method. In this method,
we fetch all the products available in the products table using the Product model and pass it on to the
view as a variable. This means in the view, the $allProducts variable will be available.

Views: creating the projects views: In Laravel, all the views are stored in the resources/views directory.
Your views usually store the HTML of your page and are the presentation layer of the MVC architecture.

Update the welcome.blade.php file in the resources/views directory to include the following code inside
the body tag of the existing HTML:

[...]

<div class="flex-center position-ref full-height">


<div class="content">
<div class="title m-b-md">Product Store</div>
<div class="links">
<a href="{{ config('app.url')}}/products/create">Create Product</a>
<a href="{{ config('app.url')}}/products">View Products</a>
</div>
</div>
</div>

[...]

Laravel uses Blade as it’s templating engine. Blade is pretty much HTML but with some injectable PHP -
like syntax. If you go back to the routes/web.php you see it stated that the welcome view should be
rendered to the user when the / is visited. Next, let’s make the ‘Create Product’ view. Create
a createproduct.blade.php file in the resources/views directory of our project. In there add the following:

<!doctype html>
<html lang="{{ app()->getLocale() }}">
<head>
<title>Create Product | Product Store</title>
<!-- styling etc. -->
</head>
<body>
<div class="flex-center position-ref full-height">
<div class="content">
<form method="POST" action="{{ config('app.url')}}/products">
<h1> Enter Details to create a product</h1>
<div class="form-input">
<label>Name</label> <input type="text" name="name">
</div>

<div class="form-input">
<label>Description</label> <input type="text" name="description">
</div>

<div class="form-input">
<label>Count</label> <input type="number" name="count">
</div>

<div class="form-input">
<label>Price</label> <input type="number" name="price">
</div>

<button type="submit">Submit</button>
</form>
</div>
</div>
</body>
</html>

This view above is a simple form that collects and submits requests to create products. When the form is
submitted, a POST request is made to the /products route of the application which is handled by
the store method in our ProductController.

The next view we want to add is the viewproducts.blade.php view. Create that file in
the resources/views directory and add the following code to the file:

<!doctype html>
<html lang="{{ app()->getLocale() }}">
<head>
<title>View Products | Product Store</title>
<!-- Styles etc. -->
</head>
<body>
<div class="flex-center position-ref full-height">
<div class="content">
<h1>Here's a list of available products</h1>
<table>
<thead>
<td>Name</td>
<td>Description</td>
<td>Count</td>
<td>Price</td>
</thead>
<tbody>
@foreach ($allProducts as $product)
<tr>
<td>{{ $product->name }}</td>
<td class="inner-table">{{ $product->description }}</td>
<td class="inner-table">{{ $product->count }}</td>
<td class="inner-table">{{ $product->price }}</td>
</tr>
@endforeach
</tbody>
</table>
</div>
</div>
</body>
</html>

In the view above, the data that was sent from the controller, $allProducts, is iterated on and displayed to
the user.

MVP

An MVP is a basic, releasable, and working model of an application that supports minimal yet must-have
features. It helps enterprises gather information about customers without investing too much time and effort.
MVP is an alpha or beta launch of a product that helps in testing the product and checking the product-market
fit. It attracts early adopters, decreases time to market, and helps in understanding the requirements of
customers. It also helps enterprises boost their confidence and evaluate whether their product can survive in
the highly volatile market.

An MVP approach does not encourage fixing all the problems at once. The idea is to maximize learning and
minimize development costs. An MVP is not just an experiment. It allows enterprises to gather customer
feedback and suggestions. It can consider those suggestions and launch a better version of the application. An
MVP plays a significant role in the success of a business idea.

Three key parts in the MVP pattern design and they are:

Model: The Model here too is used to describe the business logic and it is characterized by a set of classes.
It works on to design business rules for data on how the data is changed or handled.

View: Again, like in the case of MVC, the View here represents the UI components like HTML, CSS, jQuery,
etc. The View displays the data which the controller sends back as a form of the result. The Model also can
be converted into the UI using View.

Presenter: To address all the UI events on behalf of the View, the Presenter takes complete responsibility.
The View provides the input from the user then the data is filtered with the help of Model and the result
gets conveyed to the View. The Presenter and View are completely different things, but they make use of an
interface to communicate with each other.

There are several advantages of MVP:

• MVP allows early market entry.


• MVP helps in testing business ideas on real customers.
• MVP also allows continuous improvement of the product with the help of customer feedback or
suggestions.

Purpose of an MVP

The purpose of MVP is to launch a new application with a minimal budget and reduce its time to market. MVP
is the version of an application with minimal yet must-have features that demonstrate the business idea of an
enterprise. Eric Ries defined MVP as the version of a new application or software that allows entrepreneurs
to gather information about the early adopters with minimal effort. It is a process of launching a new
application with primary features to test how the target audience can react. The actual full-fledged
application is built after gathering customer feedback.

MVP approach is all about striking the right balance between customers’ expectations and your offerings.
MVP helps entrepreneurs target a specific group of people (target users), implement the ideas based on
experience, and save time and effort.

Disadvantages of MVP:

• MVPs require a lot of upfront work in order to get reliable customer feedback. It might require
development efforts for various product releases, which demand revisions based on feedback
• he MVP approach takes more upfront work, but it greatly reduces potential risks down the road,
which can result in high costs and wasted efforts.

How to build an MVP:

1. Identify the business needs and conduct market research: It is the first step in creating a successful
MVP. Identify the business needs that the MVP approach should meet. Identify the factors that
address customer pain points and bring value to them. Products do not achieve success by accident.
They achieve success by solving real-world problems. Therefore, you must conduct thorough market
research to understand the customers pain points. Conduct surveys to gather as much information as
possible.
2. Your product must add value to the life of your customers: You must have a clear understanding of
the product that you are building. You must ask yourself some questions: Is your idea unique? What
does your product offer to the customer? Does your product address your customers’ pain points?
Why should customers invest in this product? While developing the MVP, you must pay attention to
these questions.
3. Map out the customer flow: Development is a crucial stage of building an MVP. Keep customers at the
center of the development process and look at the product from the customer's perspective. Map out
the customer flow focusing on the usability of your product. Mapping customer flow ensures that you
incorporate each key point while evaluating customer feedback.
4. Determine the essential features: The next step is to write all the features that can benefit your
customers. After listing all the features, you can divide them into different categories: essential, nice-
to-have, low-priority, etc. This division helps in identifying the bare essentials for your product. The
MVP must showcase what makes your product unique.
5. Launching the MVP: It is the last stage of building an MVP. After you have identified the essential
features and the customer requirements, you can finalize your MVP. An MVP is a releasable version
of your final product that fulfils customers’ needs and solves their problems. Therefore, the MVP
must be simple, engaging, and suitable for your customers.

A list of some businesses that started with a small idea but made it big in the market:

• Facebook: Facebook was initially launched to connect school and college students with their friends.
The objective was to offer them a social media platform where they could post pictures and send
messages to their friends. It became a huge hit and today, Facebook has over 1.3 billion active users.

• Amazon: Amazon entered the market as an online bookstore. People started buying books online at
reasonable rates. Later, when they started gaining more popularity, they established their presence
in the retail market. Today, Amazon is one of the most trusted e-commerce platforms, serving
millions of customers.

• Airbnb: Brian Chesky and Joe Gebbia, who could not pay for their apartment, came up with the idea
of renting a room in their apartment. They started by placing a mattress in their living room. Later,
they created a website and started looking for people who travelled with a minimum budget. Now,
Airbnb has more than 100 million users.

MVVM:

The well-ordered and perhaps the most reusable way to organize your code is to use the 'MVVM' pattern.
The Model, View, ViewModel (MVVM pattern) is all about guiding you in how to organize and structure
your code to write maintainable, testable and extensible applications.

In the case of the MVVM pattern, you will find two-way data binding taking place between View and View-
Model. Here inside the View-Model and to the View, it allows carrying out modifications automatically. In
order to make changes in the View-Model, the View-Model makes use of the observer pattern. The MVVM
pattern is mostly used by Silverlight, WPF, nRoute, Caliburn, etc.

There are three key parts in the MVVM pattern design and they are:

Model: As seen in the case of MVC and MVP, the Model here too is used to describe the business logic and a
set of classes characterizes it. It works on to design business rules for data on how the data is changed or
handled.

View: Again, like in the case of MVC and MVP, the View here represents the UI components like HTML, CSS,
jQuery, etc. The View displays the data which the controller sends back as a form of the result. The Model
also can be converted into the UI using View.

ViewModel: It is the responsibility of the View-Model to present methods and functions. It needs to
present commands to operate the model, uphold the state of the View and activate the events in the View.

Advantages of MVVM:

Maintainability

• A clean separation of different kinds of code should make it easier to go into one or several of those more
granular and focused parts and make changes without worrying.
• That means you can remain agile and keep moving out to new releases quickly.

Testability

• With MVVM each piece of code is more granular and if it is implemented right your external and internal
dependences are in separate pieces of code from the parts with the core logic that you would like to test.
• That makes it a lot easier to write unit tests against a core logic.
• Make sure it works right when written and keeps working even when things change in maintenance.

Extensibility
• It sometimes overlaps with maintainability, because of the clean separation boundaries and more
granular pieces of code.
• You have a better chance of making any of those parts more reusable.
• It has also the ability to replace or add new pieces of code that do similar things into the right places in
the architecture.
Disadvantages of MVVM:
• Some people think that for simple UIs, MVVM can be overkill.
• Similarly in bigger cases, it can be hard to design the ViewModel.
• Debugging would be bit difficult when we have complex data bindings.
Server Side JavaScript with NodeJS:

What is NodeJS or Node.js?

Node.js isn't a programming language, but a run time environment of a programming language. Node.js is a

server-side, packaged software that contains predefined processes to accomplish specific tasks.As a server-

side runtime, every Node.js process is executed on a server; essentially working on the backend aspect of an

application to manage data. For instance, if you wanted to store some data in a file or a database, you'd need

to employ the use of a server-side language or application. Node.js is labeled as a JavaScript run-time

environment because it uses JavaScript to conduct backend processes.

What Makes Node.js Special?

Node.js is so special because it gives developers the tools needed to connect to a file or database and store the

data that was initially submitted from that form.

How Does Node.js Work?

Node.js is built on the V8 JavaScript engine, which is used to compile and execute JavaScript source code. So

when you execute a JS script using Node.js, that code is initially passed to the V8 JavaScript engine. The V8

JavaScript engine then compiles the script and passes the result of the compilation back to Node.js where it

can be used in the application.

Why Use Node.js?

Node.js is a pretty popular backend technology used by big companies likes Netflix and Uber. There’s no

doubt that Node.js developers are in demand. Node.js employs a non-blocking I/O module, where I/O stands

for input and output. This critical feature is one of the reasons for the technology’s popularity. Node.js being
non-blocking means that while an I/O operation is being executed, access is still granted to other aspects of

the application currently carrying out this I/O operation.

Creating a Node.js Script

A fundamental feature of Node.js is its node module system. This is a collection of different Node.js

application programming interfaces that can be used to accomplish any task, from printing data to a console

to storing data in a file. One of the most popular Node.js modules is the file system module. It allows the

developer to create and communicate with files on any given machine.

Using the File System Module Example:


// import the file system module
const fs = require('fs');
//create a new text filed called task and store the sthing "buy groceries" to it
fs.writeFile('tasks.txt', 'buy groceries', (error) =>{
if (error) throw error;
console.log('The file has been saved.')
});

To use the file system module in your Node.js projects, you'll first need to import this module. In Node.js, the

file system module is represented by the acronym fs. So by simply passing fs to the required function. The file

system module is passed to the variable called fs, which could be whatever name you think is appropriate.

That name was chosen because it accurately represents what will be stored in the fs variable.

The file system module has an extensive list of functions; the one used in the code above is called writeFile.

The writeFile function takes three arguments: a filename, the data that is to be stored in the file, and a

callback function.

The callback function takes an error argument that's only available if a problem arises when trying to execute

the writeFile function.

Executing a Node.js Script:

To execute a Node.js script, all you need to know is the name of the file that this script is stored in. Node.js is

written in JavaScript; therefore, every Node.js code has to be stored in a JavaScript file to be executable. To

execute the file above you'll need to launch a terminal/console and cd into the direct folder that contains the
index.js file. After you have gained direct access to the index.js file, you simply type the following line of code

in your console.

node index.js

Firewall:

A firewall can be defined as a special type of network security device or a software program that monitors and
filters incoming and outgoing network traffic based on a defined set of security rules. It acts as a barrier
between internal private networks and external sources (such as the public Internet).

The primary purpose of a firewall is to allow non-threatening traffic and prevent malicious or unwanted data
traffic for protecting the computer from viruses and attacks. A firewall is a cybersecurity tool that filters
network traffic and helps users block malicious software from accessing the Internet in infected computers.

Gil Shwed from Check Point Technologies introduced the first stateful inspection firewall in 1993. It was named
as FireWall-1. Back in 2000, Netscreen came up with its purpose-built firewall 'Appliance'. It gained popularity
and fast adoption within enterprises because of increased internet speed, less latency, and high throughput at
a lower cost.

Why firewalls are used?

Firewalls are primarily used to prevent malware and network-based attacks. Additionally, they can help in
blocking application-layer attacks. These firewalls act as a gatekeeper or a barrier. They monitor every attempt
between our computer and another network. They do not allow data packets to be transferred through them
unless the data is coming or going from a user-specified trusted source.

Firewalls are designed in such a way that they can react quickly to detect and counter-attacks throughout the
network. They can work with rules configured to protect the network and perform quick assessments to find
any suspicious activity. In short, we can point to the firewall as a traffic controller.

How does a firewall work?

A firewall system analyzes network traffic based on pre-defined rules. It then filters the traffic and prevents
any such traffic coming from unreliable or suspicious sources. It only allows incoming traffic that is configured
to accept.

Typically, firewalls intercept network traffic at a computer's entry point, known as a port. Firewalls perform
this task by allowing or blocking specific data packets (units of communication transferred over a digital
network) based on pre-defined security rules. Incoming traffic is allowed only through trusted IP addresses, or
sources.

Limitations of Firewalls:

The importance of using firewalls as a security system is obvious; however, firewalls have some limitations:
1. Firewalls cannot stop users from accessing malicious websites, making it vulnerable to internal threats
or attacks.
2. Firewalls cannot protect against the transfer of virus-infected files or software.
3. Firewalls cannot prevent misuse of passwords.
4. Firewalls cannot protect if security rules are misconfigured.
5. Firewalls cannot protect against non-technical security risks, such as social engineering.
6. Firewalls cannot stop or prevent attackers with modems from dialing in to or out of the internal
network.
7. Firewalls cannot secure the system which is already infected.

Types of Firewall

Depending on their structure and functionality, there are different types of firewalls. The following is a list of
some common types of firewalls:

o Proxy Firewall: The proxy service firewall is a system that can help protect your network security by
filtering messages at the application layer. It essentially serves as a gateway or middle man between
your internal network and outside servers on the web. Also known as a gateway firewall, it is
more secure in its use of stateful and deep packet inspection technology to analyze incoming traffic.
o Packet-filtering firewalls: A packet-filtering firewall is a management program that can block network
traffic IP protocol, an IP address, and a port number. This type of firewall is the most basic form of
protection and is meant for smaller networks. While packet-filtering firewalls can be helpful, they
also have limitations.
o Stateful Multi-layer Inspection (SMLI) Firewall: The stateful multi-layer inspection firewall has
standard firewall capabilities and keeps track of established connections. It filters traffic based on
state, port, and protocol, along with administrator-defined rules and context. This involves using data
from prior connections and packets from the same connection.
o Unified threat management (UTM) firewall: A unified threat management firewall is a program that
combines the functions of the SMLI firewall with intrusion prevention and antivirus. Additional
services like cloud management may be included under the UTM umbrella of services.
o Next-generation firewall (NGFW): Next-generation firewalls are more sophisticated than packet-
filtering and stateful inspection firewalls. They have more levels of security, going beyond standard
packet-filtering to inspect a packet in its entirety. That means inspecting not just the packet header,
but also a packet’s contents and source. NGFW are able to block more sophisticated and evolving
security threats like advanced malware.
o Network address translation (NAT) firewalls: A NAT firewall is able to assess internet traffic and block
unsolicited communications. In other words, it only accepts inbound web traffic if a device on your
private network solicited it.

Difference between Firewall and Anti-virus:


Firewall Anti-virus
1. A firewall is defined as the system which analyzes 1. Anti-virus is defined as the special type of software
and filters incoming or outgoing data packets based that acts as a cyber-security mechanism. The
on pre-defined rules primary function of Anti-virus is to monitor, detect,
and remove any apprehensive or distrustful file or
software from the device.
2. Firewalls can be hardware and software both. The 2. Anti-virus can only be used as software. Anti-virus
router is an example of physical firewall. is a program that is installed on the device, just like
the other programs.
3. Because firewalls come in the form of hardware 3. Because Anti-virus comes in the form of software,
and software, a firewall can be implemented either therefore, Anti-virus can be implemented only at the
way. software level. There is no possibility of
implementing Anti-virus at the hardware level.
4. A firewall is usually defined as a network 4. Anti-viruses are primarily responsible for
controlling system i.e. they are primarily responsible detecting and removing viruses from computer
for monitoring and filtering network traffic. systems or other devices.
5. Because the firewall supports both types of 5. Anti-viruses are generally considered less-
implementations, hardware, and software, therefore, scalable than firewalls. This is because anti-virus can
it is more scalable than anti-virus. only be implemented at the software level. They
don't support hardware-level implementation.
6. A firewall is mainly used to prevent network 6. Anti-virus is mainly used to scan, find, and remove
related attacks. viruses, malware, and Trojans, which can harm
system files and software and share personal
information with hackers.

You might also like