Vous êtes sur la page 1sur 90

Gayatri Vidya Parishad College of Engineering (Autonomous)

Web Programming

DEPARTMENT
OF
COMPUTER SCIENCE AND ENGINEERING

WEB PROGRAMMING
(13CT1116)

Lecture Notes

N. Durga Prasad
Asst. Professor
CSE Department

Web Programming
Gayatri Vidya Parishad College of Engineering (Autonomous)
Computer Science And Engineering
1
Gayatri Vidya Parishad College of Engineering (Autonomous)
Web Programming

UNIT-1

INTRODUCTION
TO
HTML

Web Programming
Gayatri Vidya Parishad College of Engineering (Autonomous)
Computer Science And Engineering
2
Gayatri Vidya Parishad College of Engineering (Autonomous)
Web Programming

HTML

Introduction to HTML

HTML (Hypertext Markup Language) is used to create document on


the World Wide Web. It is simply a collection of certain key words called
Tags that are helpful in writing the document to be displayed using a
browser on Internet.

It is a platform independent language that can be used on any platform


such as Windows, Linux, Macintosh, and so on. To display a document in
web it is essential to mark-up the different elements (headings, paragraphs,
tables, and so on) of the document with the HTML tags. To view a mark-up
document,
user has to open the document in a browser. A browser understands and
interpret the HTML tags, identifies the structure of the document (which part
are which) and makes decision about presentation (how the parts look) of the
document.

HTML also provides tags to make the document look attractive using
graphics, font size and colors. User can make a link to the other document or
the different section of the same document by creating Hypertext Links also
known as Hyperlinks.

Creating a HTML document

The essential tags that are required to create a HTML document are:

<HTML>.............</HTML>
<HEAD>.............</HEAD>
<BODY>.............</BODY>

Web Programming
Gayatri Vidya Parishad College of Engineering (Autonomous)
Computer Science And Engineering
3
Gayatri Vidya Parishad College of Engineering (Autonomous)
Web Programming

HTML Tag <HTML>

The <HTML> tag encloses all other HTML tags and associated text
within your document. It is an optional tag. You can create an HTML
document that omits these tags, and your browser can still read it and display
it. But it is always a good form to include the start and stop tags.

The format is:

<HTML>

Your Title and Document (contains text with HTML tags) goes here

</HTML>

Most HTML tags have two parts, an opening tag and closing tag.
The closing tag is the same as the opening tag, except for the slash mark e.g
</HTML>. The slash mark is always used in closing tags.

An HTML document has two distinct parts HEAD and BODY.

The Format is:

<HTML>

<HEAD>
.............
.............
.............

</HEAD>

<BODY>
.............
.............
.............
Web Programming
Gayatri Vidya Parishad College of Engineering (Autonomous)
Computer Science And Engineering
4
Gayatri Vidya Parishad College of Engineering (Autonomous)
Web Programming

</BODY>

</HTML>

HEAD Tag <HEAD>

HEAD tag comes after the HTML start tag. It contains TITLE tag to give the
document a title that displays on the browsers title bar at the top.

The Format is:

<HEAD>

<TITLE>

Your title goes here

</TITLE>

</HEAD>

BODY Tag <BODY>

The BODY tag contains all the text and graphics of the document with
all the HTML tags that are used for control and formatting of the page.

The Format is:

<BODY>

Your Document goes here

</BODY>

Web Programming
Gayatri Vidya Parishad College of Engineering (Autonomous)
Computer Science And Engineering
5
Gayatri Vidya Parishad College of Engineering (Autonomous)
Web Programming

An HTML document, web page can be created using a text editor,


Notepad or WordPad. All the HTML documents should have the extension
.htm or .html. It require a web browser like Internet Explorer or Netscape
Navigator/Communicator to view the document.

Example:

<HTML>

<HEAD>

<TITLE>

My first Page

</TITLE>

</HEAD>

<BODY>

WELCOME TO MY FIRST WEB PAGE

</BODY>

</HTML>

Web Programming
Gayatri Vidya Parishad College of Engineering (Autonomous)
Computer Science And Engineering
6
Gayatri Vidya Parishad College of Engineering (Autonomous)
Web Programming

INTRODUCTION TO JAVASCRIPT

Web Programming
Gayatri Vidya Parishad College of Engineering (Autonomous)
Computer Science And Engineering
7
Gayatri Vidya Parishad College of Engineering (Autonomous)
Web Programming

Introduction to JAVA SCRIPT

JavaScript is most commonly used as a client side scripting language.


This means that JavaScript code is written into an HTML page. When a user
requests an HTML page with JavaScript in it, the script is sent to the
browser and it's up to the browser to do something with it.

JavaScript is a programming language that can be included on web


pages to make them more interactive. You can use it to check or modify the
contents of forms, change images, open new windows and write dynamic
page content. You can even use it with CSS to make DHTML (Dynamic
Hypertext Markup Language). This allows you to make parts of your web
pages appear or disappear or move around on the page. JavaScripts only
execute on the page(s) that are on your browser window at any set time.
When the user stops viewing that page, any scripts that were running on it
are immediately stopped. The only exception is a cookie, which can be used
by many pages to pass information between them, even after the pages have
been closed.
JavaScript has nothing to do with Java. JavaScript is a client side,
interpreted, object oriented, high level scripting language, while Java is a
client side, compiled, object oriented high level language.
Scripting languages are often used for performing repetitive tasks.
Although they may be complete programming languages, they do not
usually go into the depths of complex programs, such as thread and memory
management. They may use another program to do the work and simply tell
it what to do. They often do not create their own user interfaces, and instead
will rely on the other programs to create an interface for them. This is quite
accurate for JavaScript. We do not have to tell the browser exactly what to
put on the screen for every pixel, we just tell it that we want it to change the
document, and it does it. The browser will also take care of the memory
management and thread management, leaving JavaScript free to get on with
the things it wants to do.

Web Programming
Gayatri Vidya Parishad College of Engineering (Autonomous)
Computer Science And Engineering
8
Gayatri Vidya Parishad College of Engineering (Autonomous)
Web Programming

The basic part of a script is a variable, literal or object. A variable is a


word that represents a piece of text, a number, a Boolean true or false value
or an object. A literal is the actual number or piece of text or Boolean value
that the variable represents. An object is a collection of variables held
together by a parent variable, or a document component.
The next most important part of a script is an operator. Operators
assign literal values to variables or say what type of tests to perform.
The next most important part of a script is a control structure. Control
structures say what scripts should be run if a test is satisfied.
Functions collect control structures, actions and assignments together
and can be told to run those pieces of script as and when necessary.
The most obvious parts of a script are the actions it performs. Some of
these are done with operators but most are done using methods. Methods are
a special kind of function and may do things like submitting forms, writing
pages or displaying messages.
Events can be used to detect actions, usually created by the user, such
as moving or clicking the mouse, pressing a key or resetting a form. When
triggered, events can be used to run functions.

Web Programming
Gayatri Vidya Parishad College of Engineering (Autonomous)
Computer Science And Engineering
9
Gayatri Vidya Parishad College of Engineering (Autonomous)
Web Programming

INTRODUCTION TO CASCADING STYLE SHEETS


(CSS)

Web Programming
Gayatri Vidya Parishad College of Engineering (Autonomous)
Computer Science And Engineering
10
Gayatri Vidya Parishad College of Engineering (Autonomous)
Web Programming

INTRODUCTION TO CSS

Introduction:
CSS is a formatting language, used to provide more customised web
pages and make it easier to make multiple pages use the same style. The
acronym stands for Cascading Style Sheets. All current browsers can handle
CSS, and it is the best Web page formatting language produced to date.
Some very popular browsers do not handle it as well as they should (see the
section on browser problems) but largely support is good and developers are
tending to use it much more often.
Using CSS, you can define colours, backgrounds, borders, margins,
alignment, fonts, sizes and loads of other things for almost any part of your
web pages.
The word cascading describes many of the features of CSS. Firstly, it
means that many stylesheets can be used and will be merged by the browser
to provide a computed style for each element. If styles defined for one
element oppose each other, the later one will be used, unless another one
more specifically refers to the element (for example, if all paragraphs are
made red, but a paragraph that is in a <div> is made blue, the blue will
override the red for paragraphs in a div, as it more specifically refers to the
desired element). Cascading also means that each object inherits some styles
from its parent object or parent class. The parents are not the same as the
parent objects in JavaScript but use a similar idea. The objects are refered to
by their element tag. The highest object in the structure is the html element.
If any elements do not have their own CSS defined but the html element
does, then the cascading behaviour means they will inherit from
the html element. So, if in the htmlelement we define the text colour to be
white, then any tables will also have white writing in them.
Each element can be in a class. For example, if we define the 'p' tag to
have a text colour red then every paragraph will be red. But if we then define
a class of paragraph called mybold where the text is bold and we create a
paragraph of class mybold, it will have bold text. But remember that style
Web Programming
Gayatri Vidya Parishad College of Engineering (Autonomous)
Computer Science And Engineering
11
Gayatri Vidya Parishad College of Engineering (Autonomous)
Web Programming

sheets cascade and elements inherit from their parent class, so the text in the
paragraph of class mybold will also be red. If we define the class mybold to
have blue text then the blue will override the red and the text in the
paragraph of class mybold will be blue.
One of the features of CSS is that if the browser does not understand
something, it will ignore it and move on to the next attribute. It will not
display warnings. This can make things easier in some circumstances, since
you can apply styles without having to worry that a browser might ignore
the entire stylesheet, because it should only ignore the parts it does not
understand (although there are a few exceptions). However, it also means
that it can be difficult to work out if a browser will correctly apply a rule or
not. For example, you may want to apply display:table-
cell;width:25% to an element if it understands it, and width:100% if
not. Unfortunately, CSS does not provide any way to test for support of a
property.

Adding CSS to a page:

When using CSS, it is important to make sure that browsers use their
most standards compliant response. You will need to ensure that your
DOCTYPE triggers standards mode rendering for these browsers, or they
will assume your code is relying on some mistakes of older browsers, and
will try to replicate some them to various degrees, which can produce
unpredictable results.
There are two ways to include CSS on a page. One is by loading it
from an external file, and one is by embedding it directly in the source code
of the page. One of the most useful features of CSS is the ability to share the
same styles across many pages, so that all pages can be changed by
modifying a single file. To do that, you will need to keep the CSS in a
separate file. This also allows you to keep the clutter out of your document,
and helps avoid several other problems, so even if you only intend to use the
CSS on one page, you may want to include it in an external file anyway.

Web Programming
Gayatri Vidya Parishad College of Engineering (Autonomous)
Computer Science And Engineering
12
Gayatri Vidya Parishad College of Engineering (Autonomous)
Web Programming

To use an external file, you would usually name the


file something.css(choose an appropriate name), and then use the LINK tag
to tell the page to use it. Inside the head of a document put this:

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

To embed CSS directly into a web page, use the STYLE tag, and set the type
to'text/css':

<style type="text/css">

/* CSS goes here */

</style>

Note that CSS should only ever be included in the head of your document,
unless you use inline style attributes on individual elements.

General Syntax:

Firstly define the element the CSS is written for. Then use { and after putting
in the styles, close it with }
This might look like this:

body { styles go in here }

In this case, the 'body' is known as the selector. This can get more
complicated, and can include many different selectors.
For several elements to use the same style, you can separate them with
commas:

