Date post: | 05-Apr-2018 |
Category: |
Documents |
Upload: | rajesh-kumar |
View: | 242 times |
Download: | 0 times |
of 137
7/31/2019 Advance Java Final Material
1/137
Advanced Java Programming Web Based Course Notes
Introducing the World Wide Web
In order for computers to share resources efficiently, they can be linked together in one of the
following structured networks:
linked within a local area network (LAN)
linked across a wide area network (WAN)
Networks are very useful; their use led to a network of networks called the Internet.
The Internet consists of millions of interconnected computers that enable users to communicate andshare information. Many early Internet tools required users to master an array of terms, acronyms, andcommands before they could navigate the Internet.
The World Wide Web was developed to make the Internet easier to use and give quick
access to users.
The Development of the World Wide Web
In 1989, Timothy Berners-Lee and other researchers at the CERN nuclear research facility laid the
foundation of the World Wide Web, or the Web. They created an information system thatmade it easy for researchers to locate and share data and required minimal training and support. They
developed a system of hypertext documents; electronic files that contain elements thatyou can easily select.
Documents on the Web are known as Web pages. A Web page is stored on a Web server, which makesthe page available to users of the Web. To view a Web page, the user runs a Webbrowser, a software program that retrieves the page and displays it. The first graphical Web browser -Mosaic - was developed by Marc Andreesen in 1993.
Common Web browsers available today:
Microsoft Internet Explorer
Safari (Macintosh, and now Windows) Mozilla Firefox Netscape NavigatorHypertext Documents
Web pages are text files, written in a language called Hypertext Markup Language (HTML).
Markup languages use symbols or tags to describe what a document should look like when
displayed by a Web browser.
Markup languages are designed to transmit documents over a network using minimal bandwidth.HTML is platform independent (can be displayed by different operating systems) and easy to use (sothat even nonprogrammers can learn to use it!).
Hypertext offers a better way of locating information. When you read a book, you follow a
linear progression, reading one page after another. With hypertext, you progress through pages inwhatever way is best suited to you and your objectives. Hypertext lets you skip from one topic toanother. The key to hypertext is the use of links, which you activate to move from one topic toanother. A link can open a document on a computer anywhere in the world.
N.Sridhar, Associate Professor, GMRIT, Rajam
7/31/2019 Advance Java Final Material
2/137
Advanced Java Programming Web Based Course Notes
Creating an HTML Document
HTML documents are text files, which a text editor such as Windows Notepad can be used to
create. You can also use an HTML converter or an HTML editor. An HTML converter like Microsoft
Word takes text in one format and converts it to HTML code.
An HTML editor helps you create an HTML file by inserting HTML codes for you as you work.(In this course we will ONLY use Notepad and write the HTML tags ourselves.)
HTML Syntax
Document content is what the user sees on the page, such as headings and images. Tags
are the HTML codes that control the appearance of the document content. tag is thename of the HTML tag
attributes are properties of the tag document content is actual content that appears in the Web pageHTML Tags
Tags can be one-sided or two-sided. two-sided tags contain an opening tag that tells the browser to turn on a feature and
apply it to the content that follows, and a closing tag that turns off the feature
one-sided tags are used to insert non-character data into the Web page, such as a graphicimage or video clip
Tags are not case sensitive; however the current standard is to type all tags in lowercaseletters.
Structure of an HTML Document
2 Main Parts:1.)Head
Contains the page title (displayed in the title bar of the browser window) Contains meta tags used by search engines
Text in the head is NOT visible in the browser window2.)Body
Contains everything that will be visible in the browser window
Creating a HTML File Using a Text Editor (i.e. Notepad)
Launch Notepad
Type document, adding tags as desired. Save File:
o File/SaveAso Location: root level of your driveo Filename: index.HTML (including quotes)
N.Sridhar, Associate Professor, GMRIT, Rajam
7/31/2019 Advance Java Final Material
3/137
Advanced Java Programming Web Based Course Notes
Initial HTML Tags in Notepad - ALL HTML documents MUST contain these tags
open the HTML file
open the head tag
open the title tagEverything typed between the opening and closingtitle tags will be the page title text that appears in
browser title bar (this is NOT the file name).
close the title tag
close the head tag
open the body tagEverything typed between the opening and closing body tags displays in the browser window.
close the body tag
close the HTML file
Creating Heading Tags
Heading Style tags contain formatting for font size, alignment, and spacing before and after. HTML
supports six levels of headings, numbered through , with being the largest and mostprominent. Headings are always displayed in a bold font. Different browsers may interpret theheading tags differently.
insert text here the largest size insert text here
insert text here
insert text here
insert text here
insert text here the smallest size
N.Sridhar, Associate Professor, GMRIT, Rajam Page 3 of 7
7/31/2019 Advance Java Final Material
4/137
Advanced Java Programming Web Based Course Notes
Creating Lists
HTML supports three kinds of lists:
anordered list, which is used to display information in a numeric order an unordered list, which list items are not listed in a particular order i.e. bullets
a definition list, which is a list of terms, each followed by a definition line that is typicallyindented slightly to the right
ORDERED LIST
This is the 1st
list item.
This is the 2nd
list item.This is the 3
rdlist item.
Remember to close the ol tag
UNORDERED LIST
The unordered list tag
creates a bulleted list.
Remember to close the ul tag.
DEFINITION LIST
Type the name of the term here
The definition of the term is placed after
the dd tag and is slightly indented.
You can continue the list with another
term
Followed by its definition, slightly
indented
N.Sridhar, Associate Professor, GMRIT, Rajam
7/31/2019 Advance Java Final Material
5/137
Advanced Java Programming Web Based Course Notes
Formatting Paragraphs and Text
HTML formats text ONLY through the use of tags and ignores such things as extra blank
spaces, blank lines, or tabs. Note that some tags are one-sided and some are two-sided.
insert text here
insert text here
insert text here
insert text here
insert text here
N.Sridhar, Associate Professor, GMRIT
inserts a line break
inserts a paragraph break
bold
center text and images
italic
underline
font color - color is an attribute of the font tag -
RRGGBB is a 6-digit hex # used to indicate the amount
of red, green, and blue used to create a specific color
Examples:
creates white text creates black text
Background color of entire Web page - bgcolor is an
attribute of the body tag - There should be only ONE
body tag in your HTML document.
Example:
creates a blue background
\
7/31/2019 Advance Java Final Material
6/137
Advanced Java Programming Web Based Course Notes
Inserting a Graphic Images
Images can be displayed directly on the Web page when the page is accessed by a user. Images should
be in one of two file formats: GIF (Graphics Interchange Format) or JPEG (Joint
Photographic Experts Group). Note: Save the image file in the same directory as your
index.HTML file.
inserts a graphic image
Inserting Horizontal Lines
A horizontal line can improve the appearance of a Web page. The attributes shown below are all
optional. The default will be a black line that spans the width of the page.
align specifies the horizontal alignment of the line on the page (center, left, or right)sizespecifies the height of the line in pixels or percentage of the screen width
width indicates the width of the line in pixels or percentage of the screen width
color indicates the color of the linenoshade specifies that the browser display a solid line
Inserting an Email link
You can create a link that will launch an email program and create a new message addressed to the
email address specified in the tag.
Text between opening and closing tags will be the text that displays on the screen and provides the
hot spot to click on.
Example:
Click here to email me!
N.Sridhar, Associate Professor, GMRIT, Rajam
7/31/2019 Advance Java Final Material
7/137
Advanced Java Programming Web Based Course Notes
Inserting a Link to another Site
You can create a link that will open another Web page.
Text between opening and closing tags will be text that displays on the screen and provides the hot
spot to click on.
Example:
Click here to visit Bills company site!
Viewing Your Web Page Offline
Launch browser. Select File/Open/Browse to find your HTML file. To make changes:
o Select View/Source - Notepad file will open. oMake changes
o SAVE (You must save in order to see the changes displayed.) In browser window, click REFRESH icon.
Further ReadingFor more information about HTML and a list of some basic HTML tags and Web page design tips
refer to Understanding Computers Today and Tomorrow 11th
edition Comprehensive
pages 430-433.
N.Sridhar, Associate Professor, GMRIT, Rajam
7/31/2019 Advance Java Final Material
8/137
HTML Frames
On many sites, the browser window is divided into a series of frames. In this case, you'llhave multiple HTML documents. The window as a whole will be defined in one document (aframeset), with each of the resulting frames being defined in its own piece of HTML.Documents called up can then replace all the frames, or one frame, or even open a newbrowser window.
Frames are useful tools on web sites where you wish to provide a control pane thatsunchanging, and a data pane in which results are presented, but they do add to the design anddevelopment complexity and its often better to use tables and refresh the whole page as younavigate a site.
There are also issues with the titling of framed pages which make them hard to bookmarksensibly, and with the printing of pages. Its very easy to provide a page that wont print out ifyou use frames, and thats why so many web sites have a "printer friendly version" option.
HTML Forms
Forms are a vital part of any web site that includes executable content as theyre themechanism that allows user data entry. With a form, you define a set of user-enter-able boxes between a and tag. Within the tag an action attribute
gives the URL to be called when the user indicates that the form has been completed, and amethod attribute may be specified too.
Element types within a form
There's much more you might want to do, and forms can have a range of differentelements. There are basically a number of classes of elements, but within each of them anumber of attributes can be applied to tailor how they look and respond.Heres a sample piece of HTML that includes most of the form elements:
Form Element Demo
Different form elementsThis calls a script that lists out all fields entered, and thewhole environment
Type = Textdefault text
Another text
Type = radioSelect a radio button from:
Orange Juice
Lemonade
Rose's Lime Cordial
N.Sridhar, Associate Professor, IT Dept, GMRIT
7/31/2019 Advance Java Final Material
9/137
Type = hiddenNothing here!Type = fileLooking for a file nameType
= checkboxLooking for a series of answers
Is it hot?
Is it sunny?
Is it daytime?
!-- ################################### --> Type = buttons1st
button
2nd button
TextareaA text area:Well House Consultants404, The SpaMelksham,
Wiltshire SN126QL
SelectsChoose ONE of these:NorthSouthEastWest
Choose several of these:Swimming
SkiingScubaSnorkellingSleeping
N.Sridhar, Associate Professor, IT Dept, GMRIT
7/31/2019 Advance Java Final Material
10/137
Submit and reset buttonsdefault reset which you should NOT
pressunless you want to clear your form contents!
default submit
Another submit
An imaged submit
7/31/2019 Advance Java Final Material
11/137
3.1 Style Sheets
To define the formatting styles and rules with CSS, you should use style sheets. A style sheetis a set of style rules that describe how HTML document elements are to be displayed on thepage. Each style rule in the style sheet looks similar to this:
p {font-family:arial; font-size:20pt; color:red}
Or for better readability,
p {
font-family:arial;
font-size:20pt;
color:red
}
Each style rule is comprised of two parts, a selector and a declaration. The selector part of the
style rule specifies which HTML elements are to be affected by the rule. The style rule aboveis defined for p (paragraph) elements. This rule is applied automatically to every p element
in every HTML document that uses this style sheet.
A selector can specify more than one element by separating the elements with commas. Thefollowing style rule applies to all h1 and h2 heading elements:
h1 h2 {font-family:arial; color:navy}
The declaration part of a style rule, contained within braces ({}), defines the style properties to
be applied to the specified elements. The properties are comprised of name and value pairs.
Each name is followed by a colon (:) and one or more values. The property name defines the
attribute, such as color or font-family. The property value defines the specification of
that attribute. Each name and value pair is separated by a semicolon (;). As a result of the
first example of style rule, all of the p elements on the web page are displayed in red, 20-point
Arial font.
At this point, you may be thinking that you can achieve the same result using HTML elementsand their associated attributes. For this particular example, you may use:
Some text
But what if you have 20 paragraphs? Do you want to repeat that font definition within every
paragraph? What if you decide later that you really want that text to be blue? Apparently,
style sheets bring many benefits to us.
4 Defining Styles
There are 3 basic ways to define styles for web pages: inline, embedded, and external.
3
7/31/2019 Advance Java Final Material
12/137
4.1 Inline Styles
You can specify a style rule directly within an HTML element using the style attribute ofthe element. This is useful when you want a style applied only for a particular element onyour web page. For example,
Some text
Since the style rule is defined within the elements tag, there is no need for a selector, only the
declaration.
Using an inline style is better than using the traditional individual element attributes because
many of the formatting attributes have been deprecated and are supposed not to be used any
more. In addition, there are more style properties than element attributes, giving you more
control over the look of the element. For example, you may use margin-left style property
allows you to set a left margin for the paragraph. There is no comparable paragraph attribute.
Nevertheless, as you can see, we cannot benefit more from CSS besides the above, especially
from the viewpoint of reusability. For more benefits, we need to use embedded and external
styles.
4.2 Embedded Styles
You can define a consistent style for all elements of a specific type using embedded styles.
This style is automatically applied to that element type throughout the page, giving you a
standard look on the page.
You declare an embedded style with a style element in the header section of the HTMLdocument. The style element contains one or more style rules. For example:
Welcome to Internet Programming
The style element has a type attribute that indicates the types of style rules to use; in this
case, it is CSS. This attribute is required for strict conformance to XHTML. The comment
markers within the style element are not required but highly recommended so that older
browsers that dont understand the style element ignore the style definition.
4
7/31/2019 Advance Java Final Material
13/137
4.3 External Styles
Above the style rules are defined in the HTML document that uses the styles. To reuse the
styles throughout multiple pages of your web application, we can instead create the styles in
an external file and link that file to all of HTML documents.
Later, if you want to change the way all of your pages look, simply change the external style
sheet file and all of the pages in your application linked to the style sheet file reflect the
change.
To create an external style sheet, simply create a text file for the style rules. This file is called a
style sheet file and is normally given a .css extension. Add your styles to that file. The style
rules are the same as for the embedded styles.
Any HTML document that wants to use the style from the style sheet file can link to that stylesheet file. Use the link element in the header section of the HTML document to link to thedesired external sheet file:
The rel attribute of the link element defines the nature of the relationship between the
linked resources; in this case, the link is to a style sheet. The type attribute defines the type
of the linked file (always text/css for cascading style sheets). The name of the style sheet
file is defined with the href attribute using relative or absolute paths.
5 Declaring Style Classes for Flexibility
The styles defined so far have been for specific elements or specific types of elements. How
if we want different styles applied respectively to different groups of elements of the same
type? CSS has the mechanism called style classes to allow us to declare named styles that can
be applied to specific elements on a web page.
Remember when you specify a particular HTML element as the selector of a style rule, thestyle properties are automatically applied to all occurrences of that particular type of element.With style classes, you may define different styles for different types of the same element. For
example, you can define two types of paragraphs: key points and normal information. If youwant the key points to stand out when your page is displayed, you could make the key pointparagraph font bigger and red. You can define two different styles for the two different typesof paragraphs by defining two style classes as follows:
7/31/2019 Advance Java Final Material
14/137
p.normal {font-size:15pt; color:navy}
.margin {margin-left:0.5in}
-->
As the example shows, you declare a style class using a dot (.) and a style class name in theselector part of the style rule. The style class names can be any name that provides a good
description of the usage of the style. If the style class is only to be used for a particular type
of element, the element name precedes the style class definition.
In the example, both the key and normal style classes can only be used with p elements,
while the margin style class is not associated with any particular element type, so it can be
used with any relevant element.
In the example, the p element style is applied automatically to every p element on the webpage. But to assign a style class to a particular HTML element, you must set the class
attribute of that element to the style class name. For example:
Welcome to Internet Programming
Announcement
We wont have class tomorrow.
And any p element without a class attribute uses the standard p element style.
Style and style class declarations assume that you want to apply a style to several elements.
There may be situations where you want to define a unique style for an individual element.You can do this with inline styles by setting the style attribute of the element as discussed
previsouly. However, you may want to keep all of your style information together. In this
case, you can define a style rule using the value of the elements id attribute.
To apply a style to a specific element, there must be a way to identify that element. To doso, you have to define the id attribute of that element and then use a pound sign (#) and thevalue of the elements id attribute as the style selector. For example:
#LastName {font-size:15pt; color:brown}
6 Cascading Style Sheets
A key feature of CSS is that style rules can cascade. That is several style rules may work
together for the same set of elements and all of the rules can influence the presentation of
those elements.
6
7/31/2019 Advance Java Final Material
15/137
As we discussed above, you may define inline, embedded, or external style rules. They may
overlap with each other when the same type of elements is used as selector. In this case, all
the style attributes are applied.
But how if there is a conflict, e.g. different colors assigned in different style rules? CSS assigns
different priorities to the style rules defined differently:
Inline > Embedded > External
Specific selectors always take priority over general selectors. A style rule with a class
defined in the selector beats a style rule without a class. And a style rule with an element
ID beats a style rule with a class.
When multiple style rules apply to the same element, the style rule defined last takes
precedence.
The cascading effect can be very useful when you define a general style for a large range of
elements and then define a different style for a subset of them.
7
7/31/2019 Advance Java Final Material
16/137
Introduction
To
JavaScriptIntroduction
Simple programming language in the browser (Totally Client Side)Basically no relation to Java - just a marketing nameUsed to be incompatible versionsLater became a standard under ECMAWorks best in IE 5 or later, Netscape 6 or later, Mozilla 1.0 or later, including Firefox.
Mozilla probably has the best JavaScript implementation.
JavaScript NicheMake the client more responsive in a client/server system Aslightly thicker client, but better user experienceAdvantages: more responsive, doesn't require a request/response roundtrip
e.g. on product detail page for a t-shirt, have a pop-up menu for color. UseJavaScript to swap the image to show different shirts without doing a wholeform submit.
JavaScript can do things in the browser: adjust the HTML in the page, adjust the
window, open new windowsJavascript cannot: use the local filesystem, do networking.
JavaScript Language Basics section in the HTML document - runs on document load Notype declarations requiredVariables are essentially global by default. e.g. count below. (variables are actuallyproperties of a global context)Function definitionsstrings - "hello" or 'hello', use + to concat"var" - declare a local variable (as opposed to a global)
alert(str) - puts up an alert panel
JavaScript and Browserdocument - the HTML documentdocument.name - refer to a named element in the documentdocument.images - array of imagesdocument.forms - array of formsThere are also ways to access the window, cookies, etc.Use Mozilla's JavaScript Console to see error messages.
N.Sridhar, Associate Proessor, GMRIT
7/31/2019 Advance Java Final Material
17/137
JavaScript ExampleJS Demo
function hello(greeting) {
var str = greeting + "!!!";
alert(str);}
count = 0;
function upCount() {count++;alert(count);
}
function noFear() {
var fear = document.affirm.fear.value;if (!document.affirm.mockMode.checked) {
alert("No " + fear + " to be seen around here!");}else {
var mock = "Being afraid of " + fear + " is stupid!";window.status = mock
document.affirm.mock.value = mock;}
}
Say Hello
Count
oops
Thing you are afraid of...
Mock mode:
N.Sridhar, Associate Proessor, GMRIT
7/31/2019 Advance Java Final Material
18/137
JavaScript ResourcesJavaScript URLs on the course pageJavaScript the Definitive Guide 4th ed, by David Flanagan (O'Reilly) The"Rhino" bookImportant to get the latest edition, since the language (and browsers) have evolved a lot
JavaScript and BeyondJavaScript has all sorts of features we're not going to worry about: objects, exceptions,
regular expressionsBut we're not messing with thatIt is, at its heart, a simple language, intended for non-programmers, so a little goes along way
UndefinedThe undefined value is like undef in PerlThe value of a variable that has not been given a valueUse == to test for undefined
if (a == undefined) { ...
StringsEither " or ' work as delimetersUse + to concat strings (converts ints to string form automatically)s.toLowerCase() // returns lowercase form== does a "deep" string compare (unlike Java, which does a reference/pointer compare)s.indexOf(target) // returns the index of the target, or -1
Arraysa = new Array(); // new empty arrayvar b= new Array(); // as above, but "b" is a local variable
Add three elementsa.push(1);a.push(2);a.push("hello");
a[0] - access element 0
a[100] = "foo"; // makes array biggera.length // current length of arrayOther obvious built-in functions: pop(), shift(), unshift(), sort(), join(), reverse()c = [1, 2, "hello"]; // [...] literal defines an array on the flyarray.toString() // returns a string form, but without the [ ]: 1,2,hello
N.Sridhar, Associate Proessor, GMRIT
7/31/2019 Advance Java Final Material
19/137
Advanced Java Programming Web Based Course Notes
Introducing the World Wide Web
In order for computers to share resources efficiently, they can be linked together in one of the
following structured networks:
linked within a local area network (LAN)
linked across a wide area network (WAN)
Networks are very useful; their use led to a network of networks called the Internet.
The Internet consists of millions of interconnected computers that enable users to communicate andshare information. Many early Internet tools required users to master an array of terms, acronyms, andcommands before they could navigate the Internet.
The World Wide Web was developed to make the Internet easier to use and give quick
access to users.
The Development of the World Wide Web
In 1989, Timothy Berners-Lee and other researchers at the CERN nuclear research facility laid the
foundation of the World Wide Web, or the Web. They created an information system thatmade it easy for researchers to locate and share data and required minimal training and support. They
developed a system of hypertext documents; electronic files that contain elements thatyou can easily select.
Documents on the Web are known as Web pages. A Web page is stored on a Web server, which makesthe page available to users of the Web. To view a Web page, the user runs a Webbrowser, a software program that retrieves the page and displays it. The first graphical Web browser -Mosaic - was developed by Marc Andreesen in 1993.
Common Web browsers available today:
Microsoft Internet Explorer
Safari (Macintosh, and now Windows) Mozilla Firefox Netscape NavigatorHypertext Documents
Web pages are text files, written in a language called Hypertext Markup Language (HTML).
Markup languages use symbols or tags to describe what a document should look like when
displayed by a Web browser.
Markup languages are designed to transmit documents over a network using minimal bandwidth.HTML is platform independent (can be displayed by different operating systems) and easy to use (sothat even nonprogrammers can learn to use it!).
Hypertext offers a better way of locating information. When you read a book, you follow a
linear progression, reading one page after another. With hypertext, you progress through pages inwhatever way is best suited to you and your objectives. Hypertext lets you skip from one topic toanother. The key to hypertext is the use of links, which you activate to move from one topic toanother. A link can open a document on a computer anywhere in the world.
N.Sridhar, Associate Professor, GMRIT, Rajam
7/31/2019 Advance Java Final Material
20/137
Advanced Java Programming Web Based Course Notes
Creating an HTML Document
HTML documents are text files, which a text editor such as Windows Notepad can be used to
create. You can also use an HTML converter or an HTML editor. An HTML converter like Microsoft
Word takes text in one format and converts it to HTML code.
An HTML editor helps you create an HTML file by inserting HTML codes for you as you work.(In this course we will ONLY use Notepad and write the HTML tags ourselves.)
HTML Syntax
Document content is what the user sees on the page, such as headings and images. Tags
are the HTML codes that control the appearance of the document content. tag is thename of the HTML tag
attributes are properties of the tag document content is actual content that appears in the Web pageHTML Tags
Tags can be one-sided or two-sided. two-sided tags contain an opening tag that tells the browser to turn on a feature and
apply it to the content that follows, and a closing tag that turns off the feature
one-sided tags are used to insert non-character data into the Web page, such as a graphicimage or video clip
Tags are not case sensitive; however the current standard is to type all tags in lowercaseletters.
Structure of an HTML Document
2 Main Parts:1.)Head
Contains the page title (displayed in the title bar of the browser window) Contains meta tags used by search engines
Text in the head is NOT visible in the browser window2.)Body
Contains everything that will be visible in the browser window
Creating a HTML File Using a Text Editor (i.e. Notepad)
Launch Notepad
Type document, adding tags as desired. Save File:
o File/SaveAso Location: root level of your driveo Filename: index.HTML (including quotes)
N.Sridhar, Associate Professor, GMRIT, Rajam
7/31/2019 Advance Java Final Material
21/137
Advanced Java Programming Web Based Course Notes
Initial HTML Tags in Notepad - ALL HTML documents MUST contain these tags
open the HTML file
open the head tag
open the title tagEverything typed between the opening and closingtitle tags will be the page title text that appears in
browser title bar (this is NOT the file name).
close the title tag
close the head tag
open the body tagEverything typed between the opening and closing body tags displays in the browser window.
close the body tag
close the HTML file
Creating Heading Tags
Heading Style tags contain formatting for font size, alignment, and spacing before and after. HTML
supports six levels of headings, numbered through , with being the largest and mostprominent. Headings are always displayed in a bold font. Different browsers may interpret theheading tags differently.
insert text here the largest size insert text here
insert text here
insert text here
insert text here
insert text here the smallest size
N.Sridhar, Associate Professor, GMRIT, Rajam Page 3 of 7
7/31/2019 Advance Java Final Material
22/137
Advanced Java Programming Web Based Course Notes
Creating Lists
HTML supports three kinds of lists:
anordered list, which is used to display information in a numeric order an unordered list, which list items are not listed in a particular order i.e. bullets
a definition list, which is a list of terms, each followed by a definition line that is typicallyindented slightly to the right
ORDERED LIST
This is the 1st
list item.
This is the 2nd
list item.This is the 3
rdlist item.
Remember to close the ol tag
UNORDERED LIST
The unordered list tag
creates a bulleted list.
Remember to close the ul tag.
DEFINITION LIST
Type the name of the term here
The definition of the term is placed after
the dd tag and is slightly indented.
You can continue the list with another
term
Followed by its definition, slightly
indented
N.Sridhar, Associate Professor, GMRIT, Rajam
7/31/2019 Advance Java Final Material
23/137
Advanced Java Programming Web Based Course Notes
Formatting Paragraphs and Text
HTML formats text ONLY through the use of tags and ignores such things as extra blank
spaces, blank lines, or tabs. Note that some tags are one-sided and some are two-sided.
insert text here
insert text here
insert text here
insert text here
insert text here
N.Sridhar, Associate Professor, GMRIT
inserts a line break
inserts a paragraph break
bold
center text and images
italic
underline
font color - color is an attribute of the font tag -
RRGGBB is a 6-digit hex # used to indicate the amount
of red, green, and blue used to create a specific color
Examples:
creates white text creates black text
Background color of entire Web page - bgcolor is an
attribute of the body tag - There should be only ONE
body tag in your HTML document.
Example:
creates a blue background
\
7/31/2019 Advance Java Final Material
24/137
Advanced Java Programming Web Based Course Notes
Inserting a Graphic Images
Images can be displayed directly on the Web page when the page is accessed by a user. Images should
be in one of two file formats: GIF (Graphics Interchange Format) or JPEG (Joint
Photographic Experts Group). Note: Save the image file in the same directory as your
index.HTML file.
inserts a graphic image
Inserting Horizontal Lines
A horizontal line can improve the appearance of a Web page. The attributes shown below are all
optional. The default will be a black line that spans the width of the page.
align specifies the horizontal alignment of the line on the page (center, left, or right)sizespecifies the height of the line in pixels or percentage of the screen width
width indicates the width of the line in pixels or percentage of the screen width
color indicates the color of the linenoshade specifies that the browser display a solid line
Inserting an Email link
You can create a link that will launch an email program and create a new message addressed to the
email address specified in the tag.
Text between opening and closing tags will be the text that displays on the screen and provides the
hot spot to click on.
Example:
Click here to email me!
N.Sridhar, Associate Professor, GMRIT, Rajam
7/31/2019 Advance Java Final Material
25/137
Advanced Java Programming Web Based Course Notes
Inserting a Link to another Site
You can create a link that will open another Web page.
Text between opening and closing tags will be text that displays on the screen and provides the hot
spot to click on.
Example:
Click here to visit Bills company site!
Viewing Your Web Page Offline
Launch browser. Select File/Open/Browse to find your HTML file. To make changes:
o Select View/Source - Notepad file will open. oMake changes
o SAVE (You must save in order to see the changes displayed.) In browser window, click REFRESH icon.
Further ReadingFor more information about HTML and a list of some basic HTML tags and Web page design tips
refer to Understanding Computers Today and Tomorrow 11th
edition Comprehensive
pages 430-433.
N.Sridhar, Associate Professor, GMRIT, Rajam
7/31/2019 Advance Java Final Material
26/137
HTML Frames
On many sites, the browser window is divided into a series of frames. In this case, you'llhave multiple HTML documents. The window as a whole will be defined in one document (aframeset), with each of the resulting frames being defined in its own piece of HTML.Documents called up can then replace all the frames, or one frame, or even open a newbrowser window.
Frames are useful tools on web sites where you wish to provide a control pane thatsunchanging, and a data pane in which results are presented, but they do add to the design anddevelopment complexity and its often better to use tables and refresh the whole page as younavigate a site.
There are also issues with the titling of framed pages which make them hard to bookmarksensibly, and with the printing of pages. Its very easy to provide a page that wont print out ifyou use frames, and thats why so many web sites have a "printer friendly version" option.
HTML Forms
Forms are a vital part of any web site that includes executable content as theyre themechanism that allows user data entry. With a form, you define a set of user-enter-able boxes between a and tag. Within the tag an action attribute
gives the URL to be called when the user indicates that the form has been completed, and amethod attribute may be specified too.
Element types within a form
There's much more you might want to do, and forms can have a range of differentelements. There are basically a number of classes of elements, but within each of them anumber of attributes can be applied to tailor how they look and respond.Heres a sample piece of HTML that includes most of the form elements:
Form Element Demo
Different form elementsThis calls a script that lists out all fields entered, and thewhole environment
Type = Textdefault text
Another text
Type = radioSelect a radio button from:
Orange Juice
Lemonade
Rose's Lime Cordial
N.Sridhar, Associate Professor, IT Dept, GMRIT
7/31/2019 Advance Java Final Material
27/137
7/31/2019 Advance Java Final Material
28/137
Submit and reset buttonsdefault reset which you should NOT
pressunless you want to clear your form contents!
default submit
Another submit
An imaged submit
7/31/2019 Advance Java Final Material
29/137
3.1 Style Sheets
To define the formatting styles and rules with CSS, you should use style sheets. A style sheetis a set of style rules that describe how HTML document elements are to be displayed on thepage. Each style rule in the style sheet looks similar to this:
p {font-family:arial; font-size:20pt; color:red}
Or for better readability,
p {
font-family:arial;
font-size:20pt;
color:red
}
Each style rule is comprised of two parts, a selector and a declaration. The selector part of the
style rule specifies which HTML elements are to be affected by the rule. The style rule aboveis defined for p (paragraph) elements. This rule is applied automatically to every p element
in every HTML document that uses this style sheet.
A selector can specify more than one element by separating the elements with commas. Thefollowing style rule applies to all h1 and h2 heading elements:
h1 h2 {font-family:arial; color:navy}
The declaration part of a style rule, contained within braces ({}), defines the style properties to
be applied to the specified elements. The properties are comprised of name and value pairs.
Each name is followed by a colon (:) and one or more values. The property name defines the
attribute, such as color or font-family. The property value defines the specification of
that attribute. Each name and value pair is separated by a semicolon (;). As a result of the
first example of style rule, all of the p elements on the web page are displayed in red, 20-point
Arial font.
At this point, you may be thinking that you can achieve the same result using HTML elementsand their associated attributes. For this particular example, you may use:
Some text
But what if you have 20 paragraphs? Do you want to repeat that font definition within every
paragraph? What if you decide later that you really want that text to be blue? Apparently,
style sheets bring many benefits to us.
4 Defining Styles
There are 3 basic ways to define styles for web pages: inline, embedded, and external.
3
7/31/2019 Advance Java Final Material
30/137
4.1 Inline Styles
You can specify a style rule directly within an HTML element using the style attribute ofthe element. This is useful when you want a style applied only for a particular element onyour web page. For example,
Some text
Since the style rule is defined within the elements tag, there is no need for a selector, only the
declaration.
Using an inline style is better than using the traditional individual element attributes because
many of the formatting attributes have been deprecated and are supposed not to be used any
more. In addition, there are more style properties than element attributes, giving you more
control over the look of the element. For example, you may use margin-left style property
allows you to set a left margin for the paragraph. There is no comparable paragraph attribute.
Nevertheless, as you can see, we cannot benefit more from CSS besides the above, especially
from the viewpoint of reusability. For more benefits, we need to use embedded and external
styles.
4.2 Embedded Styles
You can define a consistent style for all elements of a specific type using embedded styles.
This style is automatically applied to that element type throughout the page, giving you a
standard look on the page.
You declare an embedded style with a style element in the header section of the HTMLdocument. The style element contains one or more style rules. For example:
Welcome to Internet Programming
The style element has a type attribute that indicates the types of style rules to use; in this
case, it is CSS. This attribute is required for strict conformance to XHTML. The comment
markers within the style element are not required but highly recommended so that older
browsers that dont understand the style element ignore the style definition.
4
7/31/2019 Advance Java Final Material
31/137
4.3 External Styles
Above the style rules are defined in the HTML document that uses the styles. To reuse the
styles throughout multiple pages of your web application, we can instead create the styles in
an external file and link that file to all of HTML documents.
Later, if you want to change the way all of your pages look, simply change the external style
sheet file and all of the pages in your application linked to the style sheet file reflect the
change.
To create an external style sheet, simply create a text file for the style rules. This file is called a
style sheet file and is normally given a .css extension. Add your styles to that file. The style
rules are the same as for the embedded styles.
Any HTML document that wants to use the style from the style sheet file can link to that stylesheet file. Use the link element in the header section of the HTML document to link to thedesired external sheet file:
The rel attribute of the link element defines the nature of the relationship between the
linked resources; in this case, the link is to a style sheet. The type attribute defines the type
of the linked file (always text/css for cascading style sheets). The name of the style sheet
file is defined with the href attribute using relative or absolute paths.
5 Declaring Style Classes for Flexibility
The styles defined so far have been for specific elements or specific types of elements. How
if we want different styles applied respectively to different groups of elements of the same
type? CSS has the mechanism called style classes to allow us to declare named styles that can
be applied to specific elements on a web page.
Remember when you specify a particular HTML element as the selector of a style rule, thestyle properties are automatically applied to all occurrences of that particular type of element.With style classes, you may define different styles for different types of the same element. For
example, you can define two types of paragraphs: key points and normal information. If youwant the key points to stand out when your page is displayed, you could make the key pointparagraph font bigger and red. You can define two different styles for the two different typesof paragraphs by defining two style classes as follows:
7/31/2019 Advance Java Final Material
32/137
p.normal {font-size:15pt; color:navy}
.margin {margin-left:0.5in}
-->
As the example shows, you declare a style class using a dot (.) and a style class name in theselector part of the style rule. The style class names can be any name that provides a good
description of the usage of the style. If the style class is only to be used for a particular type
of element, the element name precedes the style class definition.
In the example, both the key and normal style classes can only be used with p elements,
while the margin style class is not associated with any particular element type, so it can be
used with any relevant element.
In the example, the p element style is applied automatically to every p element on the webpage. But to assign a style class to a particular HTML element, you must set the class
attribute of that element to the style class name. For example:
Welcome to Internet Programming
Announcement
We wont have class tomorrow.
And any p element without a class attribute uses the standard p element style.
Style and style class declarations assume that you want to apply a style to several elements.
There may be situations where you want to define a unique style for an individual element.You can do this with inline styles by setting the style attribute of the element as discussed
previsouly. However, you may want to keep all of your style information together. In this
case, you can define a style rule using the value of the elements id attribute.
To apply a style to a specific element, there must be a way to identify that element. To doso, you have to define the id attribute of that element and then use a pound sign (#) and thevalue of the elements id attribute as the style selector. For example:
#LastName {font-size:15pt; color:brown}
6 Cascading Style Sheets
A key feature of CSS is that style rules can cascade. That is several style rules may work
together for the same set of elements and all of the rules can influence the presentation of
those elements.
6
7/31/2019 Advance Java Final Material
33/137
As we discussed above, you may define inline, embedded, or external style rules. They may
overlap with each other when the same type of elements is used as selector. In this case, all
the style attributes are applied.
But how if there is a conflict, e.g. different colors assigned in different style rules? CSS assigns
different priorities to the style rules defined differently:
Inline > Embedded > External
Specific selectors always take priority over general selectors. A style rule with a class
defined in the selector beats a style rule without a class. And a style rule with an element
ID beats a style rule with a class.
When multiple style rules apply to the same element, the style rule defined last takes
precedence.
The cascading effect can be very useful when you define a general style for a large range of
elements and then define a different style for a subset of them.
7
7/31/2019 Advance Java Final Material
34/137
Introduction
To
JavaScriptIntroduction
Simple programming language in the browser (Totally Client Side)Basically no relation to Java - just a marketing nameUsed to be incompatible versionsLater became a standard under ECMAWorks best in IE 5 or later, Netscape 6 or later, Mozilla 1.0 or later, including Firefox.
Mozilla probably has the best JavaScript implementation.
JavaScript NicheMake the client more responsive in a client/server system Aslightly thicker client, but better user experienceAdvantages: more responsive, doesn't require a request/response roundtrip
e.g. on product detail page for a t-shirt, have a pop-up menu for color. UseJavaScript to swap the image to show different shirts without doing a wholeform submit.
JavaScript can do things in the browser: adjust the HTML in the page, adjust the
window, open new windowsJavascript cannot: use the local filesystem, do networking.
JavaScript Language Basics section in the HTML document - runs on document load Notype declarations requiredVariables are essentially global by default. e.g. count below. (variables are actuallyproperties of a global context)Function definitionsstrings - "hello" or 'hello', use + to concat"var" - declare a local variable (as opposed to a global)
alert(str) - puts up an alert panel
JavaScript and Browserdocument - the HTML documentdocument.name - refer to a named element in the documentdocument.images - array of imagesdocument.forms - array of formsThere are also ways to access the window, cookies, etc.Use Mozilla's JavaScript Console to see error messages.
N.Sridhar, Associate Proessor, GMRIT
7/31/2019 Advance Java Final Material
35/137
JavaScript ExampleJS Demo
function hello(greeting) {
var str = greeting + "!!!";
alert(str);}
count = 0;
function upCount() {count++;alert(count);
}
function noFear() {
var fear = document.affirm.fear.value;if (!document.affirm.mockMode.checked) {
alert("No " + fear + " to be seen around here!");}else {
var mock = "Being afraid of " + fear + " is stupid!";window.status = mock
document.affirm.mock.value = mock;}
}
Say Hello
Count
oops
Thing you are afraid of...
Mock mode:
N.Sridhar, Associate Proessor, GMRIT
7/31/2019 Advance Java Final Material
36/137
JavaScript ResourcesJavaScript URLs on the course pageJavaScript the Definitive Guide 4th ed, by David Flanagan (O'Reilly) The"Rhino" bookImportant to get the latest edition, since the language (and browsers) have evolved a lot
JavaScript and BeyondJavaScript has all sorts of features we're not going to worry about: objects, exceptions,
regular expressionsBut we're not messing with thatIt is, at its heart, a simple language, intended for non-programmers, so a little goes along way
UndefinedThe undefined value is like undef in PerlThe value of a variable that has not been given a valueUse == to test for undefined
if (a == undefined) { ...
StringsEither " or ' work as delimetersUse + to concat strings (converts ints to string form automatically)s.toLowerCase() // returns lowercase form== does a "deep" string compare (unlike Java, which does a reference/pointer compare)s.indexOf(target) // returns the index of the target, or -1
Arraysa = new Array(); // new empty arrayvar b= new Array(); // as above, but "b" is a local variable
Add three elementsa.push(1);a.push(2);a.push("hello");
a[0] - access element 0
a[100] = "foo"; // makes array biggera.length // current length of arrayOther obvious built-in functions: pop(), shift(), unshift(), sort(), join(), reverse()c = [1, 2, "hello"]; // [...] literal defines an array on the flyarray.toString() // returns a string form, but without the [ ]: 1,2,hello
N.Sridhar, Associate Proessor, GMRIT
7/31/2019 Advance Java Final Material
37/137
Objects in Java Script
Arrays - ObjectsArrays and objects are actually the same thing - the a[1] syntax is just an alternate way ofsaying a.1.So to access a.foo may be written as a["foo"] or a[x] where x is variable containing thestring "foo". Notice that the JSP 2.0 Expression Language adopted this syntax.
For Loop - Array
Syntax to loop an index over an array..for (int i in array) {
// i iterates 0..len-1
// use array[i] to access the actual elements}
Form/Field/ImgAccessSuppose we have a tag with a name=foo that contains a field with name=barCan refer to the field as document.foo.barCan refer to the value of the field as document.foo.bar.value
For checkbox, field.checked is true if the checkbox is checkedNames also work for images , and the src may be accessed asdocument.imgname.src, document.forms, document.images - these are arrays of theelements, numbered by the order they occur in the document.
Id accessNames do not work for all HTML elmentsHowever, any element may have an "id" and we can use that to get a pointer to thatelement on the JavaScript side.HTML - the tag is a way of identifying a section in the HTML
JavaScriptvar node = document.getElementById("foo"); if(node != null) { ...
N.Sridhar, Associate Proessor, GMRIT
7/31/2019 Advance Java Final Material
38/137
Node HTMLGiven a pointer to a node, can manipulate the HTMLThis is the same Document Object Model (DOM) tree-of-nodes that is used in XMLDOM way to add text after a node...
node.childNodes[0].data = text;There are lots of other DOM functions that can be used to edit the DOM
innerHTML way - this is much easier, although it does not have quite the officialsupport as the DOM way. However, it works on all modern browsers. The text can
include its own tags.node.innerHTML = text;
N.Sridhar, Associate Proessor, GMRIT
7/31/2019 Advance Java Final Material
39/137
Dynamic HTML with Java Script
onclick="foo();"Calls a function when a link or button or some text is clickedonclick="callJSFunction();" - works in ...
Buttonfoo - the return false prevents thejump to the next page
onsubmitRuns on form submit - submit button or return-keyThe "return false;" prevents the actual submit back to the server (some older browsers dothe submit anyway.
text - onchange, onkeypressFor text field and textareas, detect changes to the textonchange is most widely supported
onkeypress, onkeydown, onkeyup are less standard, but allow you to detect individualkeypresses. Onkeyup is handy, since it runs after the char has been added to the field
body - onloadOnly works in the
7/31/2019 Advance Java Final Material
40/137
Quotes CodeQuotes
// We allocate a global array and fill it with the quote data.
lines = new Array();
lines.push("Everybody's always telling me one thing and out the other.");lines.push("Even a fish could stay out of trouble if it would just learn to keepits mouth shut.");lines.push("Beware the lollipop of mediocrity -- lick it once and you suckforever.");lines.push("We don't have time to stop for gas -- we're already late.");lines.push("By doing just a little each day, I can gradually let the task
overwhelm me.");lines.push("Being powerful is like being a lady. If you have to tell people youare, you aren't.");lines.push("Never attribute to malice that which can satisfactorily beexplained by incompetence.");
// Search for an element with the given id // andset its innerHTML to the given text. functionsetText(id, text) {
var node = document.getElementById(id); if(node != null) {node.innerHTML = text;//node.childNodes[0].data = text; // alternative for some simple tags
}
}
// Given the name of a form, access the target field// within that form and using its target text, generate // thequote list and put it into the result tag.function setQuotes(form_name) {
// cute: use [] instead of . to access the form by name vartarget = document[form_name].target.value;//alert(target);var contents = "";target = target.toLowerCase();for (var i in lines) {
if (lines[i].toLowerCase().indexOf(target)!=-1) {contents = contents + "" + lines[i] + "\n";
}}
setText("result", contents);}
Quotes
N.Sridhar, Associate Proessor, GMRIT
7/31/2019 Advance Java Final Material
41/137
Quote search
Search:
Search:
Quotes button
Quotes tag
Quotes...
N.Sridhar, Associate Proessor, GMRIT
7/31/2019 Advance Java Final Material
42/137
XML Basics
1 Introducing XML
1.1 What is XML?
XML stands for eXtensible Markup Language. It is a markup language much like HTML, but
there are several differences between them:
HTML includes a collection of predefined tags that you can use right away in editing
your HTML files, e.g. and , but XML tags are not predefined.
To use XML, users have to define their own tags for their specific application before using
them. For example, to describe a note, , , , , and
are defined in advance and used in a nested fashion to present the following XML file as
a note:
Tove
Jani
Reminder
Dont forget the party!
With XML, one can define whatever tags needed, which together compose a user-defined
markup language similar to HTML, and then use the language to describe data. Specif-
ically XML uses Document Type Definition (DTD) or an XML Schema to define tags.
In this sense, XML is viewed as a meta-language since it can be used to define and de-
scribe a markup language instead of concrete data directly. That is also why it is called
extensible.
XML was designed to describe data while HTML was designed for displaying data.
If you remember, HTML tags control the way data is presented to browser users, color,
font size, spacing, etc. Differently XML aims to deal with the logic meaning of data, or
semantics. In the above example, the text wrapped in and is the name
7/31/2019 Advance Java Final Material
43/137
of the sender of the note. This enables the fulfillment of the task of finding all the notes
written by a specific person. So XML was designed to describe data and to focus on
what data is while HTML was designed to display data and to focus on how data looks.
Actually XML and HTML can complement each other. For example, we use XML files to
store data on a web server machine and when a request arrives, a servlet runs to retrieve
data in XML, compose a HTML file, and finally output it to the client. This way you can
concentrate on using HTML for data layout and display, and be sure that changes in the
underlying data will not require any changes to your HTML.
Besides XMLs role of storing data, with XML, data can be exchanged between
incompatible systems.
In the real world, computer systems and databases contain data in incompatible formats.
One of the most time-consuming challenges for developers has been to exchange data
between such systems over the Internet.
Converting the data to XML can greatly reduce this complexity and create data that
can be read by many different types of applications, since XML data is stored in plain text
format, which is software- and hardware-independent.
The best description of XML may be this: XML is a cross-platform, software and hardware
independent tool for transmitting information. Since the creation of XML, it has been amazing to
see how quickly the XML standard has been developed and how quickly a large number of
software vendors have adopted the standard. It is strongly believed by the IT community at
large that XML will be as important to the future of the Web as HTML has been to the
foundation of the Web and that XML will be the most common tool for all data manipulation
and data transmission.
1.2 XML Syntax
The syntax rules of XML are very simple and very strict. The rules are very easy to learn, and
very easy to use. Because of this, creating software that can read and manipulate XML is very
easy to do.
1.2.1 An Example XML Document
XML documents use a self-describing and simple syntax. For example, the following is acomplete XML file presenting a note:
Tove
2
7/31/2019 Advance Java Final Material
44/137
Jani
Reminder
Dont forget me this weekend!
The first line in the document - the XML declaration - defines the XML version and the
character encoding used in the document. In this case the document conforms to the 1.0
specification of XML and uses the ISO-8859-1 (Latin-1/West European) character set.
The next line and the last line describe the root element of the document (like it was saying:
this document is a note ). So when you look at the document, you easily detect this is a note to
Tove from Jani. So XML is pretty self-descriptive.
1.2.2 Rigid Syntax
Different from HTML, XML has a syntax that is much more rigid.
With XML, it is illegal to omit the closing tag.
In HTML some elements do not have to have a closing tag to be able to present content in
the way the user wants them to. For example:
This is a paragraph
This is another paragraph
In XML, however, all elements must have a closing tag, like this:
This is a paragraph
This is another paragraph
Note that you might have noticed from the previous example that the XML declaration
did not have a closing tag. This is not an error. The declaration is not a part of the
XML document itself. It is not an XML element, and it should not have a closing tag.
Unlike HTML, XML tags are case sensitive.
With XML, the tag is different from the tag .
Opening and closing tags must therefore be written with the same case:
This is incorrect
This is correct
Improper nesting of tags makes no sense to XML.
In HTML some elements can be improperly nested within each other and still display
content in the desired way like this:
3
7/31/2019 Advance Java Final Material
45/137
This text is bold and italic
In XML all elements must be properly nested within each other like this:
This text is bold and italic
All XML documents must contain a single tag pair to define a root element.
All other elements must be within this root element. All elements can have sub elements
(child elements). Sub elements must be correctly nested within their parent element:
.....
With XML, it is illegal to omit quotation marks around attribute values.
XML elements can have attributes in name/value pairs just like in HTML. In XML theattribute value must always be quoted. Study the two XML documents below. The first oneis incorrect, the second is correct:
Tove
Jani
Tove
Jani
The error in the first document is that the date attribute in the note element is not
quoted.
With XML, the white space in your document is not truncated.
This is unlike HTML. With HTML, a sentence like this:
Hello my name is Tove,
will be displayed like this:
7/31/2019 Advance Java Final Material
46/137
Hello my name is Tove,
because HTML strips off the white space.
With XML, CR/LF is converted to LF.
Do you know what a typewriter is? Well, a typewriter is a mechanical device used in the
previous century to produce printed documents. :-)
After you have typed one line of text on a typewriter, you have to manually return the
printing carriage to the left margin position and manually feed the paper up one line.
In Windows applications, a new line is normally stored as a pair of characters: carriage
return (CR) and line feed (LF). The character pair bears some resemblance to the type-
writer actions of setting a new line. In Unix applications, a new line is normally stored
as a LF character. Macintosh applications use only a CR character to store a new line.
Comments in XML The syntax for writing comments in XML is similar to that of HTML.
However as you see, there is nothing special about XML. It is just plain text with the addition of
some XML tags enclosed in angle brackets.
Software that can handle plain text can also handle XML. In a simple text editor, the XML
tags will be visible and will not be handled specially.
In an XML-aware application, however, the XML tags can be handled specially. The tags
may or may not be visible, or have a functional meaning, depending on the nature of the
application.
7/31/2019 Advance Java Final Material
47/137
Document Type DefinitionDocument Type DefinitionDocument Type DefinitionDocument Type Definition ---- XML ValidationXML ValidationXML ValidationXML Validation
Similar to HTML, XML with correct syntax is Well Formed XML. That is a well formed XML
document is a document that conforms to the XML syntax rules that were described in the
previous sections.
More specifically, to be well formed, an XML document must be validated against a Document
Type Definition (DTD). The purpose of a DTD is to define the legal building blocks of an
XML document. It defines the document structure with a list of legal elements. a DTD can be
specified internally or externally. The following is an example of internal DTD for the above
note example:
]>
Tove
Jani
Reminder
Dont forget me this weekend
The DTD above is interpreted like this: !DOCTYPE note (in line 2) defines that this is a
document of the type note. !ELEMENT note (in line 3) defines the note element as having
four elements: to,from,heading,body . !ELEMENT to (in line 4) defines the to element to be
of the type #PCDATA . !ELEMENT from (in line 5) defines the from element to be of the type
#PCDATA and so on ...
If the DTD is external to your XML source file, it should be wrapped in a DOCTYPE definitionwith the following syntax:
ToveJani
Reminder
Dont forget me this weekend!
7/31/2019 Advance Java Final Material
48/137
7/31/2019 Advance Java Final Material
49/137
attribute values are not easy to test against a Document Type Definition (DTD) - which is
used to define the legal elements of an XML document
If you use attributes as containers for data, you end up with documents that are difficult to
read and maintain. Try to use elements to describe data. Use attributes only to provide
information that is not relevant to the data.
Dont end up like this ( if you think this looks like XML, you have not understood the point):
7/31/2019 Advance Java Final Material
50/137
Introduction To XML SchemasIntroduction To XML SchemasIntroduction To XML SchemasIntroduction To XML Schemas
With XML, one can define whatever tags needed, which together compose a user-defined
markup language similar to HTML, and then use the language to describe data. Specif-
ically XML uses XML Schema to define tags.
In this sense, XML is viewed as a meta-language since it can be used to define and de-
scribe a markup language instead of concrete data directly. That is also why it is called
extensible.
And the following is a copy of the file note.dtd containing the DTD:
W3C supports an alternative to DTD called XML Schema. If interested, you may read more
about XML Schema in related books.
The W3C XML specification states that a program should not continue to process an XML
document if it finds a validation error. The reason is that XML software should be easy to
write, and that all XML documents should be compatible.
With HTML it was possible to create documents with lots of errors (like when you forget an end
tag). One of the main reasons that HTML browsers are so big and incompatible, is that theyhave their own ways to figure out what a document should look like when they encounter an
HTML error.
With XML this should not be possible.
1.6 Viewing XML Files
To view an XML document in IE 5.0 (and higher) you can click on a link, type the URL in the
address bar, or double-click on the name of an XML file in a files folder. If you open an XML
document in IE, it will display the document with color coded root and child elements. A plus (+)or minus sign (-) to the left of the elements can be clicked to expand or collapse the element
structure. If you want to view the raw XML source, you must select View Source from the
browser menu.
To view an XML document in Netscape 6, youll have to open the XML file and then right-click in
XML file and select View Page Source . If you open an XML document in Netscape 6, it will
display the document with color coded root and child elements.
If an erroneous XML file is opened, the browser will report the error.
Since XML tags are invented by the author of the XML document, browsers do not know if
a tag like describes an HTML table or a dining table.
7/31/2019 Advance Java Final Material
51/137
7/31/2019 Advance Java Final Material
52/137
}
COUNTRY,PRICE,YEAR,COMPANY {
display: block;
color: #000000;
margin-left: 20pt;
}
where it is specified how to display each kind of elements.
1.8 Displaying XML with XSL
Besides CSS, XSL was invented just for displaying XML. The eXtensible Stylesheet Language
(XSL) is far more sophisticated than CSS.
XSL consists of three parts:
XSLT (XSL Transformations) is a language for transforming XML documents.
XSLT is the most important part of the XSL Standards. It is the part of XSL that is
used to transform an XML document into another XML document, or another type of
document that is recognized by a browser, like HTML and XHTML. Normally XSLT
does this by transforming each XML element into an (X)HTML element.
XSLT can also add new elements into the output file, or remove elements. It can rearrange
and sort elements, and test and make decisions about which elements to display, and a
lot more.
A common way to describe the transformation process is to say that XSLT transforms an
XML source tree into an XML result tree.
XSLT uses XPath to define the matching patterns for transformations. In the transfor-
mation process, XSLT uses XPath to define parts of the source document that match
one or more predefined templates. When a match is found, XSLT will transform the
matching part of the source document into the result document. The parts of the source
document that do not match a template will end up unmodified in the result document.
XPath is a language for defining parts of an XML document.XPath uses path expressions to identify nodes in an XML document. These path expres-sions look very much like the expressions you see when you work with a computer filesystem:
w3schools/xpath/default.asp
7/31/2019 Advance Java Final Material
53/137
Introduction to Document Object Model (DOM)Introduction to Document Object Model (DOM)Introduction to Document Object Model (DOM)Introduction to Document Object Model (DOM)
Programming with XML
Since Java has been commonly used for processing XML files, this section presents one popular
Java-based method of parsing XML: the Document Object Model (DOM).
DOM represents an entire XML document in a tree-like data structure that can be easily
manipulated by a Java program. The advantage of DOM is that it is relatively simple to use
and you can modify the data structure in addition to extracting data from it. However, the
disadvantage is that DOM always parses and stores the entire document, even if you only care
about part of it. .
The use of DOM goes as follows:
1. Tell the system which parser you want to use. There are many ways to do so, of whichthe system property is the easiest method. For example the following code permits usersto specify the parser on the command line with -D option to java, and uses the ApacheXerces parser otherwise.
public static void main(String args[]) {
String jaxPropertyName = "javax.xml.parsers.DocumentBuilderFactory"; if
(System.getProperty(jaxPropertyName) == null) {
String apacheXercesPropertyValue =
"org.apache.xerces.jaxp.DocumentBuilderFactoryImpl";
System.setProperty(jaxPropertyName, apacheXercesPropertyValue);
}
}
7/31/2019 Advance Java Final Material
54/137
2. Create a JAXP document builder. This is basically a wrapper around a specific XML
parser.
DocumentBuilderFactory builderFactory =
DocumentBuilderFactory.newInstance();
DocumentBuilder builder =
builderFactory.newDocumentBuilder();
3. Invoke the parser to create a Document representing an XML document.
Document document = builder.parse(someInputStream);
4. Normalize the tree.
document.getDocumentElement().normalize();
5. Obtain the root node of the tree. This returns Element, which is a subclass of the moregeneral Node class that represents an XML element.
Element rootElement = document.getDocumentElement();
6. Examine various properties of the node. Various methods are available for access:
getNodeName(), getNodeValue(), getAttributes(), getChildNodes(), etc..
As you may image, you may simply replace the Property format configuration file for your
own web server with an XML one, and use the above process to access the configuration
information.
7/31/2019 Advance Java Final Material
55/137
Presenting XMLPresenting XMLPresenting XMLPresenting XML
Empire Burlesque
Bob Dylan
10.90
Hide your heart
Bonnie Tyler
9.90
Greatest Hits
Dolly Parton
9.90
The XPath expression below selects the ROOT element catalog:
/catalog
The XPath expression below selects all the cd elements of the catalog element:
/catalog/cd
The XPath expression below selects all the price elements of all the cd elements of thecatalog element:
/catalog/cd/price
Note: If the path starts with a slash (/) it represents an absolute path to an element!
XPath also defines a library of standard functions for working with strings, numbers and
Boolean expressions. The XPath expression below selects all the cd elements that have a
price element with a value larger than 10.80:
/catalog/cd[price>10.80]
XSL-FO is a language for formatting XML documents.
Think of XSL as set of languages that can transform XML into XHTML, filter and sort XML
data, define parts of an XML document, format XML data based on the data value, like
displaying negative numbers in red, and output XML data to different media, like screens,
paper, or voice.
7/31/2019 Advance Java Final Material
56/137
One way to use XSL is to transform XML into HTML before it is displayed by the browser. Be-low is a fraction of the XML file, with an added XSL reference. The second line, , links the XML file to the XSL file:
Belgian Waffles
$5.95
two of our famous Belgian Waffles
650
And the corresponding XSL file is as follows:
-
( calories per serving)
7/31/2019 Advance Java Final Material
57/137
XMLXML Processor APIsProcessor APIs
How applications can manipuHow applications can manipustructured documents?structured documents?
An overview of document arsAn overview of document ars
3.1 SAX: an event3.1 SAX: an event--based interfbased interf
3.2 DOM: an object3.2 DOM: an object--based intebased inte
7/31/2019 Advance Java Final Material
58/137
Document Parser InterfaDocument Parser Interfa
(See, e.g., Leventhal, Lewis & Fuchs: Desig(See, e.g., Leventhal, Lewis & Fuchs: DesigInternet Applications, Chapter 10, andInternet Applications, Chapter 10, and
D. Megginson: What is an EventD. Megginson: What is an Event--Based IBased I
kind of a parserkind of a parser editors, browserseditors, browsers
transformation/style engines, DB loatransformation/style engines, DB loa
XML parsers are becoming standXML parsers are becoming standapplication development framewoapplication development framewo
7/31/2019 Advance Java Final Material
59/137
7/31/2019 Advance Java Final Material
60/137
Document Parser InterDocument Parser Inter
I: EventI: Event--based interfacesbased interfaces
Command line and ESIS interfCommand line and ESIS interf
traditional interface to standtraditional interface to stand--alonalonparsersparsers
Event callEvent call--back interfaces: SAXback interfaces: SAX
II: TreeII: Tree--based (object model) inbased (object model) in
W3C DOM RecommendationW3C DOM Recommendation
7/31/2019 Advance Java Final Material
61/137
Command Line and ESIS InCommand Line and ESIS In
Simplest of parser interfaces;Simplest of parser interfaces;Immediately usable for simple apImmediately usable for simple ap
ESIS: Element Structure InformatESIS: Element Structure Informat
canonical output format for SGML pcanonical output format for SGML p
stream of parsing events (start elemstream of parsing events (start elemelement, attribute, ) in documentelement, attribute, ) in document
can be used as input to other progracan be used as input to other progra
Output format of, e.g., sgmls andOutput format of, e.g., sgmls and(SGML) parsers(SGML) parsers
7/31/2019 Advance Java Final Material
62/137
ESIS Example: Input docESIS Example: Input doc
< > (See.
7/31/2019 Advance Java Final Material
63/137
ESIS example: ASCII output ofESIS example: ASCII output of
(ARTICLE(ARTICLE
(PARA(PARA
--Written by the lecturer.Written by the lecturer. \\n(See.n(See.
AREFID TOKEN FIG1AREFID TOKEN FIG1
(FIG(FIG--REFREF
)FIG)FIG--REFREF
--.).)
AID TOKEN FIG1AID TOKEN FIG1
AFILE CDATA pekka.jpgAFILE CDATA pekka.jpg
ACAPTION CDATA The LecturerACAPTION CDATA The Lecturer
(FIG(FIG
)FIG)FIG
)PARA)PARA
)ARTICLE)ARTICLE
CC
7/31/2019 Advance Java Final Material
64/137
CommandCommand--line parser intline parser int
ApplicationApplication
Ai CAi C
SGML/XML ParserSGML/XML Parser
line callline callStreamStream
--Hi!Hi!)A)A
7/31/2019 Advance Java Final Material
65/137
Event CallEvent Call--Back InterfaBack Interfa
Application implements a set ofApplication implements a set of ccmethodsmethods for handling parse evenfor handling parse even
parser notifies the application by meparser notifies the application by me
parameters qualify events further (elemparameters qualify events further (elemnames and values of attributes, values names and values of attributes, values ))
Idea behind SAX (Simple API fIdea behind SAX (Simple API f
an industry standard API for XML paan industry standard API for XML pa
7/31/2019 Advance Java Final Material
66/137
An event callback appAn event callback app
Application MainApplication MainRoutineRoutine PaPa
s ar ocumens ar ocumen
startElement()startElement()
characters()characters()
CallbackRo
utines
CallbackRo
utines endElement()endElement()
7/31/2019 Advance Java Final Material
67/137
Object Model InterfaceObject Model Interface
Application interacts with an objeApplication interacts with an objerepresentation ofrepresentation of
the parserthe parser
the documentthe document parse treeparse tree consistingconsistingdocumentdocument,, element, attribute, textelement, attribute, text, ,
Abstraction level higher than in eAbstraction level higher than in einterfaces; more powerful accessinterfaces; more powerful access
descendants, following siblings)descendants, following siblings) Drawback: Higher memory consuDrawback: Higher memory consu
7/31/2019 Advance Java Final Material
68/137
An ObjectAn Object--Model Based ApModel Based Ap
ApplicationApplicationInIn--MeMe
ReRe
ParseParse
Build/Build/Load/Load/ModifyModify
DocumDocum
ParserParserObjectObject BuildBuild
Hi!Hi!
AA
"Hi!"Hi!
7/31/2019 Advance Java Final Material
69/137
DOM and SAXDOM and SAXDOM and SAXDOM and SAX
The Simple API for XML (SAX) is an alternative to avoid problem with DTDs
Since Java has been commonly used for processing XML files, this section presents one popular
Java-based method of parsing XML: the Document Object Model (DOM).
DOM represents an entire XML document in a tree-like data structure that can be easily
manipulated by a Java program. The advantage of DOM is that it is relatively simple to use
and you can modify the data structure in addition to extracting data from it. However, the
disadvantage is that DOM always parses and stores the entire document, even if you only care
about part of it.
To use DOM, you need have a DOM-compliant parser. A list of such parsers are given at
http://www.xml.com/pub/rg/Java_Parsers. Besides, the Java API for XML Processing
(JAXP) is needed and available from http://java.sun.com/. This API provides a small
layer on top of DOM that lets you plug in different vendors parsers without making any
changes to your basic code.
There are many ways to do so, of whichthe system property is the easiest method. For example the following code permits usersto specify the parser on the command line with -D option to java, and uses the ApacheXerces parser otherwise.
7/31/2019 Advance Java Final Material
70/137
Introduction to Swings
Java Swing is an alternative to AWT (Abstract Windowing Toolkit)butmost programs which use Swing exploit AWT too. Key the followingsource code into the file SwingIntro.java as a first example:
import javax.swing.JFrame;import javax.swing.JPanel;import javax.swing.JButton;import javax.swing.JLabel;import java.awt.BorderLayout;
public class SwingIntro
{ public static void main(String[]args){ MyButtons handle = new
MyButtons();handle.myMain();}
}
class MyButtons{ public void myMain()
{ JFrame.setDefaultLookAndFeelDecorated(true);JFrame myFrame = new JFrame("Swing Example");myFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); myFrame.setSize(300,100);
JButton jack = new
JButton("Jack");
JButton jill = new JButton("Jill");
JLabel myLabel = new JLabel("Please press the buttons");
JPanel topPanel = new JPanel();topPanel.add(jack);topPanel.add(jill);
JPanel botPanel = new JPanel();botPanel.add(myLabel);
myFrame.getContentPane().add(topPanel,BorderLayout.NORTH);myFrame.getContentPane().add(botPanel,BorderLayout.SOUTH);
myFrame.setVisible(true);}
}
N.Sridhar, Associate Professor, IT Dept, GMRIT
7/31/2019 Advance Java Final Material
71/137
Now compile it using the javac command:
$ javac SwingIntro.java
Then run it using the java command:
$ java SwingIntro
A new window appears within which there is a Swing JFrame. Ignoring theline of dots (which are discussed below), the outline appearance might be:
+----------------------------+Outer Title bar | |
+----------------------------+Inner Title bar | |
+----------------------------+| +------+ +------+ || | Jack | | Jill | || +------+ +------+ ||. .|
| || Please press the buttons |+----------------------------+
Unsurprisingly, pressing the buttons has no effect since noActionListeners have been supplied. They will be added later.
The outer title bar MAY NOT BE PRESENT. If it is, it belongs to anenclosingwindow which can be ignored. [This is the responsibility of the underlyingwindow manager, perhaps an X-windows system.] Everything else is theJFrame which is the subject of this first example.
The JFrame has its own title bar heading a region in which there are three
JComponents, these being two JButtons and a JLabel.
All the classes which Java Swing provides are in the package javax.swing (tobe contrasted with AWT classes which are in the java.awt package). Many ofthe Swing classes begin with the letter J.
Three JComponents can be laid out in various ways, perhaps in a single roworsingle column. Here the JFrame incorporates two JPanels: the one above thedotted line contains the two JButtons and the one below contains the JLabel.
OUTLINE OF THE PROGRAM
The program begins with four import statements for the various Swing classesand a single import statement for the one AWT class that is used,BorderLayout. This will be discussed later.
PRINCIPAL DETAILS OF THE PROGRAM
When sketching the appearance of the required JFrame the designer mightthink of the following hierarchy:
N.Sridhar, Associate Professor, IT Dept, GMRIT
7/31/2019 Advance Java Final Material
72/137
JFrame|
+-------------+-------------+
| |JPanel JPanel
| |+-------------+-------------+ || | |
JButton JButton JLabel
Each JButton, JLabel and JPanel is a child class of JComponent (a JFrameis not) but in simple cases it is convenient to think of assemblinglow-level JComponents (JButtons, JLabels and many others) into a number ofJPanels. The JPanels in their turn are assembled into a single JFrame.
Swing provides many facilities for controlling layout and in this
introductory example the two JButtons are to be arranged side-by-side withina JPanel and the two JPanels are to be arranged one above the other.
Most of the statements in method myMain() are concerned withdeclaring JComponents and assembling them:
1. JFrame myFrame = new JFr