Web Technology Notes Download
Web Technology Notes Download
com
om
Objectives:
Giving the students the insights of the Internet programming and how to design and
implement complete applications over the web.
It covers the notions of Web servers and Web Application Servers, Design Methodologies
with concentration on Object-Oriented concepts, Client-Side
Programming, Server-Side Programming, Active Server Pages, Database Connectivity to
.c
web applications, Adding Dynamic content to web applications,
Programming Common Gateway Interfaces, Programming the User Interface for the web
applications.
ul
UNIT I:
Web Basics and Overview: Introduction to Internet, World Wide Web, Web Browsers, URL,
pa
MIME, HTTP, Web Programmers Tool box.
HTML Common tags: List, Tables, images, forms, frames, Basics of CSS and types of CSS.
Client-Side Programming (Java Script): Introduction to Java Script, declaring variables,
functions, Event handlers (onclick, onsubmit, etc.,) and Form Validation.
UNIT II:
jin
Server-Side Programming (PHP): Declaring Variables, Data types, Operators, Control
structures, Functions, Reading data from web form controls like text buttons, radio buttons, list,
etc., Handling File Uploads, Handling Sessions & Cookies.
Introduction to XML: Document type definition, XML Schemas, Document Object model,
.re
Presenting XML , Introduction to XHTML, Using XML Processors: DOM and SAX.
UNIT III:
Web Servers and Servlets: Tomcat web server, Installing the Java Software Development Kit,
Tomcat Server & Testing Tomcat.
Introduction to Servlets: Lifecycle of a Servlet, JSDK, Deploying Servlet, The Servlet API,
w
The javax. Servlet Package, Reading Servlet 150 parameters, Reading Initialization parameters.
The javax.servlet HTTP package, Handling Http Request & Responses, Using Cookies-Session
Tracking.
w
UNIT IV:
Introduction to JSP: The Problem with Servlet. The Anatomy of a JSP Page, JSP Process ing.
w
JSP Application Design with MVC Setting Up and JSP Environment, JSP Declarations,
Directives, Expressions, Code Snipplets, implement objects, Requests, Using Cookies and
Session for Session Tracking.
UNIT V:
Database Access: Database Programming using JDBC, JDBC drivers, Studying Javax.sql.*
package, Connecting to database in PHP, Execute Simple Queries, Accessing a Database from a
Servlet and JSP page.
Java Beans: Introduction to Beans, Deploying java Beans in a JSP page.
www.rejinpaul.com
TEXT BOOKS:
om
REFERENCE BOOKS:
1. Programming world wide web-Sebesta, Pearson Education ,2007.
2. Core SERVLETS ANDJAVASERVER PAGES VOLUME 1: CORE TECHNOLOGIES By Marty Hall and
Larry Brown Pearson
3. Internet and World Wide Web – How to program by Dietel and Nieto PHI/Pearson Education
.c
Asia.
4. Jakarta Struts Cookbook, Bill Siggelkow, S P D O’Reilly for chap 8.
5. March’s beginning JAVA JDK 5, Murach, SPD
6. An Introduction to Web Design and Programming –Wang-Thomson
ul
OUTCOMES: pa
Analyze a web page and identify its elements and attributes.
Create web pages using XHTML and Cascading Styles sheets.
Installation and usage of Server software’s.
Database Connectivity to web applications
jin
Build web applications using Servlet and JSP
.re
w
w
w
www.rejinpaul.com
INDEX
UNIT NO TOPIC PAGE NO
om
HTML common tags 07 – 16
I
Cascading Style Sheets 17 – 19
.c
Server-Side Programming (PHP) 33 - 59
II
Introduction to XML 60 - 86
ul
Web Servers and Se rvlets 87 - 88
III
Introduction to Servlets 89 - 112
pa
Introduction to JSP 113 - 116
IV
JSP ELEMENTS 116 - 126
jin
Database Access 127 - 133
V
Java Beans 134 - 136
.re
w
w
w
www.rejinpaul.com
Web Technologies III B.Tech II Sem (R15)
UNIT - I
Web Basics and Overview: Introduction to Internet, World Wide Web, Web Browsers, URL, MIME, HTTP,
Web Programmers Tool box.
om
HTML Common tags: List, Tables, images, forms, frames, Basics of CSS and types of CSS.
Client-Side Programming (Java Script): Introduction to Java Script, declaring variables, functions, Event
handlers (onclick, onsubmit, etc.,) and Form Validation.
.c
communication protocols. "the guide is also available on the Internet"
The Internet is the global system of interconnected computer networks that use the Internet
ul
protocol suite (TCP/IP) to link devices worldwide. It is a network of networks that consists of
private, public, academic, business, and government networks of local to global scope, linked by
a broad array of electronic, wireless, and optical networking technologies. The Internet carries a
vast range of information resources and services.
pa
History of Internet
This marvelous tool has quite a history that holds its roots in the cold war scenario. A
need was realized to connect the top universities of the United States so that they can share all
the research data without having too much of a time lag. This attempt was a result of Advanced
jin
Research Projects Agency (ARPA) which was formed at the end of 1950s just after the Russians
had climbed the space era with the launch of Sputnik. After the ARPA got success in 1969, it
didn‘t take the experts long to understand that how much potential can this interconnection tool
have. In 1971 Ray Tomlinson made a system to send electronic mail. This was a big step in the
.re
making as this opened gateways for remote computer accessing i.e. telnet.
During all this time, rigorous paper work was being done in all the elite research
institutions. From giving every computer an address to setting out the rules, everything was
getting penned down. 1973 saw the preparations for the vital TCP/IP and Ethernet services. At
the end of 1970s, Usenet groups had surfaced up. By the time the 80s had started, IBM came up
w
with its PC based on Intel 8088 processor which was widely used by students and universities for
it solved the purpose of easy computing. By 1982, the Defense Agencies made the TCP/IP
compulsory and the term ―internet‖ was coined. The domain name services arrived in the year
w
1984 which is also the time around which various internet based marked their debut. A worm, or
a rust the computers, attacked in 1988 and disabled over 10% of the computer systems all over
the world. While most of the researchers regarded it as an opportunity to enhance computing as it
w
was still in its juvenile phase, quite a number of computer companies became interested in
dissecting the cores of the malware which resulted to the formation Computer Emergency
Rescue Team (CERT). Soon after the world got over with the computer worm, World Wide Web
came into existence. Discovered by Tim Berners-Lee, World Wide Web was seen as a service to
connect documents in websites using hyperlinks.
om
outside CERN in 1991, first to other research institutions starting in January 1991 and to the
general public on the Internet in August 1991.
The World Wide Web has been central to the development of the Information Age and is
the primary tool billions of people use to interact on the Internet. Web pages are primarily text
documents formatted and annotated with Hypertext Markup Language (HTML). In addition to
formatted text, web pages may contain images, video, audio, and software components that are
.c
rendered in the user's web browser as coherent pages of multimedia content.
Embedded hyperlinks permit users to navigate between web pages. Multiple web pages
with a common theme, a common domain name, or both, make up a website. Website content
can largely be provided by the publisher, or interactively where users contribute content or the
ul
content depends upon the users or their actions. Websites may be mostly informative, primarily
for entertainment, or largely for commercial, governmental, or non-governmental organizational
purposes pa
jin
.re
WWW is another example of client/server computing. Each time a link is followed, the client is
requesting a document (or graphic or sound file) from a server (also called a Web server) that's
part of the World Wide Web that "serves" up the document. The server uses a protocol called
HTTP or Hyper Text Transport Protocol. The standard for creating hypertext documents for the
w
WWW is Hyper Text Markup Language or HTML. HTML essentially codes plain text
documents so they can be viewed on the Web.
w
Browsers :
WWW Clients, or "Browser": The program you use to access the WWW is known as a
browser because it "browses" the WWW and requests these hypertext documents. Browsers can
w
text-only browsers (i.e., those with no sound or graphics capability) are also available. All of
these programs understand http and other Internet protocols such as FTP, gopher, mail, and
news, making the WWW a kind of "one stop shopping" for Internet users.
om
1994 Minuet
Internet Explorer 1, Internet Explorer 2, Netscape Navigator 2.0, OmniWeb, UdiWWW,
1995 Grail
Arachne 1.0, Internet Explorer 3.0, Netscape Navigator 3.0, Opera 2.0,
1996 PowerBrowser 1.5,[4] Cyberdog, Amaya 0.9,[5] AWeb, Voyager
.c
Internet Explorer 4.0, Netscape Navigator 4.0, Netscape Communicator 4.0, Opera
1997 3.0,[6] Amaya 1.0[5]
1998 iCab, Mozilla
ul
1999 Amaya 2.0,[5] Mozilla M3, Internet Explorer 5.0
2000 Konqueror, Netscape 6, Opera 4,[7] Opera 5,[8] K-Meleon 0.2, Amaya 3.0,[5] Amaya 4.0[5]
2001 Internet Explorer 6, Galeon 1.0, Opera 6,[9] Amaya 5.0[5]
pa
2002 Netscape 7, Mozilla 1.0, Phoenix 0.1, Links 2.0, Amaya 6.0,[5] Amaya 7.0[5]
2003 Opera 7,[10] Apple Safari 1.0, Epiphany 1.0, Amaya 8.0[5]
2004 Firefox 1.0, Netscape Browser, OmniWeb 5.0
Opera 8,[11] Apple Safari 2.0, Netscape Browser 8.0, Epiphany 1.8, Amaya 9.0,[5] AOL
jin
2005 Explorer 1.0, Maxthon 1.0,Shiira 1.0
Mozilla Firefox 2.0, Internet Explorer 7, Opera 9,[12], SeaMonkey 1.0, K-Meleon 1.0,
2006 Galeon 2.0, Camino 1.0, Avant11, iCab 3
2007 Apple Safari 3.0, Maxthon 2.0, Netscape Navigator 9, NetSurf 1.0, Flock 1.0, Conkeror
.re
Google Chrome 1, Mozilla Firefox 3, Opera 9.5,[13], Apple Safari 3.1, Konqueror 4, Amaya
2008 10.0,[5] Flock 2, Amaya 11.0[5]
Google Chrome 2–3, Mozilla Firefox 3.5, Internet Explorer 8, Opera 10,[14], Apple Safari 4,
2009 SeaMonkey 2, Camino 2,surf, Pale Moon 3.0[15]
w
Google Chrome 4–8, Mozilla Firefox 3.6, Opera 10.50,[16], Opera 11, Apple Safari 5, K-
2010 Meleon 1.5.4,
Google Chrome 9–16, Mozilla Firefox 4-9, Internet Explorer 9, Opera 11.50, Apple
2011
Safari 5.1, Maxthon 3.0, SeaMonkey 2.1–2.6
w
Google Chrome 17–23, Mozilla Firefox 10–17, Internet Explorer 10, Opera 12, Apple
2012
Safari 6, Maxthon 4.0, SeaMonkey 2.7-2.14
Google Chrome 24–31, Mozilla Firefox 18–26, Internet Explorer 11, Opera 15–18, Apple
w
Google Chrome 48–55, Mozilla Firefox 44–50, Microsoft Edge 14, Opera 35–42, Apple
2016 Safari 10, SeaMonkey 2.24–2.30, Pale Moon 26.0.0[17], Pale Moon 27.0.0[18]
Google Chrome 56–60, Microsoft Edge 15, Mozilla Firefox 51–55.0.2, Opera 43–45, Opera
2017 Neon
Uniform Resource Locators, or URLs: A Uniform Resource Locator, or URL is the address of
om
a document found on the WWW. Browser interprets the information in the URL in order to
connect to the proper Internet server and to retrieve your desired document. Each time a click on
a hyperlink in a WWW document instructs browser to find the URL that's embedded within the
hyperlink.
The elements in a URL: Protocol://server's address/filename
.c
Hypertext protocol: http://www.aucegypt.edu
File Transfer Protocol: ftp://ftp.dartmouth.edu
Telnet Protocol: telnet://pac.carl.org
ul
News Protocol: news:alt.rock-n-roll.stones
What are Domains? Domains divide World Wide Web sites into categories based on the nature
of their owner, and they form part of a site's address, or uniform resource locator (URL).
Common top- level domains are:
pa
.com—commercial enterprises .mil—military site
org—organization site (non-profits, int—organizations established by
jin
etc.) international treaty
.net—network .biz—commercial and personal
.edu—educational site (universities, .info—commercial and personal
.re
schools, etc.)
.gov—government organizations .name—personal sites
Additional three- letter, four- letter, and longer top- level domains are frequently added.
Each country linked to the Web has a two- letter top- level domain, for example .fr is France, .ie is
w
Ireland.
MIME (Multi-Purpose Internet Mail Extensions):- MIME is an extension of the
original Internet e- mail protocol that lets people use the protocol to exchange different kinds of
w
data files on the Internet: audio, video, images, application programs, and other kind s, as well as
the ASCII text handled in the original protocol, the Simple Mail Transport Protocol (SMTP). In
w
1991, Nathan Borenstein of Bellcore proposed to the IETF that SMTP be extended so that
Internet (but mainly Web) clients and servers could recognize and handle other kinds of data
than ASCII text. As a result, new file types were added to "mail" as a supported Internet Protocol
file type.
Servers insert the MIME header at the beginning of any Web transmission. Clients use
this header to select an appropriate "player" application for the type of data the header indicates.
Some of these players are built into the Web client or browser (for example, all browsers come
with GIF and JPEG image players as well as the ability to handle HTML files); other players
may need to be downloaded.
New MIME data types are registered with the Internet Assigned Numbers Authority
om
(IANA).
MIME is specified in detail in Internet Request for Comments 1521 and 1522, which
amend the original mail protocol specification, RFC 821 (the Simple Mail Transport Protocol)
and the ASCII messaging header, RFC 822.
.c
HTTP means HyperText Transfer Protocol. HTTP is the underlying protocol used by the World
Wide Web and this protocol defines how messages are formatted and transmitted, and what
actions Web servers and browsers should take in response to various commands.
ul
For example, when you enter a URL in your browser, this actually sends an HTTP command to
the Web server directing it to fetch and transmit the requested Web page. The other main
standard that controls how the World Wide Web works is HTML, which covers how Web pages
pa
are formatted and displayed.
HTTP is called a stateless protocol because each command is executed independently, without
any knowledge of the commands that came before it. This is the main reason that it is difficult to
implement Web sites that react intelligently to user input.
jin
HTTPS: A similar abbreviation, HTTPS means Hyper Text Transfer Protocol Secure.
Basically, it is the secure version of HTTP. Communications between the browser and website
are encrypted by Transport Layer Security (TLS), or its predecessor, Secure Sockets Layer
(SSL).
.re
Plug ins
o Integrated into tools like word processors, effectively converting them to
WYSIWYG HTML editors
Filters
o Convert documents in other formats to HTML
om
o You have two versions of the document, which are difficult to synchronize
XML
o A meta-markup language (a language for defining markup language)
o Used to create a new markup language for a particular purpose or area
o Because the tags are designed for a specific area, they can be meaningful
JavaScript
.c
o A client-side HTML-embedded scripting language
o Provides a way to access elements of HTML documents and dynamically change
them
Flash
ul
o A system for building and displaying text, graphics, sound, interactivity, and
animation (movies)
o Two parts: pa
1. Authoring environment
2. Player
Supports both motion and shape animation
PHP
A server-side scripting language
jin
Great for form processing and database access through the Web
Ajax
Asynchronous JavaScript + XML
No new technologies or languages
Much faster for Web applications that have extensive user/server interactions
.re
Ruby
A pure object-oriented interpreted scripting language
Every data value is an object, and all operations are via method calls
w
om
HTML stands for Hyper Text Markup Language
An HTML file is a text file containing small markup tags
The markup tags tell the Web browser how to display the page
An HTML file must have an htm or html file extension.
HTML Tags:- HTML tags are used to mark-up HTML elements .HTML tags are surrounded by the two
.c
characters < and >. The surrounding characters are called angle brackets. HTML tags normally come in
pairs like and The first tag in a pair is the start tag, the second tag is the end tag . The text between the
start and end tags is the element content . HTML tags are not case sensitive, <B>means the same as <b>.
The most important tags in HTML are tags that define headings, paragraphs and line breaks.
ul
Tag Description
<!DOCTYPE...> This tag defines the document type and HTML version.
pa
<html> This tag encloses the complete HTML document and mainly comprises of
document header which is represented by <head>...</head> and document
body which is represented by <body>...</body> tags.
<head> This tag represents the document's header which can keep other HTML tags
like <title>, <link> etc.
<title> The <title> tag is used inside the <head> tag to mention the document title.
jin
<body> This tag represents the document's body which keeps other HTML tags like
<h1>, <div>, <p> etc.
<p> This tag represents a paragraph.
.re
Headings:-
w
Headings are defined with the <h1> to <h6> tags. <h1> defines the largest heading while <h6>
defines the smallest.
<h1>This is a heading</h1>
w
<h2>This is a heading</h2>
<h3>This is a heading</h3>
<h4>This is a heading</h4>
<h5>This is a heading</h5>
<h6>This is a heading</h6>
Paragraphs:-
Paragraphs are defined with the <p> tag. Think of a paragraph as a block of text. You can use the
align attribute with a paragraph tag as well.
om
Note: You must indicate paragraphs with <p> elements. A browser ignores any
indentations or blank lines in the source text. Without <p> elements, the document becomes
one large paragraph. HTML automatically adds an extra blank line before and after a paragraph.
Line Breaks:-
.c
The <br> tag is used when you want to start a new line, but don't want to start a new paragraph.
The <br> tag forces a line break wherever you place it. It is similar to single spacing in a
document.
ul
This Code output
<p>This <br> is a para<br> graph with This
is a para
line breaks</p> pa graph with line breaks
Horizontal Rule The element is used for horizontal rules that act as dividers between sections
like this:
The horizontal rule does not have a closing tag. It takes attributes such as align and width
jin
Code Output
<hr width="50%" align="center">
<!DOCTYPE html>
<html>
<head>
<title>This is document title
</title>
w
</head>
<body>
<h1>This is a heading</h1>
<p>Document content goes here.....</p>
w
</body>
</html>
w
Type the above program in notepad and save with some file name eg:sample.html
Open the file with browser and the webpage looks like this
Lists:-HTML offers web authors three ways for specifying lists of information.
All lists must contain one or more list elements. Lists are of three types
1)Un ordered list
2)Ordered List
3)Definition list
om
HTML Unordered Lists:An unordered list is a collection of related items that have no
special order or sequence. This list is created by using HTML <ul> tag. Each item in the list is
marked with a bullet.
Example
<!DOCTYPE html>
.c
<html>
<head>
<title>HTML Unordered List</title>
</head>
ul
<body>
<ul> <li>Beetroot</li>
<li>Ginger</li> <li>Potato</li>
pa
<li>Radish</li>
</ul>
</body>
</html>
jin
HTML Ordered Lists:- items are numbered list instead of bulleted, This list is created
by using <ol> tag.
.re
<!DOCTYPE html>
<html>
<head>
<title>HTML Ordered List</title>
</head>
<body>
w
<ol>
<li>Beetroot</li>
<li>Ginger</li>
w
<li>Potato</li>
<li>Radish</li>
</ol>
w
</body>
</html>
HTML Definition Lists:- HTML and XHTML supports a list style which is called
definition lists where entries are listed like in a dictionary or encyclopedia. The definition list is
the ideal way to present a glossary, list of terms, or other name/value list. Definition List makes
use of following three tags.
1). <dl> - Defines the start of the list
2). <dt> - A term
om
3).<dd> - Term definition
4). </dl> - Defines the end of the list
<!DOCTYPE html>
<html>
<head>
.c
<title>HTML Definition List</title>
</head>
<body>
ul
<dl>
<dt><b>HTML</b></dt> <dd>This stands for Hyper Text Markup Language</dd>
<dt><b>HTTP</b></dt> <dd>This stands for Hyper Text Transfer Protocol</dd>
</dl> pa
</body>
</html>
HTML tables:
The HTML tables allow web authors to arrange data like text, images, links, other tables, etc.
jin
into rows and columns of cells. The HTML tables are created using the <table> tag in which the
<tr> tag is used to create table rows and <td> tag is used to create data cells.
Example:
.re
<!DOCTYPE html>
<html>
<head>
<title>HTML Tables</title>
</head>
w
<body>
<table border="1">
<tr>
<td>Row 1, Column 1</td> <td>Row 1, Column 2</td>
w
</tr>
<tr> <td>Row 2, Column 1</td> <td>Row 2, Column 2</td>
</tr>
w
</table>
</body>
</html>
Table Heading: Table heading can be defined using <th> tag. This tag will be put to replace
<td> tag, which is used to represent actual data cell. Normally you will put your top row as table
heading as shown below, otherwise you can use <th> element in any row.
Tables Backgrounds: set table background using one of the following two ways:
1)bgcolor attribute - You can set background color for whole table or just for one cell.
2)background attribute - You can set background image for whole table or just for one cell. You
om
can also set border color also using bordercolor attribute.
<!DOCTYPE html>
<html>
<head>
.c
<title>HTML Tables</title> </head>
<body>
<table border="1"bordercolor="red" bgcolor="yellow">
<tr> <th>Name</th>
ul
<th>Salary</th> </tr>
<td>Jayapal </td> <td>50,000.00</td>
</tr> pa
<tr> <td>Ravi</td> <td>45,000.00</td>
</tr>
</table>
</body>
</html>
jin
Images are very important to beautify as well as to depict many complex concepts in simple way
on your web page.
Insert Image:
.re
Attribute Values
w
Value Description
Example
<!DOCTYPE html>
<html>
<head>
<title>Using Image in Webpage</title>
om
</head>
<body> <p>Simple Image Insert</p>
<img src="test.png" alt="Test Image" />
</body>
</html>
.c
HTML FORMS:
HTML Forms are required to collect some data from the site visitor. For example, during
user registration you would like to collect information such as name, email address, credit card,
etc. A form will take input from the site visitor and then will post it to a back-end application
ul
such as CGI, ASP Script or PHP script etc. The back-end application will perform required
processing on the passed data based on defined business logic inside the application. There are
various form elements available like text fields, text area fields, drop-down menus, radio buttons,
pa
checkboxes, etc.
<form action="Script URL" method="GET|POST"> form elements like input, text area etc. </form>
jin
.re
w
w
w
om
Select Box Controls
File Select boxes
Hidden Controls
Clickable Buttons
Submit and Reset Button
.c
Text Input Controls:-
There are three types of text input used on forms:
1)Single-line text input controls - This control is used for items that require only one
line of user input, such as search boxes or names. They are created using HTML
ul
<input> tag.
<form>
First name:<br>
jin
<input type="text" name="firstname"><br>
Last name:<br>
<input type="text" name="lastname">
</form>
.re
2)Password input controls - This is also a single- line text input but it masks the character as
soon as a user enters it. They are also created using HTML <input> tag.
Input Type Password
w
<form>
User name:<br>
w
3)Multi-line text input controls - This is used when the user is required to give details that may
be longer than a single sentence. Multi- line input controls are created using HTML
<textarea> tag.
<!DOCTYPE html>
<html>
om
<head>
<title>Multiple-Line Input Control</title>
</head>
<body>
<form> Description: <br />
<textarea rows="5" cols="50" name="description"> Enter description here... </textarea>
.c
</form>
</body>
</html>
ul
Checkboxes Controls:-
Checkboxes are used when more than one option is required to be selected. They are also
created using HTML <input> tag but type attribute is set to checkbox.
pa
Here is an example HTML code for a form with two checkboxes:
<!DOCTYPE html>
<html> <head> <title>Checkbox Control</title> </head>
<body>
jin
<form>
<input type="checkbox" name="C++" value="on"> C++
<br>
<input type="checkbox" name="C#" value="on"> C#
.re
<br>
<input type="checkbox" name="JAVA" value="on"> JAVA
</form>
</body> </html>
Radio buttons are used when out of many options, just one option is required to be selected.
They are also created using HTML <input> tag but type attribute is set to radio.
w
<!DOCTYPE ht ml>
<html> <head> <tit le>Radio Bo x Control</tit le> </head>
<body> <p>Select a Course</p>
<form>
w
Select Box Controls :- A s elect box, also called drop down box which provides option to
list down various options in the form of drop down list, from where a user can select one or
more options.
<!DOCTYPE ht ml>
<html>
om
<head>
<title>Select Bo x Control</title>
</head>
<body>
<form>
<select name="dropdown">
<option value="C++" selected>C++</option>
<option value="JAVA">JA VA</option>
.c
<option value="HTM L">HTM L</option>
</select>
</form>
</body>
ul
</html>
File Select boxes:- If you want to allow a user to upload a file to your web site, you will
need to use a file upload box, also known as a file select box. This is also created using the
pa
<input > element but type attribute is set to file.
<!DOCTYPE ht ml>
<html>
jin
<head>
<title>File Upload Bo x</tit le>
</head>
<body>
<p>File Up load Bo x</p>
<form>
.re
Hidden Controls:- Hidden form controls are used to hide data inside the page which later on
w
can be pushed to the server. This control hides inside the code and does not appear on the
actual page. For example, following hidden form is being used to keep current page
number. When a user will click next page then the value of hidden control will be sent to the
web server and there it will decide which page will be displayed next based on the passed
w
current page.
<form>
<p>Th is is page 10</p>
<input type="hidden" name="pagename" value="10" />
<input type="submit" name="submit" value="Sub mit" />
<input type="reset" name="reset" value="Reset" />
</form> </body> </ht ml>
om
Button Controls:-
There are various ways in HTML to create clickable buttons. You can also create a clickable
button using <input> tag by setting its type attribute to button. The type attribute can take the
following values:
.c
ul
pa
jin
<!DOCTYPE html>
<html>
<head>
<title>File Upload Box</title>
</head>
.re
<body>
<form>
<input type="submit" name="submit" value="Submit" />
<input type="reset" name="reset" value="Reset" />
<input type="button" name="ok" value="OK" />
w
HTML frames: These are used to divide your browser window into multiple sections where
each section can load a separate HTML document. A collection of frames in the browser window
is known as a frameset. The window is divided into frames in a similar way the tables are
w
<frameset cols="25%,50%,25%">
<frame src="frame_a.htm">
om
<frame src="frame_b.htm">
<frame src="frame_c.htm">
</frameset>
<!DOCTYPE html>
.c
<html>
<head>
<title>Page Title</title>
</head>
ul
<body>
<iframe src="sample1.html" height="400" width="400"frameborder="1">
<h1>This is a Heading</h1>
<p>This is a paragraph.</p> pa
</iframe>
</body>
</html>
This example sets the text color of the <h1> element to blue:
<body>
<h1 style="color:blue;">This is a Blue Heading</h1>
</body>
</html>
Inte rnal CSS: An internal CSS is used to define a style for a single HTML page. An internal
CSS is defined in the <head> section of an HTML page, within a <style> element:
<html>
<head>
<style>
body {background-color: powderblue;}
om
h1 {color: blue;}
p {color: red;}
</style>
</head>
<body>
<h1>This is a heading</h1>
.c
<p>This is a paragraph.</p>
</body>
</html>
ul
External CSS:-
An external style sheet is used to define the style for many HTML pages. With an external style
pa
sheet, you can change the look of an entire web site, by changing one file! To use an external
style sheet, add a link to it in the <head> section of the HTML page:
<html>
<head>
jin
<link rel="stylesheet" href="styles.css">
</head>
<body>
<h1>This is a heading</h1>
<p>This is a paragraph.</p>
.re
</body>
</html>
An external style sheet can be written in any text editor. The file must not contain any HTML
code, and must be saved with a .css extension.
w
h1 { color: blue; }
w
p { color: red; }
CSS Fonts: The CSS color property defines the text color to be used.
The CSS font-family property defines the font to be used.
The CSS font-size property defines the text size to be used.
<html>
<head>
om
<style>
h1 {
color: blue;
font-family: verdana;
font-size: 300%;
}
.c
p {
color: red;
font-family: courier;
font-size: 160%;
ul
}
</style>
</head>
<body>
<h1>This is a heading</h1>
<p>This is a paragraph.</p>
pa
</body>
</html>
jin
CSS Border: The CSS border property defines a border around an HTML element.
CSS Padding: The CSS padding property defines a padding (space) between the text and the
border.
.re
CSS Margin: The CSS margin property defines a margin (space) outside the border.
<html> <head>
<style>
h1 {
w
co lor: blue;
font-family : verdana;
font-size: 300%; }
p {
w
co lor: red; font-size: 160%; border: 2p x solid powderb lue; padding: 30p x; marg in: 50p x; }
</style>
</head>
<body>
w
<h1>This is a heading</h1>
<p>This is a paragraph.</p>
</body>
</html>
JavaScript:
What is JavaScript?
Java Script is one popular scripting language over internet. Scripting means a small sneak (piece). It is
always independent on other languages.
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
om
to the browser and it's up to the browser to do something with it.
Difference between JavaScript and Java
JavaScript Java
Cannot live outside a Web page Can build stand-alone applications or live in a
Web page as an applet.
.c
Doesn‘t need a compiler Requires a compiler
Knows all about your page Applets are dimly aware of your Web page.
Untyped Strongly typed
ul
Somewhat object-oriented Object-oriented
There are no relationship between in java & java script. Java Script is a scripting language that always
dependent in HTML language. It used to css commands. It is mainly used to creating DHTML pages &
validating the data. This is called client side validations.
pa
Why we Use JavaScript?
Using HTML we can only design a web page but you can not run any logic on web browser
like addition of two numbers, check any condition, looping statements (for, while), decision
making statement (if-else) at client side. All these are not possible using HTML So for perform
jin
all these task at client side you need to use JavaScript.
Features of JavaScript
JavaScript is a client side technology, it is mainly used for gives client side validation, but it have lot of
features which are given below;
.re
w
w
w
Inheritance is does not support in JavaScript, so it is called object based oriented language.
JavaScript was developed by Netscape (company name) & initially called live script.
Later Microsoft developed & adds some features live script then it is called “Jscript”.
om
Jscript is nothing but Java script. We cannot create own classes in java script.
Java script is mainly useful to improve designs of WebPages, validate form data at
.c
client side, detects (find) visitor‘s browsers, create and use to cookies, and much more.
Java script is also called light weight programming language , because Java script is
ul
return with very simple syntax. Java script is containing executable code.
Java script is also called interpreted language , because script code can be executed
An important part of JavaScript is the ability to create new functions within scripts.
Creating a java script: - html script tag is used to script code inside the html page.
<script> </script>
w
1) Language attribute : -
w
<script language=―JavaScript‖>
w
2) Type attribute : - It indicates MIME (multi purpose internet mail extension) type of scripting code. It
sets to an alpha-numeric MIME type of code.
<html> <html>
<head> <head>
om
<script type=―text / JavaScript‖> </head>
Script code here <body>
</script> <script type= ―text / JavaScript‖>
</head> Script code here
.c
<body> </script>
</body> </body>
</html> </html>
ul
Scripting in both head & body section: - we can create unlimited number of scripts inside the same
page. So we can locate multiple scripts in both head & body section of page.
Ex: - <html> pa
<head>
<script type=―text / JavaScript‖>
Script code here
</script>
</head>
<body>
jin
<script type=―text / JavaScript‖>
Script code here
</script>
</body>
</html>
.re
Program: -
<html>
<head>
<script language="JavaScript">
document.write("hai my name is Kalpana")
w
</script>
</head>
<body text="red">
<marquee>
w
<script language="JavaScript">
document.write("hai my name is Sunil Kumar Reddy")
</script> </marquee>
</body>
w
</html>
O/P: - hai my name is Kalpana
om
Reacts to events: - JavaScript can be set to execute when something happens. When the page is finished
loading in browser window (or) when the user clicks on html element dynamically.
Ex: -
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional // EN">
<HTML>
<HEAD>
.c
<script language="JavaScript">
function myf( )
{
document.write("Hai Kalpana")
ul
}
</script>
</HEAD>
<BODY> pa
to execute script code:
<input type="button" value="click me" onclick="myf( )">
To execute script code:
<input type="button" value="touch me" onmouseover="myf( )">
</BODY>
</HTML>
jin
O/P: - to execute script code: To execute script code:
Creating external script: - some times you might want to run same script on several pages without
having to write the script on each page. To simplify this, write external script & save .js extension. To use
.re
save: - external.js
document.write("this is external script code 1 "+"<br>");
w
<HTML> <BODY>
<script language="JavaScript">
document.write("this is document code 1 "+"<br>");
w
JavaScript syntax rules: - JavaScript is case sensitive language. In this upper case lower case letters
are differentiated (not same).
Ex: - a=20;
A=20;
Those the variable name „a‟ is different from the variable named „A‟.
Ex: - myf( ) // correct
om
myF( ) // incorrect
; is optional in general JavaScript.
Ex: - a=20 // valid
b=30 // valid
A=10; b=40; // valid
However it is required when you put multiple statements in the same line.
.c
JavaScript ignore white space. In java script white space, tag space & empty lines are not preserved.
To display special symbols we use \.
Comment lines: - comments lines are not executable.
ul
// single line comment
/* this is multi line comment */
pa
Declaring variable: - variable is a memory location where data can be stored. In java script variables
with any type of data are declared by using the keyword ‗var‘. All keywords are small letters only.
var a; a=20;
var str; str= “Sunil”;
var c; c=‟a‟;
jin
var d; d=30.7;
But the keyword is not mandatory when declare of the variable.
c; not valid. In this solution var keyword must be declared.
During the script, we can change value of variable as well as type of value of variable.
.re
Ex: -
a=20;
a=30.7;
JavaScript functions: - in java script functions are created with the keyword ‗function‘ as shown below
w
Generally we can place script containing function head section of web page. There are 2 ways to call the
function.
1) direct call function
w
Ex: -
<HTML> </HEAD>
<HEAD> <BODY>
<TITLE> Function direct call</TITLE> <script>
<script language="JavaScript"> var r=add(30,60)
function add(x,y) document.write("addition is :"+r);
om
{ </script>
z=x+y </BODY>
return z </HTML>
}
</script> O/P: - addition is :90
2 to add dynamical effects, java script provide a list of events that call function dynamically.
Hare each event is one attribute that always specified in html tags.
.c
attrname=”attrval”
eventName=”funname( )”
Ex: -
ul
<HTML> </HEAD>
<HEAD> <BODY> to call function:
<TITLE> Function dynamically</TITLE> <input type="button" value="click hare"
<script language="JavaScript">
pa onclick="add( )">
function add( ) </script>
{ </BODY>
x=20 </HTML>
y=30
z=x+y
jin
O/P: - to call function:
document.write("addition is :"+z);
addition is :90
}
</script>
EVENT HANDLERS: Events are not case sensitive.
.re
om
<HTML> <br>
<HEAD> <b onmousemove="add( )">
<TITLE> Mouse Events </TITLE> to call function cursor move here :
<script language="JavaScript"> </b>
function add() <br>
{ <b onmouseup="add( )">
a=55 to call function cursor up here :
.c
b=45 </b>
c=a+b <br>
document.write("addition is :"+c) <b onmouseout="add( )">
} to call function cursor out here :
ul
</script> </b>
</HEAD> </BODY>
<BODY> pa </HTML>
<b onclick="add( )">
to call function click here : O/P: -
</b> to call function click here :
<br> to call function touch here :
<b onmouseover="add( )"> to call function double click here :
addition is :100
jin
to call function touch here :
</b> to call function cursor move here :
<br> to call function cursor up here :
<b ondblclick="add( )"> to call function cursor out here :
to call function double click here :
.re
</b>
Program: -
<HTML>
<HEAD>
<TITLE> display student name </TITLE>
w
<script language="JavaScript">
function disp( )
{
w
if(name=""||!isNaN(name)||!isNaN(name.charAt(0)))
window.alert("sname you entered is invalid")
else
document.write("sname you have entered is : "+name);
}
</script>
</HEAD>
<BODY>
<form name="student">
Enter Student name:
<input type="text" name="sname"id="snameid" value="enter" onblur="disp( )">
</form>
om
</BODY>
</HTML>
O/P: -
1
Enter Student name:
.c
1
Enter Student name:
sname you have entered is : true
ul
Popup boxes: - popup (arises) box is a small window that always shown before opening the
page. The purpose of popup box is to write message, accept some thing from user. Java script
pa
provides 3 types of popup boxes. They are 1) alert 2) Confirm. 3) Prompt.
c=a+b </html>
O/P: -
w
w
Result is: 60
om
Ex: - document.write("result is :"+c)
<HTML> }
<HEAD> else
<TITLE> Confirm </TITLE> {
<script> document.write("you clicked cancel button")
function sub( ) }
.c
{ }
a=50 </script>
b=45 </HEAD>
c=a-b <BODY onload="sub( )">
ul
x=window.confirm("Do you want to see to see the o/p in pop up box:
subtraction of numbers") </BODY>
if(x==true) pa </HTML>
{
O/P: -
to see the o/p in pop up box:
jin
result is :5
3) Prompt popup box:- It is useful to accept data from keyboard at runtime. Prompt box is
created by prompt method of window object.
window.prompt (“message”, “default text”);
.re
When prompt dialog box arises user will have to click either ok button or cancel button after
entering input data to proceed. If user click ok button it will return input value. If user click
cancel button the value ―null‖ will be returned.
Ex: -
<HTML> {
<HEAD> a=a*i
w
{ </script>
var b=window.prompt("enter +ve integer </HEAD>
:","enter here") <BODY onload="fact( )">
w
O/P: -
FORM VALIDATION:
When we create forms, providing form validation is useful to ensure that your customers enter valid and
complete data. For example, you may want to ensure that someone inserts a valid e-mail address into a
text box, or perhaps you want to ensure that someone fills in certain fields.
We can provide custom validation for your forms in two ways: server-side validation and client-side
validation.
om
SERVER-SIDE VALIDATION
In the server-side validation, information is being sent to the server and validated using one of server-side
languages. If the validation fails, the response is then sent back to the client, page that contains the web
form is refreshed and a feedback is shown. This method is secure because it will work even if JavaScript
is turned off in the browser and it can‘t be easily bypassed by malicious users. On the other hand, users
.c
will have to fill in the information without getting a response until they submit the form. This results in a
slow response from the server.
The exception is validation using Ajax. Ajax calls to the server can validate as you type and provide
ul
immediate feedback. Validation in this context refers to validating rules such as username availability.
Server side validation is performed by a web server, after input has been sent to the server.
pa
CLIENT-SIDE VALIDATION
Server-side validation is enough to have a successful and secure form validation. For better user
experience, however, you might consider using client-side validation. This type of validation is done on
the client using script languages such as JavaScript. By using script languages user‘s input can be
jin
validated as they type. This means a more responsive, visually rich validation.
With client-side validation, form never gets submitted if validation fails. Validation is being handled in
JavaScript methods that you create (or within frameworks/plugins) and users get immediate feedback if
.re
validation fails.
Main drawback of client-side validation is that it relies on JavaScript. If users turn JavaScript off, they
can easily bypass the validation. This is why validation should always be implemented on both the client
and server. By combining server-side and client-side methods we can get the best of the two: fast
response, more secure validation and better user experience.
w
Client side validation is performed by a web browser, before input is sent to a web server.
w
Validation can be defined by many different methods, and deployed in many different ways.
Simple Example:
w
<html>
<head>
<title>Form Validation</title>
<script type="text/javascript">
<!--
// Form validation code will come here.
function validate()
{
var n = document.myForm.Name.value;
if( n == "" || (!isNaN(parseInt(n))) || n.length < 3 || n.length >= 8)
om
{
alert( "Please enter valid name and minimum length 3 characters and maximum length 8
characters !" );
document.myForm.Name.focus();
return false;
.c
}
ul
{
alert( "Please provide your Email!" );
document.myForm.EMail.focus() ; pa
return false;
}
atpos = emailID.indexOf("@");
jin
dotpos = emailID.lastIndexOf(".");
if (atpos < 1 || ( dotpos - atpos < 2 ))
{
alert("Please enter correct email ID")
.re
document.myForm.EMail.focus() ;
return false;
}
var z = document.myForm.Zip.value;
w
document.myForm.Zip.focus() ;
return false;
}
w
var c = document.myForm.Country.value;
if( c == "-1" )
{
om
//-->
</script>
</head>
<body bgcolor="bisque">
<h1><p align="center"> <b>Application Form Validation Using JavaScript</b></p></h1>
.c
<form action="reg.html" name="myForm" onsubmit="return(validate());">
<table cellspacing="5" cellpadding="5" align="center" border="5" width="438">
<tr>
<td align="right"><b>Name</b></td>
ul
<td><input type="text" name="Name" size="50" /></td>
</tr>
<tr> pa
<td align="right"><b>EMail</b></td>
<td><input type="text" name="EMail" size="50" /></td>
</tr>
<tr>
jin
<td align="right"><b>Zip Code</b></td>
<td><input type="text" name="Zip" size="50" /></td>
</tr>
<tr>
.re
<option value="2">UK</option>
<option value="3">USA</option>
</select>
w
</td>
</tr>
<tr>
w
<td align="right"></td>
<td><input type="submit" value="Submit" /></td>
</tr>
</font> </table> </form> </body> </html>
Output:
om
.c
ul
pa
jin
.re
w
w
w
UNIT – II
TOPICS:
Introduction to PHP Introduction to XML
Declaring Variables Basic XML document
Data Types Presenting XML
om
Operators Document Type Definition(DTD)
Control Structures XML Schemas
Functions Document Object Model(DOM)
Reading data from WEB form controls Introduction to XHTML
like text boxes, radio buttons, lists etc.. Using XML Processors: DOM and SAX
Handling File Uploads
.c
Handling Sessions and Cookies
PHP INTRODUCTION
ul
PHP started out as a small open source project that evolved as more and more people found out
how useful it was. Ras mus Lerdorf unleashed the first version of PHP way back in 1994.
pa
PHP is a recursive acronym for "PHP: Hypertext Preprocessor".
PHP is a server side scripting language that is embedded in HTML. PHP scripts are executed
on the server
jin
It is used to manage dynamic content, databases, session tracking, even build entire e-
commerce sites.
PHP supports many databases (MySQL, Informix, Oracle, Sybase, Solid, PostgreSQL, Generic
ODBC, Microsoft SQL Server , etc.)
PHP is an open source software.
.re
PHP is pleasingly zippy in its execution, especially when compiled as an Apache module on the
Unix side. The MySQL server, once started, executes even very complex queries with huge
result sets in record-setting time.
PHP supports a large number of major protocols such as POP3, IMAP, and LDAP.
PHP is forgiving: PHP language tries to be as forgiving as possible.
w
You add, delete, and modify elements within your database thru PHP.
Access cookies variables and set cookies.
Using PHP, you can restrict users to access some pages of your website.
It can encrypt data.
Characteristics of PHP:
Simplicity
Efficiency
Security
Flexibility
om
Familiarity
All PHP code must be included inside one of the three special markup tags are recognized by the
PHP Parser.
.c
<script language="php"> PHP code goes here </script>
Most common tag is the <?php...?>
SYNTAX OVERVIEW:
ul
Canonical PHP tags The most universally effective PHP tag style is:
<?php...?>
<?...?>
pa
Short-open (SGML-style) tags Short or short-open tags look like this:
<?php
$txt="HelloWorld!";
$x=16;
?>
om
A variable name must start with a letter or an underscore "_"
A variable name can only contain alpha- numeric characters and underscores (a-z, A-Z,
0-9, and _ )
A variable name should not contain spaces. If a variable name is more than one word, it
should be separated with an underscore ($my_string), or with capitalization/Camel notation
($myString)
.c
PHP Variables Scope
In PHP, variables can be declared anywhere in the script. The scope of a variable is the part of
the script where the variable can be referenced / used. PHP has three different variable scopes:
ul
local
global
static
Global and Local Scope
pa
A variable declared outside a function has a GLOBAL SCOPE and can only be accessed outside
a function:
Example
<?php
$x = 5; // global scope
jin
function myTest() {
// using x inside this function will generate an error
echo "<p>Variable x inside function is: $x</p>";
}
.re
myTest();
echo "<p>Variable x outside function is: $x</p>";
?>
A variable declared within a function has a LOCAL SCOPE and can only be accessed within
that function:
w
Example
<?php
function myTest() {
$x = 5; // local scope
w
om
function myTest() {
global $x, $y;
$y = $x + $y; }
myTest();
echo $y; // outputs 15
?>
.c
PHP also stores all global variables in an array called $GLOBALS[index]. The index holds the
name of the variable. This array is also accessible from within functions and can be used to
update global variables directly. The example above can be rewritten like this:
ul
Example
<?php
$x = 5;
$y = 10; pa
function myTest() {
$GLOBALS['y'] = $GLOBALS['x'] + $GLOBALS['y'];
}
myTest();
echo $y; // outputs 15
jin
?>
echo $x;
$x++;
}
w
myTest();
myTest();
myTest(); ?> Output: 0 1 2
w
Then, each time the function is called, that variable will still have the information it contained
from the last time the function was called.
Note: The variable is still local to the function.
Variable Naming
Rules for naming a variable is-
Variable names must begin with a letter or underscore character.
A variable name can consist of numbers, letters, underscores but you cannot use characters like
+ , - , % , ( , ) . & , etc
There is no size limit for variables.
om
PHP - Data Types:
PHP has a total of eight data types which we use to construct our variables:
Integers: are whole numbers, without a decimal point, like 4195.
Doubles: are floating-point numbers, like 3.14159 or 49.1. Scalar types
Booleans: have only two possible values either true or false.
.c
Strings: are sequences of characters, like 'PHP supports string operations.'
Arrays: are named and indexed collections of other values.
Objects: are instances of programmer-defined classes. Compound types
ul
NULL: is a special type that only has one value: NULL.
Resources: are special variables that hold references to resources external Special types
to PHP (such as database connections).
pa
The first four are simple types, and the next two (arrays and objects) are compound - the
compound types can package up other arbitrary values of arbitrary type, whereas the simple
types cannot.
PHP Integers
Integers are primitive data types. They are whole numbe rs, without a decimal point, like 4195.
jin
They are the simplest type. They correspond to simple whole numbers, both positive and
negative {..., -2, -1, 0, 1, 2, ...}.
Integer can be in decimal (base 10), octal (base 8), and hexadecimal (base 16) format. Decimal
format is the default, octal integers are specified with a leading 0, and hexadecimals have a
.re
leading 0x.
Ex: $v = 12345;
$var1 = -12345 + 12345;
notation.php
<?php
w
25
49
The default notation is the decimal. The script shows these three numbers in decimal. In Java
w
and C, if an integer value is bigger than the maximum value allowed, integer overflow happens.
PHP works differently. In PHP, the integer becomes a float number. Floating point numbers have
greater boundaries. In 32bit system, an integer value size is four bytes. The maximum integer
value is 2147483647.
boundary.php
<?php
$var = PHP_INT_MAX;
echo var_dump($var);
$var++;
echo var_dump($var);
om
?>
We assign a maximum integer value to the $var variable. We increase the variable by one. And
we compare the contents.
Output:
int(2147483647)
float(2147483648)
.c
As we have mentioned previously, internally, the number becomes a floating point value.
var_dump(): The PHP var_dump() function returns the data type and value.
PHP Doubles or Floating point numbers
ul
Floating point numbers represent real numbers in computing. Real numbers measure continuous
quantities like weight, height or speed. Floating point numbers in PHP can be larger than integers
and they can have a decimal point. The size of a float is platform dependent.
pa
We can use various syntaxes to create floating point values.
<?php The $d variable is assigned a large number,
$a = 1.245; so it is automatically converted to float type.
$b = 1.2e3;
Output:
jin
$c = 2E-10;
float(1.245)
$d = 1264275425335735;
float(1200)
var_dump($a);
float(2.0E-10)
var_dump($b);
float(1264275425340000)
var_dump($c);
This is the output of beside script
.re
var_dump($d);
?>
PHP Boolean
A Boolean represents two possible states: TRUE or FALSE.
w
$x = true; $y = false;
Booleans are often used in conditional testing.
<?php
$male = False;
w
$r = rand(0, 1);
$male = $r ? True: False;
if ($male) {
w
The script uses a random integer generator to simulate our case. $r = rand(0, 1);
The rand( ) function returns a random number from the given integer boundaries 0 or 1.
$male = $r? True: False;
We use the ternary operator to set a $male variable. The variable is based on the random $r
value. If $r equals to 1, the $male variable is set to True. If $r equals to 0, the $male variable
is set to False.
PHP Strings
om
String is a data type representing textual data in computer programs. Probably the single most
important data type in programming.
<?php
$a = "PHP ";
$b = 'PERL';
echo $a . $b; ?>
.c
Output: PHP PERL
We can use single quotes and double quotes to create string literals.
ul
The script outputs two strings to the console. The \n is a special sequence, a new line.
The escape-sequence replace ments are −
\n is replaced by the newline character
\r is replaced by the carriage-return character
pa
\t is replaced by the tab character
\$ is replaced by the dollar sign itself ($)
\" is replaced by a single double-quote (")
\\ is replaced by a single backslash (\)
jin
$txt1="Hello Kalpana!";
$txt2="What a nice day!";
echo $txt1 . " " . $txt2;
?> O/P: Hello Kalpana! What a nice day!
Search for a Specific Text within a String
w
The PHP strpos() function searches for a specific text within a string. If a match is found,
the function returns the characte r position of the first match. If no match is found, it will
return FALSE. The example below searches for the text "world" in the string "Hello world!":
w
Example
<?php
echo strpos("Hello world!", "world");
w
?> output: 6
Tip: The first character position in a string is 0 (not 1).
Replace Text within a String
The PHP str_replace() function replaces some characters with some other characters in a
string. The example below replaces the text "world" with "Dolly":
Example
<?php
echo str_replace("world", "Kalpana", "Hello world!");
?> Output: Hello Kalpana!
The strlen() function:
The strlen() function is used to return the length of a string. Let's find the length of a string:
Eg: <?php
echo strlen("Hello world!"); ?> The output of the code above will be: 12
om
PHP Array
Array is a complex data type which handles a collection of elements. Each of the elements
can be accessed by an index. An array stores multiple values in one single variable. In the
following example $cars is an array. The PHP var_dump() function returns the data type and
value:
.c
Example
<?php
$cars = array("Volvo","BMW","Toyota");
print_r($cars);
ul
var_dump($cars);
?>
The array keyword is used to create a collection of elements. In our case we have names.
pa
The print_r function prints human readable information about a variable to the console.
O/P: Array ( [0] => Volvo [1] => BMW [2] => Toyota )
array(3) { [0]=> string(5) "Volvo" [1]=> string(3) "BMW" [2]=> string(6) "Toyota" }
PHP Object
An object is a data type which stores data and information on how to process that data. In
jin
PHP, an object must be explicitly declared. First we must declare a class of object. For this,
we use the class keyword. A class is a structure that can contain properties and methods:
Example
<?php
.re
class Car {
function Car() {
$this->model = "VW";
} }
$herbie = new Car(); // create an object
w
PHP NULL
NULL is a special data type that only has one value: NULL. To give a variable the NULL
value, simply assign it like this −
w
om
PHP Resource
The special resource type is not an actual data type. It is the storing of a reference to
functions and resources external to PHP. A common example of using the resource data type
is a database call. Resources are handlers to opened files, database connections or image
canvas areas. We will not talk about the resource type here, since it is an advanced topic.
.c
constant() function
As indicated by the name, this function will return the value of the constant. This is useful
when you want to retrieve value of a constant, but you do not know its name, i.e. It is stored
ul
in a variable or returned by a function.constant() example
<?php
define("MINSIZE", 50);
pa
echo MINSIZE;
echo constant("MINSIZE"); // same thing as the previous line
?>
Output: 50 50
jin
Only scalar data (boolean, integer, float and string) can be contained in constants.
PHP - Operators:
What is Operator?
Simple answer can be given using expression 4 + 5 is equal to 9. Here 4 and 5 are called
.re
operands and + is called operator. PHP language supports following type of operators.
w
Arithmetic Operators:
w
om
Ope rator Description Example
== Checks if the value of two operands are equal or not ($A==$B) is not true.
=== Identical(Returns true if $A is equal to $B, and they $A === $B
are of the same type)
!= Checks if the values of two operands are equal or not, ($A != $B) is true.
if values are not equal then condition becomes true.
.c
<> Returns true if $x is not equal to $y $A <> $B
!== Not identical (Returns true if $A is not equal to $B, or $A !== $B
they are not of the same type)
ul
> Checks if the value of left operand is greater than the ($A > $B) is not true.
value of right operand, if yes then condition becomes
true.
< Checks if the value of left operand is less (A < B) is
pa
true. Than the value of right operand, if yes then
condition becomes true.
>= Checks if the value of left operand is greater than or ($A >= $B) is not true.
equal to the value of right operand, if yes then returns
true.
jin
<= Checks if the value of left operand is less than or equal ($A <= $B) is true.
to the value of right operand, if yes then condition
becomes true.
.re
Logical Operators:
There are following logical operators supported by PHP language
Assume variable A holds 10 and variable B holds 20 then:
Ope rator Description Example
and (or) Called Logical AND operator. If both the operands ($A and $B) is true.
w
&& are true then then condition becomes true. ($A && $B) is true.
or (or) || Called Logical OR Operator. If any of the two ($A or $B) is true.
operands are non zero then then condition becomes ($A || $B) is true.
w
true.
! Called Logical NOT Operator. Use to reverses the !( $A && $B) is false.
logical state of its operand. If a condition is true
w
om
/= Divide AND assignment operator, It divides left $C /= $A is equivalent
operand with the right operand and assign the result to to $C = $C / $A
left operand
%= Modulus AND assignment operator, It takes modulus $C %= $A is
using two operands and assign the result to left equivalent to
operand $C = $C % $A
.c
Conditional Ope rator
There is one more operator called conditional operator. This first evaluates an expression for
a true or false value and then execute one of the two given statements depending upon the
ul
result of the evaluation.
The conditional operator has this syntax:
Operator Description Example
pa
?: Conditional Expression If Condition is true ? Then value X : Otherwise value Y
PHP String Operators
PHP has two operators that are specially designed for strings.
Operator Description Example
jin
expression is evaluated. Certain operators have higher precedence than others; for example,
the multiplication operator has higher precedence than the addition operator −
For example x = 7 + 3 * 2; Here x is assigned 13, not 20 because operator * has higher
precedence than + so it first get multiplied with 3*2 and then adds into 7. Ans:13
Here operators with the highest precedence appear at the top of the table; those with the
lowest appear at the bottom. Within an expression, higher precedence operators will be
evaluated first.
om
Logical OR || Left to right
Conditional ?: Right to left
Assignment = += -= *= /= % = Right to left
.c
<?php <?php <?php
$x = 10; $x = 100; $x = 100;
$y = 6; $y = 50; $y = 50;
ul
echo $x + $y; var_dump($x > $y); // if ($x == 100 xor $y == 80) {
?> returns true because $x is echo "Hello world!";
</body> greater than $y }
</html> ?> ?>
pa
O/P: 16 O/P: bool(true) O/P: Hello world!
if (condition) <body>
code to be executed if condition is true; <?php
else $d=date("D");
w
om
if (condition) <body>
code to be executed if condition is true; <?php
elseif (condition) $d=date("D");
code to be executed if condition is true; if ($d=="Fri")
else echo "Have a nice weekend!";
code to be executed if condition is false; elseif ($d=="Sun")
echo "Have a nice Sunday!";
.c
Example
The following example will output "Have a else
nice weekend!" if the current day is Friday, echo "Have a nice day!";
and "Have a nice Sunday!" if the current day ?>
ul
is Sunday. Otherwise, it will output "Have a </body>
nice day!" </html>
pa
The Switch Statement
If you want to select one of many blocks of code to be executed, use the Switch statement.
The switch statement is used to avoid long blocks of if..elseif..else code.
Syntax Example
switch (expression) The switch statement works in an unusual
jin
case label2:
code to be executed if expression = label2; matches then statement will execute any
break; specified default code.
default:
code to be executed
if expression is different
w
om
{
code to be executed;
}
The initializer is used to set the start value for the counter of the number of loop iterations. A
variable may be declared here for this purpose and it is traditional to name it $i.
Example
.c
The following example makes five iterations and changes the assigned value of two
variables on each pass
` of the loop −
<html> <body>
ul
<?php
$a = 0;
$b = 0;
pa
for( $i=0; $i<5; $i++ )
{
$a += 10;
$b += 5;
}
jin
Syntax
while (condition)
{
w
code to be executed;
}
Example
w
$num = 50;
while( $i < 10)
{
$num--;
$i++;
}
echo ("Loop stopped at i = $i and num = $num" );
?> </body> </html>
om
This will produce the following result –
Loop stopped at i = 10 and num = 40
.c
Syntax
do
ul
{
code to be executed;
}while (condition);
pa
Example
The following example will increment the value of i at least once, and it will continue
incrementing the variable i as long as it has a value of less than 10 −
<html> }while( $i < 10 );
<body> echo ("Loop stopped at i = $i" );
jin
<?php ?>
$i = 0; $num = 0; </body>
do{ </html>
$i++;
.re
Syntax }
foreach (array as value) ?>
{ </body> </html>
This will produce the following result −
w
code to be executed;
} Value is 1
Example Value is 2
Try out beside example to list out the values Value is 3
of an array. Value is 4
Value is 5
om
when the counter value reaches 3 and loop terminates.
<?php
$i = 0;
while( $i < 10) {
$i++;
if( $i == 3 )break; }
echo ("Loop stopped at i = $i" );
.c
?> O/P: Loop stopped at i=3
The continue statement
The PHP continue keyword is used to halt the current iteration of
ul
a loop but it does not terminate the loop. Just like the break statement
the continue statement is situated inside the statement block containing
the code that the loop executes, preceded by a conditional test. For the
pass encountering continue statement, rest of the loop code is skipped
pa
and next pass starts.
Example
In the following example loop prints the value of array but for which condition becomes true
it just skip the code and next value is printed.
jin
<html>
<body>
<?php
$nos = array( 1, 2, 3, 4, 5);
foreach( $nos as $value )
.re
{
if( $value == 3 ) This will produce the following result −
continue; Value is 1
echo "Value is $value <br />"; Value is 2
} Value is 4
w
?> Value is 5
</body>
</html>
w
PHP – Functions
PHP functions are similar to other programming languages. A function is a piece of code
w
which takes one more input in the form of parameter and does some processing and returns a
value. You already have seen many functions like fopen() and fread() etc. They are built- in
functions but PHP gives you option to create your own functions as well.
There are two parts which should be clear to you –
Creating a PHP Function
Calling a PHP Function
In fact you hardly need to create your own PHP function because there are already more
than 1000 of built- in library functions created for different area and you just need to call
them according to your requirement.
Creating PHP Function
It‘s very easy to create your own PHP function. Suppose you want to create a PHP function
which will simply write a simple message on your browser when you will call it. Following
example creates a function called writeMessage() and then calls it just after creating it.
om
<html> <head> echo "Have a nice time Kalpana!";
<title>Writing PHP Function</title> } /* Calling a PHP Function */
</head> writeMessage();
<body> ?>
<?php </body>
/* Defining a PHP Function */ </html>
.c
function writeMessage() Output: Have a nice time Kalpana!
{
PHP Functions with Parameters
ul
PHP gives you option to pass your parameters inside a function. You can pass as many as
parameters you‘re like. These parameters work like variables inside your function.
Following example takes two integer parameters and add them together and then print them.
pa
<html>
<head> <title>Writing PHP Function with Parameters</title> </head>
<body>
<?php
function addFunction($num1, $num2)
jin
{
$sum = $num1 + $num2;
echo "Sum of the two numbers is : $sum";
}
.re
addFunction(10, 20);
?> </body> </html>
Output: Sum of the two numbers is : 30
It is possible to pass arguments to functions by reference. This means that a reference to the
variable is manipulated by the function rather than a copy of the variable's value. Any
changes made to an argument in these cases will change the value of the original variable.
w
You can pass an argument by reference by adding an ampersand to the variable name in
either the function call or the function definition.
<html>
w
<head>
<title>Passing Argument by Reference</title>
</head>
<body>
<?php
function addFive($num)
{
$num += 5;
}
function addSix(&$num)
{
$num += 6;
}
$orignum = 10;
addFive( $orignum );
om
echo "Original Value is $orignum<br />";
addSix( $orignum );
echo "Original Value is $orignum<br />";
?>
</body>
</html>
.c
Output: Original Value is 10
Original Value is 16
PHP Functions returning value
ul
A function can return a value using the return statement in conjunction with a value or
object. return stops the execution of the function and sends the value back to the calling
code. You can return more than one value from a function using return array(1,2,3,4).
pa
<html> <head> <title>Writing PHP Function which returns value</title> </head>
<body>
<?php
function addFunction($num1, $num2)
{
jin
}
printMe("This is test");
printMe();
?>
</body> </html>
Output: This is test
<html> <html>
<head> <head>
<title>Dynamic Function Calls</title> <title>Dynamic Function Calls</title>
</head> </head>
om
<body> <body>
<?php <?php
function sayHello() function add($x,$y)
{ {
echo "Hello<br />"; echo "addition=" . ($x+$y);
} }
.c
$function_holder = "sayHello"; $function_holder = "add";
$function_holder(); $function_holder(20,30);
?> </body> </html> ?> </body> </html>
Output: Hello Output: addition=50
ul
PHP Default Argument Value
The following example shows how to use a default parameter. If we call the function
setHeight() without arguments it takes the default value as argument:
pa
Example
<?php
function setHeight($minheight = 50) {
echo "The height is : $minheight \t";
jin
}
setHeight(350);
setHeight(); // will use the default value of 50
setHeight(135);
setHeight(80);
.re
?>
O/P: 350 50 135 80
PHP creates some useful environme nt variables that can be seen in the phpinfo.php page
that was used to setup the PHP environment. One of the environment variables set by PHP
w
<?php
if( $_POST["name"] || $_POST["age"] )
{
if (preg_match("/[^A- Za-z'-]/",$_POST['name'] ))
{
die ("invalid name and name should be alpha"); }
echo "Welcome ". $_POST['name']. "<br />";
om
<input type="submit" />
</form> </body> </html>
The PHP default variable $_PHP_SELF is used for the PHP script name and when yo u
click "submit" button then same PHP script will be called and will produce following result
The method = "POST" is used to post user data to the server script.
.c
PHP Forms and User Input:
The PHP $_GET and $_POST variables are used to retrieve information from forms, like
user input.
ul
PHP - GET & POST Methods
There are two ways the browser client can send information to the web server.
The GET Method
pa
The POST Method
Before the browser sends the information, it encodes it using a scheme called URL
encoding or URL Parameters. In this scheme, name/value pairs are joined with equal signs
and different pairs are separated by the ampersand.
name1=value1&name2=value2&name3=value3
jin
http://www.sampletest.com/index.htm?name1=value1&name2=value2
The GET method produces a long string that appears in your server logs, in the browser's
Location: box.
The GET method is restricted to send upto 1024 characters only.
w
Never use GET method if you have password or other sensitive information to be sent to
the server.
GET can't be used to send binary data, like images or word documents, to the server.
The PHP provides $_GET associative array to access all the sent information using GET
w
method.
<?php
if( $_GET["name"] || $_GET["age"] )
w
{
echo "Welcome ". $_GET['name']. "<br />";
echo "You are ". $_GET['age']. " years old.";
exit();
}
?> <html> <body>
om
information is encoded as described in case of GET method and put into a header called
QUERY_STRING.
The POST method does not have any restriction on data size to be sent.
The POST method can be used to send ASCII as well as binary data.
The data sent by POST method goes through HTTP header so security depends on HTTP
protocol. By using Secure HTTP you can make sure that your information is secure.
.c
The PHP provides $_POST associative array to access all the sent information using POST
method.
PHP Form Handling
ul
Example : The example below contains an HTML form with two input fields and a submit
button:
<html>
<body>
pa
<form action="we lcome.php" method="post">
Name: <input type="text" name="fname" />
Age: <input type="text" name="age" />
<input type="submit" />
</form>
jin
</body>
</html>
When a user fills out the form above and click on the submit button, the form data is sent
to a PHP file, called "welcome.php": its looks like this:
.re
<html> <body>
Welcome <?php echo $_POST["fname"]; ?>!
You are <?php echo $_POST["age"]; ?> years old.
</body>
</html> Output: Welcome Kalpana! You are 29 years old.
w
$_GET is an array of variables passed to the current script via the URL parameters.
$_POST is an array of variables passed to the current script via the HTTP POST method.
w
om
that the file has arrived and then copies the file into an intended directory.
The PHP script confirms the success to the user.
As usual when writing files it is necessary for both temporary and final locations to have
permissions set that enable file writing. If either is set to be read-only then process will fail.
An uploaded file could be a text file or image file or any document.
.c
Creating an upload form
The following HTML code below creates an up loader form. This form is having method
attribute set to post and enctype attribute is set to multipart/form-data
ul
There is one global PHP variable called $_FILES. This variable is an associate double
dimension array and keeps all the information related to uploaded file. So if the value
assigned to the input's name attribute in uploading form was file, then PHP would create
following five variables –
pa
$_FILES['file']['tmp_name'] the uploaded file in the temporary dir on the web server.
$_FILES['file']['name'] − the actual name of the uploaded file.
$_FILES['file']['size'] − the size in bytes of the uploaded file.
$_FILES['file']['type'] − the MIME type of the uploaded file.
$_FILES['file']['error'] − the error code associated with this file upload.
jin
Example: Below example should allow upload images and gives back result as uploaded
file information.
<?php <ul>
.re
} </ul>
?> <img src=" <?php echo
<html> <body> $_FILES['image']['name']; ?>"
w
PHP - Cookies
Cookies are text files stored on the client computer and they are kept of use tracking purpose.
PHP transparently supports HTTP cookies.
There are three steps involved in identifying returning users −
Server script sends a set of cookies to the browser. For example name, age, or
identification number etc.
Browser stores this information on local machine for future use.
When next time browser sends any request to web server then it sends those cookies
om
information to the server and server uses that information to identify the user.
Setting Cookies with PHP
PHP provided setcookie() function to set a cookie. This function requires upto six
arguments and should be called before <html> tag. For each cookie this function has to be
called separately.
.c
setcookie(name, value, expire, path, domain, security);
ul
Name − This sets the name of the cookie and is stored in an environment variable
called HTTP_COOKIE_VARS. This variable is used while accessing cookies.
Value − This sets the value of the named variable and is the content that you actually
want to store.
pa
Expiry − This specify a future time in seconds since 00:00:00 GMT on 1st Jan 1970.
After this time cookie will become inaccessible. If this parameter is not set then
cookie will automatically expire when the Web Browser is closed.
Path − This specifies the directories for which the cookie is valid. A single forward
slash character permits the cookie to be valid for all directories.
jin
Domain − This can be used to specify the domain name in very large domains and
must contain at least two periods to be valid. All cookies are only valid for the host
and domain which created them.
Security − This can be set to 1 to specify that the cookie should only be sent by
.re
secure transmission using HTTPS otherwise set to 0 which mean cookie can be sent
by regular HTTP.
Following example will create two cookies name and age these cookies will be expired after
one hour.
<?php
w
<html>
<head> <title>Setting Cookies with PHP</title> </head>
<body>
w
<html>
<head> <title>Accessing Cookies with PHP</title> </head>
<body>
<?php
echo $_COOKIE["name"]. "<br />";
/* is equivalent to */
echo $HTTP_COOKIE_VARS["name"]. "<br />";
om
echo $_COOKIE["age"] . "<br />";
/* is equivalent to */
echo $HTTP_COOKIE_VARS["name"] . "<br />";
?>
</body> </html>
.c
<html> <head> <title>Accessing Cookies with PHP</title> </head>
<body>
<?php
ul
if( isset($_COOKIE["name"]))
echo "Welcome " . $_COOKIE["name"] . "<br />";
else
pa
echo "Sorry... Not recognized" . "<br />";
?>
</body> </html>
this does not always work well, however, and should not be relied on.
It is safest to set the cookie with a date that has already expired –
<?php
setcookie( "name", "", time()- 60, "/","", 0);
.re
PHP - Session
w
When you work with an application, you open it, do some changes, and then you close it.
This is much like a Session.
Session ID is stored as a cookie on the client box or passed along through URL's.
w
The values are actually stored at the server and are accessed via the session id from your
cookie. On the client side the session ID expires when connection is broken.
Session variables solve this problem by storing user information to be used across multiple
pages (e.g. username, favorite color, etc). By default, session variables last until the user
closes the browser.
Session variable values are stored in the 'superglobal' associative array '$_SESSION'
om
?> <?php
<html> session_start();
<body> ?>
<?php <html>
// Set session variables <?php
$_SESSION["favcolor"] = "green"; $_SESSION["favcolor"] = "yellow";
.c
$_SESSION["favanimal"] = "cat"; print_r($_SESSION); ?> </html>
echo "Session variables are set.";
?>
</body> </html>
ul
Get PHP Session Variable Values
Next, we create another page called "de mo_session2.php". From this page, we will access
pa
the session information we set on the first page ("demo_session1.php").
Notice that session variables are not passed individually to each new page, instead they are
retrieved from the session we open at the beginning of each page (session_start()).
<?php
session_start();
jin
?>
<!DOCTYPE html>
<html>
<body>
.re
<?php
// Echo session variables that were set on previous page
echo "Favorite color is " . $_SESSION["favcolor"] . ".<br>";
echo "Favorite animal is " . $_SESSION["favanimal"] . ".";
?>
</body> </html>
w
session_destroy():
Example
<?php
session_start();
w
?>
<html>
<body>
<?php
session_unset(); // remove all session variables
session_destroy(); // destroy the session
?> </body> </html>
om
information user information
2 Session Max life time is 1440 Seconds(24 We have to set cookie max life time
Minutes) as defined in php.ini file manually with php code with setcookie
in php.ini on line 1604 you can find function.
; http://php.net/session.gc- maxlifetime setcookie("email", 'test@example.com',
session.gc_maxlifetime = 1440 time()+3600); /* expire in 1 hour */
.c
You can edit this value if you need custom Expire time : I hour after current time
session life.
3 In php $_SESSION super global variable is used In php $_COOKIE super global
to manage session. variable is used to manage cookie.
ul
4 Before using $_SESSION, you have to write You don't need to start Cookie as It is
session_start(); In that way session will start stored in your local machine.
pa
5 You can store as much data as you like within in Official MAX Cookie size is 4KB
sessions.(default is 128MB.) memory_limit=
128M
php.ini line 479 ;http://php.net/memory- limit
6 Session is dependent on COOKIE. Because when you start session with session_start() then
jin
SESSIONID named key will be set in COOKIE with Unique Identifier Value for your
system.
7 session_destroy(); is used to "Destroys all data There is no function named
registered to a session", and if you want to unset unsetcookie()
some key's of SESSION then use unset() time()-3600);//expire before 1hour
.re
Write a Program to create simple Login and Logout example using sessions.
login.php
<html>
w
<head>
<title>Login Form</title>
</head>
<body>
<h2>Login Form</h2>
<form method="post" action="checklogin.php">
User Id: <input type="text" name="uid"><br>
om
$uid = $_POST['uid'];
$pw = $_POST['pw'];
if($uid == 'arun' and $pw == 'arun123')
{
session_start();
$_SESSION['sid']=session_id();
.c
header("location:securepage.php");
}
?>
ul
securepage.php
<?php
session_start();
pa
if($_SESSION['sid']==session_id())
{
echo "Welcome to you<br>";
echo "<a href='logout.php'>Logout</a>";
}
jin
else
{
header("location:login.php");
}
?>
.re
logout.php
<?php
echo "Logged out scuccessfully";
session_start();
w
session_destroy();
setcookie(PHPSESSID,session_id(),time()-1);
?>
w
w
XML - XML stands for Extensible Mark-up Language, developed by W3C in 1996. It is a
text-based mark-up language derived from Standard Generalized Mark-up Language
(SGML). XML 1.0 was officially adopted as a W3C recommendation in 1998. XML was
designed to carry data, not to display data. XML is designed to be self-descriptive. XML is a
subset of SGML that can define your own tags. A Meta Language and tags describe the
content. XML Supports CSS, XSL, DOM. XML does not qualify to be a programming
language as it does not performs any computation or algorithms. It is usually stored in a
om
simple text file and is processed by special software that is capable of interpreting XML.
The Difference between XML and HTML
1. HTML is about displaying information, where asXML is about carrying information. In
other words, XML was created to structure, store, and transport information. HTML was
designed to display the data.
.c
2. Using XML, we can create own tags where as in HTML it is not possible instead it offers
several built in tags.
3. XML is platform independent neutral and language independent.
ul
4. XML tags and attribute names are case-sensitive where as in HTML it is not.
5. XML attribute values must be single or double quoted where as in HTML it is not
compulsory.
pa
6. XML elements must be properly nested.
7. All XML elements must have a closing tag.
<from>MRGI</from>
<heading>KALPANA</heading>
<body>Hello, world! </body>
</note>
Xml document begins with XML declaration statement: <? xml version="1.0"
encoding="ISO-8859-1"?> .
The next line describes the root element of the document: <note>.
om
Valid XML document
If an XML document is well- formed and has an associated Document Type Declaration
(DTD), then it is said to be a valid XML document. We will study more about DTD in the
chapter XML - DTDs.
XML DTD
Document Type Definition purpose is to define the structure of an XML document. It defines
.c
the structure with a list of defined elements in the xml document. Using DTD we can specify
the various elements types, attributes and their relationship with one another. Basically DTD
is used to specify the set of rules for structuring data in any XML file.
ul
Why use a DTD?
XML provides an application independent way of sharing data. With a DTD, independent
groups of people can agree to use a common DTD for interchanging data. Your application
can use a standard DTD to verify that data that you receive from the outside world is valid.
pa
You can also use a DTD to verify your own data.
DTD - XML building blocks
Various building blocks of XML are-
1. Elements: The basic entity is element. The elements are used for defining the tags. The
jin
elements typically consist of opening and closing tag. Mostly only one element is used to
define a single tag.
Syntax1: <!ELEMENT element- name (element-content)>
Syntax 2: <!ELEMENT element- name (#CDATA)>
.re
#CDATA means the element contains character data that is not supposed to be parsed by a
parser. or
Syntax 3: <!ELEMENT element- name (#PCDATA)>
#PCDATA means that the element contains data that IS going to be parsed by a parser. or
Syntax 4: <!ELEMENT element- name (ANY)>
The keyword ANY declares an element with any content.
w
Example:
<!ELEMENT note (#PCDATA)>
w
When children are declared in a sequence separated by commas, the children must appear in
the same sequence in the document. In a full declaration, the children must also be declared,
and the children can also have children. The full declaration of the note document will be:
2. Tags
Tags are used to markup elements. A starting tag like <element_name> mark up the
beginning of an element, and an ending tag like </element_name> mark up the end of an
om
element.
Examples:
A body element: <body>body text in between</body>.
A message element: <message>some message in betwee n</message>
3. Attribute: The attributes are generally used to specify the values of the element. These
.c
are specified within the double quotes. Ex: <flag type=‖true‖>
4. Entities
Entities as variables used to define common text. Entity references are references to entities.
ul
Most of you will known the HTML entity reference: " " that is used to insert an extra
space in an HTML document. Entities are expanded when a document is parsed by an XML
parser.
The following entities are predefined in XML:
pa
< (<), >(>), &(&), "(") and '(').
5. CDATA: It stands for character data. CDATA is text that will NOT be parsed by a
parser. Tags inside the text will NOT be treated as markup and entities will not be expanded.
6. PCDATA: It stands for Parsed Character Data(i.e., text). Any parsed character data should
jin
not contain the markup characters. The markup characters are < or > or &. If we want to use
these characters then make use of < , > or &. Think of character data as the text
found between the start tag and the end tag of an XML element. PCDATA is text that will be
parsed by a parser. Tags inside the text will be treated as markup and entities will be
.re
expanded.
<!DOCTYPE note
[
<!ELEMENT note (to,from,heading,body)>
<!ELEMENT to (#PCDATA)>
w
]>
Where PCDATA refers parsed character data. In the above xml document the elements to,
from, heading, body carries some text, so that, these elements are declared to carry text in
w
DTD file.
This definition file is stored with .dtd extension.
DTD identifier is an identifier for the document type definition, which may be the path to a
file on the system or URL to a file on the internet. If the DTD is pointing to external path, it
is called External Subset.
The square brackets [ ] enclose an optional list of entity declarations called Internal Subset.
Types of DTD:
1. Internal DTD
2. External DTD
1. Inte rnal DTD
A DTD is referred to as an internal DTD if elements are declared within the XML files. To
refer it as internal DTD, standalone attribute in XML declaration must be set to yes. This
means, the declaration works independent of external source.
om
Syntax:
The syntax of internal DTD is as shown:
<!DOCTYPE root-element [element-declarations]>
Where root-element is the name of root element and element-declarations is where you
declare the elements.
.c
Example:
Following is a simple example of internal DTD:
<?xml version="1.0" encoding="UTF-8" standalone="yes" ?>
ul
<!DOCTYPE address [
<!ELEMENT address (name,company,phone)>
<!ELEMENT name (#PCDATA)>
<!ELEMENT company (#PCDATA)>
pa
<!ELEMENT phone (#PCDATA)>
]>
<address>
<name>Kalpana</name>
<company>MRCET</company>
jin
<phone>(040) 123-4567</phone>
</address>
Let us go through the above code:
Start Declaration- Begin the XML declaration with following statement <?xml version="1.0"
.re
The DOCTYPE declaration has an exclamation mark (!) at the start of the element name. The
DOCTYPE informs the parser that a DTD is associated with this XML document.
DTD Body- The DOCTYPE declaration is followed by body of the DTD, where you declare
w
Rules
The document type declaration must appear at the start of the document (preceded only by
the XML header) — it is not permitted anywhere else within the document.
Similar to the DOCTYPE declaration, the element declarations must start with an
exclamation mark.
The Name in the document type declaration must match the element type of the root
element.
External DTD
om
In external DTD elements are declared outside the XML file. They are accessed by
specifying the system attributes which may be either the legal .dtd file or a va lid URL. To
refer it as external DTD, standalone attribute in the XML declaration must be set as no. This
means, declaration includes information from the external source.
Syntax Following is the syntax for external DTD:
.c
<!DOCTYPE root-element SYSTEM "file-name">
where file- name is the file with .dtd extension.
Example The following example shows external DTD usage:
ul
<?xml version="1.0" encoding="UTF-8" standalone="no" ?>
<!DOCTYPE address SYSTEM "address.dtd">
<address>
pa
<name>Kalpana</name>
<company>MRCET</company>
<phone>(040) 123-4567</phone>
</address>
The content of the DTD file address.dtd are as shown:
jin
Types
You can refer to an external DTD by using either system identifiers or public identifiers.
SYSTEM IDENTIFIERS
A system identifier enables you to specify the location of an external file containing DTD
w
the document.
PUBLIC IDENTIFIERS
w
Public identifiers provide a mechanism to locate DTD resources and are written as below:
<!DOCTYPE name PUBLIC "-//Beginning XML//DTD Address Example//EN">
As you can see, it begins with keyword PUBLIC, followed by a specialized identifier. Public
identifiers are used to identify an entry in a catalog. Public identifiers can follow any format;
however, a commonly used format is called Formal Public Identifiers, or FPIs.
XML Schemas
XML Schema is commonly known as XML Schema Definition (XSD). It is used to
describe and validate the structure and the content of XML data. XML schema defines the
elements, attributes and data types. Schema element supports Namespaces. It is similar to
a database schema that describes the data in a database. XSD extension is “.xsd”.
This can be used as an alternative to XML DTD. The XML schema became the W#C
recommendation in 2001.
XML schema defines elements, attributes, element having child elements, order of child
om
elements. It also defines fixed and default values of elements and attributes.
XML schema also allows the developer to us data types.
.c
Example : contact.xsd
The following example shows how to use schema:
<?xml version="1.0" encoding="UTF-8"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
ul
<xs:element name="contact">
<xs:complexType>
<xs:sequence>
pa
<xs:element name="name" type="xs:string" />
<xs:element name="company" type="xs:string" />
<xs:element name="phone" type="xs:int" />
</xs:sequence>
</xs:complexType>
jin
</xs:element>
</xs:schema>
The basic idea behind XML Schemas is that they describe the legitimate format that an XML
document can take.
.re
<company>04024056789</company>
<phone>9876543210</phone>
</contact>
w
Limitations of DTD:
There is no built- in data type in DTDs.
No new data type can be created in DTDs.
w
om
SCHEMA STRUCTURE
The Schema Element
<xs: schema xmlns: xs="http://www.w3.org/2001/XMLSchema">
Element definitions
.c
As we saw in the chapter XML - Elements, elements are the building blocks of XML
document. An element can be defined within an XSD as follows:
<xs:element name="x" type="y"/>
ul
Data types:
These can be used to specify the type of data stored in an Element.
String (xs:string)
pa
Date (xs:date or xs:time)
Numeric (xs:integer or xs:decimal)
Boolean (xs:boolean)
EX: Sample.xsd
<?xml version=‖1.0‖ encoading=‖UTF-8‖?>
jin
<xs:schema xmlns:xs=http://www.w3.org/XMLSchema>
<xs:element name="sname‖ type=‖xs:string"/>
/* <xs:element name="dob” type=”xs:date"/>
<xs:element name="dobtime” type=”xs:time"/>
.re
Sample.xml:
<?xml version=‖1.0‖ encoading=‖UTF-8‖?>
<sname xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
w
xsi:noNamespaceSchemaLocation="sample.xsd">
Kalpana /*yyyy-mm-dd 23:14:34 600 92.5 true/false */
</sname>
w
Definition Types
You can define XML schema elements in following ways:
Simple Type - Simple type element is used only in the context of the text. Some of
predefined simple types are: xs:integer, xs:boolean, xs:string, xs:date. For example:
<xs:element name="phone_number" type="xs:int" />
<phone>9876543210</phone>
Complex Type - A complex type is a container for other element definitions. This allows
you to specify which child elements an element can contain and to provide some structure
om
within your XML documents. For example:
<xs:element name="Address">
<xs:complexType>
<xs:sequence>
<xs:element name="name" type="xs:string" />
<xs:element name="company" type="xs:string" />
.c
<xs:element name="phone" type="xs:int" />
</xs:sequence>
</xs:complexType>
</xs:element>
ul
In the above example, Address element consists of child elements. This is a container for
other <xs:element> definitions, that allows to build a simple hierarchy of elements in the
XML document.
pa
Global Types - With global type, you can define a single type in your document, which can
be used by all other references. For example, suppose you want to generalize the person and
company for different addresses of the company. In such case, you can define a general type
as below:
<xs:element name="AddressType">
jin
<xs:complexType>
<xs:sequence>
<xs:element name="name" type="xs:string" />
<xs:element name="company" type="xs:string" />
.re
</xs:sequence>
</xs:complexType>
</xs:element>
Now let us use this type in our example as below:
<xs:element name="Address1">
w
<xs:complexType>
<xs:sequence>
<xs:element name="address" type="AddressType " />
w
<xs:element name="Address2">
<xs:complexType>
<xs:sequence>
<xs:element name="address" type="AddressType " />
<xs:element name="phone2" type="xs:int" />
</xs:sequence> </xs:complexType> </xs:element>
Instead of having to define the name and the company twice (once for Address1 and once for
Address2), we now have a single definition. This makes maintenance simpler, i.e., if you
decide to add "Postcode" elements to the address, you need to add them at just one place.
Attributes
Simple elements cannot have attributes. If an element has attributes, it is considered to be of a
complex type. But the attribute itself is always declared as a simple type. Attributes in XSD
provide extra information within an element. Attributes have name and type property as
om
shown below:
<xs:attribute name="x" type="y"/>
Ex: <lastname lang="EN">Smith</lastname>
<xs:attribute name="lang" type="xs:string"/>
Default and Fixed Values for Attributes
<xs:attribute name="lang" type="xs:string" default="EN"/>
.c
<xs:attribute name="lang" type="xs:string" fixed="EN"/>
Optional and Required Attributes
Attributes are optional by default. To specify that the attribute is required, use the "use"
ul
attribute:
<xs:attribute name="lang" type="xs:string" use="required"/>
Restrictions on Content
pa
When an XML element or attribute has a data type defined, it puts restrictions on the
element's or attribute's content. If an XML element is of type "xs:date" and contains a string
like "Hello World", the element will not validate.
Restrictions on Values:
jin
<xs:minInclusive value="0"/>
<xs:maxInclusive value="120"/>
</xs:restriction>
</xs:simpleType> </xs:element>
w
<xs:element name="car">
<xs:simpleType>
<xs:restriction base="xs:string">
w
<xs:enumeration value="Audi"/>
<xs:enumeration value="Golf"/>
<xs:enumeration value="BMW"/>
</xs:restriction>
</xs:simpleType>
</xs:element>
Restrictions on Length
To limit the length of a value in an element, we would use the length, maxLength, and
minLength constraints. The value must be exactly eight characters:
<xs:element name="password">
<xs:simpleType>
<xs:restriction base="xs:string">
<xs:length value="8"/> [<xs:minLength value="5"/> <xs:maxLength value="8"/>]
</xs:restriction> </xs:simpleType> </xs:element>
om
XSD Indicators
We can control HOW elements are to be used in documents with indicators.
Indicators: There are seven indicators
Orde r indicators:
All
.c
Choice
Sequence
Occurrence indicators:
maxOccurs
ul
minOccurs
Group indicators:
Group name
pa
attributeGroup name
Order Indicators
Order indicators are used to define the order of the elements.
All Indicator
jin
The <all> indicator specifies that the child elements can appear in any order, and that each
child element must occur only once:
<xs:element name="person">
<xs:complexType>
<xs:all>
.re
Note: When using the <all> indicator you can set the <minOccurs> indicator to 0 or 1 and the
<maxOccurs> indicator can only be set to 1 (the <minOccurs> and <maxOccurs> are
w
described later).
Choice Indicator
The <choice> indicator specifies that either one child element or another can occur:
w
<xs:element name="person">
<xs:complexType>
<xs:choice>
<xs:element name="employee" type="employee"/>
<xs:element name="member" type="member"/>
</xs:choice> </xs:complexType> </xs:element>
Sequence Indicator
The <sequence> indicator specifies that the child elements must appear in a specific order:
<xs:element name="person">
<xs:complexType>
<xs:sequence>
<xs:element name="firstname" type="xs:string"/>
<xs:element name="lastname" type="xs:string"/>
</xs:sequence> </xs:complexType> </xs:element>
om
Occurrence Indicators
Occurrence indicators are used to define how often an element can occur.
Note: For all "Order" and "Group" indicators (any, all, choice, sequence, group name, and group
reference) the default value for maxOccurs and minOccurs is 1.
maxOccurs Indicator
.c
The <maxOccurs> indicator specifies the maximum number of times an element can occur:
<xs:element name="person">
<xs:complexType>
ul
<xs:sequence>
<xs:element name="full_name" type="xs:string"/>
<xs:element name="child_name" type="xs:string" maxOccurs="10"/>
</xs:sequence>
pa
</xs:complexType>
</xs:element>
minOccurs Indicator
The <minOccurs> indicator specifies the minimum number of times an element can occur:
jin
<xs:element name="person">
<xs:complexType>
<xs:sequence>
<xs:element name="full_name" type="xs:string"/>
.re
maxOccurs="unbounded" statement:
EX: An XML file called "Myfamily.xml":
<?xml version="1.0" encoding="UTF-8"?>
w
<full_name>KALPANA</full_name>
<child_name>mrcet</child_name>
</person>
<person>
<full_name>Tove Refsnes</full_name>
<child_name>Hege</child_name>
<child_name>Stale</child_name>
<child_name>Jim</child_name>
<child_name>Borge</child_name>
</person>
<person>
<full_name>Stale Refsnes</full_name>
</person>
</persons>
The XML file above contains a root element named "persons". Inside this root element we
om
have defined three "person" elements. Each "person" element must contain a "full_name"
element and it can contain up to five "child_name" elements.
Here is the schema file "family.xsd":
<?xml version="1.0" encoding="UTF-8"?>
<xs:schema xmlns:xs=http://www.w3.org/2001/XMLSchema
.c
elementFormDefault="qualified">
<xs:element name="persons">
<xs:complexType>
<xs:sequence>
ul
<xs:element name="person" maxOccurs="unbounded">
<xs:complexType>
<xs:sequence>
pa
<xs:element name="full_name" type="xs:string"/>
<xs:element name="child_name" type="xs:string" minOccurs="0" maxOccurs="5"/>
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:sequence>
jin
</xs:complexType>
</xs:element>
</xs:schema>
Group Indicators: Group indicators are used to define related sets of elements.
.re
</xs:group>
You must define an all, choice, or sequence element inside the group declaration. The
following example defines a group named "persongroup", that defines a group of elements
w
After you have defined a group, you can reference it in another definition, like this:
<xs:element name="person" type="personinfo"/>
<xs:complexType name="personinfo">
<xs:sequence>
<xs:group ref="pe rsongroup"/>
<xs:element name="country" type="xs:string"/>
</xs:sequence>
om
</xs:complexType>
Attribute Groups
Attribute groups are defined with the attributeGroup declaration, like this:
<xs:attributeGroup name="groupname">
...
.c
</xs:attributeGroup>
The following example defines an attribute group named "personattrgroup":
ul
<xs:attributeGroup name="personattrgroup">
<xs:attribute name="firstname" type="xs:string"/>
<xs:attribute name="lastname" type="xs:string"/>
<xs:attribute name="birthday" type="xs:date"/>
pa
</xs:attributeGroup>
After you have defined an attribute group, you can reference it in another definition, like this:
<xs:element name="person">
<xs:complexType>
jin
xmlns:xsi=http://www.w3.org/2001/XMLSchema- instance
xsi:noNamespaceSchemaLocation="shiporder.xsd">
<orderperson>John Smith</orderperson>
<shipto>
<name>Ola Nordmann</name>
w
<address>Langgt 23</address>
<city>4000 Stavanger</city>
<country>Norway</country>
w
</shipto>
<item>
<title>Empire Burlesque</title>
<note>Special Edition</note>
w
<quantity>1</quantity>
<price>10.90</price>
</item>
<item>
<title>Hide your heart</title> <quantity>1</quantity>
<price>9.90</price> </item>
</shiporder>
om
<xs:complexType>
<xs:sequence>
<xs:element name="name" type="xs:string"/>
<xs:element name="address" type="xs:string"/>
<xs:element name="city" type="xs:string"/>
<xs:element name="country" type="xs:string"/>
.c
</xs:sequence>
</xs:complexType>
</xs:element>
<xs:element name="ite m" maxOccurs="unbounded">
ul
<xs:complexType>
<xs:sequence>
<xs:element name="title" type="xs:string"/>
pa
<xs:element name="note" type="xs:string" minOccurs="0"/>
<xs:element name="quantity" type="xs:positiveInteger"/>
<xs:element name="price" type="xs:decimal"/>
</xs:sequence>
</xs:complexType>
</xs:element>
jin
</xs:sequence>
<xs:attribute name="orderid" type="xs:string" use="re quired"/>
</xs:complexType>
</xs:element>
.re
</xs:schema>
PCDATA is parsed. In a schema you can have primitive data types and custom data types
like you have used in programming.
Schema vs. DTD
w
types
• XMLSchemas support namespaces
XML Parsers
An XML parser converts an XML document into an XML DOM object - which can then be
manipulated with a JavaScript.
om
• It can ignore external DTD
.c
which are commonly used to parse XML documents.
Types of parsers:
Dom Parser - Parses the document by loading the complete contents of the document and
ul
creating its complete hiearchical tree in memory.
SAX Parser - Parses the document on event based triggers. Does not load the complete
document into the memory.
pa
JDOM Parser - Parses the document in similar fashion to DOM parser but in more easier
way.
StAX Parser - Parses the document in similar fashion to SAX parser but in more efficient
way.
XPath Parser - Parses the XML based on expression and is used extensively in
conjuction with XSLT.
jin
DOM4J Parser - A java library to parse XML, XPath and XSLT using Java Collections
Framework , provides support for DOM, SAX and JAXP.
The Document Object Model protocol converts an XML document into a collection of
objects in your program. XML documents have a hierarchy of informational units called
nodes; this hierarchy allows a developer to navigate through the tree looking for specific
information. Because it is based on a hierarchy of information, the DOM is said to be tree
based. DOM is a way of describing those nodes and the relationships between them.
w
You can then manipulate the object model in any way that makes sense. This mechanism is
also known as the "random access" protocol, because you can visit any part of the data at any
w
time. You can then modify the data, remove it, or insert new data.
The XML DOM, on the other hand, also provides an API that allows a developer to add, edit,
w
move, or remove nodes in the tree at any point in order to create an application. A DOM
parser creates a tree structure in memory from the input document and then waits for requests
from client. A DOM parser always serves the client application with the entire document no
matter how much is actually needed by the client. With DOM parser, method calls in client
application have to be explicit and forms a kind of chained method calls.
Document Object Model is for defining the standard for accessing and manipulating XML
documents. XML DOM is used for
om
Every XML element is an element node
The text in the XML elements are text nodes
Every attribute is an attribute node
Comments are comment nodes
.c
DOM Core- This portion defines the basic set of interfaces and objects for any structured
documents.
XML DOM- This part specifies the standard set of objects and interfaces for XML
ul
documents only.
HTML DOM- This part specifies the objects and interfaces for HTML documents only.
DOM Levels
pa
Level 1 Core: W3C Recommendation, October 1998
It has feature for primitive navigation and manipulation of XML trees
other Level 1 features are: All HTML features
Level 2 Core: W3C Recommendation, November 2000
It adds Namespace support and minor new features
other Level 2 features are: Events, Views, Style, Traversal and Range
jin
om
Property Meaning
nodeName Finding the name of the node
nodeValue Obtaining value of the node
parentNode To get parnet node
childNodes Obtain child nodes
Attributes For getting the attributes values
.c
Method Meaning
getElementByTagName(name) To access the element by specifying its name
appendChild(node) To insert a child node
ul
removeChild(node) To remove existing child node
#document
BODY
<html>
<body>
pa
HTML <h1>Heading 1</h1>
lastChild
parentNode
<p>Paragraph.</p>
firstChild
HEAD
<h2>Heading 2</h2>
<p>Paragraph.</p>
BODY </body>
</html> nextSibling nextSibling nextSibling
H1
#text
H1 P H2 P
jin
parentNode
parentNode
parentNode
P
firstChild
firstChild
firstChild
firstChild
lastChild
lastChild
lastChild
lastChild
#text
H2
#text
om
{ var color = document.bg.color.value;
document.body.style.backgroundColor=color; }
</script>
<form name="bg">
Type the Color Name:<input type="text" name="color" size="20">
<br>
.c
Click the Submit Button to change this Background color as your Color.
<br>
<input type="button" value="Submit" onClick='background()'>
</form>
ul
</body>
</html>
DOM NODE Methods
pa
Method Name Description
ADVANTAGES
- Robust API for the DOM tree
- Relatively simple to modify the data structure and extract data
- It is good when random access to widely separated parts of a document is required
w
DOM or SAX
DOM
- Suitable for small documents
- Easily modify document
- Memory intensive;Load the complete XML document
SAX
- Suitable for large documents; saves significant amounts of memory
om
- Only traverse document once, start to end
- Event driven
- Limited standard functions.
-
Loading an XML file:one.html
<html> <body>
<script type=‖text/javascript‖>
.c
try
{
xmlDocument=new ActiveXObject(―Microsoft.XMLDOM‖);
ul
}
catch(e)
{
pa
try {
xmlDocument=document.implementation.createDocument("","",null);
}
catch(e){alert(e.message)}
}
try
jin
{
xmlDocument.async=false;
xmlDocument.load(―faculty.xml‖);
document.write(―XML document student is loaded‖);
.re
}
catch(e){alert(e.message)}
</script>
</body> </html>
faculty.xml:
<?xml version=‖1.0‖?>
w
<name>Kalpana</name>
<address>Hyd</address>
<phone>9959967192</phone>
w
</personal_inf>
<dept>CSE</dept>
<col>MRCET</col>
<group>MRGI</group>
</faculty>
OUTPUT: XML document student is loaded
ActiveXObject: It creates empty xml document object.
om
}
catch(e)
{
try
{
xmlDocument=document.implementation.createDocument("","",null);
.c
}
catch(e){alert(e.message)}
}
try
ul
{
xmlDocument.async=false;
xmlDocument.load(―faculty.xml‖);
pa
return(xmlDocument);
}
catch(e){alert(e.message)}
return(null);
}
</script>
jin
</head>
<body>
<script type=‖text/javascript‖>
xmlDoc=‖My_function(―faculty.xml‖);
.re
<html> <head>
<script type=‖text/javascript‖ src=‖my_function_file.js‖></script>
</head> <body>
w
<script type=‖text/javascript‖>
xmlDocument=My_function(“faculty.xml”);
document.write(―XML document faculty is loaded and content of this file is:‖);
w
document.write(―<br>‖);
document.write(―ENO:‖+
xmlDocument.getElementsByTagName(―eno‖)[0].childNodes[0].nodeValue);
document.write(―<br>‖);
document.write(―Name:‖+
xmlDocument.getElementsByTagName(―name‖)[0].childNodes[0].nodeValue);
document.write(―<br>‖);
document.write(―ADDRESS:‖+
xmlDocument.getElementsByTagName(―address‖)[0].childNodes[0].nodeValue);
document.write(―<br>‖);
document.write(―PHONE:‖+
xmlDocument.getElementsByTagName(―phone‖)[0].childNodes[0].nodeValue);
document.write(―<br>‖);
om
document.write(―DEPARTMENT:‖+
xmlDocument.getElementsByTagName(―dept‖)[0].childNodes[0].nodeValue);
document.write(―<br>‖);
document.write(―COLLEGE:‖+
xmlDocument.getElementsByTagName(―col‖)[0].childNodes[0].nodeValue);
document.write(―<br>‖);
.c
document.write(―GROUP:‖+
xmlDocument.getElementsByTagName(―group‖)[0].childNodes[0].nodeValue);
</script>
ul
</body>
</html>
OUTPUT:
pa
XML document faculty is loaded and content of this file is
ENO: 30
NAME: Kalpana
ADDRESS: Hyd
jin
PHONE: 9959967192
DEPARTMENT: CSE
COLLEGE: MRCET
GROUP: MRGI
.re
We can access any XML element using the index value: four.html
<html> <head>
<script type=‖text/javascript‖ src=‖my_function_file.js‖></script>
</head> <body>
w
<script type=‖text/javascript‖>
xmlDoc=My_function(“faculty1.xml”);
value=xmlDoc. getElementsByTagName(―name‖);
w
document.write(―value[0].childNodes[0].nodeValue‖);
</script></body></html>
OUTPUT: Kalpana
w
HTML Vs XHTML
HTML XHTML
1. The HTML tags are case insensitive. 1. The XHTML tags are case sensitive.
EX: <BoDy>---------</body> EX: <body>---------</body>
2. We can omit the closing tags sometimes. 2. For every tag there must be a closing tag.
EX: <h1>---------</h1> or <h1------------/>
3. The attribute values not always 3. The attribute values are must be quoted.
om
necessary to quote.
4. In HTML there are some implicit 4. In XHTML the attribute values must be
attribute values. specified explicitly.
5. In HTML even if we do not follow the 5. In XHTML the nesting rules must be
nesting rules strictly it does not cause much strictly followed. These nesting rules are-
difference. - A form element cannot contain another form
element.
.c
-an anchor element does not contain another
form element
-List element cannot be nested in the list
ul
element
-If there are two nested elements then the
inner element must be enclosed first before
closing the outer element
pa
-Text element cannot be directly nested in
form element
The relationship between SGML, XML, HTML and XHTML is as given below
jin
.re
EX:
<!DOCTYPE html PUBLIC"-//W3C//DTD XHTML 1.0 Transitional//EN"
w
"http://www.w3.org/TR/xhtml1/DTD/xhtml11.dtd">
<html xmlns="http://www.w3c.org/1999/xhtml">
<head>
<title>Sample XHTML Document</title>
</head>
<body bgcolor=‖#FF0000‖>
<basefont face=‖arial‖ size=‖14‖ color=‖white‖>
<h1>MRCET</h1>
<h2>MRCET</h2>
<h3>MRCET</h3>
<h4> KALPANA </h4>
<h5> KALPANA </h5>
<h6>KALPANA</h6>
<p><center> XHTML syntax rules are specified by the file xhtml11.dtd file. </center></p>
<div align="right"> <b>XHTML standards for eXtensible Hypertext Markup Language.</b>
om
XHTML syntax rules are specified by the file xhtml11.dtd file.</div>
<pre> <b>XHTML standards for <i>eXtensible Hypertext Markup Language.</i></b>
XHTML syntax rules are specified by the file xhtml11.dtd file.</pre>
</basefont>
</body>
</html>
.c
DOM in JAVA
DOM interfaces
ul
The DOM defines several Java interfaces. Here are the most common interfaces:
Node - The base datatype of the DOM.
pa
Ele ment - The vast majority of the objects you'll deal with are Elements.
Attr Represents an attribute of an element.
Text The actual content of an Element or Attr.
Document Represents the entire XML document. A Document object is often
referred to as a DOM tree.
jin
Node.
Node.getAttribute(attrName) - For a given Node, returns the attribute with the
requested name.
w
DOM
import java.io.*;
import javax.xml.parsers.*;
import org.w3c.dom.*;
import org.xml.sax.*;
public class parsing_DOMDemo
{
public static void main(String[] args)
om
{
try
{
System.out.println(―enter the name of XML document‖);
BufferedReader input=new Bufferedreader(new InputStreamReader(System.in));
String file_name=input.readLine();
.c
File fp=new File(file_name);
if(fp.exists())
{
try
ul
{
DocumentBuilderFactory Factory_obj= DocumentBuilderFactory.newInstance();
DocumentBuilder builder=Factory_obj.newDocumentBuilder();
pa
InputSource ip_src=new InputSource(file_name);
Document doc=builder.parse(ip_src);
System.out.println(―file_name+‖is well- formed.‖);
}
catch (Exception e)
jin
{
System.out.println(file_name+‖is not well- formed.‖);
System.exit(1);
} }
else
.re
{
System.out.println(―file not found:‖+file_name);
} }
catch(IOException ex)
{
w
ex.printStackTrace();
}
} }
w
SAX:
SAX (the Simple API for XML) is an event-based parser for xml documents. Unlike a
w
DOM parser, a SAX parser creates no parse tree. SAX is a streaming interface for XML,
which means that applications using SAX receive event notifications about the XML
document being processed an element, and attribute, at a time in sequential order starting at
the top of the document, and ending with the closing of the ROOT element.
Reads an XML document from top to bottom, recognizing the tokens that make up a
well- formed XML document
Tokens are processed in the same order that they appear in the document
Reports the application program the nature of tokens that the parser has encountered
as they occur
The application program provides an "event" handler that must be registered with the
parser
As the tokens are identified, callback methods in the handler are invoked with the
relevant information
When to use?
om
You should use a SAX parser when:
You can process the XML document in a linear fashion from the top down
The document is not deeply nested
You are processing a very large XML document whose DOM tree would consume
too much memory.Typical DOM implementations use ten bytes of memory to
.c
represent one byte of XML
The problem to be solved involves only part of the XML document
Data is available as soon as it is seen by the parser, so SAX works well for an XML
document that arrives over a stream
ul
Disadvantages of SAX
We have no random access to an XML document since it is processed in a forward-
pa
only manner
If you need to keep track of data the parser has seen or change the order of items, you
must write the code and store the data on your own
The data is broken into pieces and clients never have all the information as a whole
unless they create their own data structure
jin
Scanning the XML file from start to end, each event invokes a corresponding callback method
that the programmer writes.
w
SAX packages
javax.xml.parsers: Describing the main classes needed for parsing
org.xml.sax: Describing few interfaces for parsing
w
SAX classes
SAXParser Defines the API that wraps an XMLReader implementation class
SAXParserFactory Defines a factory API that enables applications to configure and
obtain a SAX based parser to parse XML documents
ContentHandler Receive notification of the logical content of a document.
om
document.
StartElement() and endElement() – methods called at the start and end of a document
element.
Characters() – method called with the text contents in between the start and end tags of
an XML document element.
.c
ContentHandler Interface
This interface specifies the callback methods that the SAX parser uses to notify an
application program of the components of the XML document that it has seen.
ul
void startDocument() - Called at the beginning of a document.
void endDocument() - Called at the end of a document.
void startElement(String uri, String localName, String qName, Attributes atts) -
pa
Called at the beginning of an element.
void endElement(String uri, String localName,String qName) - Called at the end
of an element.
void characte rs(char[] ch, int start, int length) - Called when character data is
encountered.
jin
void ignorableWhitespace( char[] ch, int start, int length) - Called when a DTD is
present and ignorable whitespace is encountered.
void processingInstruction(String target, String data) - Called when a processing
instruction is recognized.
void setDocumentLocator(Locator locator)) - Provides a Locator that can be used
.re
This interface specifies methods for processing the attributes connected to an element.
int getLength() - Returns number of attributes, etc.
SAX simple API for XML
w
import java.io.*;
import org.xml.sax;
import org.xml.sax.helpers;
public class parsing_SAXDemo
{
public static void main(String[] args) throws IOException
{
try {
System.out.println(―enter the name of XML document‖);
BufferedReader input=new Bufferedreader(new InputStreamReader(System.in));
String file_name=input.readLine();
File fp=new File(file_name);
if(fp.exists())
{
try
om
{
XMLReader reader=XMLReaderFactory.createXMLReader();
reader.parse(file_name);
System.out.println(―file_name+‖is well- formed.‖);
}
catch (Exception e)
.c
{
System.out.println(file_name+‖is not well- formed.‖);
System.exit(1);
}
ul
}
else
{
pa
System.out.println(―file not found:‖+file_name);
}
}
catch(IOException ex){ex.printStackTrace();}
} }
jin
before processing
Occupies more memory Doesn‘t store the XML in memory
We can insert or delete nodes We can‘t insert or delete a node
DOM is a tree model parser SAX is an event based parser
Document Object Model (DOM) API SAX is a Simple API for XML
Preserves comments Doesn‘t preserve comments
w
DOM is slower than SAX, heavy weight. SAX generally runs a little faster than DOM,
light weight.
Traverse in any direction. Top to bottom traversing is done in this
w
approach
Random Access Serial Access
Packages required to import Packages required to import
w
UNIT III
Web Servers and Servlets
Web Servers:
Web servers are computers that deliver (serves up) Web pages. Every Web server has an IP
om
address and possibly a domain name. For example, if you enter the URL
http://www.mrcet.com/index.html in your browser, this sends a request to the Web server whose
domain name is mrcet.com. The server then fetches the page named index.html and sends it to your
browser.
Any computer can be turned into a Web server by installing server software and connecting the
.c
machine to the Internet. There are many Web server software applications, including public domain
software and commercial packages.
ul
While installation, we assign port number 8080 to APACHE. Make sure that these ports are
available i.e., no other process is using this port.
DESCRIPTION:
pa
Set the JAVA_HOME Variable
You must set the JAVA_HOME environment variable to tell Tomcat where to find Java.
Failing to properly set this variable prevents Tomcat from handling JSP pages. This variable
should list the base JDK installation directory, not the bin subdirectory. On Windows XP,
jin
you could also go to the Start menu, select Control Panel, choose System, click on the
Advanced tab, press the Environment Variables button at the bottom, and enter the
JAVA_HOME variable and value directly as:
Name: JAVA_HOME
.re
Value: C:\jdk
Set the CLASSPATH
Since servlets and JSP are not part of the Java 2 platform, standard edition, you have to
identify the servlet classes to the compiler. The server already knows about the servlet
classes, but the compiler (i.e., javac) you use for development probably doesn't. So, if you
w
don't set your CLASSPATH, attempts to compile servlets, tag libraries, or other classes that
use the servlet and JSP APIs will fail with error messages about unknown classes.
w
Name: JAVA_HOME
Value: install_dir/common/lib/servlet-api.jar
w
om
.c
ul
RESULT: Thus TOMCAT web server was installed successfully.
pa
Access the developed static web pages for books web site, using these servers by putting the
web pages developed in week-1 and week-2 in the document root.
jin
.re
w
w
w
om
RESULT: These pages are accessed using the TOMCAT web server successfully.
.c
INTRODUCTION TO SERVLETS
Servlets:
ul
• Servlets are server side programs that run on a Web or Application server and act as a
middle layer between a requests coming from a Web browser and databases or
applications on the server.
pa
• Using Servlets, you can collect input from users through web page forms, present records
from a database or another source, and create web pages dynamically.
• Servlets don‘t fork new process for each request, instead a new thread is created.
• Servlets are loaded and ready for each request.
jin
Web Container: It is web server that supports servlet execution. Individual Servlets
.re
are registered with a container. Tomcat is a popular servlet and JSP container.
w
w
w
Servlet Architecture:
om
Servlets Tasks:
.c
Servlets perform the following major tasks:
Read the explicit data sent by the clients (browsers). This includes an HTML form on a
Web page or it could also come from an applet or a custom HTTP client program.
ul
Read the implicit HTTP request data sent by the clients (browsers). This includes cookies,
media types and compression schemes the browser understands, and so forth.
Process the data and generate the results. This process may require talking to a database,
pa
executing an RMI or CORBA call, invoking a Web service, or computing the response
directly.
Send the explicit data (i.e., the document) to the clients (browsers). This document can be
sent in a variety of formats, including text (HTML or XML), binary (GIF images), Excel,
etc.
jin
Send the implicit HTTP response to the clients (browsers). This includes telling the
browsers or other clients what type of document is being returned (e.g., HTML), setting
cookies and caching parameters, and other such tasks.
Life Cycle
om
.c
Steps:
The sequence in which the Web containe r calls the life cycle methods of a servlet is:
ul
1. The Web container loads the servlet class and creates one or more instances of the
servlet class.
2. The Web container invokes init() method of the servlet instance during initialization of
the servlet. The init() method is invoked only once in the servlet life cycle.
pa
3. The Web container invokes the service() method to allow a servlet to process a client
request.
4. The service() method processes the request and returns the response back to the Web
container.
5. The servlet then waits to receive and process subsequent requests as explained in steps
jin
3 and 4.
6. The Web container calls the destroy() method before removing the servlet instance
from the service. The destroy() method is also invoked only once in a servlet life cycle.
.re
When a user invokes a servlet, a single instance of each servlet gets created, with each
user request resulting in a new thread that is handed off to doGet or doPost as appropriate.
The init() method simply creates or loads some data that will be used throughout the life
w
of the servlet.
publicvoidinit()throwsServletException{
// Initialization code...
w
Each time the server receives a request for a servlet, the server spawns a new thread and
calls service.
The service() method checks the HTTP request type (GET, POST, PUT, DELETE, etc.)
and calls doGet, doPost, doPut, doDelete, etc. methods as appropriate.
publicvoid service(ServletRequest request,
ServletResponse response)
throwsServletException,IOException{
}
om
The doGet() Method
The doGet() method processes client request, which is sent by the client, using the
HTTP GET method.
To handle client requests that are received using GET method, we need to override
the doGet() method in the servlet class.
.c
In the doGet() method, we can retrieve the client information of the
HttpServletRequest object. We can use the HttpServletResponse object to send the
response back to the client.
ul
publicvoiddoGet(HttpServletRequest request,
HttpServletResponse response)
throwsServletException,IOException{
// Servlet code
pa
}
The doPost() Method:
The doPost() method handles requests in a servlet, which is sent by the client, using the
HTTP POST method.
jin
For example, if a client is entering registration data in an HTML form, the data can be
sent using the POST method.
Unlike the GET method, the POST request sends the data as part of the HTTP request
body. As a result, the data sent does not appear as a p art of URL.
.re
To handle requests in a servlet that is sent using the POST method, we need to override
the doPost() method. In the doPost() method, we can process the request and send the
response back to the client.
publicvoiddoPost(HttpServletRequest request,
HttpServletResponse response)
w
throwsServletException,IOException{
// Servlet code
}
w
threads, write cookie lists or hit counts to disk, and perform other such cleanup activities.
After the destroy() method is called, the servlet object is marked for garbage collection.
publicvoid destroy()
{
// Finalization code...
}
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
om
}
public void doGet(HttpServletRequestrequest,HttpServletResponse response)
throwsServletException, IOException {
// Set response content type
response.setContentType("text/html");
// Actual logic goes here.
PrintWriter out = response.getWriter();
out.println("<h1>" + message + "</h1>");
.c
}
public void destroy() {
// do nothing.
}
ul
}
- The JAVA_HOME environment variable should be set so that Tomcat can find JDK
JAVA_HOME = c:\jdk1.5
4. Setup deployment environment
.re
w
w
om
.c
ul
pa
5. Creating ServletDemoServlet
There are three different ways to create a servlet.
a. By implementing Servlet interface
b. By extending GenericServlet class
c. By extending HttpServlet class
jin
<servlet>
<servlet-name>Demo</servlet-name>
<servlet-class>DemoServlet</servlet-class>
w
</servlet>
<servlet-mapping>
<servlet-name>Demo</servlet-name>
w
<url-patte rn>/welcome</url-pattern>
</servlet-mapping>
</web-app>
8. Start Tomcat server
9. Open browser and type http://localhost/MyApp/DemoServlet
Servlet API
Servlet API consists of two important packages that encapsulates all the important classes
and interface, namely :
1. javax.servlet
2. javax.servlet.http
1. javax.servlet
om
Inte rfaces
1. Servlet – Declares life cycle methods for a servlet.
2. ServletConfig – To get initialization parameters
3. ServletContext- To log events and access information
4. ServletRequest- To read data from a client request
5. ServletResponse – To write data from client response
Classes
.c
1. GenericServlet – Implements Servlet and ServletConfig
2. ServletInputStream – Provides an input stream for reading client requests.
3. ServletOutputStream - Provides an output stream for writing
ul
responses to a client.
4. ServletException – Indicates servlet error occurred.
5. UnavailableException - Indicates servlet is unavailable
pa
jin
.re
w
w
w
Servlet Interface
Method Description
public void init(ServletConfigconfig) initializes the servlet. It is the life cycle
method of servlet and invoked by the web
container only once.
public void provides response for the incoming request.
service(ServletRequestrequest,ServletResponse It is invoked at each request by the web
response) container.
public void destroy() is invoked only once and indicates that
om
servlet is being destroyed.
public ServletConfiggetServletConfig() returns the object of ServletConfig.
public String getServletInfo() returns information about servlet such as
writer, copyright, version etc.
import java.io.*;
.c
import javax.servlet.*;
public class First implements Servlet{
ServletConfig config=null;
ul
public void init(ServletConfig config){
this.config=config;
System.out.println("servlet is initialized");
pa
}
public void service(ServletRequest req,ServletResponse res)
throws IOException,ServletException{
res.setContentType("text/html");
PrintWriter out=res.getWriter();
jin
out.print("<html><body>");
out.print("<b>hello KALPANA</b>");
out.print("</body></html>");
}
.re
return config;
}
public String getServletInfo(){
w
ServletConfig interface
• When the Web Container initializes a servlet, it creates a ServletConfig object for the
servlet.
Methods
• getInitParameter(String name): returns a String value initialized parameter
• getInitParameterNames(): returns the names of the servlet's initialization parameters as an
Enumeration of String objects
• getServletContext(): returns a reference to the ServletContext
• getServletName(): returns the name of the servlet instance
om
ServletContext Interface
• For every Web application a Se rvletContext object is created by the web container.
• ServletContext object is used to get configuration information from Deployme nt
Descriptor(web.xml) which will be available to any servlet.
.c
Methods :
• getAttribute(String name) - returns the container attribute with the given name
• getInitParameter(String name) - returns parameter value for the specified parameter name
ul
• getInitParameterNames() - returns the names of the context's initialization parameters as
an Enumeration of String objects
• setAttribute(String name,Objectobj) - set an object with the given attribute name in the
pa
application scope
• removeAttribute(String name) - removes the attribute with the specified name from the
application context
Servlet RequestInterface
jin
Methods
• getAttribute(String name), removeAttribute(String name), setAttribute(String name,
w
Object o), getAttributeName() – used to store and retrieve an attribute from request.
• getParameter(String name) - returns value of parameter by name
• getParameterNames() - returns an enumeration of all parameter names
• getParameterValues(String name) - returns an array of String objects containing all of the
w
values the given request parameter has, or null if the parameter does not exist
Servlet ResponseInterface
w
Methods
• getWriter()- returns a PrintWriter object that can send character text to the client.
• setContentType(String type)- sets the content type of the response being sent to the client
before sending the respond.
GenericServlet class
GenericServlet class implements Servlet, ServletConfig and Serializable interfaces.
It provides the implementation of all the methods of these interfaces except the service
method.
GenericServlet class can handle any type of request so it is protocol- independent.
You may create a generic servlet by inheriting the GenericServlet class and providing the
implementation of the service method .
om
Methods
.c
public void destroy() is invoked only once throughout the life cycle and indicates that
servlet is being destroyed.
publicServletConfiggetServletConfig() returns the object of ServletConfig.
ul
public String getServletInfo() returns information about servlet such as writer, copyright,
version etc.
public void init() it is a convenient method for the servlet programmers, now there is no
need to call super.init(config)
pa
publicServletContextgetServletContext() returns the object of ServletContext.
public String getInitParameter(String name) returns the parameter value for the given
parameter name.
public Enumeration getInitParameterNames() returns all the parameters defined in the
we b.xml file.
jin
ServletInputStream Class
It provides stream to read binary data such as image etc. from the request object. It is an
abstract class.
The getInputStream() method of ServletRequest interface returns the instance of
w
ServletInputStream class
intreadLine(byte[] b, int off, intlen) it reads the input stream.
w
ServletOutputStream Class
It provides a stream to write binary data into the response. It is an abstract class.
The getOutputStream() method of Se rvletResponse interface returns the instance of
w
ServletOutputStream class.
ServletOutputStream class provides print() and println() methods that are overloaded.
2. javax.servlet.http
om
Inte rfaces
1. HttpServletRequest
2. HttpServletResponse
3. HttpSession
.c
Classes
1. HttpServlet
2.Cookie
ul
HTTPServletRequest and HTTPServletResponse
pa
jin
.re
The HttpServletRequest breaks a request down into parsed elements, such as request URI,
query arguments and headers. Various get methods allow you to access different parts of
the request.
w
2. Parameters -
The HttpServletRequest provides methods for accessing parameters of a request. The
methods getParameter(), getParameterValues()and getParameterNames() are offered
as ways to access the arguments.
3. Attributes –
The request object defines a method called getAttribute(). The servlet interface
provides this as a way to include extra information about the request that is not covered
by any of the other HttpServletRequest methods.
4. ServletInputStream –
The ServletInputStream is an InputStream that allows your servlets to read all of the
request‘s input following the headers.
om
HTTPServletResponseExtends the ServletResponse interface and can perform these tasks
1. Set Response Codes –
The response code for a request is a numeric value that represents the status of the
response. For example, 200 represents a successful response, 404 represents a file not
found.
.c
2. Set Headers –
Headers for the response can be set by calling setHeader, specifying the name and value
of the header to be set.
ul
3. Send Redirects –
The sendRedirect method is used to issue a redirect to the browser, causing the browser
to issue a request to the specified URL. The URL passed to sendRedirect must be an
absolute URL—it must include protocol, machine, full path, and so on.
pa
4. Set ServletOutputStream –
The ServletOutputStream is obtained by calling getOutputStream on the
HttpServletResponse. It is a subclass of OutputStream that contains a number of
convenient print and println methods.Data written to the ServletOutputStream goes
jin
HTTPSession
HttpSession object is used to store entire session with a specific client.
.re
HTTPServlet
w
HttpServlet is extends from GenericServlet and does not override init, destroy and other
methods.
It implements the service () method which is abstract method in GenericServlet.
w
A subclass of HttpServlet must override at least one method, usually one of these:
o doGet(), if the servlet supports HTTP GET requests
o doPost(), for HTTP POST requests
w
Cookie
A cookie is a small piece of information that is persisted between the multiple client
requests.
javax.servlet.http.Cookie class provides the functionality of using cookies. It provides a
lot of useful methods for cookies.
public void addCookie(Cookie ck):method of HttpServletResponse interface is used to
add cookie in response object.
om
public Cookie[] getCookies():method of HttpServletRequest interface is used to return all
the cookies from the browser.
Reading Servlet Parameters(or) Handling HTTPRequest and HTTPResponse
The parameters are the way in which a client or user can send information to the Http
Server.
The HTTPSe rvletRequest interface includes methods that allow you to read the names
.c
and values of parameters that are included in a client request.
The HttpServletResponse Interface provides functionality for sending response to client.
The browser uses two methods to pass this information to web server. These methods are
ul
GET Method and POST Method.
GET method:
The GET method sends the encoded user information appended to the page request.
pa
The page and the encoded information are separated by the ? character as follows:
http://www.test.com/hello?key1=value1&key2=value2
The GET method is the defualt method to pass information from browser to web server.
Never use the GET method if you have password or other sensitive information to pass to
jin
the server.
The GET method has size limtation: only 1024 characters can be in a request string.
This information is passed using QUERY_STRING header and will be accessible through
QUERY_STRING environment variable.
.re
This message comes to the backend program in the form of the standard input which you
can parse and use for your processing.
Servlet handles this type of requests using doPost() method.
w
the situation:
getParameter(): You call request.getParameter() method to get the value of a form
parameter.
getParameterValues(): Call this method if the parameter appears more than once and
returns multiple values, for example checkbox.
getParameterNames(): Call this method if you want a complete list of all parameters in
the current request.
om
import java.io.*;
import java.util.*;
import javax.servlet.http.*;
public class HelloForm extends HTTPServlet {
public void doPost(HttpServletRequest request,HttpServletResponse response)throws
IOException,ServletException{
PrintWriter pw = response.getWriter();
.c
pw.print("<html><body>");
pw.print("Name: "+request.getParameter("first_name")+
― ―+request.getParameter("last_name"));
ul
pw.print("</body></html>");
pw.close();
}
}
pa
Compile HelloForm.java as follows: $javac HelloForm.java
Compilation would produce HelloForm.class file.
Next you would have to copy this class file in
<Tomcat- installation-directory>/webapps/ROOT/WEB-INF/classes
jin
<servlet>
<servlet-name>HelloForm</servlet-name>
.re
<servlet-class>HelloForm</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>HelloForm</servlet-name>
w
<url-pattern>/HelloForm</url-pattern>
</servlet- mapping>
<formaction="HelloForm"method="GET">
First Name: <inputtype="text"name="first_name"><br/>
Last Name: <inputtype="text"name="last_name"/></br>
<inputtype="submit"value="Submit"/>
</form>
</body>
</html>
Submit
Start Tomcat Server and open browser.
om
Now enter firstname and lastname, Click Submit
It will generate result
Name: KalpanaMrcet
.c
Reading Initialization Parameters
1. Using Servlet Config:
ul
An object of ServletConfig is created by the web container for each servlet. This object
can be used to get configuration information from web.xml file.
If the configuration information is modified from the web.xml file, we don't need to
change the servlet. So it is easier to manage the web application if any specific content is
pa
modified from time to time.
Methods
• getInitParameter(String name): returns a String value initialized parameter
• getInitParameterNames(): returns the names of the servlet's initialization parameters as an
Enumeration of String objects
jin
for a servlet.
<web-app>
<servlet>
......
w
<init-param>
<param-name>email</param-name>
<param-value>kalpana@gamil.com</param-value>
w
</init-param>
......
</servlet>
w
</web-app>
Retrieve ServletConfig
ServletConfigsc = getServletConfig();
out.println(sc.getInitParameter("email"));
Ex: we b.xml
<web-app>
servlet>
<servlet-name>TestInitParam</servlet-name>
<servlet-class>TestInitParam</servlet-class>
<init-param>
<param-name>email</param-name>
om
<param-value>kalpana@gmail.com</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>TestInitParam</servlet-name>
<url-pattern>/TestInitParam</url-pattern>
.c
</servlet- mapping>
</web-app>
ul
TestInitParam.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
pa
public class TestInitParam extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
jin
ServletConfigsc=getServletConfig();
out.print("<html><body>");
out.print("<b>"+sc.getInitParameter("email")+"</b>");
out.print("</body></html>");
.re
out.close();
}
}
It will generate result
w
kalpana@gmail.com
w
2. Using ServletContext
An object of ServletContext is created by the web container at time of deploying the
project.
w
This object can be used to get configuration information from web.xml file.
There is only one ServletContext object per web application.
If any information is shared to many servlet, it is better to provide it from the web.xml file
using the <context-param> element.
Advantage
Easy to maintain if any information is shared to all the servlet, it is better to make it
available for all the servlet.
We provide this information from the web.xml file, so if the information is changed, we
don't need to modify the servlet. Thus it removes maintenance problem.
Uses
om
1. The object of ServletContext provides an interface between the container and servlet.
2. The ServletContext object can be used to get configuration information from the web.xml
file.
3. The ServletContext object can be used to set, get or remove attribute from the web.xml
file.
.c
4. The ServletContext object can be used to provide inter-application communication.
Methods:
getAttribute(String name) - returns the container attribute with the given name
ul
getInitParameter(String name) - returns parameter value for the specified parameter name
getInitParameterNames() - returns the names of the context's initialization parameters as
an Enumeration of String objects
pa
setAttribute(String name,Objectobj) - set an object with the given attribute name in the
application scope
removeAttribute(String name) - removes the attribute with the specified name from the
application context
jin
Retrieve ServletContext
ServletContextapp = getServletContext();
OR
ServletContextapp = getServletConfig().getServletContext();
.re
Ex: we b.xml
<web-app>
<context-param>
<param-name>driverName</param-name>
w
<param-value>sun.jdbc.JdbcOdbcDriver</param-value>
</context-param>
w
<servlet>
<servlet-name>TestServletContext</servlet- name>
<servlet-class>TestServletContext</servlet-class>
w
</servlet>
<servlet-mapping>
<servlet-name>TestServletContext</servlet- name>
<url-pattern>/TestServletContext</url-pattern>
</servlet- mapping>
</web-app>
TestServletContext.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class TestServletContext extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
om
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
ServletContextsc = getServletContext();
out.println(sc.getInitParameter("driverName"));
}
.c
}
ul
sun.jdbc.JdbcOdbcDriver
pa
Context Init parameters Servlet Init parameter
Available to all servlets and JSPs that are part Available to only servlet for which the
of web <init-param> was configured
Context Init parameters are initialized within Initialized within the <servlet> for each
jin
Only one ServletContext object for entire web Each servlet has its own ServletConfig
app object
Session Tracking
w
om
• We use session tracking to recognize the user It is used to recognize the particular user.
• Session Tracking Techniques
.c
– Cookies
– Hidden Form Field
– URL Rewriting
ul
– HttpSession
Cookies
pa
Cookies are text files stored on the client computer and they are kept for various
information tracking purpose
There are three steps involved in identifying returning users:
o Server script sends a set of cookies to the browser in response header.
o Browser stores this information on local machine for future use.
jin
o When next time browser sends any request to web server then it sends those cookies
information to the server in request header and server uses that information to identify the
user.
Cookies are created using Cookie class present in Servlet API.
.re
For adding cookie or getting the value from the cookie, we need some methods provided
by other interfaces. They are:
a. public void addCookie(Cookie ck):method of HttpServletResponse interface is used
to add cookie in response object.
b. public Cookie[] getCookies():method of HttpServletRequest interface is used to return
all the cookies from the browser.
w
w
w
Disadvantage of Cookies
• It will not work if cookie is disabled from the browser.
• Only textual information can be set in Cookie object.
Methods
public void setMaxAge(int expiry) Sets the maximum age of the cookie in seconds.
public String getName() Returns the name of the cookie. The name cannot
om
be changed after creation.
public String getValue() Returns the value of the cookie.
public void setName(String name) changes the name of the cookie.
public void setValue(String value) changes the value of the cookie.
.c
Create Cookie
Cookie ck=ne w Cookie("user","kalpana ");//creating cookie object
response.addCookie(ck);//adding cookie in the response
ul
Delete Cookie
It is mainly used to logout or signout the user.
Cookie ck=ne w Cookie("user","");//deleting value of cookie
pa
ck.setMaxAge(0);//changing the maximum age to 0 seconds
response.addCookie(ck);//adding cookie in the response
Get Cookies
Cookie ck[]=request.getCookies();
jin
for(int i=0;i<ck.length;i++)
out.print("<br>"+ck[i].getName()+" "+ck[i].getValue());
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
w
response.setContentType("text/html");
PrintWriter out = response.getWriter();
Cookie cookie = null;
out.println("<html><body>"+
"<form method='get' action='/mrcet/CookieLab'>"+
"Name:<input type='text' name='user' /><br/>"+
if(!pass.equals("") || !name.equals("")) {
om
Cookie ck = new Cookie(name,pass);
response.addCookie(ck);
}
.c
out.println("<h2> Found Cookies Name and Value</h2>");
for (inti = 0; i<cookies.length; i++){
cookie = cookies[i];
out.print("Cookie Name : " + cookie.getName() + ", ");
ul
out.print("Cookie Value: " + cookie.getValue()+" <br/>");
}
}
pa
out.println("</body></html>");
}
}
we b.xml
<web-app>
jin
<servlet>
<servlet-name>ListandAddCookie</servlet-name>
<servlet-class>ListandAddCookie</servlet-class>
</servlet>
.re
<servlet-mapping>
<servlet-name>ListandAddCookie</servlet-name>
<url-pattern>/ListandAddCookie</url-pattern>
</servlet- mapping>
w
</web-app>
Session
w
• HttpSession Interface provides a way to identify a user across more than one page request
or visit to a Web site and to store information about that user.
• Web container creates a session id for each user. The container uses this id to identify the
w
particular user.
• The servlet container uses this interface to create a session between an HTTP client and an
HTTP server.
• The session persists for a specified time period, across more than one connection or page
request from the user.
The HttpServletRequest interface provides two methods to get the object of HttpSession:
1. publicHttpSessiongetSession():Returns the current session associated with this
request, or if the request does not have a session, creates one.
2. publicHttpSessiongetSession(boolean create):Returns the current HttpSession
associated with this request or, if there is no current session and create is true, returns
om
a new session.
Destroy Session
session.invalidate();
.c
session.setAttribute(name,value);
session.getAttribute(name);
Methods
ul
1. public String getId():Returns a string containing the unique identifier value.
2. public long getCreationTime():Returns the time when this session was created,
measured in milliseconds since midnight January 1, 1970 GMT.
pa
3. public long getLastAccessedTime():Returns the last time the client sent a request
associated with this session, as the number of milliseconds since midnight January 1,
1970 GMT.
4. public void invalidate():Invalidates this session then unbinds any objects bound to it.
jin
Steps
• On client's first request, the Web Container generates a unique session ID and gives it
back to the client with response. This is a temporary session created by web container.
.re
• The client sends back the session ID with each request. Making it easier for the web
container to identify where the request is coming from.
• The Web Container uses this ID, finds the matching session with the ID and associates
the session with the request.
w
w
w
Ex: SessionTrack.java
import java.io.*;
importjavax.servlet.*;
importjavax.servlet.http.*;
om
public void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
// Create a session object if it is already not created.
HttpSession session = request.getSession(true);
.c
String title = "Welcome to my website";
String userID = "";
Integer visitCount = new Integer(0);
ul
if (session.isNew())
{
pa
userID = "Kalpana";
session.setAttribute("UserId", "Kalpana");
}
else {
visitCount = (Integer)session.getAttribute("visitCount");
jin
visitCount = visitCount + 1;
userID = (String)session.getAttribute("UserId");
}
session.setAttribute("visitCount", visitCount);
.re
response.setContentType("text/html");
PrintWriter out = response.getWriter();
w
out.println("<html>" +
"<body>" +
"<h1>Session Infomation</h1>" +
w
"<table border='1'>" +
"<tr><th>Session info</th><th>value</th></tr>" +
"<tr><td>id</td><td>" + session.getId() + "</td></tr>" +
w
we b.xml
<web-app>
<servlet>
<servlet-name>SessionTrack</servlet-name>
<servlet-class>SessionTrack</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>SessionTrack</servlet-name>
om
<url-pattern>/SessionTrack</url-pattern>
</servlet- mapping>
</web-app>
Output:
.c
ul
pa
jin
.re
w
w
w
UNIT IV
JAVA SERVER PAGES
Introduction to JSP: The Problem with Servlet. The Anatomy of a JSP Page, JSP Processing. JSP
Application Design with MVC Setting Up and JSP Environment, JSP Declarations, Directives,
Expressions, Code Snipplets, implement objects, Requests, Using Cookies and Session for Session
om
The Servlet technology and JavaServer Pages (JSP) are the two main technologies for
developing java Web applications. When first introduced by Sun Microsystems in 1996, the
Servlet technology was considered superior to the reigning Common Gateway Interface
(CGI) because servlets stay in memory after they service the first requests. Subsequent
requests for the same servlet do not require instantiation of the servlet‘s class therefore
enabling better response time.
.c
Servlets are Java classes that implement the javax.servlet.Servlet interface. They are
compiled and deployed in the web server. The problem with servlets is that you embed
ul
HTML in Java code. If you want to modify the cosmetic look of the page or you want to
modify the structure of the page, you have to change code. Generally speaking, this
is left to the better hands (and brains) of a web page designer and not to a Java developer.
pa
PrintWriter pw = response.getWriter();
pw.println("<html><head><title>Testing</title></head>"); pw.println("<body
bgcolor=\"# ffdddd\"> ");
As seen from the example above this method presents several difficulties to the web
developer:
jin
1. The code for a servlet becomes difficult to understand for the programmer.
2. The HTML content of such a page is difficult if not impossible for a web designer to
understand or design.
3. This is hard to program and even small changes in the presentation, such as the page‘s
.re
background color, will require the servlet to be recompiled. Any changes in the
HTML content require the rebuilding of the whole servlet.
4. It's hard to take advantage of web-page development tools when designing the
application interface. If such tools are used to develop the web page layout, the
generated HTML must then be manually embedded into the servlet code, a process
which is time consuming, error prone, and extremely boring.
w
5. In many Java servlet-based applications, processing the request and generating the
response are both handled by a single servlet class.
6. The servlet contains request processing and business logic (implemented by methods ),
w
and also generates the response HTML code, are embedded directly in the servlet code.
JSP solves these problems by giving a way to include java code into an HTML page using
w
scriptlets. This way the HTML code remains intact and easily accessible to web designers,
but the page can sill perform its task.
In late 1999, Sun Microsystems added a new element to the collection of Enterprise Java
tools: JavaServer Pages (JSP). JavaServer Pages are built on top of Java servlets and
designed to increase the efficiency in which programmers, and even nonprogrammers, can
create web content.
Instead of embedding HTML in the code, you place all static HTML in a JSP page, just as in
a regular web page, and add a few JSP elements to generate the dynamic parts of the page.
The request processing can remain the domain of the servlet, and the business logic can be
handled by JavaBeans and EJB components.
A JSP page is handled differently compared to a servlet by the web server. When a servlet is
deployed into a web server in compiled (bytecode) form, then a JSP page is deployed in its
original, human-readable form.
om
When a user requests the specific page, the web server compiles the page into a servlet and
from there on handles it as a standard servlet.
This accounts for a small delay, when a JSP page is first requested, but any subsequent
requests benefit from the same speed effects that are associated with servlets.
The Problem with Servlet
• Servlets are difficult to code which are overcome in JSP. Other way, we can say, JSP is
.c
almost a replacement of Servlets, (by large, the better word is extension of Servlets),
where coding decreases more than half.
• In Servlets, both static code and dynamic code are put together. In JSP, they are
separated. For example,In Servlets:
ul
out.println(―Hello Mr.‖ + str + ‖ you are great man‖);
where str is the name of the client which changes for each client and is known as dynamic
content. The strings, ―Hello Mr.‖ and ―you are great man‖ are static content which is the
same irrespective of client. In Servlets, in println(), both are put together.
pa
• In JSP, the static content and dynamic content is separated. Static content is written in
HTML and dynamic content in JSP. As much of the response comprises of static content
(nearly 70%) only, the JSP file more looks as a HTML file.
• Programmer inserts, here and there, chunks of JSP code in a running HTML developed
by Designer. As much of the response delivered to cleint by server comprises of static
content (nearly 70%), the JSP file more looks like a HTML file. Other way we can say,
jin
they are builtin and are known as "implicit objects". That is, in JSP, Programmer never
creates these objects and straightaway use them as they are implicitly created and given
by JSP container. This decreases lot of coding.
• JSP can easily be integrated with JavaBeans.
w
• Writing alias name in <url-pattern> tag of web.xml is optional in JSP but mandatory in
Servlets.
• A Servlet is simply a Java class with extension .java written in normal Java code.
• A Servlet is a Java class. It is written like a normal Java. JSP is comes with some
elements that are easy to write.
om
Anatomy of JSP
.c
ul
pa
jin
.re
JSP Processing
Once you have a JSP capable web-server or application server, you need to know the
following information about it:
w
Hello, world
</BODY> </HTML>
Know where to place this file and how to see it in your browser with an http:// prefix.
Since this step is different for each web-server, you would need to see the web-server
documentation to find out how this is done. Once you have completed this step, proceed to
the next.
om
What is happening behind the scenes is that your JSP is being turned into a Java file,
compiled and loaded. This compilation only happens once, so after the first load, the file
doesn't take long to load anymore. (But everytime you change the JSP file, it will be re-
compiled again.)
Of course, it is not very useful to just write HTML pages with a .jsp e xtension! We now
.c
proceed to see what makes JSP so useful
Adding dynamic content via expressions
As we saw in the previous section, any HTML file can be turned into a JSP file by changing
ul
its extension to .jsp. Of course, what makes JSP useful is the ability to embed Java. Put the
following text in a file with .jsp extension (let us call it hello.jsp), place it in your JSP
directory, and view it in a browser.
pa
<HTML>
<BODY>
Hello! The time is now <%= new java.util.Date() %>
</BODY>
jin
</HTML>
Notice that each time you reload the page in the browser, it comes up with the current time.
The character sequences
<%= and %> enclose Java expressions, which are evaluated at run time.
.re
This is what makes it possible to use JSP to generate dyamic HTML pages that change in
response to user actions or vary from user to user.
In this lesson we will learn about the various elements available in JSP with suitable
examples. In JSP elements can be dividedinto 4 different types.
These are:
w
1. Expressions
We can use this tag to output any data on the generated page. These data are automatically
converted to string and printed on the output stream.
w
JSP Expressions start with Syntax of JSP Scriptles are with <%= and ends with %>.
Between these this you can put anything and that will convert to the String and that will be
displayed.
Example: <%="Hello World!" %> Above code will display 'Hello World!'
2. Scriplets
In this tag we can insert any amount of valid java code and these codes are placed in
_jspService method by the JSP engine.
Syntax of JSP Scriptles are:
<% //java codes
%>
JSP Scriptlets begins with <% and ends %> .We can embed any amount of java code in the
om
JSP Scriptlets. JSP Engine places these code in the _jspService() method. Variables available
to the JSP Scriptlets are:
.c
String userName=null; userName=request.getParameter("userName");
%>
b. Response: Response represents the server response and is a subclass of
ul
HttpServletResponse.
<% response.setContentType("text/html"); %>
pa
c. Session: represents the HTTP session object associated with the
request. Your Session ID: <%= session.getId() %>
d. Out: out is an object of output stream and is used to send any output to the client.
3. Directives
jin
A JSP "directive" starts with <%@ characters. In the directives we can import packages,
define error handling pages or the session information of the JSP page.
Syntax of JSP directives is:
.re
b. include: include is used to include a file in the JSP page. Example: <%@ include
file="/header.jsp" %>
w
c. taglib: taglib is used to use the custom tags in the JSP pages (custom tags allows us to
defined our own tags). Example: <%@ taglib uri="tlds/taglib.tld" prefix="mytag" %>
Page tag attributes are:
w
a. language="java"
This tells the server that the page is using the java language. Current JSP specification
w
om
4. Declarations
This tag is used for defining the functions and variables
to be used in theJSP. Syntax of JSP Declaratives are:
<%!
//java codes
.c
%>
JSP Declaratives begins with <%! and ends %> with .We can embed any amount of java code
in the JSP Declaratives. Variables and functions defined in the declaratives are class level and
ul
can be used anywhere in the JSP page.
Example
<%@ page import="java.util.*" %>
pa
<HTML>
<BODY>
<%!
Date theDate = new Date(); Date getDate()
jin
{
System.out.println( "In getDate() method" ); return theDate;
}
%>
.re
<HEAD>
<TITLE>A Web Page</TITLE>
</HEAD>
w
<BODY>
<% out.println("Hello there!"); %>
</BODY>
</HTML>
Using a Literal
<HTML>
<HEAD>
<TITLE>Using a Literal</TITLE>
</HEAD>
<BODY>
<H1>Using a Literal</H1>
om
<%
out.println("Number of days = "); out.println(365);
%>
</BODY>
</html>
.c
Declaration Tag Example
<%!
String name = "Joe";
ul
String date = "8th April, 2002";
%>
<HTML>
pa
<TITLE>Declaration Tag Example</TITLE>
<BODY>
This page was last modified on <%= date %> by <%= name %>.
</BODY>
jin
</HTML>
Embedding Code
<%!
.re
<BODY>
<H1>List of people</H1>
<TABLE BORDER="1">
w
<TH>Name</TH>
<% for (int i=0; i<names.length; i++) { %>
w
<TR><TD><%= names[i]%></TD></TR>
<% } %>
</TABLE>
</BODY>
</HTML>
Use out
<%@ page language="java" %>
<HTML>
<HEAD><TITLE>JSP Example</TITLE></HEAD>
<BODY>
<H1>Quadratic Equation: y = x^2</H1>
<TABLE BORDER="1">
om
<TH>x</TH><TH>y</TH>
<%
for (int i=0; i<10; i++)
out.print("<TR><TD WIDTH='100'>" + i + "</TD><TD WIDTH='100'>" + (i*i) +
"</TD></TR>");
.c
%>
</TABLE>
</BODY>
ul
</HTML>
Casting to a New Type
<HTML>
pa
<HEAD>
<TITLE>Casting to a New Type</TITLE>
</HEAD>
<BODY>
jin
</BODY>
</HTML>
w
Creating a String
<HTML>
<HEAD>
w
<TITLE>Creating a String</TITLE>
</HEAD>
<BODY>
<H1>Creating a String</H1>
<%
String greeting = "Hello from JSP!";
out.println(greeting);
%>
</BODY>
</HTML>
om
Use for loop to dis play string array
<%@ page session="false" %>
<%
String[] colors = {"red", "green", "blue"};
for (int i = 0; i < colors.length; i++) { out.print("<P>" + colors[i] + "</p>");
.c
}
%>
ul
Creating an Array
<HTML>
<HEAD>
pa
<TITLE>Creating an Array</TITLE>
</HEAD>
<BODY>
<H1>Creating an Array</H1>
jin
<%
double accounts[];
accounts = new double[100]; accounts[3] = 119.63;
out.println("Account 3 holds $" + accounts[3]);
.re
%>
</BODY>
</HTML>
<HTML>
<HEAD>
w
Finding a Factorial
om
<HTML>
<HEAD>
<TITLE>Finding a Factorial</TITLE>
</HEAD>
<BODY>
.c
<H1>Finding a Factorial</H1>
<%
int value = 6, factorial = 1, temporaryValue = value;
ul
while (temporaryValue > 0) { factorial *= temporaryValue; temporaryValue--;
}
out.println("The factorial of " + value + " is " + factorial + ".");
pa
%>
</BODY>
</HTML>
jin
</HEAD>
<BODY>
<H1>Using Buttons</H1>
<FORM NAME="form1" ACTION="basic.jsp" METHOD="POST">
w
<!--
function button1()
{
document.form1.buttonName.value = "button 1" form1.submit()
}
function button2()
{
document.form1.buttonName.value = "button 2" form1.submit()
}
function button3()
{
document.form1.buttonName.value = "button 3" form1.submit()
om
}
// -->
</SCRIPT>
</BODY>
</HTML>
.c
basic.jsp
<HTML>
ul
<HEAD>
<TITLE>Determining Which Button Was Clicked</TITLE>
</HEAD>
pa
<BODY>
<H1>Determining Which Button Was Clicked</H1> You clicked
<%= request.getParameter("buttonName") %>
</BODY>
jin
</HTML>
<HTML>
<HEAD>
<TITLE>Submitting Check Boxes</TITLE>
</HEAD>
w
<BODY>
<H1>Submitting Check Boxes</H1>
<FORM ACTION="basic.jsp" METHOD="post">
w
<BR>
<INPUT TYPE="CHECKBOX" NAME="check2" VALUE="check2">
Checkbox 2
<BR>
<INPUT TYPE="CHECKBOX" NAME="check3" VALUE="check3">
Checkbox 3
<BR>
<INPUT TYPE="SUBMIT" VALUE="Submit">
</FORM>
</BODY>
</HTML>
basic.jsp
om
<HTML>
<HEAD>
<TITLE>Reading Checkboxes</TITLE>
</HEAD>
<BODY>
.c
<H1>Reading Checkboxes</H1>
<%
if(request.getParameter("check1") != null) { out.println("Checkbox 1 was checked.<BR>");
ul
}
else {
out.println("Checkbox 1 was not checked.<BR>");
pa
}
if(request.getParameter("check2") != null) { out.println("Checkbox 2 was checked.<BR>");
}
else {
jin
else {
out.println("Checkbox 3 was not checked.<BR>");
}
%>
w
</BODY>
</HTML>
w
Let introduce a design model called Model- View-Controller (MVC), suitable for both simple
and complex applications.
MVC was first described by Xerox in a number of papers published in the late 1980s. The
key point of using MVC is to separate logic into three distinct units: the Model, the View,
and the Controller. In a server application, we commonly classify the parts of the
application as business logic, presentation, and request processing.
Business logic is the term used for the manipulation of an application's data, such as
customer, product, and order information. Presentation refers to how the application data is
displayed to the user, for example, position, font, and size. And finally, request
processing is what ties the business logic and presentation parts together.
In MVC terms, presentation should be separated from the business logic. Presentation of that
data (the View) changes fairly often. Just look at all the face- lifts many web sites go through
to keep up with the latest fashion in web design. Some sites may want to present the data in
different languages or present different subsets of the data to internal and external users.
om
cookies:
A cookie is a small piece of information created by a JSP program that is stored in the client‘s
hard disk by the browser. Cookies are used to store various kind of information such as
username, password, and user preferences, etc.
.c
Different methods in cookie class are:
1.String getName()- Returns a name of cookie
2.String getValue()-Returns a value of cookie
ul
3.int getMaxAge()-Returns a maximum age of cookie in millisecond
4. String getDomain()-Returns a domain
5.boolean getSecure()-Returns true if cookie is secure otherwise false
pa
6.String getPath()-Returns a path of cookie
7.void setPath(Sting)- set the path of cookie
8.void setDomain(String)-set the domain of cookie
9.void setMaxAge(int)-set the maximum age of cookie
10.void setSecure(Boolean)-set the secure of cookie.
jin
Creating cookie:
Cookie are created using cookie class constructor.
Content of cookies are added the browser using addCookies() method.
.re
Reading cookies:
Reading the cookie information from the browser using getCookies() method.
Find the length of cookie class.
Retrive the information using different method belongs the cookie class
w
PROGRAM: To create and read the cookie for the given cookie name as “EMPID” and
its value as”AN2356”.
w
om
out.println(―name=‖+name);
out.println(―value=‖+value);
}
%>
.c
The HttpSession object associated to the request
Session object has a session scope that is an instance of javax.servlet.http.HttpSession class.
ul
Perhaps it is the most commonly used object to manage the state contexts.
This object persist information across multiple user connection.
Created automatically by
pa
Different methods of HttpSession interface are as follows:
Program:
<%!
HttpSession h=req.getSesssion(true);
Date d=(Date) h.getAttribute(“Date”);
w
d1=h.setAttribute(“date”,d1);
out.println(―current date and time=‖+d1);
%>
w
UNIT-5
DATABASE ACCESS & JAVA BEANS
Database Access: Database Programming using JDBC, JDBC drivers, Studying Javax.sql.* package,
Connecting to database in PHP, Execute Simple Queries, Accessing a Database from a Servlet and JSP
page.Java Beans: Introduction to Beans, Deploying java Beans in a JSP page.
om
What is JDBC Driver?
JDBC drivers implement the defined interfaces in the JDBC API, for interacting with your
database server.
For example, using JDBC drivers enable you to open database connections and to interact
with it by sending SQL or database commands then receiving results with Java.
.c
The Java.sql package that ships with JDK, contains various classes with their behaviours
defined and their actual implementaions are done in third-party drivers. Third party vendors
implements the java.sql.Driver interface in their database driver.
ul
JDBC Drivers Types
JDBC driver implementations vary because of the wide variety of operating systems and
pa
hardware platforms in which Java operates. Sun has divided the implementation types into
four categories, Types 1, 2, 3, and 4, which is exp lained below −
In a Type 1 driver, a JDBC bridge is used to access ODBC drivers installed on each client
machine. Using ODBC, requires configuring on your system a Data Source Name (DSN) that
represents the target database.
When Java first came out, this was a useful driver because most databases only supported
ODBC access but now this type of driver is recommended only for experimental use or when
.re
The JDBC-ODBC Bridge that comes with JDK 1.2 is a good example of this kind of driver.
om
.c
ul
pa
The Oracle Call Interface (OCI) driver is an example of a Type 2 driver.
jin
You can think of the application server as a JDBC "proxy," meaning that it makes calls for
the client application. As a result, you need some knowledge of the application server's
configuration in order to effectively use this driver type.
Your application server might use a Type 1, 2, or 4 driver to communicate with the database,
understanding the nuances will prove helpful.
om
through socket connection. This is the highest performance driver available for the database
and is usually provided by the vendor itself.
This kind of driver is extremely flexible, you don't need to install special software on the
client or server. Further, these drivers can be downloaded dynamically.
.c
ul
pa
jin
.re
MySQL's Connector/J driver is a Type 4 driver. Because of the proprietary nature of their
network protocols, database vendors usually supply type 4 drivers.
If you are accessing one type of database, such as Oracle, Sybase, or IBM, the preferred
driver type is 4.
If your Java application is accessing multiple types of databases at the same time, type 3 is
w
The type 1 driver is not considered a deployment- level driver, and is typically used for
development and testing purposes only.
The first thing you need to do is check that you are set up properly. This involves the
following steps:
To install both the Java tm platform and the JDBC API, simply follow the instructions for
downloading the latest release of the JDK tm (Java Development Kit tm ). When you
download the JDK, you will get JDBC as well.
Your driver should include instructions for installing it. For JDBC drivers written for specific
om
DBMSs, installation consists of just copying the driver onto your machine; there is no special
configuration needed.
The JDBC-ODBC Bridge driver is not quite as easy to set up. If you download JDK, you will
automatically get the JDBC-ODBC Bridge driver, which does not itself require any special
configuration. ODBC, however, does. If you do not already have ODBC on your machine,
you will need to see your ODBC driver vendor for information on installation and
.c
configuration.
ul
If you do not already have a DBMS installed, you will need to follow the vendor's
instructions for installation. Most users will have a DBMS installed and will be working with
an established database.
pa
Configuring Database:
Configuring a database is not at all difficult, but it requires special permissions and is
normally done by a database administrator.
First, open the control panel. You might find "Administrative tools" select it, again you may
jin
find shortcut for "Data Sources (ODBC)". When you open the ―Data Source (ODBC)" 32bit
ODBC‖ icon, you‘ll see a "ODBC Data Source Administrator" dialog window with a
number of tabs, including ―User DSN,‖ ―System DSN,‖ ―File DSN,‖ etc., in which ―DSN‖
means ―Data Source Name.‖ Select ―System DSN,‖. and add a new entry there, Select
appropriate driver for the data source or directory where database lives. You can name the
.re
entry anything you want, assume here we are giving our data source name as "MySource".
JDBC Database Access
JDBC was designed to keep simple things simple. This means that the JDBC API makes
everyday database tasks, like simple SELECT statements, very easy.
w
Import a package java.sql.* : This package provides you set of all classes that enables a
network interface between the front end and back end database.
w
prepareCall()
•Statement interface used to interact with database via the execution of SQL statements.
Methods of this interface are executeQuery(), executeUpdate(), execute() and getResultSet().
•A ResultSet is returned when you execute an SQL statement. It maintains a pointer to a row
within the tablur results. Mehods of this interface are next(), getBoolean(), getByte(),
getDouble(), getString() close() and getInt().
Establishing a Connection
The first thing you need to do is establish a connection with the DBMS you want to use. This
involves two
steps: (1) loading the driver and (2) making the connection.
Loading Drivers: Loading the driver or drivers you want to use is very simple and involves
just one line of code. If, for example, you want to use the JDBC-ODBC Bridge driver, the
following code will load it
om
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Your driver documentation will give you the class name to use. For instance, if
the class name is jdbc.DriverXYZ , you would load the driver with the following line of
code:
.c
Class.forName("jdbc.DriverXYZ");
Making the Connection: The second step in establishing a connection is to have the
appropriate driver connect to the DBMS. The following line of code illustrates the general
ul
idea:
Connection con = DriverManager.getConnection(url,"myLogin", "myPassword");
pa
If you are using the JDBC-ODBC Bridge driver, the JDBC URL will start with jdbc:odbc: .
The rest of the URL is generally your data source name or database system. So, if you are
using ODBC to access an ODBC data source called "MySource, " for example, your JDBC
URL could be jdbc:odbc:MySource . In place of " myLogin " you put the name you use to
log in to the DBMS; in place of " myPassword " you put your password for the DBMS. So if
jin
you log in to your DBMS with a login name of " scott " and a password of "tiger" just these
two lines of code will establish a connection:
statement you want to send. For a SELECT statement, the method to use is executeQuery .
For statements that create or modify tables, the method to use is executeUpdate .
w
For example, in the following code fragment, we supply executeUpdate with the SQL
statement from the example above:
om
into two strings concatenated by a plus sign (+) so that it will compile. Executing Statements.
Statements that create a table, alter a table, or drop a table are all examples of DDL
statements and are executed with the method executeUpdate. The method executeUpdate is
also used to execute SQL statements that update a table. In practice, executeUpdate is used
far more often to update tables than it is to create them because a table is created once but
may be updated many times.
.c
The method used most often for executing SQL statements is executeQuery . This method is
used to execute SELECT statements, which comprise the vast majority of SQL statements.
ul
Entering Data into a Table
We have shown how to create the table STUDENT by specifying the names of the columns
and the data types to be stored in those columns, but this only sets up the structure of the
pa
table. The table does not yet contain any data. We will enter our data into the table one row at
a time, supplying the information to be stored in each column of that row. Note that the
values to be inserted into the columns are listed in the same order that the columns were
declared when the table was created, which is the default order.
Note that we use single quotation marks around the student name because it is nested
within double quotation marks. For most DBMSs, the general rule is to alternate
double quotation marks and single quotation marks to indicate nesting.
The code that follows inserts a second row into the table STUDENT . Note that we can just
reuse the Statement object stmt rather than having to create a new one for each execution.
w
those values. The star (*) in the following SQL statement indicates that all columns should be
selected. Since there is no WHERE clause to narrow down the rows from which to select, the
following SQL statement selects the whole table:
We now show how you send the above SELECT statements from a program written in the
Java programming language and how you get the results we showed.
JDBC returns results in a ResultSet object, so we need to declare an instance of the class
ResultSet to hold our results. The following code demonstrates declaring the ResultSet
object rs and assigning the results of our earlier query to it:
ResultSet rs = stmt.executeQuery( "SELECT S_NAME, YEAR FROM STUDENT");
om
The following code accesses the values stored in the current row of rs. Each time the method
next is invoked, the next row becomes the current row, and the loop continues until there are
no more rows in rs .
String query = "SELECT COF_NAME, PRICE FROM STUDENT";
ResultSet rs = stmt.executeQuery(query);
.c
while (rs.next())
{
String s = rs.getString("S_NAME");
ul
Integer i = rs.getInt("S_ID");
String c = rs.getString("COURSE");
String y = rs.getString(―YEAR‖);
pa
System.out.println(i + " " + s + " " + c + " " + y);
}
Updating Tables
Suppose that after a period of time we want update the YEAR column in the table
jin
STUDENT. The SQL statement to update one row might look like this:
Using the Statement object stmt , this JDBC code executes the SQL statement contained in
updateString :
stmt.executeUpdate(updateString);
w
method throws an exception, there be some mechanism to handle it. Generally a catch block
will catch the exception and specify what happens (which you may choose to be nothing). In
the sample code, we use two try blocks and two catch blocks. The first try block contains
w
the method Class.forName, from the java.lang package. This method throws a
ClassNotFoundException, so the catch block immediately following it deals with t hat
exception. The second try block contains JDBC methods, which all throw SQLExceptions, so
one catch block at the end of the application can handle all of the rest of the exceptions
that might be thrown because they will all be SQLException objects.
Retrieving Exceptions
JDBC lets you see the warnings and exceptions generated by your DBMS and by the Java
compiler. To see exceptions, you can have a catch block print them out. For example, the
following two catch blocks from the sample code print out a message explaining the
exception:
Try
{
// Code that could generate an exception goes here.
om
// If an exception is generated, the catch block below
// will print out information about it.
} catch(SQLException ex)
{
System.err.println("SQLException: " + ex.getMessage());
.c
}
JavaBeans
JavaBeans:
ul
JavaBeans is architecture for both using and building components in Java. This architecture
supports the features of software reuse, component models, and object orientation. One of the
most important features of JavaBeans is that it does not alter the existing Java language.
pa
Although Beans are intended to work in a visual application development tool, they don't
necessarily have a visual representation at run-time (although many will). What this does
mean is that Beans must allow their property values to be changed through some type of
visual interface, and their methods and events should be exposed so that the development tool
can write code capable of manipulating the component when the application is executed.
jin
Bean Development Kit (BDK) is a tool for testing whether your JavaBeans meets the
JavaBean specification.
Features of JavaBeans
Compact and Easy: JavaBeans components are simple to create and easy to use. This is an
.re
important goal of the JavaBeans architecture. It doesn't take very much to write a simple
Bean, and such a Bean is lightweight, it doesn't have to carry around a lot of inherited
baggage just to support the Beans environment.
Portable: Since JavaBeans components are built purely in Java, they are fully portable to any
platform that supports the Java run-time environment. All platform specifics, as well as
w
development tool at design-time. The default behavior of this process allows for the
automatic introspection of any Bean. A low- level reflection mechanism is used to analyze the
Bean's class to determine its methods. Next it applies some simple design patterns to
w
determine the properties and events that are supported. To take advantage of reflection, you
only need to follow a coding style that matches the design pattern. This is an important
feature of JavaBeans. It means that you don't have to do anything more than code your
methods using a simple convention. If you do, your Beans will automatically support
introspection without you having to write any extra code.
Customization: When you are using a visual development tool to assemble
components into applications, you will be presented with some sort of user interface for
customizing Bean attributes. These attributes may affect the way the Bean operates or the
way it looks on the screen. The application tool you use will be able to determine the
properties that a Bean supports and build a property sheet dynamically. This property sheet
will contain editors for each of the properties supported by the Bean, which you can use to
customize the Bean to your liking. The Beans class library comes with a number of property
editors for common types such as float, boolean, and String. If yo u are using custom classes
for properties, you will have to create custom property editors to associate with them.
Persistence: It is necessary that Beans support a large variety of storage mechanisms. This
om
way, Beans can participate in the largest number of applications. The simplest way to support
persistence is to take advantage of Java Object Serialization. This is an automatic mechanism
for saving and restoring the state of an object. Java Object Serialization is the best way to
make sure that your Beans are fully portable, because you take advantage of a standard
feature supported by the core Java platform. This, however, is not always desirable. There
may be cases where you want your Bean to use other file formats or mechanisms to save and
.c
restore state. In the future, JavaBeans will support an alternative externalization mechanism
that will allow the Bean to have complete control of its persistence mechanism.
ul
The Bean Development kit is a tool that allows the user to configure and interconnect a set of
beans. The user can change the properties of a Bean, link two or more Beans and execute
Beans.
pa
Start the "beanbox" by running "$bdk\beanbox\run.bat".
The Bean Development Kit (BDK) represents a Toolbox, a Bea n Box and a Property
Window. The Toolbox window that lists the demonstration Beans.
The BeanBox window that provides an
jin
The BDK is also represents a Properties window that provides an interface through which the
user configure a Bean.
w
om
Java beans- development phases
1. The Construction Phase
2. The Build Phase
3. The Execution Phase
JavaBeans component design conventions govern the properties of the class, and the
.c
public methods that give access to the properties.
A JavaBeans component property can be:
ul
It means it contains a single value, or indexed, i.e. it represents an array of values.
There is no requirement that a property be implemented by an instance variable; the
property must simply be accessible using public methods that conform to certain
pa
conventions:
For each readable property, the bean must have a method of the form:
PropertyClass getProperty () { ... }
For each writable property, the bean must have a method of the form:
jin