Web Programming
Gayatri Vidya Parishad College of Engineering (Autonomous)
Computer Science And Engineering
13
Gayatri Vidya Parishad College of Engineering (Autonomous)
Web Programming

p, div, span { styles go in here }

The syntax for the styles follows this pattern:

name_of_style_attribute: value;

You can include as many styles as you want inside the { and } curly braces.
Occasionally, there may be more than one value for a single style, for
example with the border attribute:

border: 3px double red;

To define styles that should only target elements with a certain class, put a
fullstop then the name of the class, after the element. This might look like:

p.nameofclass { styles go in here }

This would also need the class to be written inside the HTML 'p' element
tags to which it refers:

<p class="nameofclass">

If we use the syntax without specifying an element name, then every


element of class 'nameofclass', not just p tags, will use this style:

.nameofclass { styles go in here }

There are also some pseudo-classes such as :hover. This particular one
will only work in some browsers (most notably, Internet Explorer 6-)
with 'a'elements. It will be applied when the mouse hovers over the element.

Web Programming
Gayatri Vidya Parishad College of Engineering (Autonomous)
Computer Science And Engineering
14
Gayatri Vidya Parishad College of Engineering (Autonomous)
Web Programming

a:hover { color: red; }

The pseudo-classes can be used along with classes, like this:

a.nameofclass:hover { color: red; }

One of the most powerful uses of this pseudo class is to produce menus
written only using pure CSS.
If an element has been defined with an ID then it can be given its own style
by using the ID selector. Try to restrict this to cases where it is actually
needed:

#id { color: red; font-weight: bold; }

You can also target the specific element type, combined with the ID selector:

element_type#id { color: red; font-weight: bold; }

Now for some clever stuff. It is possible to target an element based on


what its parent elements are, by writing the name of the parent, followed by
a space, followed by the name of the element you want to target. Note that
the parent does not have to be a direct parent. It could be anywhere in the
chain of ancestors. For example, if you want to assign a style to li elements
where one of their parents is a ul whose parents include a td whose parents
include a trwhose parents include a table whose parents include the body,
you can write this:

body table tr td ul li { styles go in here }

If you also want to assign that style to p elements, you can combine this with
the comma, as shown earlier:
Web Programming
Gayatri Vidya Parishad College of Engineering (Autonomous)
Computer Science And Engineering
15
Gayatri Vidya Parishad College of Engineering (Autonomous)
Web Programming

body table tr td ul li, p { styles go in here }

Or mix that up however you like. You can also combine it with class
selectors. For example, this will match all li elements whose parents include
a td of classfish:

td.fish li { styles go in here }

If at any time you define two or more conflicting styles, the more
specific one should be used by the browser. If you use an inline style, that
should override other styles. There are exceptions to these rules, but I will
not go into those here.
All styles will have a default value, and that may be different for
different elements (for example, the border style has a default value
of 'none', but most browsers use something like '2px groove black' as the
default border for a fieldset). If you have styled an element with a generic
style, and you want to reset it to its default style for that specific element,
you will need to manually set it back to its default value. For example, you
could set all paragraphs to have a 1 pixel border, then set paragraphs not to
have a border if they are inside a div:

p { border: 1px solid black; }

div p { border: none; }

Some styles can be represented in a number of different ways. For


example, theborder style can be used to apply a border to all sides of an
element:

p { border: 1px solid black; }

It is also possible to specify one border at a time:


Web Programming
Gayatri Vidya Parishad College of Engineering (Autonomous)
Computer Science And Engineering
16
Gayatri Vidya Parishad College of Engineering (Autonomous)
Web Programming

