Documenti di Didattica
Documenti di Professioni
Documenti di Cultura
UNIT I
OVERVIEW:
This unit provides information about web technologies that relate to the interface
between web servers and their clients. This information includes markup languages,
programming interfaces and languages, and standards for document identification
and display. The term "Web 2.0" (2004present) is commonly associated with web
applications that facilitate interactive information sharing, interoperability, usercentered design and collaboration on the World Wide Web. Examples of Web 2.0
include web-based communities, hosted services, web applications, socialnetworking sites, video-sharing sites, wikis, blogs and folksonomies. A Web 2.0 site
allows its users to interact with other users or to change website content, in contrast
to non-interactive websites where users are limited to the passive viewing of
information that is provided to them.
OBJECTIVES
A web page refers to any document on the web. Every web page is identified by a unique URL in
the internet and it contains hyper text i.e different types of text such as plain text ,graphics,
animation, Audio, video etc.
Web technology relates to the interface between web servers and their clients. It includes markup
languages, programming interfaces and languages, and standards for document identification and
display.
A web application is any application that is specifically used through a web browser. Some
examples of web applications include , ON Line Book Store , Shopping , Citrix Meta frame
applications and any number of tools such as package tracking that are found on the Internet.
Client/server describes the relationship between two computer programs in which one program,
the client, makes a service request from another program, the server, which fulfils the request.
Although programs within a single computer can use the client/server idea, it is a more important
idea in a network. In a network, the client/server model provides a convenient way to
interconnect programs that are distributed efficiently across different locations. Computer
transactions using the client/server model are very common. For example, to check your bank
account from your computer, a client program in your computer forwards your request to a
server program at the bank. That program might in turn forward the request to its own client
program that sends a request to a database server at another bank computer to retrieve your
account balance. The balance is returned back to the bank data client, which in turn serves it
back to the client in your personal computer, which displays the information for you.
HTML
HTML, Hypertext Mark-up Language, is the predominant markup language for developing
web pages. It provides a means to describe the structure of text-based information in a
documentby denoting certain text as links, headings, paragraphs, lists, etc.and to supplement
that text with interactive forms, embedded images, and other objects. HTML is written in the
form of "tags" consisting minimally of "elements" surrounded by angle brackets. HTML can also
describe, to some degree, the appearance and semantics of a document, and can include
embedded scripting language code (such as JavaScript) that can affect the behavior of Web
browsers and other HTML processors.
HTML is a language for describing web pages.
HTML is a markup language
A markup language is a set of markup tags
The tags describe document content
HTML documents contain HTML tags and plain text
HTML documents are also called web pages
<tagname>content</tagname>
HTML Versions
Since the early days of the web, there have been many versions of HTML:
Version
Year
HTML
1991
HTML+
1993
HTML 2.0
1995
HTML 3.2
1997
HTML 4.01
1999
XHTML 1.0
2000
HTML5
2012
XHTML5
2013
Web Browsers
The purpose of a web browser (such as Google Chrome, Internet Explorer, Firefox, Safari) is to
read HTML documents and display them as web pages.
<head>
<title>Welcome To WWW </title>
</head>
<body>
<h1>This a heading</h1>
<p>This is a paragraph.</p>
<p>This is another paragraph.</p>
</body>
</html>
<pre> Tag
It is a pre-formatted tag : Displays as it is..
The data in html is displayed from left right and top to bottom irrespective of what ever format
we write in program Therefore to display as it is how we write in program we can use <pre> tag
HTML Headings
HTML defines different types of headers using six header tags i,e <h1> to <h6> tags.
The order of Font size is in decreasing order from h1 to h6
Example
<h1>HELLO</h1>
<h2>HELLO</h2>
<h3>HELLO</h3>
<h4>HELLO</h4>
<h5>HELLO</h5>
<h6>HELLO</h6>
<font> tag
Specify the font size, font face and color of text:
<font size="3" color="red">This is some text!</font>
<font size="2" color="blue">This is some text!</font>
<font face="verdana" color="green">This is some text!</font>
Description
<b>
<em>
<i>
<sup>
<u>
Defines underline
Description
Defines a variable
<pre>
Tag
Description
<abbr>
<address>
<bdo>
<blockquote>
<q>
<cite>
<dfn>
Attributes
Every Tag is associated with set of Attributes an attribute defines the characteristic of a
particular tag.
An Attribute is represented as a name value pair with in a tag
A tag can contain any no of attributes separated by space
Example
The attributes of body tag are
<body bgcolor=red text= green>
bgcolor represent the background color of the document and text represent the foreground color
of the document.
HTML Lists
Lists are used to display the list of elements in an order
Basically HTML supports Three types of lists Ordered List , Un Ordered List Definition List
The list items are marked with bullets (typically small black circles).
Example
<ul>
<li>Coffee</li>
<li>Milk</li>
</ul>
How the HTML code above looks in a browser:
Coffee
Milk
Example
<dl>
<dt>Coffee</dt>
<dd>- black hot drink</dd>
<dt>Milk</dt>
<dd>- white cold drink</dd>
</dl>
How the HTML code above looks in a browser:
Coffee
- black hot drink
Milk
- white cold drink
HTML Links
Linking or Navigating from one page to another
Html supports three types of Hyper Links
Text Hyper Link ( Text a Link)
Graphical HyperLink ( Image as a link)
Link with in single document or Internal Link
HTML links are defined with the <a> tag.
Example
Text Hyper Link
<a href="http://www.w3schools.com">Click</a>
Graphical Hyper Link
<a href="Pictures.html"> <img src =flower.gif ></a>
Internal Link
<h1><a name="seealso">See also</a></h1>
Or:
<h1 id="seealso">See also</h1>
then link to it:
HTML Images
HTML images are defined with the <img> tag.
Example
HTML Tables
Tables are defined with the <table> tag.
A table is divided into rows using <tr> , and each row is divided into data cells using<td> tag).
td stands for "table data," and holds the content of a data cell. A <td> tag can contain text, links,
images, lists, forms, other tables, etc.
Example
<caption> Time Table </caption>
<table border="1">
<tr>
<td>row 1, cell 1</td>
<td>row 1, cell 2</td>
</tr>
<tr>
<td>row 2, cell 1</td>
Width
Border
Bgcolor
Colspan
Row span
Cell spacing
Cell Padding
HTML FORMS
HTML forms are used to pass data to a server.
An HTML form can contain input elements like text fields, checkboxes, radio-buttons, submit
buttons and more. A form can also contain select lists, textarea, fieldset, legend, and label
elements.
The <form> tag is used to create an HTML form:
The most important form element is the <input> element.
The <input> element is used to select user information.
An <input> element can vary in many ways, depending on the type attribute. An <input>
element can be of type text field, checkbox, password, radio button, submit button, and more.
Text Fields
<input type="text"> defines a one-line input field that a user can enter text into:
<form>
First name: <input type="text" name="firstname"><br>
Last name: <input type="text" name="lastname">
</form>
How the HTML code above looks in a browser:
First name:
Last name:
ROSE
LILLY
********
Male
Female
Check Box
<input type="checkbox"> defines a checkbox. Checkboxes let a user select ZERO or MORE
options of a limited number of choices.
<form>
<input type="checkbox" name="vehicle" value="Bike">I have a bike<br>
<input type="checkbox" name="vehicle" value="Car">I have a car
</form>
How the HTML code above looks in a browser:
I have a bike
I have a car
Submit Button
<input type="submit"> defines a submit button.
A submit button is used to send form data to a server. The data is sent to the page specified in the
form's action attribute. The file defined in the action attribute usually does something with the
received input:
<form name="input" action="html_form_action.asp" method="get">
Username: <input type="text" name="user">
<input type="submit" value="Submit">
</form>
How the HTML code above looks in a browser:
Username:
Submit
If you type some characters in the text field above, and click the "Submit" button, the browser
will send your input to a page called "html_form_action.asp". The page will show you the
received input.
HTML FRAMES
Frames in HTML
To divide a web page into different partitions we use Frames
Two tags called <frameset> </frameset> and <frame > are used for creating frames and loading
pages into those frames.
Ex:
<frameset rows="60%,*">
<frame src="first.html"/>
<frame src="second.html"/>
</frameset>
<frameset> tag is a
If a user clicks the Visit James link, the James page will open in the Authors frame
Ex1:
<frameset rows="40%,60%">
<frame src="top.htm" name="top">
<frame src="bottom.htm" name="bottom">
</frameset>
Ex2 :
<frameset rows="16%,84%">
<frame src="top.htm" name="top">
<frameset cols="50%,50%">
<frame src="left.htm" name="left">
<frame src="right.htm" name="right">
</frameset></frameset>
body
{
background-color:#d0e4fe;
}
h1
{
color:orange;
text-align:center;
}
p
{
font-family:"Times New Roman";
font-size:20px;
}
Inline Styles
To use inline styles you use the style attribute in the relevant tag. The style attribute can contain
any CSS property. The example shows how to change the color and the left margin of a
paragraph:
<p style="color:sienna;margin-left:20px;">This is a paragraph.</p>
Note:
If we represent style as an attribute it is called Inline Style Sheeet
If we represent style as a tag it is called Embeded style Sheeet
If we represent styles in a seperate file and link that to a web page it is called External
style sheet
Important Questions :
1. a) Explain the purpose of cascading style sheets.
b) Design and create the page(s) for accepting the values of name and marks in a table then
displays them in the descending order of the marks.
2. Explain the following input components in HTML forms with proper syntax of the
corresponding HTML tags.
a) Text Input
b) Selectable list with multiple selection option
c) Radio Buttons.
3. Write HTML code to create a frame with a table contents on the left side of the window, and
have each entry in the table of contents. Use internal linking to scroll down the document
frame to the appropriate subsection.
Web Technologies
B.Tech III Year II Semester
IT DEPT
Java Script
Unit II
JavaScript
Introduction
data types & expressions
Arrays in Java Scripts
control statements
functions & libraries
Java Script Objects
Event Handling
Dynamic HTML Introduction
Dynamic HTML with Java Sripts
Introduction
HTML is good for developing static Web pages
can specify text/image layout, presentation, links,
Web page looks the same each time it is accessed
in order to develop interactive/reactive pages, must integrate programming in some form or
another
client-side programming
Client side validations of a Web application can be Performed using a scripting language
e.g., JavaScript, JScript, VBScript
Scripting elements are embedded in the HTML of a Web page, with (HTML) tags to identify
the program component
e.g., <script
type="text/javascript"> </script>
the browser executes the program as it loads the page, integrating the dynamic output of
the program with the static content of HTML
could also allow the user (client) to input information and process it, might be used to
validate input before its submitted to a remote server
JavaScript
JavaScript code can be embedded in a Web page using <script> tags
the output of JavaScript code is displayed as if directly entered in HTML
<html>
<head>
<title>JavaScript Page</title>
<script type="text/javascript">
// silly code to demonstrate output
document.write("<p>Hello world!</p>");
</body>
</html>
JavaScript Arrays
arrays store a sequence of items, accessible via an index
since JavaScript is loosely typed, elements do not have to be the same type
to create an array, allocate space using new
// displays elements
Array Example
<html>
<head>
<title>Die Statistics</title>
<script type="text/javascript"
src="http://www.csc.liv.ac.uk/~martin/teaching/comp519/JS/r
andom.js">
</script>
</head>
<body>
<script type="text/javascript">
numRolls = 60000;
dieSides = 6;
rolls = new Array(dieSides+1);
for (i = 1; i < rolls.length; i++) {
rolls[i] = 0;
}
for(i = 1; i <= numRolls; i++) {
rolls[randomInt(1, dieSides)]++;
}
suppose we want to
simulate die rolls and
verify even distribution
keep an array of counters:
initialize each count to 0
each time you roll X,
increment rolls[X]
display each counter
Arrays (cont.)
Arrays have predefined methods that allow them to be used as stacks,
queues, or other common programming data structures.
var stack = new Array();
stack.push("blue");
stack.push(12);
stack.push("green");
var item = stack.pop();
//
//
var q = [1,2,3,4,5,6,7,8,9,10];
item = q.shift();
// item is now equal to 1, remaining
// elements of q move down one position
// in the array, e.g. q[0] equals 2
q.unshift(125); // q is now the array [125,2,3,4,5,6,7,8,9,10]
q.push(244);
// q = [125,2,3,4,5,6,7,8,9,10,244]
if , if-else, switch
while, for, do-while,
PUZZLE: Suppose you took a piece
of paper and folded it in half, then in
half again, and so on.
<body>
<script type="text/javascript">
var userName = prompt("What is your name?", "");
var userAge = prompt("Your age?", "");
var userAge = parseFloat(userAge);
document.write("Hello " + userName + ".")
if (userAge < 18) {
document.write(" Do your parents know " +
"you are online?");
}
else {
document.write(" Welcome friend!");
}
</script>
<p>The rest of the page...</p>
</body>
</html>
User-Defined Functions
function definitions are similar to C++/Java, except:
no return type for the function (since variables are loosely typed)
no variable typing for parameters (since variables are loosely typed)
by-value parameter passing only (parameter gets copy of argument)
function isPrime(n)
// Assumes: n > 0
// Returns: true if n is prime, else false
{
if (n < 2) {
return false;
}
else if (n == 2) {
return true;
}
else {
for (var i = 2; i <= Math.sqrt(n); i++) {
if (n % i == 0) {
return false;
}
}
return true;
}
}
Function Example
<html>
<head>
<title>Prime Tester</title>
<script type="text/javascript">
function isPrime(n)
// Assumes: n > 0
// Returns: true if n is prime
{
// CODE AS SHOWN ON PREVIOUS SLIDE
}
</script>
</head>
<body>
<script type="text/javascript">
testNum = parseFloat(prompt("Enter a positive integer", "7"));
if (isPrime(testNum)) {
document.write(testNum + " <b>is</b> a prime number.");
}
else {
document.write(testNum + " <b>is not</b> a prime number.");
}
</script>
</body>
</html>
Function definitions
(usually) go in the
<head> section
<head> section is
loaded first, so then
the function is
defined before code
in the <body> is
executed (and,
therefore, the
function can be
used later in the
body of the HTML
document)
<html>
<head>
<title> Random Dice Rolls Revisited</title>
<script type="text/javascript">
function randomInt(low, high)
// Assumes: low <= high
// Returns: random integer in range [low..high]
{
return Math.floor(Math.random()*(high-low+1)) + low;
}
</script>
</head>
Another
Example
recall the dynamic dice
page
<body>
<div style="text-align: center">
<script type="text/javascript">
roll1 = randomInt(1, 6);
roll2 = randomInt(1, 6);
document.write("<img src='http://www.csc.liv.ac.uk/"+
"~martin/teaching/comp519/Images/die" +
roll1 + ".gif'/>");
document.write(" ");
document.write("<img src='http://www.csc.liv.ac.uk/"+
"~martin/teaching/comp519/Images/die" +
roll2 + ".gif'/>");
</script>
</div>
</body>
</html>
easier to remember,
promotes reuse
JavaScript Libraries
better still: if you define functions that may be useful to many pages, store in a
separate library file and load the library when needed
Note: as with external style sheets, do not put <script> tags in the external JavaScript library file
load a library using the SRC attribute in the SCRIPT tag (put nothing between the beginning
and ending tags)
<script type="text/javascript"
src="http://www.csc.liv.ac.uk/~martin/teaching/comp519/JS/random.js">
</script>
Library Example
<html>
<head>
<title> Random Dice Rolls Revisited</title>
<script type="text/javascript"
src="http://www.csc.liv.ac.uk/~martin/teaching/comp519/JS/random.js">
</script>
</head>
<body>
<div style="text-align: center">
<script type="text/javascript">
roll1 = randomInt(1, 6);
roll2 = randomInt(1, 6);
document.write("<img src='http://www.csc.liv.ac.uk/"+
"~martin/teaching/comp519/Images/die" +
roll1 + ".gif'/>");
document.write(" ");
document.write("<img src='http://www.csc.liv.ac.uk/"+
"~martin/teaching/comp519/Images/die" +
roll2 + ".gif'/>");
</script>
</div>
</body>
</html>
JavaScript Objects
an object defines a new type (formally, Abstract Data Type)
String Object
a String object encapsulates a sequence of characters, enclosed in quotes
properties include
length
methods include
charAt(index)
substring(start, end)
toUpperCase()
toLowerCase()
to create a string, assign using new or (in this case) just make a direct assignment (new is implicit)
word = new String("foo");
word = "foo";
word.charAt(0)
suppose we want to
test whether a word
or phrase is a
palindrome
noon
Radar
Madam, I'm Adam.
A man, a plan, a canal:
Panama!
must strip non-letters out of the
word or phrase
<html>
<head>
<title>Palindrome Checker</title>
<script type="text/javascript">
function strip(str)
{
// CODE AS SHOWN ON PREVIOUS SLIDE
}
function isPalindrome(str)
{
// CODE AS SHOWN ON PREVIOUS SLIDE
}
</script>
</head>
<body>
<script type="text/javascript">
text = prompt("Enter a word or phrase", "Madam, I'm Adam");
if (isPalindrome(text)) {
document.write("'" + text + "' <b>is</b> a palindrome.");
}
else {
document.write("'" + text + "' <b>is not</b> a palindrome.");
}
</script>
</body>
</html>
Date Object
String & Array are the most commonly used objects in JavaScript
other, special purpose objects also exist
the Date object can be used to access the date and time
to create a Date object, use new & supply year/month/day/ as desired
today = new Date();
12:00AM
methods include:
newYear.getYear()
newYear.getMonth()
newYear.getDay()
newYear.getHours()
newYear.getMinutes()
newYear.getSeconds()
newYear.getMilliseconds()
<html>
Date Example
<head>
<title>Time page</title>
</head>
<body>
Time when page was loaded:
<script type="text/javascript">
now = new Date();
document.write("<p>" + now + "</p>");
time = "AM";
hours = now.getHours();
if (hours > 12) {
hours -= 12;
time = "PM"
}
else if (hours == 0) {
hours = 12;
}
document.write("<p>" + hours + ":" +
now.getMinutes() + ":" +
now.getSeconds() + " " +
time + "</p>");
</script>
</body>
</html>
Another Example
<html>
<head>
<title>Time page</title>
</head>
<body>
<p>Elapsed time in this year:
<script type="text/javascript">
now = new Date();
newYear = new Date(2012,0,1);
secs = Math.round((now-newYear)/1000);
days = Math.floor(secs / 86400);
secs -= days*86400;
hours = Math.floor(secs / 3600);
secs -= hours*3600;
minutes = Math.floor(secs / 60);
secs -= minutes*60
document.write(days + " days, " +
hours + " hours, " +
minutes + " minutes, and " +
secs + " seconds.");
</script>
</p>
</body>
</html>
document Object
Internet Explorer, Firefox, Opera, etc. allow you to access information about an
HTML document using the document object
<html>
<head>
<title>Documentation page</title>
</head>
<body>
<table width="100%">
<tr>
<td><i>
<script type="text/javascript">
document.write(document.URL);
</script>
</i></td>
<td style="text-align: right;"><i>
<script type="text/javascript">
document.write(document.lastModified);
</script>
</i></td>
</tr>
</table>
</body>
</html>
document.write()
document.lastModified
navigator Object
navigator.appName
<html>
<!- COMP519
<head>
<title>Dynamic Style Page</title>
navigator.appVersion
-->
a {text-decoration:none;
font-size:larger;
color:red;
font-family:Arial}
a:hover {color:blue}
<!-- Netscape.css
-->
a {font-family:Arial;
color:white;
background-color:red}
js14.html
16.08.2006 -->
<script type="text/javascript">
if (navigator.appName == "Netscape") {
document.write('<link rel=stylesheet '+
'type="text/css" href="Netscape.css">');
}
else {
document.write('<link rel=stylesheet ' +
'type="text/css" href="MSIE.css">');
}
</script>
</head>
<body>
Here is some text with a
<a href="javascript:alert('GO AWAY')">link</a>.
</body>
</html>
User-Defined Objects
can define new objects, but the notation can be somewhat awkward
simply define a function that serves as a constructor
specify data fields & methods using this
Object Example
<html>
<head>
<title>Dice page</title>
<script type="text/javascript"
src="Die.js">
</script>
</head>
<body>
<script type="text/javascript">
die6 = new Die(6);
die8 = new Die(8);
roll6 = -1;
// dummy value to start loop
roll8 = -2;
// dummy value to start loop
while (roll6 != roll8) {
roll6 = die6.roll();
roll8 = die8.roll();
document.write("6-sided: " + roll6 +
" " +
"8-sided: " + roll8 + "<br />");
}
document.write("<br />Number of rolls: " +
die6.numRolls);
</script>
</body>
</html>
An event is something that happens, e.g. a mouse click on a button, an image that has loaded.
Events usually occur as a result of human interaction with the browser, e.g. selecting a document to
load, entering form information.
Event Handlers
Event handlers are JavaScript methods, i.e. functions of objects, that allow us as JavaScript
programmers to control what happens when events occur.
For example, the following form has an onSubmit event handler that displays an alert message:
<FORM NAME="formName" onSubmit="alert('Form submitted') >
<INPUT TYPE="SUBMIT"> </FORM>
Event Handlers
Area
button
checkbox
form
onReset(), onSubmit()
frame
onLoad(), onUnload()
image
link
password
radio
reset
select
submit
text
textarea
window
What is DHTML
Generally, DHTML refers to applications that allow a Web page to change dynamically without
requiring the request is to be passed to/from a web server.
More specifically, DHTML refers to the interaction of HTML, CSS and Scripting language
(JavaScript).
Example 2 :
Changing Font Dynamically using Mouse Events:
<html>
<head> <title> dynamic font styles and colors for links</title>
</head>
<body bgcolor=red>
<a style= color : blue;
onmouseover =this.style.color=red; this.style.font =italic 16pt Times ;
onmouseout =this.style.color=blue; this.style.font =normal 16pt Times ; >
Click Here </a>
</body>
</html>
OUT PUT :
When the mouse is placed on Hyper link text it will be changed from blue to red color.
When the mouse is out of the Hyper link it will be change back to blue color.
Important questions
1.
2.
3.
4.
5.
6.
Write a java script to verify a phone number, email-id and date formats.
7.
8.
Explain all the Implicit java script objects their properties and methods
Web Technologies
B.Tech. IT III Year II Semester
UNIT III
XML
eXtensible
Markup Language
(XML)
By:
G Indira Priyadarshini
IT DEPT, VJIT
Outline of Presentation
Introduction
Comparison between XML and HTML
XML Syntax
Document Type Definition (DTD)
Name Spaces
XML Schema
XSLT
XML Parsers
XML.
Based on Standard Generalized Markup Language
(SGML)
Version 1.0 introduced by World Wide Web
Consortium (W3C) in 1998
Bridge for data exchange on
the Web
Comparisons
XML
Extensible set of tags
Content orientated
Standard Data
infrastructure
Allows multiple output
forms
HTML
Fixed set of tags
Presentation oriented
No data validation
capabilities
Single presentation
XML Documents
Whats in an XML document?
Elements
Attributes
plus some other details
End Tag
Element
Content of
the Element
(Subelements
and/or Text)
Attributes with
name and value
author
title
text
number=1
Gerhard
Weikum
abstract
title=
In order
The Web
in 10 years
section
The
index
Web
provides
article
title
author
text
abstract
section
literature
index
(title,author+,text)>
(#PCDATA)>
(#PCDATA)>
(abstract,section*,literature?)>
(#PCDATA)>
(#PCDATA|index)+>
(#PCDATA)>
(#PCDATA)>
c
c+
c*
c?
Attribute Examples
<ATTLIST publication type
pubid
<ATTLIST cite
cid
<ATTLIST citation
ref
cid
(journal|inproceedings) #REQUIRED
ID #REQUIRED>
IDREF #REQUIRED>
IDREF #IMPLIED
ID #REQUIRED>
<publications>
<publication type=journal pubid=Weikum01>
<author>Gerhard Weikum</author>
<text>In the Web of 2010, XML <cite cid=12/>...</text>
<citation cid=12 ref=XML98/>
<citation cid=15>...</citation>
</publication>
<publication type=inproceedings pubid=XML98>
<text>XML, the extended Markup Language, ...</text>
</publication>
</publications>
Attribute Examples
<ATTLIST publication type
pubid
<ATTLIST cite
cid
<ATTLIST citation
ref
cid
(journal|inproceedings) #REQUIRED
ID #REQUIRED>
IDREF #REQUIRED>
IDREF #IMPLIED
ID #REQUIRED>
<publications>
<publication type=journal pubid=Weikum01>
<author>Gerhard Weikum</author>
<text>In the Web of 2010, XML <cite cid=12/>...</text>
<citation cid=12 ref=XML98/>
<citation cid=15>...</citation>
</publication>
<publication type=inproceedings pubid=XML98>
<text>XML, the extended Markup Language, ...</text>
</publication>
</publications>
keywords
Root element
Flaws of DTDs
No support for basic data types like integers, doubles,
dates, times,
No structured, self-definable data types
No type derivation
id/idref links are quite loose (target is not specified)
XML Schema
Namespaces
<library>
<description>Library of the CS Department</description>
<book bid=HandMS2000>
<title>Principles of Data Mining</title>
<description>
Short introduction to <em>data mining</em>, useful
for the IRDM course
</description>
</book>
</library>
Namespace Syntax
<dbs:book xmlns:dbs=http://www-dbs/dbs>
Prefix as abbrevation
of URI
Namespace Example
<dbs:book xmlns:dbs=http://www-dbs/dbs>
<dbs:description> ... </dbs:description>
<dbs:text>
<dbs:formula>
<mathml:math
xmlns:mathml=http://www.w3.org/1998/Math/MathML>
...
</mathml:math>
</dbs:formula>
</dbs:text>
</dbs:book>
Default Namespace
Default namespace may be set for an element and its
content (but not its attributes):
<book xmlns=http://www-dbs/dbs>
<description>...</description>
<book>
<?xml version=1.0/>
<address>
<name>Alice Lee</name>
<email>alee@aol.com</email>
<phone>212-346-234</phone>
<birthday>1985-03-02 </birthday>
</address>
XSLT
Extensible Stylesheet Language Transformations
To Present an XML document there are two approaches
1) Using Cascading Style Sheets or
2) Using XSLT
OUTPUT
Alice Lee
alee@aol.com
123-45-6789
1983-7-15
XML Parsers
All modern browsers have a built-in XML parser.
An XML parser converts an XML document into an XML DOM object - which
can then be manipulated with JavaScript.
XML supports two parsers
SAX Simple API for XML
Uses a call-back method
Similar to javax listeners
SAX approach to processing an XML document is called event processing.
The Processor scans the XML document from beginning to end.
DOM Document Object Model
Creates a parse tree
Requires a tree traversal
DOM approach build a hierarchical syntactical structure of XML
document which creates dynamic document s
References
Programming The World Wide Web Fourth Edition
by Robert W Sebesta
Elliotte Rusty Harold, Processing XML with Java,
Addison Wesley, 2002.
Elliotte Rusty Harold and Scott Means, XML
Programming, OReilly & Associates, Inc., 2002.
W3Schools Online Web Tutorials,
Important Questions
1. What is XML? How is XML useful? How is XML compatible with others
2. a) What is a document type definition (DTD)? How do you create DTD?
b) Explain DTD sequences
3. What is an XML schema? With an example explain the working of XML
schema.
4. Explain the working of XSL. ..
5. a)What is Document Object Model (DOM)? Explain the DOM levels
b) Differentiate SAX and DOM Parsers
Web Technologies
B.Tech. IT III Year II Semester
UNIT IV
Java Beans
By:
G Indira Priyadarshini
IT DEPT, VJIT
Outline of Presentation
Introduction
Java Bean API
Properties
Introspection Using Design Patterns
BDK
Example (Animation Bean)
Introspection using BeanInfo Interface
Definition
Java Bean is a reusable software component that
can be manipulated visually in a builder tool.
(from Java Bean Specification)
The JavaBeans API provides a framework for
defining reusable, embeddable, modular software
components.
Introduction
JavaBeans (beans)
Reusable software component model
Assemble predefined components
Create powerful applications and applets
Component assembler
Programmer who use defined components
Work on design of GUI and functionality
Do not need to know implementation
Just need to know services
GUI merging
Persistence
Event Handling
Introspection
Application Builder Support
Security issues
Persistence
Components can be stored and retrieved
Default inherit serialization
Can define more complex solutions based on
needs of the components
Event Handling
Defines how components interact
Java AWT event model serves as basis for the
event handling APIs
Provides a consistent way for components to
interact with each other
Introspection
Defines techniques so components can expose
internal structure at design time
Allows development tools to query a component
to determine member variables, methods, and
interfaces
Two Approaches of Introspection are
1. Standard naming patterns (Design Patterns)
2. Using BeanInfo Interface
Security Issues
JavaBeans are sbject to the standard Java security
model
The security model has neither extended nor
relaxed.
If a bean runs as an untrusted applet then it will be
subject to applet security
If a bean runs as a stand-alone application then it
will be treated as a normal Java application.
Properties
A builder tool can:
Types of Properties
Simple Properties.
Adding a Color property
Create and initialize a private instance variable
private Color color = Color.blue;
BeanInfo interface
Question: how does a Bean exposes its features in
a property sheet?
Answer: using java.beans.Introspector class
(which uses Core Reflection API)
The discovery process is named introspection
OR you can associate a class that implements the
BeanInfo with your bean
BeanInfo interface.
Why use BeanInfo then?
Using BeanInfo you can:
Expose features that you want to expose
Bean Customization
The appearance and behavior of a bean can be
customized at design time.
Two ways to customize a bean:
using a property editor
each bean property has its own editor
a beans property is displayed in a property sheet
using customizers
gives you complete GUI control over bean customization
used when property editors are not practical
Property Editors
If you provide a custom property editor class, then
you must refer to this class by calling
PropertyDescriptor.setPropertyEditorClass in a
BeanInfo class.
Each bean may have a BeanInfo class which
customizes how the bean is to appear.
SimpleBeanInfo implements that interface
BDK
ToolBox contains the beans available
BeanBox window is the form where you visually
wire beans together.
Properties sheet: displays the properties for the
Bean currently selected within the BeanBox
window.
24
MyFirstBean
import java.awt.*;
import java.io.Serializable;
public class FirstBean extends Canvas implements
Serializable {
public FirstBean() {
setSize(50,30);
setBackground(Color.blue);
}
}
First Bean
Compile: javac FirstBean.java
Create a manifest file:
manifest.txt
Name: FirstBean.class
Java-Bean: True
Properties
customizes selected
bean.
Resize button
Put mouse in corner, resize cursor
Drag mouse to change size
Edit menu
Access to events from beans that are an event source (bean can
notify listener)
Swing GUI components are beans
Select "Stop the Animation"
Edit->Events->button push -> actionPerformed
Opening
Applet beans (like Juggler) begin executing immediately
<html>
<head>
</head>
<body>
OurJuggler applet.
HTML file
10 <p>
11 <applet
12
archive="./OurJuggler.jar,./support.jar
13
,./juggler.jar
14
,./buttons.jar
15
"
16
code="OurJuggler"
17
width=382
18
height=150
19 >
20 Trouble instantiating applet OurJuggler!!
21 </applet>
1. archive
Program Output
getPropertyDescriptors (overridden)
Returns array of PropertyDescriptor objects
Each describes property
new PropertyDescriptor( "propertyName", beanClass )
Property must have named set and get methods
26
currentValue.setBound( true );
setBound( true )
Specifies property is bound
40
41
42
return 1;
}
getDefaultPropertyIndex (overridden)
Returns array index of default property
In this case, currentValue
44
getEventSetDescriptors
Returns array of EventSetDescriptor objects
Describes events supported by bean
EventSetDescriptor changed =
new EventSetDescriptor( beanClass,
"propertyChange",
java.beans.PropertyChangeListener.class,
"propertyChange");
Constructor arguments
1: Class object, represents event source
2: String, event set name
mouse includes mousePressed, mouseClicked...
We use propertyChange
3: Class object, implemented event listener interface
Creates anonymous object of class
4: String, name of listener method called when event occurs
changed.setDisplayName(
"SliderFieldPanel value changed" );
Class EventSetDescriptor
Method setDisplayName( stringName )
Specifies name for event set in builder tool
Same package as
// The BeanInfo class for SliderFieldPanel
package jhtp3beans;
4
5
import java.beans.*;
bean.
Extend SimpleBeanInfo class, with
default implementation of BeanInfo
interface.
1. package
6
7
11
1.1 import
public final static Class beanClass =
Create Class object, provides
SliderFieldPanel.class;
access to class
1.2 definition.
extends
Specify properties that can be
SimpleBeanInfo
by builder.
public PropertyDescriptor[]exposed
getPropertyDescriptors()
12
8
9
10
13
14
15
16
17
18
19
20
21
22
23
);
24
1.3 Class
try {
PropertyDescriptor fieldWidth =
new PropertyDescriptor( "fieldWidth", beanClass );
PropertyDescriptor currentValue =
new PropertyDescriptor(
"currentValue", beanClass );
PropertyDescriptor maximumValue =
2.1 setBound
new PropertyDescriptor(
"maximumValue", beanClass );
PropertyDescriptor minimumValue =
new PropertyDescriptor( "minimumValue", beanClass
Specify bound
25
26
currentValue.setBound( true );
27
2. getProperty
Descriptors
property.
28
29
30
31
32
33
34
}
catch ( IntrospectionException ie ) {
throw new RuntimeException( ie.toString() );
35
36
3.
getDefaultProperty
Index
Get array index of default
property
(currentValue).
37
38
39
40
41
42
return 1;
45
46
4.2 setDisplayName
public EventSetDescriptor[] getEventSetDescriptors() {
try {
EventSetDescriptor changed =
47
48
"propertyChange",
49
java.beans.PropertyChangeListener.class,
50
"propertyChange");
51
52
53
changed.setDisplayName(
"SliderFieldPanel value changed" );
54
55
4.1 Constructor
43
44
4. getEventSet
Descriptors
56
57
58
59
60
61
62
63 }
return descriptors;
}
catch (IntrospectionException e) {
throw new RuntimeException(e.toString());
}
}
Program Output
Important Questions
1.
Web Technologies
B.Tech. IT III Year II Semester
UNIT V
Outline of Presentation
Tomcat Webserver
Introduction To Servlets
Life Cycle of Servlet
Servlet API
Reading Servlet Parameters
Steps to Run a Servlet
Example to handle Http Request and Response
Using Cookies and Session Tracking
Security Issues
Tomcat WebServer
A servlet container is like a mini server, but only
for serving html, jsp and servlets.
Many servlet containers could be used for this course.
Some may even be easier to configure than tomcat,
but tomcat provides an easy-to-use
development/deployment tool and also complies with
the servlet specification best of all containers.
Tomcat is from Apache and is open-source.
Tomcat can be used as a stand-alone servlet container.
You can install the Apache server with Tomcat, and
then proceed to configure each for their individual
purposes. (The server would relay servlet requests to
Tomcat.)
Introduction to Servlets
What can you build with Servlets?
Search Engines
E-Commerce Applications
Shopping Carts
Product Catalogs
Intranet Applications
Groupware Applications:
bulletin boards
file sharing
Perl 1
Browser 1
Browser 2
Web
Server
Perl 2
Browser N
Perl N
Browser 1
Browser 2
Browser N
Web
Server
Servlet
Portability
Like other Java technologies, servlet applications are portable.
Robustness
Servlets are managed by the Java Virtual Machine.
Don't need to worry about memory leak or garbage collection, which
helps you write robust applications.
Widespread acceptance
Java is a widely accepted technology.
Definitions
A servlet is a Java class that can be loaded
dynamically into and run by a special web server.
This servlet-aware web server, is known as servlet
container.
Servlets interact with clients via a request-response
model based on HTTP.
Therefore, a servlet container must support HTTP as
the protocol for client requests and server responses.
A servlet container also can support similar protocols
such as HTTPS (HTTP over SSL) for secure
transactions.
HTTP Request
Browser
HTTP Response
HTTP
Server
Servlet
Container
Static
Content
Servlet
Receive
Request
is servlet
loaded?
No
Yes
is servlet
current?
No
Load Servlet
Yes
Send
Response
Process Request
Initialization
init()
Service
service()
doGet()
doPost()
doDelete()
doHead()
doTrace()
doOptions()
Destruction
destroy()
Concurrent
Threads
of Execution
thread safe
Servlet APIs
Client
request
Server
service ( )
response
HTTPServlet
Browser
doGet( )
request
HTTP
Server
response
service ( )
doPost( )
Interface javax.servlet.Servlet
The Servlet interface defines methods
to initialize a servlet
Life
Cycle
to receive and respond to client requests
Methods
to destroy a servlet and its resources
to get any startup information
to return basic information about itself, such as its author,
version and copyright.
GenericServlet - Methods
void init(ServletConfig config)
Initializes the servlet.
void destroy()
Cleans up whatever resources are being held (e.g., memory, file
handles, threads) and makes sure that any persistent state is
synchronized with the servlet's current in-memory state.
ServletConfig getServletConfig()
Returns a servlet config object, which contains any initialization
parameters and startup configuration for this servlet.
String getServletInfo()
Returns a string containing information about the servlet, such as its
author, version, and copyright.
HttpServlet - Methods
void doGet (HttpServletRequest request,
HttpServletResponse response)
handles GET requests
void doPost (HttpServletRequest request,
HttpServletResponse response)
handles POST requests
void doPut (HttpServletRequest request,
HttpServletResponse response)
handles PUT requests
void doDelete (HttpServletRequest request,
HttpServletResponse response)
handles DELETE requests
HttpServletRequest - Methods
Enumeration getParameterNames()
an Enumeration of String objects, each String
containing the name of a request parameter; or
an empty Enumeration if the request has no
parameters
java.lang.String[] getParameterValues (java.lang.String name)
Returns an array of String objects containing
all of the values the given request parameter
has, or null if the parameter does not exist.
java.lang.String getParameter (java.lang.String name)
Returns the value of a request parameter as a
String, or null if the parameter does not exist.
HttpServletRequest - Methods
Cookie[] getCookies()
Returns an array containing all of the Cookie objects the
client sent with this request.
java.lang.String getMethod()
Returns the name of the HTTP method with which\thi
request was made, for example, GET, POST, or PUT.
java.lang.String getQueryString()
Returns the query string that is contained in the request
URL after the path.
HttpSession getSession()
Returns the current session associated with this request, or
if the request does not have a session, creates one.
HttpServletResponse - Methods
java.io.PrintWriter getWriter()
Returns a PrintWriter object that can send
character text to the client
void setContentType (java.lang.String type)
Sets the content type of the response being
sent to the client. The content type may
include the type of character encoding used,
for example, text/html; charset=ISO-8859-4
int getBufferSize()
Returns the actual buffer size used for the
response
Servlet Example
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
14:
16:
17:
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class MyServlet extends HttpServlet
{
protected void doGet(HttpServletRequest req,
HttpServletResponse res)
{
res.setContentType("text/html");
PrintWriter out = res.getWriter();
out.println( "<HTML><HEAD><TITLE> Hello You! +
</Title></HEAD> +
<Body> HelloYou!!!</BODY></HTML> );
out.close();
}
}
Deployment Descriptor
The deployment descriptor is a XML file called web.xml that resides in the WEBINF directory whitin an application.
<web-app xmlns=http://java.sun.com/xml/ns/j2ee>
<display-name>test</display-name>
<description>test example</description>
<servlet>
<servlet-name>Testing</servlet-name>
<servlet-class>TestingServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Testing</servlet-name>
<url-pattern>/servlet/TestingServlet</url-pattern>
</servlet-mapping>
</web-app>
Servlet Cookies
Cookies are text files that store sets of param/value
pairs. The Servlet at the server side generates the
cookie based on the clients HTTP request.
The cookie is created on the server side and sent back
to the client along with the HttpServletResponse
object.
The cookie is stored in the clients browser.
URL Rewriting
Security Issues
Server-side Security Issues
User Authentication
Logging of Sensitive Information
Importanat questions
1. Briefly explain about Tomcat web server.
2 a) What are the limitations of Servlets?
b) Explain Servlet Vs CGI
3. Explain the life cycle of a servlet.
4. Write a session tracker that tracks the number of accesses and last access
data of a particular web page.
5.a) Discuss about javax.servelet package.
b) What are the security issues related to servlets.
Web Technologies
B.Tech. IT III Year II Semester
UNIT VI
JSP
Java Server Pages
Outline of Presentation
Introduction to JSP
Servlets Vs JSP
Lifecycle of JSP
JSP Elements
Anatomy of a JSP page
JSP Processing
JSP Application Design with MVC setting
Installing JSDK
Installing Tomcat Server
Introduction
JavaServer Pages (JSP) is a technology that
helps software developers create dynamically
generated web pages based on HTML XML or other document
types.
JSP separates content generation from content presentation
Released in 1999 by Sun Microsystems JSP is similar to the
Java Programming language.
To deploy and run JavaServer Pages, a compatible web server
with a servlet container, such as Apache Tomcat or Jetty, is
required.
Servlets
Server side Java programs
Solve scalability issue
serlvets are run on threads of execution not separate
processes
Issue
html tags are embedded in java programs within out.print()
statements which reduces flexibilty of programming
JSP
server-side technology
separate dynamic content from static content
of a page
Java scriptlets embedded into html-like page
JSP file
Servlet
Java file
JSP engine
Servlet Container
Process of a JSP page
compile
Servlet
Class
JSP Elements
Besides HTML tag elements, JSP provides four basic
categories of constructors (markup tags): directives, scripting
elements, standard actions, and comments.
JSP Directives
JSP Actions
JSP Scripting Elements
JSP comments
Expression Language
JSP Syntax
Elements
<%! ..%>
<jsp:declaration> .. </jsp:declaration>
<jsp:directive.include .. />
Expressions
<%= ..%>
<jsp:expression> .. </jsp:expression>
Scriptlets
<% ..%>
<jsp:scriptlet> .. </jsp:scriptlet>
Comments
<%--.. --%>
<!-- .. -->
Declarations
Directives
JSP Directives
JSP directives provide directions and instructions to the container,
telling it how to handle certain aspects of JSP processing.
A JSP directive affects the overall structure of the servlet class.
Syntax:
<%@ directive attribute="value" %>
Description
Purpose
buffer
autoFlush
contentType
errorPage
isErrorPage
extends
import
info
isThreadSafe
language
session
isELIgnored
isScriptingEnabled
Page Directive
Example:
<%@ page import="package.class" %>
<%@ page import="java.util.*" %>
<%@ page contentType="text/html" %>
<% response.setContentType("text/html"); %>
Include Directive
<%@ include file="Relative URL">
Included at Translation time
May contain JSP code such as response header
settings, field definitions, etc... that affect the
main page
Scripting Elements
There are three types of Scripting Elements
Declaration
Expression
Scriptlets
Declaration Element
The JSP declaration element defines page-scope
variables to store information or defines supporting
methods that the rest of a JSP page may need.
Declaration elements do not produce outputs.
Its syntax is
<%! Java Code %>
Example:
<%! int i=0; Double d; %>
Expression Element
Typically, expressions are used to display simple values of
variables or return values of shared data by invoking a bean's
getter methods.
In JSP, the results of an expression evaluation are always
converted to a string and directly included in the output page.
The predefined JSP objects such as request, response, and
session can also be used within the expression element to
make the expression as simple as possible.
Syntax : <%= expr %>
// No semicolon
<%= i * j + k %>
<%= myBean.getSalary() %>
<%= request.getRemoteHost() %>
<%= new java.util.Date() %> // To display Date & Time
Scriptlet Element
JSP scriptlets are embedded within <% ... %> tags. They are
executed at the runtime.
<% Java code
%>
The scriptlets are inserted into the _jspService() method of the
translated Servlet code which is invoked by the Servlet
service() method. This java code is executed when the request
is serviced by the JSP page. You can put any valid Java code
within a scriptlet element, and it is not limited to one line of
source code. For example, the following displays the counter
during execution of a loop, combining the use of the
expressions element and the scriptlets element:
<% for (int i=1; i<=4; i++) { %>
or (with no body)
attr2=value2 />
page
Only active in the page , default scope
request Active for the current request
session Active for the current session
application
Active for the current application
Once you have a bean reference, you can also modify its
properties by calling the beans getXXX() or setXXX()
methods explicitly in a scriptlets element.
Note that the class specified for the bean must be in the
server's regular class path. For example, in Tomcat, this class
and all the classes it uses should go in the classes directory or
be in a jar file in the lib directory.
jsp:setProperty Action
You use jsp:setProperty to assign values to properties of a
bean. You can either use jsp:setProperty after, but outside of, a
jsp:useBean element or within the body of jsp:useBean action
element.
Option 1:
<jsp:useBean id="myBook" ... />
...
<jsp:setProperty name="myBook" property="price" ... />
In this case, the jsp:setProperty is executed regardless of
whether a new bean was instantiated or an existing bean was
found.
class='shopping.Book'
scope='session' >
...
The next action can return the number of copies of myBook,
which may reference a specific book at the time.
Example
The form.jsp takes user name input on the form request, saves the
input in a JavaBean, and redirects to response.jsp. The
response.jsp JSP page gets the username from the bean, and
finally it responds to the user with a message Hello, <user
name>.
<%@ page import="user.NameBean" %>
<jsp:useBean id="myBean" scope="request" class="user.NameBean" />
<jsp:setProperty name="myBean" property="*" />
<html>
<body>
<form method="get">
<input type="text" name="userName" size="20">
<br>
<input type="submit" value="Submit">
</form>
<% if (request.getParameter("userName") != null) { %>
<%@ include file="response.jsp" %>
<% } %>
</body>
</html>
(cont.)
JSP Comments
JSP Comments: Different from HTML comments
<!-- an HTML comment -->
<%-- a JSP comment --%>
JSP comments are used for documenting JSP code
and are not visible client-side (using browser's View
Source option) where as HTML comments are
visible.
Example:
HTML>
<HEAD>
<TITLE>Hello World</TITLE>
Template data
</HEAD>
<BODY>
<H1>Hello World</H1>
Today is: <%= new java.util.Date().toString() %> // Jsp element
</BODY>
</HTML>
JSP Processing
When a JSP page request is processed, the template text and dynamic
content generated by the JSP elements are merged, and the result is sent as
the response to the browser
Whenever a .jsp is requested for the first time, the server needs a JSP
container to process JSP pages
The JSP container initiates the translation phase for a page
automatically when it receives the first request for the page
1. Translates the .jsp page into a servlet
2. Compiles the servlet into a class file
3. Executes the servlet (response is sent to the client)
As long as the JSP page remains unchanged, any subsequent request goes
straight to the request processing phase
When the JSP page is modified, it goes through the translation phase again
It is loaded once and called repeatedly, until the server is shut down
The third part, the controller, accepts input and converts it to commands for
the model or view.
The controller object is master Servlet. Every request goes through the controller
who retrieves the necessary model object.
The model may interact with other business entities such as databases or Enterprise
Java Beans (EJB).
The model object sends the output results back to the controller. The controller
takes the results and places it inside the web browser session and forwards a
redirect request to a particular Java Server Page. The JSP, in the case, is the view.
The controller has to bind a model and a view
Apache Tomcat
Installing Tomcat
What is Tomcat?
Tomcat is a Servlet container (Web server that
interacts with Servlets) developed under the Jakarta
Project of Apache Software Foundation
Tomcat implements the Servlet and the Java Server
Pages (JSP) specifications of Sun Microsystems
Tomcat is an open-source, non commercial project
Licensed under the Apache Software License
Install Instructions
Get & install 5.5.15 Core Windows Executable
(apache-tomcat-5.5.15.exe)
Configuration
Port? (8080 or 80)
User: admin
Password: webtech
Installation Configuration
(pswd: webtech)
conf
logs
webapps
server
server.xml
ROOT
myApp1
myApp2
work
shared
lib
classes
WEB-INF
web.xml
lib
classes
Tomcat-Home
bin
common
lib
classes
<web-app>
</web-app>
WEB-INF
web.xml
Configuring a Web
Application(web.xml)
Installing JSDK
1.
2
3
4
5
6
7
8
9
Download the latest version of the *Java JDK from Sun Microsystems
Double-click on the install file and it should open an installer
Click next, then read and accept the license.
On the next screen you will encounter some options. Just leave these alone
and click next
The next page you encounter should install (and in some cases download)
the Java Development Kit.
After the installer is finished, open run by clicking Start > Run.
In the text box, type "cmd" and click "OK
A simple window should be opened with a black background and a text
prompt.
After focusing the window, type "javac" and press enter. If the prompt
returns something along the lines of: "'javac' is not recognized as an
internal or external command, operable program or batch file" then
continue with the next step. If it shows many more options and lines, skip
to step 15.
Installing JSDK(cont..)
9 Open the properties of "My Computer" by either right-clicking the icon on
the desktop or right-clicking Start > My Computer. When the pop up menu
opens, scroll to the bottom and select "Properties".
10 This should open a window named "System Properties". Click on the
"Advanced" tab and then click "Environment Variables".
11 Next, another window opens with a lot of confusing sentences and letters.
Double-click on the "Path" variable on either of the option boxes.
12 Once the variable is opened, a text box in yet another window appears.
Careful not to delete anything in this box. At the end of the text box, add a
semi-colon if there is not one already, and add "C:\Program
Files\Java\jdk1.6.0\bin" to the text box. This is assuming you did not
change the file path of the installation.
13 Click "Apply" and "OK" to all the windows you have just opened. Open
the command prompt again, while following steps 6-9 to see if that "javac"
command works.
Important Questions
1. a) Briefly explain about Tomcat web server
b) How do you Test Tomcat Webserver
2. What are the limitations of Servlets?
3. Explain the Directive and Scripting elements of JSP.
4. Explain JSP Processing with a neat diagram
5. Explain the anatomy of JSP page.
6. Give an overview of java software development kit.
7. Explain various Elements of JSP
Web Technologies
B.Tech. IT III Year II Semester
UNIT VII
JSP
Application Development
Outline of Presentation
JSP scripting elements
Expressions, Scriptlets and declarations
Implicit JSP Objects
Conditional Processing
Displaying Values, Declaring variables & Methods ..
Error handling and Debugging
Sharing Data Between JSP Pages, Requests, and Users
Sharing Session and Application Data
Memory usage Considerations
application: javax.servlet.ServletContext
config: javax.servlet.ServletConfig
exception: java.lang.Throwable
out: javax.servlet.jsp.JspWriter
page: java.lang.Object
pageContext: javax.servlet.jsp.PageContext
request: javax.servlet.ServletRequest
response: javax.servlet.ServletResponse
session: javax.servlet.http.HttpSession
JSP Expressions
Format
<%= Java Expression %>
Result
Expression evaluated, converted to String, and placed into HTML page
at the place it occurred in JSP page
That is, expression placed in _jspService inside out.print
Examples
Current time: <%= new java.util.Date() %>
Your hostname: <%= request.getRemoteHost() %>
XML-compatible syntax
<jsp:expression>Java Expression</jsp:expression>
XML version not supported by Tomcat 3. Until JSP 1.2, servers are not
required to support it.
Example:
<HTML><HEAD>
<TITLE>JSP Expressions</TITLE>
<META NAME="author" CONTENT="Marty Hall">
<META NAME="keywords"
CONTENT="JSP,expressions,JavaServer,Pages,servlets">
<META NAME="description"
CONTENT="A quick example of JSP expressions.">
<LINK REL=STYLESHEET HREF="JSP-Styles.css" TYPE="text/css">
</HEAD>
<BODY>
<H2>JSP Expressions</H2>
<UL>
<LI>Current time: <%= new java.util.Date() %>
<LI>Your hostname: <%= request.getRemoteHost() %>
<LI>Your session ID: <%= session.getId() %>
<LI>The <CODE>testParam</CODE> form parameter:
<%= request.getParameter("testParam") %>
</UL></BODY></HTML>
Example
Example Result
With default setup, if location was
C:\<tomcatHome>\webapps\ROOT\Expressions.jsp
URL would be
http://localhost/Expressions.jsp
JSP Scriptlets
Format: <% Java Code %>
Result
Code is inserted verbatim into servlet's _jspService
Example
<%
String queryData = request.getQueryString();
out.println("Attached GET data: " + queryData);
%>
<% response.setContentType("text/plain"); %>
XML-compatible syntax
<jsp:scriptlet>Java Code</jsp:scriptlet>
<%
for (int i=100; i>=0; i--)
{
%>
<%= i %> bottles of beer on the
wall.<br>
<%
}
%>
JSP Scriptlets
Example
JSP Declarations
Format
<%! Java Code %>
Result
Code is inserted verbatim into servlet's class definition,
outside of any existing methods
Examples
<%! private int someField = 5; %>
<%! private void someMethod(...) {...} %>
XML-compatible syntax
<jsp:declaration>Java Code</jsp:declaration>
<body>
<h1>JSP Declarations</h1>
<%! private int accessCount = 0; %>
<h2>Accesses to page since server reboot:
<%= ++accessCount %></h2>
</body></html>
After
15 total
visits by an
arbitrary number
of different clients
13
int count=100;
out.print( "\r\n" );
out.print( String.valueOf(
unt ) );
out.print( "\r\n" );
}
out.print( "\r\n" );
++co
out.print( String.valueOf(
unt ) );
out.print( "\r\n" );
}
}
++co
14
15
1
2
3
4
JSP gives you an option to specify Error Page for each JSP. Whenever the page
throws an exception, the JSP container automatically invokes the error page.
Now you would have to write one Error Handling JSP ShowError.jsp, which is given
below.
Notice that the error-handling page includes the directive <%@ page isErrorPage="true"
%>. This directive causes the JSP compiler to generate the exception instance variable.
To share Data
Example
Various ways that JSP pages for collection of payment details can be
structured. Can even have everything on a single JSP page (messy for
anything but simplest apps)
Userinput.jsp
Displays a form
into which
user enters their
details
Presentation
infovalidate.jsp
infovalidate.jsp
Validates the info
provided in
userinput.jsp
and passes back to
userinput.jsp
if theres an error, or
confirmed.jsp
if info is valid.
Request
processing and
business logic
confirmed.jsp
confirmed.jsp
displays a message
to user to confirm
payment made.
Presentation
<tr>
<td>Name:</td>
<td>
<input type="text" name="userName" value = "<c:out value =
"${param.userName}"/>">
</td>
<td>Credit card number:</td>
<td>
<input type="text" name="creditCardNumber" value = "<c:out valu
= "${param.creditCardNumber}"/>">
</td>
</tr>
<tr>
<td colspan=2>
<input type="submit" value="Send Data">
</td>
Display any previously enter
<tr>
values of username/credit card
</table>
number
</form>
</body>
html>
<c:choose>
<c:when test="${empty param.userName}">
<c:set var = "msg" value = "You must enter your username"
scope = "request"/>
<jsp:forward page="userinfoinput.jsp" />
</c:when>
<c:when test="${empty param.creditCardNumber}">
<c:set var = "msg" value = "You must enter your credit card
number" scope = "request"/>
<jsp:forward page="userinfoinput.jsp" />
</c:when>
<c:otherwise>
<jsp:forward page="confirmed.jsp" />
</c:otherwise>
Must set scope to request.
</c:choose>
Otherwise, the message wont be
available to userinputinfo.jsp
<html>
<head>
<title>User Info Validated</title>
</head>
<body bgcolor="white">
<font color="green" size="+3">
Your payment details are correct - thank you
</font>
</body>
</html>
Note: This page is just template text (apart from comment) so could be created
as a regular HTML file. Making it a JSP page allows dynamic content later
without changing the referring page
Sharing Session..(cont..)
Bank employee selects the branch they are a member of. Session
stores this info in some way:
-> branch, 931012
Application remembers the branch number so that employee does
not have to re-enter. Only customers relevant to the branch are
shown throughout.
Sharing Session..(cont..)
Set the scope to session, and the relevant attribute will be available
throughout the entire session of the client
Example: a JSP page that displays two counters a hit counter for the
session, and a hit counter for the application
Sharing Session..(cont..)
<%@ taglib prefix="c" uri="http://java.sun.com/jstl/core" %>
<html>
<head> header details etc </html>
<body bgcolor="white">
<html><head>
<title>Session Values</title>
</head><body>
<%
session.setMaxInactiveInterval(10);
String name = (String)
session.getAttribute("username");
out.print("Welcome to my site " + name + "<br>");
%>
INE2720 Web Application
All copyrights reserved by C.C. Cheung
</body></html>
Software Development
2003.
38
Important Questions
1. Explain Implicit Objects in JSP
2. Explain Error Handling and Debugging in JSP
3. Explain Memory usage considerations in JSP
Application development
4. Explain the dynamic content generation with an example
using JSP
5. Explain Sharing Session and an application with an
example
6. Explain Data sharing between JSP pages with an
example
JDBC
Java Database Connectivity
Outline of Presentation
Introduction to JDBC
JDBC Driver Types
General Architecture
JDBC Components
Introduction to JDBC
JDBC is a front end tool which is used to connect
front end java application to back end database
JDBC is an alternative to ODBC and ADO that
provides database access to programs written in
Java.
JDBC drivers are available for most DBMS
products
A JDBC Driver
Is an interpreter that translates JDBC method calls to
JDBC calls
Driver
Database
standard
General Architecture
JDBC Components
Using JDBC
1. Load the driver:
Class.forName(sun.jdbc.odbc.JdbcOdbcDriver);
//Type1 Driver
2. Establish a connection to the database:
A connection URL string includes the literal jdbc:, followed by the
name of the driver and a URL to the database
String url = "jdbc:odbc:dsn;
Create a Connection object:
Connection con = DriverManager.getConnection(url,
scott,tiger);
3. Create a statement object
Statement stmt = conn.createStatement();
Associate SQL with the statement object
String queryString = select * from emp";
Using a PreparedStatement
// Once you have a connection, you can create a
// "prepared statement" object. A prepared statement is
// precompiled, and can be used repeatedly with new values
// for its parameters.
// Use question marks for parameter place-holders.
PreparedStatement prepStmt = con.prepareStatement(
"INSERT INTO Artist (ArtistID, Name, "
+ "Nationality, BirthDate, DeceasedDate)"
+ "VALUES (ArtistSeq.nextVal, ?, ?, ?, ? )" );
// Now supply values for the parameters
// Parameters are referenced in order starting with 1.
prepStmt.setString( 1, "Galvan" );
prepStmt.setString( 2, "French" );
prepStmt.setInt
( 3, 1910 );
prepStmt.setNull ( 4, Types.INTEGER );
// The PreparedStatement object methods:
// 1) executeUpdate -- statements that modify the database
// 2) executeQuery -- SELECT statements (reads)
prepStmt.executeUpdate();
System.out.println( "Prepared statement executed" );
// Now do it again
prepStmt.setString(
prepStmt.setString(
prepStmt.setInt
(
prepStmt.setInt
(
1,
2,
3,
4,
"Monet" );
"French" );
1840 );
1879 );
prepStmt.executeUpdate();
System.out.println( "Prepared statement executed again" );
Java.sql.* package
java.sql.Connection
Statement createStatement (int resultSetType, int resultSetConcurrency)
PreparedStatement prepareStatement (String sql, int resultSetType, int
resultSetConcurrency)
CallableStatement prepareCall (String sql, int resultSetType, int resultSetConcurrency)
resultSetType
resultSetConcurrency
ResultSet.TYPE_FORWARD_ONLY
ResultSet.CONCUR_READ_ONLY
ResultSet.TYPE_SCROLL_INSENSITIVE
ResultSet.CONCUR_UPDATABLE
ResultSet.TYPE_SCROLL_SENSITIVE
Java.sql.* package
java.sql.ResultS
et
void beforeFirst() throws SQLException
void afterLast() throws SQLException
boolean first() throws SQLException
Example : Backward
Statement stmt = conn.createStatement
(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE);
symbol id
company symbol
price
num_shares
Register w/ODBC
Create an ODBC data source.
Click on the Start button.
Choose Settings, Control Panel
Double-click on ODBC Data Sources
Choose the System DSN tab
Click Add
Click on the desired driver (Microsoft ODBC for oracle)
Click on the Finish button
Enter a Data Source Name (I called my database CoolStocks
and that name appears in the java code below)
<%
Connection con = null;
try {
// Load the Driver class file
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
// Make a connection to the ODBC datasource Movie Catalog
con = DriverManager.getConnection("jdbc:odbc:CoolStocks,scott,tiger);
// Create the statement
Statement statement = con.createStatement();
// Use the created statement to SELECT the DATA
// FROM the customer Table.
ResultSet rs = statement.executeQuery("SELECT * " +
"FROM customer");
// Iterate over the ResultSet
%>
finally {
try {
if ( con != null ) {
// Close the connection no matter what
con.close();
}
}
catch (SQLException sqle) {
out.println(sqle.getMessage());
}
}
%>
</BODY>
</HTML>
It Works!(output)
You can use the JSP action tag, <jsp:useBean> to include a bean
reference in your JSP page.
The <jsp:useBean> action tag creates an instance of the JavaBean and
stores the bean reference in a variable.
The variable can then be used to access the JavaBean throughout the JSP
page.
The following code snippet shows the syntax of the <jsp:useBean> action
tag:
<jsp:useBean
id=Bean Name
scope=ScopeName
class=class name />
Attribute
Description
name
property
Attribute
Description
name
property
Represents the bean property for which you want to retrieve the
value.
Demonstration-Implementing
JavaBeans in JSP
Problem Statement
Demonstration-Implementing
JavaBeans in JSP (Contd.)
Solution
maintainable
Struts
helps structuring these components in a Java web app.
these components
unifies the interaction between them
This separation between presentation, business logic and control is
achieved
by implementing the Model-View-Controller (MVC)
Design Pattern
Model
holds application data and business logic
Controller
bridge between Model and View
controls the flow of the application
Benefits:
better maintainability and testability of applications
ability to easily develop different kinds of UIs (e.g. console, GUI, )
separation of different tasks in development
code reusability
Controller ActionServlet
The central component in a Struts application
manages the flow of the application
receives user requests and delegates
them
Controller Actions
perform logic depending on a users request
Actions
are Java classes that extend Struts Action
class org.apache.struts.action.Action
The Action's execute() method is called by
the ActionServlet
Tasks are usually performed by Actions:
depending on the type of action:
Controller ActionForms
represent the data stored in HTML forms
hold the state of a form in their properties
provide getter/setter methods to access them
may provide a method to validate form data
ActionForms
are Java classes that extend Struts ActionForm
class org.apache.struts.action.ActionForm
are filled with the form data by the ActionServlet
one ActionForm can be used for more than one HTML form
very useful when building wizards or similar types of forms
...
The Model
Holds the data of an application and provides
business logic methods
Not directly part of the Struts framework!
The Model is usually built of different kinds
of Business Objects:
JavaBeans
simple
Important Questions
1. Explain Different Types of JDBC Drivers
2. Explain the process of Accessing Database from a
JSP Page
3. Explain Struts Framework
4. Explain Deploying of Java Beans in a JSP Page
5. Explain Java.sql.* package
6. Explain Various types of ResultSets with example