p{

border-top: 1px solid black;

border-right: 1px solid green;

border-bottom: 1px solid black;

border-left: 3em solid black;

It is also possible to specify the thickness, colour, and style separately.


Each one can accept 1, 2, 3 or 4 values. If one value is specified, all sides
will use it. If you specify two, the first will be used by top and bottom, and
the second will be used by right and left. If you specify three, the first will
be used by top, the second will be used by right and left, and the third will
be used by bottom. If you specify four, they will be used by top, right,
bottom and left respectively:

p{

border-width: 1px 2px 3px;

border-style: solid solid solid double;

border-color: black green;

And this can be done for one side at a time as well. This is generally most
useful to specify a normal style, then override it for just one side:

p{

Web Programming
Gayatri Vidya Parishad College of Engineering (Autonomous)
Computer Science And Engineering
17
Gayatri Vidya Parishad College of Engineering (Autonomous)
Web Programming

border: 1px solid black;

border-right-color: green;

These styles are all considered to be as specific as each other, so if you


specify the border-right style and then the border style, the right border will
be styled according to what you define in the border style.

Web Programming
Gayatri Vidya Parishad College of Engineering (Autonomous)
Computer Science And Engineering
18
Gayatri Vidya Parishad College of Engineering (Autonomous)
Web Programming

UNIT-2
INTRODUCTION TO XML

Web Programming
Gayatri Vidya Parishad College of Engineering (Autonomous)
Computer Science And Engineering
19
Gayatri Vidya Parishad College of Engineering (Autonomous)
Web Programming

XML
A number of companies (in 2000) expect that it will be used more
extensively on the web in the future. XML looks something like HTML, in
that it uses tags that surround data. XML tags are intended to contain
information about the data they surround, whereas HTML tags mainly
indicate how to format the data so humans can read it.

Lots of companies have data they would like other people to use,
however often it is hard to exchange data between different applications.
XML tags should let diffrent computer systems read data and allow
programs to act on that data. You might think of it as the start of a universal
database. This should assist in searching for data, especially on the web, as it
should be easier to exclude irrelevant data that happens to include the terms
for which you are searching. It should make it easier to do "intelligent"
searches.

XML is an open standard, so there is no need to use proprietary


software to view it. Some XML readers will certainly be free, and we can
also expect they will eventually exist for most computer systems.

XML files can be expected to be somewhat larger than proprietary


database formats, however this is not a major problem. Disk drive capacity
has been increasing 60% a year for the past few decades, while prices
continue to drop, so raw storage costs are now under a half cent a megabyte.
Automatic compression is available in recent web protocols, so there is no
great need for compression of the source material before it is sent through a
communication link. XML is in ASCII text, so it can be read by humans if
they need to make corrections or locate problems.

XML is for structuring data

Structured data includes things like spreadsheets, address books,


configuration parameters, financial transactions, and technical drawings.
XML is a set of rules (you may also think of them as guidelines or
conventions) for designing text formats that let you structure your data.
XML is not a programming language, and you don't have to be a
Web Programming
Gayatri Vidya Parishad College of Engineering (Autonomous)
Computer Science And Engineering
20
Gayatri Vidya Parishad College of Engineering (Autonomous)
Web Programming

programmer to use it or learn it. XML makes it easy for a computer to


generate data, read data, and ensure that the data structure is unambiguous.
XML avoids common pitfalls in language design: it is extensible, platform-
independent, and it supports internationalization and localization. XML is
fully Unicode-compliant.

2. XML looks a bit like HTML

Like HTML, XML makes use of tags (words bracketed by '<' and '>')
and attributes (of the form name="value"). While HTML specifies what
each tag and attribute means, and often how the text between them will look
in a browser, XML uses the tags only to delimit pieces of data, and leaves
the interpretation of the data completely to the application that reads it. In
other words, if you see "<p>" in an XML file, do not assume it is a
paragraph. Depending on the context, it may be a price, a parameter, a
person, a p... (and who says it has to be a word with a "p"?).

3. XML is text, but isn't meant to be read

Programs that produce spreadsheets, address books, and other


structured data often store that data on disk, using either a binary or text
format. One advantage of a text format is that it allows people, if necessary,
to look at the data without the program that produced it; in a pinch, you can
read a text format with your favorite text editor. Text formats also allow
developers to more easily debug applications. Like HTML, XML files are
text files that people shouldn't have to read, but may when the need arises.
Compared to HTML, the rules for XML files allow fewer variations. A
forgotten tag, or an attribute without quotes makes an XML file unusable,
while in HTML such practice is often explicitly allowed. The official XML
specification forbids applications from trying to second-guess the creator of
a broken XML file; if the file is broken, an application has to stop right there
and report an error.

4. XML is verbose by design

Since XML is a text format and it uses tags to delimit the data, XML
files are nearly always larger than comparable binary formats. That was a
conscious decision by the designers of XML. The advantages of a text
format are evident (see point 3), and the disadvantages can usually be
Web Programming
Gayatri Vidya Parishad College of Engineering (Autonomous)
Computer Science And Engineering
21
Gayatri Vidya Parishad College of Engineering (Autonomous)
Web Programming

compensated at a different level. Disk space is less expensive than it used to


be, and compression programs like zip and gzip can compress files very well
and very fast. In addition, communication protocols such as modem
protocols and HTTP/1.1, the core protocol of the Web, can compress data on
the fly, saving bandwidth as effectively as a binary format.

5. XML is a family of technologies

XML 1.0 is the specification that defines what "tags" and "attributes"
are. Beyond XML 1.0, "the XML family" is a growing set of modules that
offer useful services to accomplish important and frequently demanded
tasks. XLink describes a standard way to add hyperlinks to an XML file.
XPointer is a syntax in development for pointing to parts of an XML
document. An XPointer is a bit like a URL, but instead of pointing to
documents on the Web, it points to pieces of data inside an XML file. CSS,
the style sheet language, is applicable to XML as it is to HTML. XSL is the
advanced language for expressing style sheets. It is based on XSLT a
transformation language used for rearranging, adding and deleting tags and
attributes. The DOM is a standard set of function calls for manipulating
XML (and HTML) files from a programming language. XML Schemas 1 and
2 help developers to precisely define the structures of their own XML-based
formats. There are several more modules and tools available or under
development. Keep an eye on W3C's technical reports page.

6. XML is new, but not that new

Development of XML started in 1996 and it has been a W3C


Recommendation since February 1998, which may make you suspect that
this is rather immature technology. In fact, the technology isn't very new.
Before XML there was SGML, developed in the early '80s, an ISO standard
since 1986, and widely used for large documentation projects. The
development of HTML started in 1990. The designers of XML simply took
the best parts of SGML, guided by the experience with HTML, and
produced something that is no less powerful than SGML, and vastly more
regular and simple to use. Some evolutions, however, are hard to distinguish
from revolutions... And it must be said that while SGML is mostly used for
technical documentation and much less for other kinds of data, with XML it
is exactly the opposite.

Web Programming
Gayatri Vidya Parishad College of Engineering (Autonomous)
Computer Science And Engineering
22
Gayatri Vidya Parishad College of Engineering (Autonomous)
Web Programming

7. XML leads HTML to XHTML

There is an important XML application that is a document format:


W3C's XHTML, the successor to HTML. XHTML has many of the same
elements as HTML. The syntax has been changed slightly to conform to the
rules of XML. A format that is "XML-based" inherits the syntax from XML
and restricts it in certain ways (e.g, XHTML allows "<p>", but not "<r>"); it
also adds meaning to that syntax (XHTML says that "<p>" stands for
"paragraph", and not for "price", "person", or anything else).

8. XML is modular

XML allows you to define a new document format by combining and


reusing other formats. Since two formats developed independently may have
elements or attributes with the same name, care must be taken when
combining those formats (does "<p>" mean "paragraph" from this format or
"person" from that one?). To eliminate name confusion when combining
formats, XML provides a namespace mechanism. XSL and RDF are good
examples of XML-based formats that use namespaces. XML Schema is
designed to mirror this support for modularity at the level of defining XML
document structures, by making it easy to combine two schemas to produce
a third which covers a merged document structure.

9. XML is the basis for RDF and the Semantic Web

W3C's Resource Description Framework (RDF) is an XML text


format that supports resource description and metadata applications, such as
music playlists, photo collections, and bibliographies. For example, RDF
might let you identify people in a Web photo album using information from
a personal contact list; then your mail client could automatically start a
message to those people stating that their photos are on the Web. Just as
HTML integrated documents, images, menu systems, and forms applications
to launch the original Web, RDF provides tools to integrate even more, to
make the Web a little bit more into a Semantic Web. Just like people need to
have agreement on the meanings of the words they employ in their
communication, computers need mechanisms for agreeing on the meanings
of terms in order to communicate effectively. Formal descriptions of terms
Web Programming
Gayatri Vidya Parishad College of Engineering (Autonomous)
Computer Science And Engineering
23
Gayatri Vidya Parishad College of Engineering (Autonomous)
Web Programming

in a certain area (shopping or manufacturing, for example) are called


ontologies and are a necessary part of the Semantic Web. RDF, ontologies,
and the representation of meaning so that computers can help people do
work are all topics of the Semantic Web Activity.

10. XML is license-free, platform-independent and well-supported

By choosing XML as the basis for a project, you gain access to a large
and growing community of tools (one of which may already do what you
need!) and engineers experienced in the technology. Opting for XML is a bit
like choosing SQL for databases: you still have to build your own database
and your own programs and procedures that manipulate it, but there are
many tools available and many people who can help you. And since XML is
license-free, you can build your own software around it without paying
anybody anything. The large and growing support means that you are also
not tied to a single vendor. XML isn't always the best solution, but it is
always worth considering.

Web Programming
Gayatri Vidya Parishad College of Engineering (Autonomous)
Computer Science And Engineering
24
Gayatri Vidya Parishad College of Engineering (Autonomous)
Web Programming

UNIT-3
JDBC(JAVA Database Connectivity)

Web Programming
Gayatri Vidya Parishad College of Engineering (Autonomous)
Computer Science And Engineering
25
Gayatri Vidya Parishad College of Engineering (Autonomous)
Web Programming

What is JDBC?

JDBC is Java application programming interface that allows the Java


programmers to access database management system from Java code. It was
developed by JavaSoft, a subsidiary of Sun Microsystems.

Definition
Java Database Connectivity in short called as JDBC. It is a java API which
enables the java programs to execute SQL statements. It is an application
programming interface that defines how a java programmer can access the
database in tabular format from Java code using a set of standard interfaces
and classes written in the Java programming language.

JDBC has been developed under the Java Community Process that allows
multiple implementations to exist and be used by the same application.
JDBC provides methods for querying and updating the data in Relational
Database Management system such as SQL, Oracle etc.

The Java application programming interface provides a mechanism for


dynamically loading the correct Java packages and drivers and registering
them with the JDBC Driver Manager that is used as a connection factory for
creating JDBC connections which supports creating and executing
statements such as SQL INSERT, UPDATE and DELETE. Driver Manager
is the backbone of the jdbc architecture.

Generally all Relational Database Management System supports SQL and


we all know that Java is platform independent, so JDBC makes it possible
to write a single database application that can run on different platforms and
interact with different Database Management Systems.

Java Database Connectivity is similar to Open Database Connectivity


(ODBC) which is used for accessing and managing database, but the
difference is that JDBC is designed specifically for Java programs, whereas
ODBC is not depended upon any language.

In short JDBC helps the programmers to write java applications that manage
these three programming activities:

1. It helps us to connect to a data source, like a database.


Web Programming
Gayatri Vidya Parishad College of Engineering (Autonomous)
Computer Science And Engineering
26
Gayatri Vidya Parishad College of Engineering (Autonomous)
Web Programming

2. It helps us in sending queries and updating statements to the database and


3. Retrieving and processing the results received from the database in terms
of answering to your query.

Product Components of JDBC

JDBC has four Components:

1. The JDBC API.


2. The JDBC Driver Manager.
3. The JDBC Test Suite.
4. The JDBC-ODBC Bridge.

1. The JDBC API.

The JDBC application programming interface provides the facility for


accessing the relational database from the Java programming language. The
API technology provides the industrial standard for independently
connecting Java programming language and a wide range of databases. The
user not only execute the SQL statements, retrieve results, and update the
data but can also access it anywhere within a network because of it's "Write
Once, Run Anywhere" (WORA) capabilities.

Due to JDBC API technology, user can also access other tabular data sources
like spreadsheets or flat files even in the a heterogeneous environment.
JDBC application programmming interface is a part of the Java platform
that have included Java Standard Edition (Java SE ) and the Java Enterprise
Edition (Java EE) in itself.

The JDBC API has four main interface:

The latest version of JDBC 4.0 application programming interface is


divided into two packages
i-) java.sql
ii-) javax.sql.

Web Programming
Gayatri Vidya Parishad College of Engineering (Autonomous)
Computer Science And Engineering
27
Gayatri Vidya Parishad College of Engineering (Autonomous)
Web Programming

Java SE and Java EE platforms are included in both the packages.

2. The JDBC Driver Manager.

The JDBC Driver Manager is a very important class that defines objects
which connect Java applications to a JDBC driver. Usually Driver Manager
is the backbone of the JDBC architecture. It's very simple and small that is
used to provide a means of managing the different types of JDBC database
driver running on an application. The main responsibility of JDBC database
driver is to load all the drivers found in the system properly as well as to
select the most appropriate driver from opening a connection to a database.
The Driver Manager also helps to select the most appropriate driver from the
previously loaded drivers when a new open database is connected.

3. The JDBC Test Suite.

The function of JDBC driver test suite is to make ensure that the JDBC
drivers will run user's program or not . The test suite of JDBC application
program interface is very useful for testing a driver based on JDBC
technology during testing period. It ensures the requirement of Java
Platform Enterprise Edition (J2EE).

4. The JDBC-ODBC Bridge.

The JDBC-ODBC bridge, also known as JDBC type 1 driver is a database


driver that utilize the ODBC driver to connect the database. This driver
translates JDBC method calls into ODBC function calls. The Bridge
implements Jdbc for any database for which an Odbc driver is available. The
Bridge is always implemented as the sun.jdbc.odbc Java package and it
contains a native library used to access ODBC.

Now we can conclude this topic: This first two component of JDBC, the
JDBC API and the JDBC Driver Manager manages to connect to the
database and then build a java program that utilizes SQL commands to
communicate with any RDBMS. On the other hand, the last two components
are used to communicate with ODBC or to test web application in the
specialized environment.

Web Programming
Gayatri Vidya Parishad College of Engineering (Autonomous)
Computer Science And Engineering
28
Gayatri Vidya Parishad College of Engineering (Autonomous)
Web Programming

Understanding the JDBC Architecture


JDBC is an API specification developed by Sun Microsystems that defines
a uniform interface for accessing various relational databases. JDBC is a
core part of the Java platform and is included in the standard JDK
distribution.

The primary function of the JDBC API is to provide a means for the
developer to issue SQL statements and process the results in a consistent,
database-independent manner. JDBC provides rich, object-oriented access
to databases by defining classes and interfaces that represent objects such
as:
1. Database connections
2. SQL statements
3. Result Set
4. Database metadata
5. Prepared statements
6. Binary Large Objects (BLOBs)
7. Character Large Objects (CLOBs)
8. Callable statements
9. Database drivers
10.Driver manager

The JDBC API uses a Driver Manager and database-specific drivers to


provide transparent connectivity to heterogeneous databases. The JDBC
driver manager ensures that the correct driver is used to access each data
source. The Driver Manager is capable of supporting multiple concurrent
drivers connected to multiple heterogeneous databases. The location of the
driver manager with respect to the JDBC drivers and the servlet is shown
in Figure1.

Web Programming
Gayatri Vidya Parishad College of Engineering (Autonomous)
Computer Science And Engineering
29
Gayatri Vidya Parishad College of Engineering (Autonomous)
Web Programming

Layers of the JDBC Architecture

A JDBC driver translates standard JDBC calls into a network or database


protocol or into a database library API call that facilitates communication
with the database. This translation layer provides JDBC applications with
database independence. If the back-end database changes, only the JDBC
driver need be replaced with few code modifications required. There are
four distinct types of JDBC drivers.

Type 1 JDBC-ODBC Bridge. Type 1 drivers act as a "bridge" between


JDBC and another database connectivity mechanism such as ODBC. The
JDBC- ODBC bridge provides JDBC access using most standard ODBC
drivers. This driver is included in the Java 2 SDK within the sun.jdbc.odbc
package. In this driver the java statements are converted to a jdbc
statements. JDBC statements calls the ODBC by using the JDBC-ODBC
Bridge. And finally the query is executed by the database. This driver has
Web Programming
Gayatri Vidya Parishad College of Engineering (Autonomous)
Computer Science And Engineering
30
Gayatri Vidya Parishad College of Engineering (Autonomous)
Web Programming

serious limitation for many applications. (See Figure 2.)

Type 1 JDBC Architecture

Type 2 Java to Native API. Type 2 drivers use the Java Native Interface
(JNI) to make calls to a local database library API. This driver converts
the JDBC calls into a database specific call for databases such as SQL,
ORACLE etc. This driver communicates directly with the database server.
It requires some native code to connect to the database. Type 2 drivers are
usually faster than Type 1 drivers. Like Type 1 drivers, Type 2 drivers
require native database client libraries to be installed and configured on
the client machine. (See Figure 3.)

Type 2 JDBC Architecture

Type 3 Java to Network Protocol Or All- Java Driver. Type 3 drivers are
pure Java drivers that use a proprietary network protocol to communicate
with JDBC middleware on the server. The middleware then translates the
network protocol to database-specific function calls. Type 3 drivers are the
most flexible JDBC solution because they do not require native database
Web Programming
Gayatri Vidya Parishad College of Engineering (Autonomous)
Computer Science And Engineering
31
Gayatri Vidya Parishad College of Engineering (Autonomous)
Web Programming

libraries on the client and can connect to many different databases on the
back end. Type 3 drivers can be deployed over the Internet without client
installation. (See Figure 4.)
Java-------> JDBC statements------> SQL statements ------> databases.

Type 3 JDBC Architecture

Type 4 Java to Database Protocol. Type 4 drivers are pure Java drivers that
implement a proprietary database protocol (like Oracle's SQL*Net) to
communicate directly with the database. Like Type 3 drivers, they do not
require native database libraries and can be deployed over the Internet
without client installation. One drawback to Type 4 drivers is that they are
database specific. Unlike Type 3 drivers, if your back-end database
changes, you may save to purchase and deploy a new Type 4 driver (some
Type 4 drivers are available free of charge from the database
manufacturer). However, because Type drivers communicate directly with
the database engine rather than through middleware or a native library,
they are usually the fastest JDBC drivers available. This driver directly
converts the java statements to SQL statements.
Web Programming
Gayatri Vidya Parishad College of Engineering (Autonomous)
Computer Science And Engineering
32
Gayatri Vidya Parishad College of Engineering (Autonomous)
Web Programming

(See Figure 5.)

Type 4 JDBC Architecture

So, you may be asking yourself, "Which is the right type of driver for your
application?" Well, that depends on the requirements of your particular
project. If you do not have the opportunity or inclination to install and
configure software on each client, you can rule out Type 1 and Type 2
drivers.

However, if the cost of Type 3 or Type 4 drivers is prohibitive, Type 1 and


type 2 drivers may become more attractive because they are usually
available free of charge. Price aside, the debate will often boil down to
whether to use Type 3 or Type 4 driver for a particular application. In this
case, you may need to weigh the benefits of flexibility and interoperability
against performance. Type 3 drivers offer your application the ability to
transparently access different types of databases, while Type 4 drivers
usually exhibit better performance and, like Type 1 and Type 2 drivers,
may be available free if charge from the database manufacturer.

Web Programming
Gayatri Vidya Parishad College of Engineering (Autonomous)
Computer Science And Engineering
33
Gayatri Vidya Parishad College of Engineering (Autonomous)
Web Programming

INTRODUCTION TO SERVLETS

Web Programming
Gayatri Vidya Parishad College of Engineering (Autonomous)
Computer Science And Engineering
34
Gayatri Vidya Parishad College of Engineering (Autonomous)
Web Programming

Java Servlet

Servlets are server side components that provide a powerful


mechanism for developing server side programs. Servlets provide
component-based, platform-independent methods for building Web-based
applications, without the performance limitations of CGI programs. Unlike
proprietary server extension mechanisms (such as the Netscape Server API
or Apache modules), servlets are server as well as platform-independent.
This leaves you free to select a "best of breed" strategy for your servers,
platforms, and tools. Using servlets web developers can create fast and
efficient server side application which can run on any servlet enabled web
server. Servlets run entirely inside the Java Virtual Machine. Since the
Servlet runs at server side so it does not checks the browser for
compatibility. Servlets can access the entire family of Java APIs, including
the JDBC API to access enterprise databases. Servlets can also access a
library of HTTP-specific calls, receive all the benefits of the mature java
language including portability, performance, reusability, and crash
protection. Today servlets are the popular choice for building interactive web
applications. Third-party servlet containers are available for Apache Web
Server, Microsoft IIS, and others. Servlet containers are usually the
components of web and application servers, such as BEA WebLogic
Application Server, IBM WebSphere, Sun Java System Web Server, Sun
Java System Application Server and others.

Servlets are not designed for a specific protocols. It is different thing


that they are most commonly used with the HTTP protocols Servlets uses the
classes in the java packages javax.servlet and javax.servlet.http. Servlets
provides a way of creating the sophisticated server side extensions in a
server as they follow the standard framework and use the highly portable
java language.

Web Programming
Gayatri Vidya Parishad College of Engineering (Autonomous)
Computer Science And Engineering
35
Gayatri Vidya Parishad College of Engineering (Autonomous)
Web Programming

HTTP Servlet typically used to:

* Priovide dynamic content like getting the results of a database query and
returning to the client.
* Process and/or store the data submitted by the HTML.
* Manage information about the state of a stateless HTTP. e.g. an online
shopping car manages request for multiple concurrent customers.

Installation, Configuration and running Servlets

In this section, we will see as how to install a WebServer, configure it


and finally run servlets using this server. Throughout this tutorial, we will be
using Apaches Tomcat server as the WebServer. Tomcat is not only an open
and free server, but also the most preferred WebServer across the world. A
few reasons we can attribute for its popularity is Easy to install and
configure, very less memory footprint, fast, powerful and portable. It is the
ideal server for learning purpose.

1. Installation of Tomcat Server and JDK

As mentioned earlier, Apaches Tomcat Server is free software


available for download @ www.apache.org. The current version of Tomcat
Server is 6.0 (as of November 2007). This Server supports Java Servlets 2.5
and Java Server Pages (JSPs) 2.1 specifications. In case of doubt or
confusion, you can refer to the abundant documentation repository available
on this site.

Important software required for running this server is Suns JDK (Java
Development Kit) and JRE (Java Runtime Environment). The current
version of JDK is 6.0. Like Tomcat, JDK is also free and is available for
download at www.java.sun.com.

Web Programming
Gayatri Vidya Parishad College of Engineering (Autonomous)
Computer Science And Engineering
36
Gayatri Vidya Parishad College of Engineering (Autonomous)
Web Programming

2. Configuring Tomcat Server

* Set JAVA_HOME variable - You have to set this variable which


points to the base installation directory of JDK installation. (e.g. c:\program
file\java\jdk1.6.0). You can either set this from the command prompt or from
My Computer -> Properties -> Advanced -> Environment Variables.
* Specify the Server Port You can change the server port from 8080
to 4040 (if you wish to) by editing the server.xml file in the conf folder. The
path would be something like this c:\program files\apache software
foundation\tomcat6\conf\server.xml

3. Run Tomcat Server

Once the above pre-requisites are taken care, you can test as whether the
server is successfully installed as follows:

Step 1

Go to C:\Program Files\Apache Software Foundation\Tomcat 6.0\bin


and double click on tomcat6

OR

Go to Start->Programs->Apache Tomcat 6.0 -> Monitor Tomcat. You


will notice an icon appear on the right side of your Status Bar. Right click
on this icon and click on Start service.

Step 2

Open your Browser (e.g. MS Internet Explorer) and type the following
URL :

http://localhost/ (If you have changed to port # to 4040)

OR

Web Programming
Gayatri Vidya Parishad College of Engineering (Autonomous)
Computer Science And Engineering
37
Gayatri Vidya Parishad College of Engineering (Autonomous)
Web Programming

Open your Browser (e.g. MS Internet Explorer) and type the following
URL :

http://localhost:8080/ (If you have NOT changed the default port #)

In either case, you should get a page similar to the one in Figure-8 which
signifies that the Tomcat Server is successfully running on your machine.

4. Compile and Execute your Servlet

This section through a step by step (and illustration) approach explains


as how to compile and then run a servlet using Tomcat Server. Though this
explanation is specific to Tomcat, the procedure explained holds true for
other Web servers too (e.g. JRun, Cauchos Resin).

Step 1 Compile your servlet program

The first step is to compile your servlet program. The procedure is no


different from that of writing and compiling a java program. But, the point to
be noted is that neither the javax.servlet.* nor the javax.servlet.http.* is part
of the standard JDK. It has to be exclusively added in the CLASSPATH. The
set of classes required for writing servlets is available in a jar file called
servlet-api.jar. This jar file can be downloaded from several sources.
However, the easiest one is to use this jar file available with the Tomcat
server (C:\Program Files\Apache Software Foundation\Tomcat
6.0\lib\servlet-api.jar). You need to include this path in CLASSPATH. Once
you have done this, you will be able to successfully compile your servlet
program. Ensure that the class file is created successfully.

Step 2 Create your Web application folder

The next step is to create your web application


folder. The name of the folder can be any valid and logical name that
represents your application (e.g. bank_apps, airline_tickets_booking,
shopping_cart,etc). But the most important criterion is that this folder should
be created under webapps folder. The path would be similar or close to this -
C:\Program Files\Apache Software Foundation\Tomcat 6.0\webapps. For
demo purpose, let us create a folder called demo-examples under the
Web Programming
Gayatri Vidya Parishad College of Engineering (Autonomous)
Computer Science And Engineering
38
Gayatri Vidya Parishad College of Engineering (Autonomous)
Web Programming

webapps folder.

Step 3 Create the WEB-INF folder

The third step is to create the WEB-INF folder. This folder should be created
under your web application folder that you created in the previous step.
Figure-10 shows the WEB-INF folder being placed under the demo-
examples folder.

Step 4 Create the web.xml file and the classes folder

The fourth step is to create the web.xml file and the classes folder. Ensure
that the web.xml and classes folder are created under the WEB-INF folder.
Figure-11 shows this file and folder being placed under the WEB-INF folder.

Note Instead of creating the web.xml file an easy way would be to copy an
existing web.xml file (e.g. C:\Program Files\Apache Software
Foundation\Tomcat 6.0\webapps\examples\WEB-INF) and paste it into this
folder. You can later edit this file and add relevant information to your web
application.

Step 5 Copy the servlet class to the classes folder

We need to copy the servlet class file to the classes folder in order to run the
servlet that we created. All you need to do is copy the servlet class file (the
file we obtained from Step 1) to this folder. Figure-12 shows the
servlet_lifecycle (refer section 1.2.3.) class being placed in the classes
folder.

Step 6 Edit web.xml to include servlets name and url pattern

This step involves two actions viz. including the servlets name and then
mentioning the url pattern. Let us first see as how to include the servlets
Web Programming
Gayatri Vidya Parishad College of Engineering (Autonomous)
Computer Science And Engineering
39
Gayatri Vidya Parishad College of Engineering (Autonomous)
Web Programming

name in the web.xml file. Open the web.xml file and include the servlets
name as shown in Figure-13.

Note The servlet-name need not be the same as that of the class name.
You can give a different name (or alias) to the actual servlet. This is one of
the main reasons as why this tag is used for.

Next, include the url pattern using the <servlet-mapping> </servlet-


mapping> tag. The url pattern defines as how a user can access the servlet
from the browser. Figure-14 shows the url pattern entry for our current
servlet.

Note Please remember that the path given in the url-pattern is a relative
path. This means that this path is w.r.t. your web applications folder (demo-
examples in this case).

Step 7 Run Tomcat server and then execute your Servlet

This step again involves two actions viz. running the Web Server and then
executing the servlet.

After ensuring that the web server is running successfully, you can run your
servlet. To do this, open your web browser and enter the url as specified in
the web.xml file. The complete url that needs to be entered in the browser is:

http://localhost/demo-examples/servlet_lifecycle

Heres the output of our first servlet. After a long and pain staking
effort, we finally got an output! As mentioned in Section 1.2.3. you can keep
refreshing the browser window and see for yourself as how i value is
incremented (a proof that the doGet is called every time you re-invoke a
servlet).

How to Run a Servlet


Web Programming
Gayatri Vidya Parishad College of Engineering (Autonomous)
Computer Science And Engineering
40
Gayatri Vidya Parishad College of Engineering (Autonomous)
Web Programming

To run a servlet one should follow the steps illustrated below:

* Download and Install the tomcat server: Install the tomcat server in a
directory in which you want to install and set the classpath.for the variable
JAVA_HOME in the environment variable. To get details about the
installation process and setting the classpath click the link Tomcat
installation.
* Set the class for the jar file: Set the classpath of the servlet-api.jar file in
the variable CLASSPATH inside the environment variable by using the
following steps.

For Windows XP,

Go to Start->Control Panel->System->Advanced->Environment
Variables->New button and Set the values as
Variable Name: CLASSPATH
Variable Value: C:\Program Files\Java\Tomcat 6.0\lib\servlet-api.jar

For Windows 2000 and NT

Go to Start->Settings->Control Panel->System->Environment Variables-


>New button and Set the values as
Variable Name: CLASSPATH
Variable Value: C:\Program Files\Java\Tomcat 6.0\lib\servlet-api.jar
* Create a java source file and a web.xml file in a directory structure.
* Compile the java source file, put the compiled file (.class file) in the
classes folder of your application and deploy the directory of your
application in the webapps folder inside the tomcat directory.
* Start the tomcat server, open a browser window and type the URL
http://localhost:8080/directory (folder name of your application)
name/servler name and press enter.

If everything is correct your servlet will run.

Web Programming
Gayatri Vidya Parishad College of Engineering (Autonomous)
Computer Science And Engineering
41
Gayatri Vidya Parishad College of Engineering (Autonomous)
Web Programming

Writing Servlet Hello World

We should start understanding the servlets from the beginning. Lets start by
making one program which will just print the "Hello World" on the browser.
Each time the user visits this page it will display "Hello World" to the user.

As we know that the our servlet extends the HttpServlet and overrides the
doGet() method which it inherits from the HttpServlet class. The server
invokes doGet() method whenever web server recieves the GET request
from the servlet. The doGet() method takes two arguments first is
HttpServletRequest object and the second one is HttpServletResponse object
and this method throws the ServletException.

Whenever the user sends the request to the server then server generates two
obects, first is HttpServletRequest object and the second one is
HttpServletResponse object. HttpServletRequest object represents the
client's request and the HttpServletResponse represents the servlet's
response.

Inside the doGet(() method our servlet has first used the setContentType()
method of the response object which sets the content type of the response to
text/html. It is the standard MIME content type for the Html pages. After
that it has used the method getWriter() of the response object to retrieve a
PrintWriter object. To display the output on the browser we use the println()
method of the PrintWriter class.

The code the program is given below:

Web Programming
Gayatri Vidya Parishad College of Engineering (Autonomous)
Computer Science And Engineering
42
Gayatri Vidya Parishad College of Engineering (Autonomous)
Web Programming

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class HelloWorld extends HttpServlet{


public void doGet(HttpServletRequest request, HttpServletResponse
response)
throws ServletException,IOException{
response.setContentType("text/html");
PrintWriter pw = response.getWriter();
pw.println("<html>");
pw.println("<head><title>Hello World</title></title>");
pw.println("<body>");
pw.println("<h1>Hello World</h1>");
pw.println("</body></html>");
}
}

web.xml file for this program:

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


<!--<!DOCTYPE web-app
PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
"http://java.sun.com/dtd/web-app_2_3.dtd"> -->

<web-app>
<servlet>
<servlet-name>Hello</servlet-name>
<servlet-class>HelloWorld</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Hello</servlet-name>
<url-pattern>/HelloWorld</url-pattern>
</servlet-mapping>
</web-app>
Example Program to maintain sessions using cookies

CookieExample.java
Web Programming
Gayatri Vidya Parishad College of Engineering (Autonomous)
Computer Science And Engineering
43
Gayatri Vidya Parishad College of Engineering (Autonomous)
Web Programming

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class CookieExample extends HttpServlet


{

public void doPost(HttpServletRequest request, HttpServletResponse


response)
throws IOException, ServletException
{
Cookie cookie1=new Cookie("user1","pwd1");
Cookie cookie2=new Cookie("user2","pwd2");
Cookie cookie3=new Cookie("user3","pwd3");
Cookie cookie4=new Cookie("user4","pwd4");
response.addCookie(cookie1);
response.addCookie(cookie2);
response.addCookie(cookie3);
response.addCookie(cookie4);
}

public void doGet(HttpServletRequest request, HttpServletResponse


response)
throws IOException, ServletException
{
response.setContentType("text/html");
PrintWriter out=response.getWriter();
Cookie[] cookies=request.getCookies();
for(int i=0;i<cookies.length;i++)
{
String name=cookies[i].getName();
String value=cookies[i].getValue();
Web Programming
Gayatri Vidya Parishad College of Engineering (Autonomous)
Computer Science And Engineering
44
Gayatri Vidya Parishad College of Engineering (Autonomous)
Web Programming

out.println("name="+ name + "; value=" + value+"\n");


}
}
}

Execution procedure:

1. Create CookieExample.java file in your directory


( Ex. C:\CookieExample.java)
2. Be sure that CLASSPATH is set on your system. If not set the
CLASSPATH as below:
The set of classes required for writing servlets is available in a jar file called
servlet-api.jar.
C:\Program Files\Apache Software Foundation\Tomcat 6.0\lib\servlet-api.jar

Web Programming
Gayatri Vidya Parishad College of Engineering (Autonomous)
Computer Science And Engineering
45
Gayatri Vidya Parishad College of Engineering (Autonomous)
Web Programming

PROCEDURE to access http://localhost:8080/dp/CookieExample

After installing Apache Tomcat 6.0 with port number 8080,


generate a class file CookieExample.class in classes folder as
shown below:
Copy the servlet class to the classes folder

Tomcat
Tomcat
6.0
6.0

Webapps
Webapps

dp ROOT
dp ROOT

Web Programming
Gayatri Vidya Parishad College of Engineering (Autonomous)
Computer Science And Engineering
WEB-INF 46
Classes WEB-INF
Classes
Gayatri Vidya Parishad College of Engineering (Autonomous)
Web Programming

WEB-INF
WEB-INF

Web.xml
Web.xml

CookieE
CookieE
xample.
xample.
class
class

After generating class file create the web.xml file and the classes
folder.Ensure that the web.xml and classes folder are created under
the WEB-INF folder. The above figure shows this file and folder being
placed under the WEB-INF folder.

Web.xml

<web-app>
<servlet>
<servlet-name>CookieExample</servlet-name>
<servlet-class>CookieExample</servlet-class>
</servlet>

<servlet-mapping>
<servlet-name> CookieExample </servlet-name>
<url-pattern>/ CookieExample </url-pattern>
</servlet-mapping>
</web-app>
Web Programming
Gayatri Vidya Parishad College of Engineering (Autonomous)
Computer Science And Engineering
47
Gayatri Vidya Parishad College of Engineering (Autonomous)
Web Programming

Run Tomcat server and then execute your Servlet


After ensuring that the web server is running successfully, you can run
your servlet. To do this, open your web browser and enter the url as
specified in the web.xml file. The complete url that needs to be entered
in the browser is:

http://localhost:8080/dp/CookieExample

OUTPUT

http://localhost:8080/dp/CookieExample
http://localhost:8080/dp/CookieExample

Web Programming
Gayatri Vidya Parishad College of Engineering (Autonomous)
Computer Science And Engineering
48
Gayatri Vidya Parishad College of Engineering (Autonomous)
Web Programming

Web Programming
Gayatri Vidya Parishad College of Engineering (Autonomous)
Computer Science And Engineering
49
Gayatri Vidya Parishad College of Engineering (Autonomous)
Web Programming

UNIT-4
JAVA SERVER PAGES

Introducing JavaServer Pages

Based on servlet technology, and currently shaping up at breakneck speed,


JavaServer Pages (JSP) is set to be one of the most important elements of
Java server programming. It's by no means complete yet, but that will
change as the Java 2 Enterprise Edition comes together.

So what are JavaServer Pages? Well, they combine markup (whether HTML
or XML) with nuggets of Java code to produce a dynamic web page. Each
page is automatically compiled to a servlet by the JSP engine, the first time
it is requested, and then executed. JSP provides a variety of ways to talk to
Web Programming
Gayatri Vidya Parishad College of Engineering (Autonomous)
Computer Science And Engineering
50
Gayatri Vidya Parishad College of Engineering (Autonomous)
Web Programming

Java classes, servlets, applets and the web server. With it, you can split the
functionality of your web applications into components with well-defined
public interfaces glued together by a simple page.

Architectural Overview

A JavaServer Page is a simple text file consisting of HTML or XML content


along with JSP elements (a sort of shorthand for Java code). When a client
requests a JSP page of the web server and it has not been run before, the
page is first passed to a JSP engine which compiles the page to a servlet,
runs it and returns the resulting content to the client. Thereafter, the web
server's servlet engine will run the compiled page.

It should be no surprise, given the flexibility of the servlet model, that the
current reference implementation of the JSP engine is itself a servlet.

It is possible to view the finished servlet code that is generated by locating it


within the directory structure of the servlet engine. For example, with JRun,
you can find the source code for your JSP files (in servlet form) in the
jrun/jsm-default/services/jse/servlets/jsp directory. This is very helpful when
trying to debug your JSP files.

If you take a look in the source files for the javax.servlet.jsp package, you'll
find the following classes :

JSPPage
HttpJspPage

They define the interface for the compiled JSP page - namely that it must
have three methods. Not surprisingly they are :

jspInit()
jspDestroy()
_jspService(HttpServletRequest request, HttpServletResponse
response)

The first two methods can be defined by the JSP author (we'll see how in a
moment), but the third is the compiled version of the JSP page, and its
creation is the responsibility of the JSP engine.

Web Programming
Gayatri Vidya Parishad College of Engineering (Autonomous)
Computer Science And Engineering
51
Gayatri Vidya Parishad College of Engineering (Autonomous)
Web Programming

It's time we saw a JSP file :

<html>
<head>
<title>Demo of a JSP page</title>
</head>
<body>

<!-- Set global information for the page -->


<%@ page language="java" %>

<!-- Declare the character variable -->


<%! char c = 0; %>

<!-- Scriptlet - Java code -->


<%
for (int i = 0; i < 26; i++)
{
for (int j = 0; j < 26; j++)
{
Web Programming
Gayatri Vidya Parishad College of Engineering (Autonomous)
Computer Science And Engineering
52
Gayatri Vidya Parishad College of Engineering (Autonomous)
Web Programming

// Output capital letters of the alphabet, and change starting letter


c = (char)(0x41 + (26 - i + j)%26);
%>

<!-- Output the value of c.toString() to the HTML page -->


<%= c %>

<%
}
%>
<br>
<%
}
%>

</body>
</html>

This page just outputs the alphabet 26 times and changes the starting letter.
The HTML is self-explanatory and written the way it should be, rather than
cluttering up methods of a servlet.

Elements of a JavaServer Page

The Java code in the page includes :

Directives these provide global information to the page, for


example, import statements, the page for error handling or whether the
page is part of a session. In the above example we set the script
language to Java.
Declaratives - these are for page-wide variable and method
declarations.
Scriptlets - the Java code embedded in the page.
Expressions - formats the expression as a string for inclusion in the
output of the page.

JSP Directives

Web Programming
Gayatri Vidya Parishad College of Engineering (Autonomous)
Computer Science And Engineering
53
Gayatri Vidya Parishad College of Engineering (Autonomous)
Web Programming

A JSP directive is a statement that gives the JSP engine information for the
page that follows. The general syntax of a JSP directive is <%@ directive
{ attribute=value } %>, where the directive may have a number of
(optional) attributes. Each directive has an optional XML equivalent, but
these are intended for future JSP tools, so we won't consider them here.

Possible directives in JSP 1.0 are :

Page information for that page


Include files to be included verbatim
Taglib the URI for a library of tags that you'll use in the page
(unimplemented at the time of writing)

As is to be expected, the page directive has many possible attributes.


Specifying these is optional, as the mandatory ones have default values.

Attribute and possible values Description


language=java The language variable tells the
server what language will be used
in the file. Java is the only
supported syntax for a JSP in the
current specification.
Support for other scripting
languages is available at
http://www.plenix.org/polyjsp and
http://www.caucho.com
(JavaScript).
extends="package.class" The extends variable defines the
parent class of the generated
servlet. It isn't normally necessary
to use anything other than the
provided base classes.
import="package.*,package.class The import variable is similar to
" the first section of any Java
program. As such, it should

Web Programming
Gayatri Vidya Parishad College of Engineering (Autonomous)
Computer Science And Engineering
54
Gayatri Vidya Parishad College of Engineering (Autonomous)
Web Programming

always be placed at the top of the


JSP file. The value of the import
variable should be a comma-
separated list of the packages and
classes that you wish to import.
session="true|false" By default, the session variable is
true, meaning that session data is
available to a page.
buffer="none|8kb|sizekb" Determines if the output stream is
buffered. By default it is set to
8kb. Use with autoFlush
autoFlush="true|false" If set to true, flushes the output
buffer when it's full, rather than
raising an exception.
Continued on Following Page

Web Programming
Gayatri Vidya Parishad College of Engineering (Autonomous)
Computer Science And Engineering
55
Gayatri Vidya Parishad College of Engineering (Autonomous)
Web Programming

Attribute and possible values Description


isThreadSafe="true|false" By default this is set true, signaling to
the JSP engine that that multiple client
requests can be dealt with at once. It's
the JSP author's job to synchronize
shared state, so that the page really is
thread safe.
If isThreadSafe is set to false, the
single thread model will be used,
controlling client access to the page.
This doesn't let you off the hook,
however, as servers may, at their
discretion, have multiple instances of
the page running to deal with the
client request load. And there's no
guarantee that consecutive requests
from the same client will be directed
to the same instance of JSP page. Any
resources or state that are shared
between page requests must therefore
be synchronized.
info="text" Information on the page that can be
accessed through the page's
Servlet.getServletInfo() method.
errorPage="pathToErrorPage" Gives the relative path to the JSP page
that will handle unhandled exceptions.
That JSP page will have isErrorPage
set to true
isErrorPage="true|false" Marks the page as an error page. We'll
see this in action later.
contentType="text/html; The mime type and character set of the
charset=ISO-8859-1" JSP and the final page. This
information must come early in the
file, before any non-latin-1 characters
Web Programming
Gayatri Vidya Parishad College of Engineering (Autonomous)
Computer Science And Engineering
56
Gayatri Vidya Parishad College of Engineering (Autonomous)
Web Programming

appear in the file.

In the JSWDK-1.0-ea1 release there's a bug - the import statement needs to


be imports to satisfy the JSP engine.

JSP Declarations

A JSP declaration can be thought of as the definition of class-level variables


and methods that are to be used throughout the page. To define a declarative
block, begin the block of code with <%! declaration>.

<%!
String var1 = "x";
int count = 0;

private void incrementCount()


{
count++;
}
%>

Note that you put semi-colons after each variable declaration, just as if you
were writing it in a class.

This is how you would define the optional jspInit() and jspDestroy()
methods that we mentioned earlier.

JSP Scriptlets

Scriptlets are defined as any block of valid Java code that resides between <
% and %> tags.

This code will be placed in the generated servlet's _jspService() method.


Code that is defined within a scriptlet can access any variable and any beans
that have been declared. There are also a host of implicit objects available to
a scriptlet from the servlet environment.
Web Programming
Gayatri Vidya Parishad College of Engineering (Autonomous)
Computer Science And Engineering
57
Gayatri Vidya Parishad College of Engineering (Autonomous)
Web Programming

Implicit Description
Objects
request The client's request. This is usually a subclass of
HttpServletRequest. This has the parameter list if
there is one.
response The JSP page's response, a subclass of
HttpServletResponse.
pageContext Page attributes and implicit objects (essentially what
makes up the server environment in which the JSP
runs) need to be accessible through a uniform API, to
allow the JSP engine to compile pages. But each
server will have specific implementations of these
attributes and objects.
The solution to this problem is for the JSP engine to
compile in code that uses a factory class to return the
server's implementation of the PageContext class.
That PageContext class has been initialized with the
request and response objects and some of the
attributes from the page directive (errorpage, session,
buffer and autoflush) and provides the other implicit
objects for the page request. We'll see more on this in
a moment.
session The HTTP session object associated with the request.
application The servlet context returned by a call to
getServletConfig().getContext() (see Chapter 5).
out The object representing the output stream.

Web Programming
Gayatri Vidya Parishad College of Engineering (Autonomous)
Computer Science And Engineering
58
Gayatri Vidya Parishad College of Engineering (Autonomous)
Web Programming

Implicit Description
Objects
config The ServletConfig object for the page.
page The page's way of referring to itself (as an
alternative to this in any Java code).
exception The uncaught subclass of Throwable that is passed to
the errorpage URL.

The following snippet shows both how to get a named parameter from the
request object, and how to pass a string to the output stream for the page.

<%
String var1 = request.getParameter("lname");
out.println(var1);
%>

Having discussed implicit objects, we're in a better position to understand


the code featured in the comment for the PageContext source from the JSP
1.0 reference implementation. This shows the code that the JSP 1.0 reference
engine injects into the JSP page's _jspService() method.

public void _jspService(HttpServletRequest request,


HttpServletResponse response)
throws IOException, ServletException
{
JspFactory factory = JspFactory.getDefaultFactory();
PageContext pageContext = factory.getPageContext(
this, // servlet
request,
response,
null, // errorPageURL
false, // needsSession
JspWriter.DEFAULT_BUFFER,
true // autoFlush
);

Web Programming
Gayatri Vidya Parishad College of Engineering (Autonomous)
Computer Science And Engineering
59
Gayatri Vidya Parishad College of Engineering (Autonomous)
Web Programming

// Initialize implicit variables for scripting environment


HttpSession session = pageContext.getSession();
JspWriter out = pageContext.getOut();
Object page = this;

try {
// Body of translated JSP here...
} catch (Exception e)
{
out.clear();
pageContext.handlePageException(e);
} finally {
out.close();
factory.releasePageContext(pageContext);
}
}

JspFactory returns the pageContext implicit object, from which the other
implicit objects are obtained for the duration of the _jspService() method.

JSP Expressions

A JSP expression is a very nice tool for embedding values within your
HTML code. Anything between <%= and %> tags will be evaluated,
converted to a string, and then displayed. Conversion from a primitive type
to a string is handled automatically.

The current price of item A100 is


<%= request.getParameter("price") %>

Web Programming
Gayatri Vidya Parishad College of Engineering (Autonomous)
Computer Science And Engineering
60
Gayatri Vidya Parishad College of Engineering (Autonomous)
Web Programming

Something you'll want to note is that the expression doesn't end with a semi-
colon. That's because the JSP engine will put the expression within an
out.println() call for you.

JSP expressions allow you to essentially parameterize HTML (just as you


would parameterize a SQL query that differs by only a couple of values).
Again and again, your code will set up conditions and loops using a one-line
JSP scriptlet and then include the HTML code directly beneath it. Simply
enclose the beginning and the ending of the condition or loop in separate
pairs of <% and %> tags :

<% for (int i = 0; i < 10; i++)


{ %>
<br>
Counter value is <%= i %>
<% } %>

Coding JSP Pages

A big advantage in developing a JavaServer Page is that you can code the
HTML without enclosing it in Java code, as you must do in a servlet. You
can then take advantage of HTML editors to develop your content.

So from the drudgery of coding HTML output in servlets, we've arrived at


the flexibility of coding Java snippets into the HTML page. But don't be
dragged too far the other way. Heard of the people who can't fit their ASP
files into Notepad? And if there's one problem with ASP and JSP, it's
debugging the pages, making improvements to them, and untangling the
meaning of that section you coded months back.

The "third way" is a mixture of presentation-based calls to a Bean or servlet,


which components can be better tested, are well-encapsulated and good OOP
citizens. This moves from embedding code to embedding components and
action tags in the page.

Note that the current reference JSP implementations don't automatically


reload the new Bean if you recompile while the server is running. You'll
need to restart the servlet engine.

Web Programming
Gayatri Vidya Parishad College of Engineering (Autonomous)
Computer Science And Engineering
61
Gayatri Vidya Parishad College of Engineering (Autonomous)
Web Programming

Using JavaBeans Components with JSP

So, when setting up an application development architecture that involves


JavaServer Pages, it is a good idea to try and put all of your business logic
inside reusable components. These components can then be 'plugged' into
any JavaServer Page that requires them.

What is a JavaBean?

The Java language has implemented the idea of a component as something


called a JavaBean. A JavaBean is a Java class that fits the following criteria :

Public class.
Public constructor with no arguments.
Public set and get methods to simulate properties. The get method has
no arguments, unless it acts on an indexed property.

The JavaBeans architecture uses reflection to infer the public methods. But
you can provide a BeanInfo class, called BeanName BeanInfo to give more
explicit information.

A bean can also be serialized and saved for later use. It does this by
implementing the Serializable interface. When a bean component is
serialized, it saves its current state. The current state of a bean is defined by
the current values of its public properties.

Properties are always set and retrieved using a common naming convention.
For each property, two methods must exist, a getxxx() and setxxx() method
(where xxx is the name of the property).

Apart from that a bean is just like any other Java class. Typically, a bean
component is imported into a program, its properties are set and its methods
are called.

Most of the time beans are used to encapsulate visual and non-visual
elements of a GUI. There's some snazzy stuff to link beans up, to implement
drag-and-drop and to save the state of a bean between instances. The

Web Programming
Gayatri Vidya Parishad College of Engineering (Autonomous)
Computer Science And Engineering
62
Gayatri Vidya Parishad College of Engineering (Autonomous)
Web Programming

ultimate aim is to make them part of graphical application assembly tools. I


found that once I stopped thinking about these graphical tools and
concentrated on it just being a class that follows a few design patterns,
things were easier to understand!

Because of this history, Beans don't sit obviously in JSP. Don't get me wrong
- they work well. But it's not what they were originally designed for. If we
think of them as components, simple encapsulations of Java code, then their
purpose is clearer. Beans mean that your page isn't clogged with code.

Much of the business logic we're hinting at might be better placed in an


Enterprise JavaBean, where the transactions and scaling issues are explicitly
the problem of the container and not the bean. That kind of heavyweight use
may be necessary sometimes but I think that beans will stay around for the
lighter work we show here. And beans as graphical components of your final
web page, for a richer user interface, will be another expression of their
code- and complexity-wrapping role.

Letters from a Bean

To show how to use a simple bean, we're going to develop the alphabet
example from earlier, and associate each letter with a color.

The presentation of the letters will remain the responsibility of the JSP page,
but the color mapping will be the bean's job.

package com.wrox.jspexamples;

import java.awt.Color;
import java.util.*;

public class AlphabetCode


{
HashMap map;
char c = 0;
Integer colorNumber;
static int FIRST_LETTER = 0x41;
static int ALPHABET_LENGTH = 26;
Web Programming
Gayatri Vidya Parishad College of Engineering (Autonomous)
Computer Science And Engineering
63
Gayatri Vidya Parishad College of Engineering (Autonomous)
Web Programming

float s = 0.9f;
float b = 0.9f;

public AlphabetCode()
{
this.map = new HashMap(ALPHABET_LENGTH);

for (int i = 0; i < ALPHABET_LENGTH; i++)


{
this.c = (char)(FIRST_LETTER + i);
float h = (float)i/ALPHABET_LENGTH;
this.map.put(new Character(c), Color.getHSBColor(h, s, b));
}
}

public void setCharacter(String nextChar)


{
this.c = nextChar.charAt(0);
}

public String getCharacter()


{
return (new Character(this.c).toString());
}

public String getColor()


{
Color rgb = (Color)map.get(new Character(this.c));
StringBuffer htmlColor = new StringBuffer(
colorNumber.toHexString(rgb.getRGB()
& 0x00ffffff));
// toHexString() won't preserve leading zeros, so need to add them
back in
// if they've gone missing...
if (htmlColor.length() != 6)
{
htmlColor.insert(0, "\"#00");
} else htmlColor.insert(0, "\"#");
Web Programming
Gayatri Vidya Parishad College of Engineering (Autonomous)
Computer Science And Engineering
64
Gayatri Vidya Parishad College of Engineering (Autonomous)
Web Programming

htmlColor.append("\"");

return htmlColor.toString();
}
}

The bean things to note are the public class and constructor, and the set and
get methods. The class sets up the color of each character in the constructor,
and then returns the color of the current character as an HTML color.

Letters from a Bean

The modified JSP page looks like :

<html>
<head>
<title>
Color demo I</title>
</head>
<body>

<!-- This page generates a series of rainbow colored letters -->


<!-- It uses plain method calls to the Bean -->

<%@ page language="java" %>

<%! char c = 0; %>

<jsp:useBean id="letterColor" scope="application"


class="com.wrox.jspexamples.AlphabetCode" />
<%
for (int i = 0; i < 26; i++)
{
for (int j = 0; j < 26; j++)
{
c = (char)(0x41 + (26 - i + j)%26);

Web Programming
Gayatri Vidya Parishad College of Engineering (Autonomous)
Computer Science And Engineering
65
Gayatri Vidya Parishad College of Engineering (Autonomous)
Web Programming

Character thisChar = new Character(c);


letterColor.setCharacter(thisChar.toString());
%>

<font color=<%= letterColor.getColor() %> >


<%= letterColor.getCharacter() %>
</font>
<%
}
%>
<BR>
<%
}
%>
</body>
</html>

Giving the result :

Web Programming
Gayatri Vidya Parishad College of Engineering (Autonomous)
Computer Science And Engineering
66
Gayatri Vidya Parishad College of Engineering (Autonomous)
Web Programming

The JSP page uses straight method calls ( setCharacter(), getCharacter() and
getColor()) to the bean. The only new syntax is <jsp:useBean ... />, so let's
look at that :

<jsp:useBean id="letterColor" scope="application"


class="com.wrox.jspexamples.AlphabetCode" />

The jsp:useBean tag first searches for a bean instance that matches the scope
and class. If it can't find one it instantiates the named class, using its public,
no-args constructor. If there are any initialization time properties you need to
set, you can place the appropriate tags between <jsp:useBean> and
</jsp:useBean> - these are only executed when a new instance is created.

Letters from a Bean

Web Programming
Gayatri Vidya Parishad College of Engineering (Autonomous)
Computer Science And Engineering
67
Gayatri Vidya Parishad College of Engineering (Autonomous)
Web Programming

In the JSP 1.0 reference implementation, the server looks for your packages
in the CLASSPATH environment variable (on my machine, startserver
includes jsp1.0/examples/WEB-INF/jsp/beans). Let's look at the attributes :

useBean Attributes Description


id="name" The name by which the instance of the bean
can be referenced in the page. Other Bean
tags use name to refer to it, so do note the
difference.
scope="page" The scope over which the bean can be called.
More below.
class="package.class" Fully qualified name of the bean class.
Because this needs to be the full name, you
don't need to import these classes in the page
directive.
beanName="name" This allows you to specify a serialized bean
(.ser file) or a bean's name that can be passed
to the instantiate() method from the
java.beans.Beans. Needs an associated type
tag rather than class.
type="package.class" A synonym for class that is used for
beanName.

Scope on a JSP page goes something like this :

Scope Description
page This is the scope of the PageContext object we
saw earlier. It lasts until the page completes, and
there is no storage of state.
page wasn't implemented in the EA1 reference
version of JSP 1.0.
request The bean instance lasts for the client request.
The named bean instance is available as an
attribute of the ServletRequest object, so it
Web Programming
Gayatri Vidya Parishad College of Engineering (Autonomous)
Computer Science And Engineering
68
Gayatri Vidya Parishad College of Engineering (Autonomous)
Web Programming

follows the request to another servlet / JSP if


control is forwarded.
session The bean lasts as long as the client session. A
reference is available through
HttpSession.getValue(name).
Don't use this scope level if you have declared
the page directive session false.
application The bean instance is created with the
application and remains in use until the
application ends. It's an attribute of the
ServletContext object.

We're not finished in our tour of tags, though. With a couple of changes to
our JSP code, we can show you two more - jsp:getProperty and
jsp:setProperty :

<html>
<head>
<title>
Color demo
</title>
</head>
<body>
<!-- This page generates a series of rainbow colored letters -->
<!-- It uses the JSP property set and get tags -->
<%@ page language="java" %>
<%! char c = 0; %>
<jsp:useBean id="letterColor" scope="application"
class="com.wrox.jspexamples.AlphabetCode" />
<%
for (int i = 0; i < 26; i++)
{
for (int j = 0; j < 26; j++)
{
c = (char)(0x41 + (26 - i + j)%26);
Character thisChar = new Character(c);
%>
Web Programming
Gayatri Vidya Parishad College of Engineering (Autonomous)
Computer Science And Engineering
69
Gayatri Vidya Parishad College of Engineering (Autonomous)
Web Programming

<jsp:setProperty name="letterColor" property="Character"


value="<%= thisChar.toString() %>" />

<FONT COLOR=<jsp:getProperty name="letterColor"


property="Color" /> >
<jsp:getProperty name="letterColor" property="Character" />
</FONT>

...

The <jsp:setProperty ... /> needs the bean name, the property name and the
value with which to set the property. Note that the property name is the
setCharacter() method without the prefix. <jsp:getProperty ... /> is self-
explanatory.

Web Programming
Gayatri Vidya Parishad College of Engineering (Autonomous)
Computer Science And Engineering
70
Gayatri Vidya Parishad College of Engineering (Autonomous)
Web Programming

UNIT-5
PHP

Web Programming
Gayatri Vidya Parishad College of Engineering (Autonomous)
Computer Science And Engineering
71
Gayatri Vidya Parishad College of Engineering (Autonomous)
Web Programming

PHP Tutorial

PHP tutorial for beginners and professionals provides deep knowledge of


PHP scripting language. Our PHP tutorial will help you to learn PHP
scripting language easily. This PHP tutorial covers all the topics of PHP such
as introduction, control statements, functions, array, string, file handling,
form handling, regular expression, date and time, object-oriented
programming in PHP, math, PHP mysql, PHP with ajax, PHP with jquery
and PHP with XML.

What is PHP

o PHP stands for HyperText Preprocessor.


o PHP is an interpreted language, i.e. there is no need for compilation.
o PHP is a server side scripting language.
o PHP is faster than other scripting language e.g. asp and jsp.

PHP Example

In this tutorial, you will get a lot of PHP examples to understand the topic
well. The PHP file must be save with .php extension. Let's see a simple PHP
example.

File: hello.php
1. <!DOCTYPE>
2. <html>
3. <body>
4. <?php
5. echo "<h2>Hello by PHP</h2>";
6. ?>
7. </body>
8. </html>

Output:

Web Programming
Gayatri Vidya Parishad College of Engineering (Autonomous)
Computer Science And Engineering
72
Gayatri Vidya Parishad College of Engineering (Autonomous)
Web Programming

Hello by PHP

Web Development

PHP is widely used in web development now a days. Dynamic websites can
be easily developed by PHP. But you must have the basic the knowledge of
following technologies for web development as well.

o HTML
o CSS
o JavaScript
o AJAX
o XML and JSON
o JQuery

Web Programming
Gayatri Vidya Parishad College of Engineering (Autonomous)
Computer Science And Engineering
73
Gayatri Vidya Parishad College of Engineering (Autonomous)
Web Programming

What is PHP

PHP is a open source, interpreted and object-oriented scripting language i.e.


executed at server side. It is used to develop web applications (an application
i.e. executed at server side and generates dynamic page).

What is PHP

o PHP is a server side scripting language.


o PHP is an interpreted language, i.e. there is no need for compilation.
o PHP is an object-oriented language.
o PHP is an open-source scripting language.
o PHP is simple and easy to learn language.

PHP Features

There are given many features of PHP.

o Performance: Script written in PHP executes much faster then those


scripts written in other languages such as JSP & ASP.
o Open Source Software: PHP source code is free available on the
web, you can developed all the version of PHP according to your
requirement without paying any cost.
o Platform Independent: PHP are available for WINDOWS, MAC,
LINUX & UNIX operating system. A PHP application developed in
one OS can be easily executed in other OS also.
o Compatibility: PHP is compatible with almost all local servers used
today like Apache, IIS etc.
o Embedded: PHP code can be easily embedded within HTML tags and
script.

Web Programming
Gayatri Vidya Parishad College of Engineering (Autonomous)
Computer Science And Engineering
74
Gayatri Vidya Parishad College of Engineering (Autonomous)
Web Programming

Install PHP

To install PHP, we will suggest you to install AMP (Apache, MySQL, PHP)
software stack. It is available for all operating systems. There are many AMP
options available in the market that are given below:

o WAMP for Windows


o LAMP for Linux
o MAMP for Mac
o SAMP for Solaris
o FAMP for FreeBSD
o XAMPP (Cross, Apache, MySQL, PHP, Perl) for Cross Platform: It
includes some other components too such as FileZilla, OpenSSL,
Webalizer, OpenSSL, Mercury Mail etc.

PHP Echo

PHP echo is a language construct not a function, so you don't need to use
parenthesis with it. But if you want to use more than one parameters, it is
required to use parenthesis.

The syntax of PHP echo is given below:

1. void echo ( string $arg1 [, string $... ] )

PHP echo statement can be used to print string, multi line strings, escaping
characters, variable, array etc

PHP Variables

A variable in PHP is a name of memory location that holds data. A variable


is a temporary storage that is used to store data temporarily.

In PHP, a variable is declared using $ sign followed by variable name.

Web Programming
Gayatri Vidya Parishad College of Engineering (Autonomous)
Computer Science And Engineering
75
Gayatri Vidya Parishad College of Engineering (Autonomous)
Web Programming

Syntax of declaring a variable in PHP is given below:

1. $variablename=value;
PHP Data Types

PHP data types are used to hold different types of data or values. PHP
supports 8 primitive data types that can be categorized further in 3 types:

1. Scalar Types
2. Compound Types
3. Special Types

PHP Data Types: Scalar Types

There are 4 scalar data types in PHP.

1. boolean
2. integer
3. float
4. string

PHP Data Types: Compound Types

There are 2 compound data types in PHP.

1. array
2. object

PHP Data Types: Special Types

There are 2 special data types in PHP.

1. resource
2. NULL

Web Programming
Gayatri Vidya Parishad College of Engineering (Autonomous)
Computer Science And Engineering
76
Gayatri Vidya Parishad College of Engineering (Autonomous)
Web Programming

PHP Operators

PHP Operator is a symbol i.e used to perform operations on operands. For


example:

1. $num=10+20;//+ is the operator and 10,20 are operands

In the above example, + is the binary + operator, 10 and 20 are operands and
$num is variable.

PHP Operators can be categorized in following forms:

o Arithmetic Operators
o Comparison Operators
o Bitwise Operators
o Logical Operators
o String Operators
o Incrementing/Decrementing Operators
o Array Operators
o Type Operators
o Execution Operators
o Error Control Operators
o Assignment Operators

We can also categorize operators on behalf of operands. They can be


categorized in 3 forms:

o Unary Operators: works on single operands such as ++, -- etc.


o Binary Operators: works on two operands such as binary +, -, *, / etc.
o Ternary Operators: works on three operands such as "?:".

PHP Operators Precedence

Let's see the precedence of PHP operators with associativity.

Web Programming
Gayatri Vidya Parishad College of Engineering (Autonomous)
Computer Science And Engineering
77
Gayatri Vidya Parishad College of Engineering (Autonomous)
Web Programming

Operators Additional Information

clone new clone and new

[ array()

** arithmetic

++ -- ~ (int) (float) (string) (array) (object) (bool) @ increment/decrement and types

Instanceof types

! logical (negation)

*/% arithmetic

+-. arithmetic and string concatena

<< >> bitwise (shift)

< <= > >= comparison

== != === !== <> comparison

& bitwise AND

^ bitwise XOR

| bitwise OR

&& logical AND

|| logical OR

?: ternary

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

Web Programming
Gayatri Vidya Parishad College of Engineering (Autonomous)
Computer Science And Engineering
78
Gayatri Vidya Parishad College of Engineering (Autonomous)
Web Programming

And logical

Xor logical

Or logical

, many uses (comma)

PHP Arrays

PHP array is an ordered map (contains value on the basis of key). It is used
to hold multiple values of similar type in a single variable.

Advantage of PHP Array

Less Code: We don't need to define multiple variables.

Easy to traverse: By the help of single loop, we can traverse all the
elements of an array.

Sorting: We can sort the elements of array.

PHP Array Types

There are 3 types of array in PHP.

1. Indexed Array
2. Associative Array
3. Multidimensional Array

Web Programming
Gayatri Vidya Parishad College of Engineering (Autonomous)
Computer Science And Engineering
79
Gayatri Vidya Parishad College of Engineering (Autonomous)
Web Programming

PHP Functions

PHP function is a piece of code that can be reused many times. It can take
input as argument list and return value. There are thousands of built-in
functions in PHP.

In PHP, we can define Conditional function, Function within


Function and Recursive function also.

Advantage of PHP Functions

Code Reusability: PHP functions are defined only once and can be invoked
many times, like in other programming languages.

Less Code: It saves a lot of code because you don't need to write the logic
many times. By the use of function, you can write the logic only once and
reuse it.

Easy to understand: PHP functions separate the programming logic. So it is


easier to understand the flow of the application because every logic is
divided in the form of functions.

PHP User-defined Functions

We can declare and call user-defined functions easily. Let's see the syntax to
declare user-defined functions.

Syntax

Web Programming
Gayatri Vidya Parishad College of Engineering (Autonomous)
Computer Science And Engineering
80
Gayatri Vidya Parishad College of Engineering (Autonomous)
Web Programming

1. function functionname(){
2. //code to be executed
3. }

Note: Function name must be start with letter and underscore only like
other labels in PHP. It can't be start with numbers or special
symbols.

Example

File: function1.php
1. <?php
2. function sayHello(){
3. echo "Hello PHP Function";
4. }
5. sayHello();//calling function
6. ?>

Output:

Hello PHP Function

PHP Function Arguments

We can pass the information in PHP function through arguments which is


separated by comma.

PHP supports Call by Value (default), Call by Reference, Default


argument values and Variable-length argument list.

Let's see the example to pass single argument in PHP function.

File: functionarg.php
1. <?php
2. function sayHello($name){
Web Programming
Gayatri Vidya Parishad College of Engineering (Autonomous)
Computer Science And Engineering
81
Gayatri Vidya Parishad College of Engineering (Autonomous)
Web Programming

3. echo "Hello $name<br/>";


4. }
5. sayHello("Sonoo");
6. sayHello("Vimal");
7. sayHello("John");
8. ?>

Output:

Hello Sonoo
Hello Vimal
Hello John

Let's see the example to pass two argument in PHP function.

File: functionarg2.php
1. <?php
2. function sayHello($name,$age){
3. echo "Hello $name, you are $age years old<br/>";
4. }
5. sayHello("Sonoo",27);
6. sayHello("Vimal",29);
7. sayHello("John",23);
8. ?>

Output:

Hello Sonoo, you are 27 years old


Hello Vimal, you are 29 years old
Hello John, you are 23 years old

PHP Call By Reference

Value passed to the function doesn't modify the actual value by default (call
by value). But we can do so by passing value as a reference.
Web Programming
Gayatri Vidya Parishad College of Engineering (Autonomous)
Computer Science And Engineering
82
Gayatri Vidya Parishad College of Engineering (Autonomous)
Web Programming

By default, value passed to the function is call by value. To pass value as a


reference, you need to use ampersand (&) symbol before the argument
name.

Let's see a simple example of call by reference in PHP.

File: functionref.php
1. <?php
2. function adder(&$str2)
3. {
4. $str2 .= 'Call By Reference';
5. }
6. $str = 'Hello ';
7. adder($str);
8. echo $str;
9. ?>

Output:

Hello Call By Reference

PHP Function: Default Argument Value

We can specify a default argument value in function. While calling PHP


function if you don't specify any argument, it will take the default argument.
Let's see a simple example of using default argument value in PHP function.

File: functiondefaultarg.php
1. <?php
2. function sayHello($name="Sonoo"){
3. echo "Hello $name<br/>";
4. }
5. sayHello("Rajesh");
6. sayHello();//passing no value
7. sayHello("John");
8. ?>
Web Programming
Gayatri Vidya Parishad College of Engineering (Autonomous)
Computer Science And Engineering
83
Gayatri Vidya Parishad College of Engineering (Autonomous)
Web Programming

Output:

Hello Rajesh
Hello Sonoo
Hello John

PHP Function: Returning Value

Let's see an example of PHP function that returns value.

File: functiondefaultarg.php
1. <?php
2. function cube($n){
3. return $n*$n*$n;
4. }
5. echo "Cube of 3 is: ".cube(3);
6. ?>

Output:

Cube of 3 is: 27
PHP Form Handling

We can create and use forms in PHP. To get form data, we need to use PHP
superglobals $_GET and $_POST.

The form request may be get or post. To retrieve data from get request, we
need to use $_GET, for post request $_POST.

PHP Get Form

Get request is the default form request. The data passed through get request
is visible on the URL browser so it is not secured. You can send limited
amount of data through get request.
Web Programming
Gayatri Vidya Parishad College of Engineering (Autonomous)
Computer Science And Engineering
84
Gayatri Vidya Parishad College of Engineering (Autonomous)
Web Programming

Let's see a simple example to receive data from get request in PHP.

File: form1.html
1. <form action="welcome.php" method="get">
2. Name: <input type="text" name="name"/>
3. <input type="submit" value="visit"/>
4. </form>
File: welcome.php
1. <?php
2. $name=$_GET["name"];//receiving name field value in $name variabl
e
3. echo "Welcome, $name";
4. ?>

PHP Post Form

Post request is widely used to submit form that have large amount of data
such as file upload, image upload, login form, registration form etc.

The data passed through post request is not visible on the URL browser so it
is secured. You can send large amount of data through post request.

Let's see a simple example to receive data from post request in PHP.

File: form1.html
1. <form action="login.php" method="post">
2. <table>
3. <tr><td>Name:</td><td> <input type="text" name="name"/></td></t
r>
4. <tr><td>Password:</td><td> <input type="password" name="passwo
rd"/></td></tr>
5. <tr><td colspan="2"><input type="submit" value="login"/> </td></t
r>
6. </table>
7. </form>
File: login.php
1. <?php
Web Programming
Gayatri Vidya Parishad College of Engineering (Autonomous)
Computer Science And Engineering
85
Gayatri Vidya Parishad College of Engineering (Autonomous)
Web Programming

2. $name=$_POST["name"];//receiving name field value in $name varia


ble
3. $password=$_POST["password"];//receiving password field value in
$password variable
4.
5. echo "Welcome: $name, your password is: $password";
6. ?>

Output:

Web Programming
Gayatri Vidya Parishad College of Engineering (Autonomous)
Computer Science And Engineering
86
Gayatri Vidya Parishad College of Engineering (Autonomous)
Web Programming

PHP Cookie

PHP cookie is a small piece of information which is stored at client browser.


It is used to recognize the user.

Cookie is created at server side and saved to client browser. Each time when
client sends request to the server, cookie is embedded with request. Such
way, cookie can be received at the server side.

In short, cookie can be created, sent and received at server end.

Note: PHP Cookie must be used before <html> tag.

PHP setcookie() function

PHP setcookie() function is used to set cookie with HTTP response. Once
cookie is set, you can access it by $_COOKIE superglobal variable.

Syntax

1. bool setcookie ( string $name [, string $value [, int $expire = 0 [, strin


g $path
2. [, string $domain [, bool $secure = false [, bool $httponly = false ]]]]]]
)

Example
Web Programming
Gayatri Vidya Parishad College of Engineering (Autonomous)
Computer Science And Engineering
87
Gayatri Vidya Parishad College of Engineering (Autonomous)
Web Programming

1. setcookie("CookieName", "CookieValue");/* defining name and value


only*/
2. setcookie("CookieName", "CookieValue", time()+1*60*60);//using ex
piry in 1 hour(1*60*60 seconds or 3600 seconds)
3. setcookie("CookieName", "CookieValue", time()+1*60*60, "/mypath/
", "mydomain.com", 1);

PHP $_COOKIE

PHP $_COOKIE superglobal variable is used to get cookie.

Example

1. $value=$_COOKIE["CookieName"];//returns cookie value

PHP Cookie Example

File: cookie1.php
1. <?php
2. setcookie("user", "Sonoo");
3. ?>
4. <html>
5. <body>
6. <?php
7. if(!isset($_COOKIE["user"])) {
8. echo "Sorry, cookie is not found!";
9. } else {
10. echo "<br/>Cookie Value: " . $_COOKIE["user"];
11. }
12. ?>
13. </body>
14. </html>

Output:

Sorry, cookie is not found!

Web Programming
Gayatri Vidya Parishad College of Engineering (Autonomous)
Computer Science And Engineering
88
Gayatri Vidya Parishad College of Engineering (Autonomous)
Web Programming

Firstly cookie is not set. But, if you refresh the page, you will see cookie is
set now.

Output:

Cookie Value: Sonoo

PHP Delete Cookie

If you set the expiration date in past, cookie will be deleted.

File: cookie1.php
1. <?php
2. setcookie ("CookieName", "", time() - 3600);// set the expiration date
to one hour ago
3. ?>

PHP MySQL Connect

Since PHP 5.5, mysql_connect() extension is deprecated. Now it is


recommended to use one of the 2 alternatives.

o mysqli_connect()
o PDO::__construct()

PHP mysqli_connect()

PHP mysqli_connect() function is used to connect with MySQL database.


It returns resource if connection is established ornull.

Syntax
1. resource mysqli_connect (server, username, password)

Web Programming
Gayatri Vidya Parishad College of Engineering (Autonomous)
Computer Science And Engineering
89
Gayatri Vidya Parishad College of Engineering (Autonomous)
Web Programming

PHP mysqli_close()

PHP mysqli_close() function is used to disconnect with MySQL database. It


returns true if connection is closed or false.

Syntax
1. bool mysqli_close(resource $resource_link)

PHP MySQL Connect Example

Example
1. <?php
2. $host = 'localhost:3306';
3. $user = '';
4. $pass = '';
5. $conn = mysqli_connect($host, $user, $pass);
6. if(! $conn )
7. {
8. die('Could not connect: ' . mysqli_error());
9. }
10. echo 'Connected successfully';
11. mysqli_close($conn);
12. ?>

Output:

Connected successfully

Web Programming
Gayatri Vidya Parishad College of Engineering (Autonomous)
Computer Science And Engineering
90

Vous aimerez peut-être aussi