0% found this document useful (0 votes)
1 views

WP Full Notes

The document provides an overview of web page designing using HTML, including the basics of HTML structure, tags, and elements. It also covers scripting languages, specifically client-side and server-side scripting, as well as the use of Cascading Style Sheets (CSS) for styling web documents. Key concepts such as HTML attributes, logical vs. physical tags, and the importance of the HTML DOCTYPE are discussed to aid in web development.

Uploaded by

Vivek Gudise
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
1 views

WP Full Notes

The document provides an overview of web page designing using HTML, including the basics of HTML structure, tags, and elements. It also covers scripting languages, specifically client-side and server-side scripting, as well as the use of Cascading Style Sheets (CSS) for styling web documents. Key concepts such as HTML attributes, logical vs. physical tags, and the importance of the HTML DOCTYPE are discussed to aid in web development.

Uploaded by

Vivek Gudise
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 130

www.rejinpaul.

com
www.rejinpaul.com
UNIT I SCRIPTING. 9

Web page Designing using HTML, Scripting basics- Client side and server side scripting. Java
Script-Object, names, literals, operators and expressions- statements and features- events -
windows -documents - frames - data types - built-in functions- Browser object model - Verifying
forms.-HTML5-CSS3- HTML 5 canvas - Web site creation using tools.

Web page designing using HTML:


Introduction to HTML:
What is an html File?
HTML is a format that tells a computer how to display a web page. The documents themselves
are plain text files with special "tags" or codes that a web browser uses to interpret and display
information on your computer screen. ƒ
 HTML stands for Hyper Text Markup Language ƒ
 An HTML file is a text file containing small markup tags ƒ
 The markup tags tell the Web browser how to display the page ƒ
 An HTML file must have an htm or html file extension
Example:
<html>
<head>
<title>My First Webpage</title>
</head>
<body>
This is my first homepage. <b>This text is bold</b>
</body>
</html>
The first tag is <html>. This tag tells browser that this is the start of an html document. The last
tag is </html>. This tag tells browser that this is the end of the html document. The text between
the <head> tag and the </head> tag is header information. Header information is not displayed in
the browser window. The text between the <title> tags is the title of the document. The <title>
tag is used to uniquely identify each document and is also displayed in the title bar of the
browser window. The text between the <body> tags is the text that will be displayed in browser.
The text between the <b> and </b> tags will be displayed in a bold font.
HTML TAGS:
What are HTML tags?
ƒ HTML tags are used to mark-up HTML elements
ƒ HTML tags are surrounded by the two characters < and >
ƒ The surrounding characters are called angle brackets
ƒ HTML tags normally come in pairs like <b> and </b>
ƒ The first tag in a pair is the start tag, the second tag is the end tag
ƒ The text between the start and end tags is the element content
ƒ HTML tags are not case sensitive, <b> means the same as <B>

Download Useful Materials from Rejinpaul.com


www.rejinpaul.com
www.rejinpaul.com

Logical vs. Physical Tags:


In HTML there are both logical tags and physical tags. Logical tags are designed to describe (to
the browser) the enclosed text's meaning. An example of a logical tag is the <strong> </strong>
tag. By placing text in between these tags you are telling the browser that the text has some
greater importance. By default all browsers make the text appear bold when in between the
<strong> and </strong> tags.
Physical tags on the other hand provide specific instructions on how to display the text they
enclose. They are invented to add style to HTML page.
Examples of physical tags include:
ƒ <b>: Makes the text bold.
ƒ <big>: Makes the text usually one size bigger than what's around it.
ƒ <i>: Makes text italic.
HTML Elements:
An HTML element is defined by a starting tag. If the element contains other content, it ends with
a closing tag, where the element name is preceded by a forward slash.
<p>....</p> is an HTML element, <h1>...</h1> is another HTML element. There are some
HTML elements which don't need to be closed, such as <img.../>, <hr /> and <br /> elements.
These are known as void elements.
Nested HTML Elements: to keep one HTML element inside another HTML element
Eg: <h1>This is <i>italic</i> heading</h1>
<p>This is <u>underlined</u> paragraph</p>
HTML Attribute:
An attribute is used to define the characteristics of an HTML element and is placed inside the
element's opening tag. All attributes are made up of two parts: a name and a value

The name is the property you want to set. For example, the paragraph <p> element in the
example carries an attribute whose name is align, which you can use to indicate the alignment of
paragraph on the page.
The value is what you want the value of the property to be set and always put within quotations.
The below example shows three possible values of align attribute: left, center and right.
<p align="left">This is left aligned</p><p align="center">This is center aligned</p><p
align="right">This is right aligned</p>

Download Useful Materials from Rejinpaul.com


www.rejinpaul.com
www.rejinpaul.com

HTML Entities:

Download Useful Materials from Rejinpaul.com


www.rejinpaul.com
www.rejinpaul.com
Some characters have a special meaning in HTML, like the less than sign (<) that defines the
start of an HTML tag. If we want the browser to actually display these characters we must insert
character entities in place of the actual characters themselves.

What is the importance of the HTML DOCTYPE?


The doctype declaration should be the very first thing in an HTML document, before the html
tag.The doctype declaration is not an HTML tag; it is an instruction to the web browser about
what version of the markup language the page is written in.The doctype declaration refers to a
Document Type Definition (DTD). The DTD specifies the rules for the markup language, so that
the browsers can render the content correctly.
Scripting Language:
A scripting or script language is a programming language that supports scripts, programs written
for a special run-time environment that automate the execution of tasks that could alternatively
be executed one-by-one by a human operator. Scripting languages are often interpreted (rather
than compiled).
Two types of scripting:
Client side Scripting.
Server side Scripting.
Client Side Scripting:
Client side scripts run in the browser and process requests without call backs to the server.
Example: javascript, AJAX.
Work of client side script:
 Scripts are embedded within and interact with the HTML of site, selecting elements of it,
then manipulating those elements to provide an interactive experience.
 Scripts interact with a cascading style sheet (CSS) file that styles the way the page looks.
 It dictates what work the server-side code is going to have to accomplish, and returns data
that’s pulled from the site in a way that’s readable by the browser. For example: If there’s
a form for updating a profile, the back end is built to pull specific data from the database
to populate that form, while front-end scripts populate the form with that information.
 Scripts put less stress on the server because they don’t require processing on the server
once they’re downloaded, just when post-backs are made. “Post-backs” perform specific
call-and-answers with the server-side code, and respond to the user immediately.
Server side Script:

Download Useful Materials from Rejinpaul.com


www.rejinpaul.com
www.rejinpaul.com
Server-side scripting is a technique used in web development which involves
employing scripts run on a web server which produce a response customized for each user's
(client's) request to the website.
Example:
ASP:Active server page
JSP:Java Server page
PHP:Hypertext Preprocessor.
Ruby
PERL

Cascading Style Sheets :


Cascading Style Sheets (CSS) is a simple mechanism for adding style (e.g., fonts, colors,
spacing) to Web documents.
Advantages of Style Sheet:
 Increases download speed.
 Makes pages more accessible.
 Reduces time spent for maintaining and changing the wed sites.
 Multiple styles are cascaded into one.
CSS Syntax:
A CSS rule-set consists of a selector and a declaration block:
Selector { property1: some value; property2: somevalue; }

Download Useful Materials from Rejinpaul.com


www.rejinpaul.com
www.rejinpaul.com

Eg:
p{
color: red;
text-align: center;
}
CSS Selectors:
CSS selectors are used to "find" (or select) HTML elements based on their element name, id,
class, attribute, and more.
Element Selector: The element selector selects elements based on the element name.
Eg:
p{
text-align: center;
color: red;
}
The id Selector: The id selector uses the id attribute of an HTML element to select a specific
element. To select an element with a specific id, write a hash (#) character, followed by the id of
the element.
Eg:
#para1 {
text-align: center;
color: red;
}
The class Selector: The class selector selects elements with a specific class attribute. To select
elements with a specific class, write a period (.) character, followed by the name of the class.
Eg:
.center {
text-align: center;
color: red;
}
<p class="center large">This paragraph refers to two classes.</p>
Grouping Selectors: If you have elements with the same style definitions, It will be better to
group the selectors, to minimize the code.
Eg:
h1, h2, p {
text-align: center;
6

Download Useful Materials from Rejinpaul.com


www.rejinpaul.com
www.rejinpaul.com
color: red;
}
Types of CSS:
When a browser reads a style sheet, it will format the HTML document according to the
information in the style sheet.
 External style sheet
 Internal style sheet
 Inline style
External Style Sheet
With an external style sheet, you can change the look of an entire website by changing just one
file.Each page must include a reference to the external style sheet file inside the <link> element.
The <link> element goes inside the <head> section:
Example
<head>
<link rel="stylesheet" type="text/css" href="mystyle.css">
</head>
An external style sheet can be written in any text editor. The file should not contain any html
tags. The style sheet file must be saved with a .css extension.Here is how the "myStyle.css"
looks:
body {
background-color: lightblue;
}

h1 {
color: navy;
margin-left: 20px;
}
Do not add a space between the property value and the unit (such as margin-left: 20 px;). The
correct way is: margin-left: 20px;
Internal Style Sheet:
An internal style sheet may be used if one single page has a unique style. Internal styles are
defined within the <style> element, inside the <head> section of an HTML page:
Eg:
<head>
<style>
body {
background-color: linen;
}

h1 {
color: maroon;
margin-left: 40px;
}

Download Useful Materials from Rejinpaul.com


www.rejinpaul.com
www.rejinpaul.com
</style>
</head>
Inline Styles:
An inline style may be used to apply a unique style for a single element.To use inline styles, add
the style attribute to the relevant element. The style attribute can contain any CSS property.
The example below shows how to change the color and the left margin of a <h1> element:
<h1 style="color:blue;margin-left:30px;">This is a heading.</h1>
An inline style loses many of the advantages of a style sheet (by mixing content with
presentation). Use this method sparingly.
Multiple Style Sheets:
If some properties have been defined for the same selector (element) in different style sheets, the
value from the last read style sheet will be used. Assume that an external style sheet has the
following style for the <h1> element:
h1 {
color: navy;
}
then, assume that an internal style sheet also has the following style for the <h1> element:
h1 {
color: orange;
}
If the internal style is defined after the link to the external style sheet, the <h1> elements will be
"orange":
<head>
<link rel="stylesheet" type="text/css" href="mystyle.css">
<style>
h1 {
color: orange;
}
</style>
</head>
However, if the internal style is defined before the link to the external style sheet, the <h1>
elements will be "navy":
<head>
<style>
h1 {
color: orange;
}
</style>
<link rel="stylesheet" type="text/css" href="mystyle.css">
</head>
Cascading Order:
What style will be used when there is more than one style specified for an HTML element?

Download Useful Materials from Rejinpaul.com


www.rejinpaul.com
www.rejinpaul.com
Generally speaking we can say that all the styles will "cascade" into a new "virtual" style sheet
by the following rules, where number one has the highest priority:
1. Inline style (inside an HTML element)
2. External and internal style sheets (in the head section)
3. Browser default
So, an inline style (inside a specific HTML element) has the highest priority, which means that it
will override a style defined inside the <head> tag, or in an external style sheet, or a browser
default value.
When there are different stylesheets, here is how style rules are ranked:
A document can have several stylesheets involved with it. Besides the ones you create, all
browsers have a built-in stylesheets (where you set the default font, body and link colors). Unless
the user changes the default settings, here's how the stylesheets are ranked:
1. Author (Designer) stylesheets take top priority
2. Then user stylesheets
3. Finally, browser default styles
Author stylesheets: You as the author (designer) of the web pages can create several stylesheets.
Here's how they are ranked.
1. Inline styles and embedded styles (styles on the HTML page itself). Inline and embedded
styles are called Persistent styles, and they usually have the top weight; in other words,
persistent styles override any styles in external stylesheets.
2. The main or Preferred external stylesheet, which is linked with the attribute rel= in the LINK
tag, follows in the hierarchy.
3. Alternate stylesheets are not used until the user selects them explicitly. If an alternate
stylesheet is selected, the preferred one is turned off, but the persistent styles remain.
When there is only one stylesheet, here is how style rules are ranked:
1. It's possible to push a style rule up to the "front of the line", by giving it an !important label,
regardless of which stylesheet it's in. For instance, if there are two conflicting rules for the same
selector: H1 {font-family: verdana;} H1 {font-family: times !important;} Then the second
rule will prevail and the H1 element will be in Times.
2. The more specific a rule is, the more weight it has. This means for example that style rules
applied to an ID selector or a class selector have more weight than style rules applied to generic
type selectors. 3. Finally, when all other rules are exhausted, the style rules that are listed last
take higher precedence. (That's why persistent styles (the ones actually on the HTML page) take
higher precedence over linked external stylesheets, because they get processed last.)
CSS Styles:
Text and Font Styles:
Now that you are getting the hang of CSS rules, let's look at applying text, font, border and list
styles. To apply styles, you redefine HTML elements like <p>, <h1>, <h2> and others. An
example
of redefining the <p> tag:
p{
font-family: verdana, arial, helvetica, sans-serif;
font-size: 12px;

Download Useful Materials from Rejinpaul.com


www.rejinpaul.com
www.rejinpaul.com
color: #000000;
}
Font and text appearance are the things we most want to control with CSS. Font selector rules
mostly apply to things we used to control with the tag, while text selector rules cover other things
that influence the way a piece of text if presented.
Background Styles:
The background property will let you set the background color, set the background as an image,
repeat a background image and set a background image position on a page.
Border and List Styles:
Border Styles Borders can be applied to most HTML elements within the body. The Border
properties allow you to specify the style, color, and width of an element's border. In HTML
tables are usually used to create borders around text, but with the CSS Border properties you can
create borders that can be applied to any element. You can apply a border style to any of the four
sides of an element by using top, bottom, right or left designations in your selector. The
following border styles created the border around this example box:
p { border-top-color: red; border-top-style: solid; border-bottom-color: navy; border-bottom-
style: dashed; border-bottom-size: 5px; }
Lengths and Percentages:
There are many property-specific units for values used in CSS, but there are some general units
that are used in a number of properties
 em (such as font-size: 2em) is an element approximately equal to the height of a
character.
 px (such as font-size: 12px) is the unit for pixels.
 pt (such as font-size: 12pt) is the unit for points.
 % (such as font-size: 80%) is the unit for... wait for it... percentages.
 Other units include pc (picas), cm (centimeters), mm (millimeters) and in (inches).
When a value is zero, you do not need to state a unit. For example, if you wanted to specify no
border, it would be border: 0. A web page is not a static, absolute medium. It is meant to be
flexible. Because of this, it is generally accepted that 'em' or '%' are the best units to use for font-
sizes, rather than 'px', which leads to non-re sizable text in most browsers, and should be used
sparingly, for border sizes.
Colors :
CSS brings 16,777,216 colors to your disposal. They can take the form of a name, an ' rgb'
(red/green/blue) value or a hex code.
Defining your font-color as red is the same as rgb(255,0,0), which is the same as
rgb(100%,0%,0%), which is the same as #ff0000, which is the same as #f00.
There are 16 valid predefined color names. These are aqua, black, blue, fuchsia, gray, green,
lime, maroon, navy, olive, purple, red, silver, teal, white, and yellow. Transparent is also a valid
value.
The three values in the rbg value are from 0 to 255, 0 being the lowest level (for example no
red), 255 being the highest level (for example full red). These values can also be a percentage.
Hexadecimal (or hex) is a base-16 number system.

10

Download Useful Materials from Rejinpaul.com


www.rejinpaul.com
www.rejinpaul.com
The hex number is defined by a hash character ( #) and can be three or six digits in length.
Basically, the three-digit version is a compressed version of the six-digit (#f00 becomes #ff0000,
#c96 becomes #cc9966 etc.). The three-digit version is easier to decipher (the first digit, like the
first value in rgb, is red, the second green and the third blue) but the six-digit version gives you
more control over the exact color.
CSS Margins:
The CSS margin properties are used to generate space around elements.The margin properties set
the size of the white space outside the border.
With CSS, you have full control over the margins. There are CSS properties for setting the
margin for each side of an element (top, right, bottom, and left).
All the margin properties can have the following values:
 auto - the browser calculates the margin
 length - specifies a margin in px, pt, cm, etc.
 % - specifies a margin in % of the width of the containing element
 inherit - specifies that the margin should be inherited from the parent element
Negative values are allowed.
Eg:
p{
margin-top: 100px;
margin-bottom: 100px;
margin-right: 150px;
margin-left: 80px;
}
CSS Padding:
The CSS padding properties are used to generate space around content.
The padding clears an area around the content (inside the border) of an element.With CSS, you
have full control over the padding. There are CSS properties for setting the padding for each side
of an element (top, right, bottom, and left).
CSS has properties for specifying the padding for each side of an element:
 padding-top
 padding-right
 padding-bottom
 padding-left
All the padding properties can have the following values:
 length - specifies a padding in px, pt, cm, etc.
 % - specifies a padding in % of the width of the containing element
 inherit - specifies that the padding should be inherited from the parent element
The following example sets different padding for all four sides of a <p> element:
p{
padding-top: 50px;
padding-right: 30px;
padding-bottom: 50px;
padding-left: 80px;}

11

Download Useful Materials from Rejinpaul.com


www.rejinpaul.com
www.rejinpaul.com
Setting height and width
The height and width properties are used to set the height and width of an element.
The height and width can be set to auto (this is default. Means that the browser calculates the
height and width), or be specified in length values, like px, cm, etc., or in percent (%) of the
containing block.
div {
height: 200px;
width: 50%;
background-color: powderblue;
}
The CSS Box Model:
All HTML elements can be considered as boxes. In CSS, the term "box model" is used when
talking about design and layout.
The CSS box model is essentially a box that wraps around every HTML element. It consists of:
margins, borders, padding, and the actual content. The image below illustrates the box model:

Explanation of the different parts:


 Content - The content of the box, where text and images appear
 Padding - Clears an area around the content. The padding is transparent
 Border - A border that goes around the padding and content
 Margin - Clears an area outside the border. The margin is transparent
The box model allows us to add a border around elements, and to define space between
elements.
Eg:
div {
width: 300px;
border: 25px solid green;
padding: 25px;
margin: 25px;
}
CSS3:
CSS3 is the latest standard for CSS.
CSS3 is completely backwards-compatible with earlier versions of CSS.
CSS3 Modules
CSS3 has been split into "modules". It contains the "old CSS specification" (which has been split
into smaller pieces). In addition, new modules are added.
12

Download Useful Materials from Rejinpaul.com


www.rejinpaul.com
www.rejinpaul.com
Some of the most important CSS3 modules are:
 Selectors
 Box Model
 Backgrounds and Borders
 Image Values and Replaced Content
 Text Effects
 2D/3D Transformations
 Animations
 Multiple Column Layout
 User Interface
Images:
Rounded Image: coding:
img {
border-radius: 8px;
}
Circled Image:
img {
border-radius: 50%;
}
Animation:
CSS3 animations allows animation of most HTML elements without using JavaScript or Flash!
What are CSS3 Animations?
An animation lets an element gradually change from one style to another.
You can change as many CSS properties you want, as many times you want.
To use CSS3 animation, you must first specify some keyframes for the animation.
Keyframes hold what styles the element will have at certain times.
The @keyframes Rule:
When you specify CSS styles inside the @keyframes rule, the animation will gradually change
from the current style to the new style at certain times.
To get an animation to work, you must bind the animation to an element.
The following example binds the "example" animation to the <div> element. The animation will
lasts for 4 seconds, and it will gradually change the background-color of the <div> element from
"red" to "yellow":
/* The animation code */
@keyframes example {
from {background-color: red;}
to {background-color: yellow;}
}
/* The element to apply the animation to */
div {
width: 100px;
height: 100px;
background-color: red;

13

Download Useful Materials from Rejinpaul.com


www.rejinpaul.com
www.rejinpaul.com
animation-name: example;
animation-duration: 4s;
}
If the animation-duration property is not specified, the animation will have no effect, because the
default value is 0.
CSS3 Multi-column Layout:
The CSS3 multi-column layout allows easy definition of multiple columns of text - just like in
newspapers:
CSS3 Multi-column Properties
 column-count-
div {
column-count: 3;
}
 column-gap: column-gap: 40px;
 column-rule-style: column-rule-style: solid;
 column-rule-width: column-rule-width: 1px;
 column-rule-color: column-rule-color: lightblue;
 column-rule: The column-rule property is a shorthand property for setting all the column-
rule-* properties above. column-rule: 1px solid lightblue;
 column-span: The column-span property specifies how many columns an element should
span across. column-span: all;
 column-width: column-width property specifies a suggested, optimal width for the
columns. column-width: 100px;

HTML5:
HTML5 is a core technology markup language of the Internet used for structuring and presenting
content for the World Wide Web. As of October 2014 [update] this is the final and complete fifth
revision of the HTML standard of the World Wide Web Consortium (W3C).
HTML5 itself, according to the standard, is a markup language (just like HTML4) but the way
the term is being commonly used is as a conglomerate of web technologies, including javascript
(a programming language), CSS (a styling mechanism), HTML (a markup language) and
sometimes server side languages as well.
The DOCTYPE declaration for HTML5 is very simple: <!DOCTYPE html>
The character encoding (charset) declaration is also very simple: <meta charset="UTF-8">
HTML5 Example:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Title of the document</title>
</head>

<body>
14

Download Useful Materials from Rejinpaul.com


www.rejinpaul.com
www.rejinpaul.com
Content of the document......
</body>

</html>

New HTML5 Elements


The most interesting new HTML5 elements are:
New semantic elements like <header>, <footer>, <article>, and <section>.
New attributes of form elements like number, date, time, calendar, and range.
New graphic elements: <svg> and <canvas>.
New multimedia elements: <audio> and <video>.

HTML5 Canvas:
The HTML <canvas> element is used to draw graphics on a web page. The graphic to the left is
created with <canvas>.
It shows four elements: a red rectangle, a gradient rectangle, a multicolor rectangle, and a
multicolor text.
What is HTML Canvas?
The HTML <canvas> element is used to draw graphics, on the fly, via JavaScript.
The <canvas> element is only a container for graphics. You must use a JavaScript to actually
draw the graphics.
Canvas has several methods for drawing paths, boxes, circles, text, and adding images.
Canvas Examples
A canvas is a rectangular area on an HTML page. By default, a canvas has no border and no
content. Always specify an id attribute (to be referred to in a script), and a width and height
attribute to define the size of the canvas. To add a border, use the style attribute.
<canvas id="myCanvas" width="200" height="100"></canvas>
Empty canvas:
<canvas id="myCanvas" width="200" height="100" style="border:1px solid #000000;">
</canvas>

Draw a Line
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
ctx.moveTo(0,0);
ctx.lineTo(200,100);
ctx.stroke();

15

Download Useful Materials from Rejinpaul.com


www.rejinpaul.com
www.rejinpaul.com
Draw a Circle
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
ctx.beginPath();
ctx.arc(95,50,40,0,2*Math.PI);
ctx.stroke();

Draw a Text
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
ctx.font = "30px Arial";
ctx.fillText("Hello World",10,50);

Stroke Text
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
ctx.font = "30px Arial";
ctx.strokeText("Hello World",10,50);

Draw Linear Gradient


var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");

// Create gradient
var grd = ctx.createLinearGradient(0,0,200,0);
grd.addColorStop(0,"red");
grd.addColorStop(1,"white");
// Fill with gradient
ctx.fillStyle = grd;
ctx.fillRect(10,10,150,80);

16

Download Useful Materials from Rejinpaul.com


www.rejinpaul.com
www.rejinpaul.com
UNIT II JAVA
Introduction to object oriented programming-Features of Java – Data types, variables and
arrays – Operators – Control statements – Classes and Methods – Inheritance. Packages and
Interfaces –Exception Handling – Multithreaded Programming – Input/Output – Files –
Utility Classes – String Handling.

Java: Java is a programming language and a platform. Java is a high level, robust, secured
and object-oriented programming language.
Platform: Any hardware or software environment in which a program runs is known as a
platform. Since Java has its own runtime environment (JRE) and API, it is called platform.
I. Features of Java OR java buzzwords:
1. Simple
2. Object-Oriented
3. Platform independent
4. Secured
5. Robust
6. Architecture neutral
7. Portable
8. Dynamic
9. Interpreted
10. High Performance
11. Multithreaded
12. Distributed
Simple
Java language is simple because:
syntax is based on C++ (so easier for programmers to learn it after C++).
removed many confusing and/or rarely-used features e.g., explicit pointers, operator
overloading etc.
No need to remove unreferenced objects because there is Automatic Garbage Collection
in java.
Object-oriented
Object-oriented means we organize our software as a combination of different types of
objects that incorporates both data and behaviour.
Basic concepts of OOPs are: Object Class Inheritance Polymorphism Abstraction
Encapsulation
Platform Independent
A platform is the hardware or software environment in which a program runs. There are
two types of platforms software-based and hardware-based. Java provides software-based
platform. The Java platform differs from most other platforms in the sense that it's a
software-based platform that runs on top of other hardware-based platforms.It has two
components:
1. Runtime Environment
2. API(Application Programming Interface)
www.rejinpaul.com
www.rejinpaul.com

Java code can be run on multiple platforms e.g.Windows,Linux,Sun Solaris,Mac/OS etc. Java
code is compiled by the compiler and converted into bytecode.This bytecode is a platform
independent code because it can be run on multiple platforms i.e. Write Once and Run
Anywhere(WORA).
Secured:
Java is secured because:
 No explicit pointer
 Programs run inside virtual machine sandbox.

 Classloader- adds security by separating the package for the classes of the local file system from
that are imported from network sources.
 Bytecode Verifier- checks the code fragments for illegal code that can violate access right to objec
 Security Manager- determines what resources a class can access such as reading and writing
local disk.
These security are provided by java language. Some security can also be provided by application develope
through SSL,JAAS,cryptography etc.
Robust:
Robust simply means strong. Java uses strong memory management. There are lack of
pointers that avoids security problem. There is automatic garbage collection in java. There is
exception handling and type checking mechanism in java. All these points make java robust.
Architecture-neutral:
No implementation dependent features e.g. size of primitive types is set.
Portable:
May carry the java bytecode to any platform.
High-performance:
Java is faster than traditional interpretation since byte code is "close" to native code .
Distributed:
Can able to create distributed applications in java using RMI and EJB. Files can be accessed
by calling the methods from any machine on the internet.
Multi-threaded:
A thread is like a separate program, executing concurrently. Possible to write Java programs
that deal with many tasks at once by defining multiple threads. The main advantage of multi-
threading is that it shares the same memory. Threads are important for multi-media, Web
applications etc.
Simple Java Program:
class Simple{
www.rejinpaul.com
www.rejinpaul.com
public static void main(String args[])
{
System.out.println("Hello Java");
}
}
 class keyword is used to declare a class in java.
 public keyword is an access modifier which represents visibility, it means it is visible
to all.
 static is a keyword, any method declared as static, is known as static method. The
core advantage of static method is that there is no need to create object to invoke the
static method. The main method is executed by the JVM, so it doesn't require creating
object to invoke the main method. So it saves memory.
 void is the return type of the method, it means it doesn't return any value.
 main represents startup of the program.
 String[] args is used for command line argument.
 System.out.println() is used print statement.

II. Data types, variables and arrays:


Variables:
Variable is a name of memory location. There are three types of variables: local,
instance and static.
Local Variable:
A variable that is declared inside the method is called local variable.
Instance Variable:
A variable that is declared inside the class but outside the method is called instance variable .
It is not declared as static. Instance variable doesn't get memory at compile time. It gets
memory at runtime when object(instance) is created. That is why, it is known as instance
variable.
Static variable:
A variable that is declared as static is called static variable. It cannot be local.
Example:
class A{
int data=50;//instance variable
static int m=100;//static variable
void method(){
int n=90;//local variable
}
}//end of class
Data types:
There are two types of data types in java, primitive and non-primitive.
www.rejinpaul.com
www.rejinpaul.com
Data Type Default Value Default size
boolean false 1 bit
char '\u0000' 2 byte
byte 0 1 byte
short 0 2 byte
int 0 4 byte
long 0L 8 byte
float 0.0f 4 byte
double 0.0d 8 byte
Java Array:
Java array is an object the contains elements of similar data type.
Advantage of java array:
Code Optimization, Random access
Disadvantage: Size Limit- It doesn't grow its size at runtime.
Array
types Single Dimensional Array Multidimensional Array
1. dataType[][] arrayRefVar; (or)
1. dataType[] arr; (or)
Declarati 2. dataType [][]arrayRefVar; (or)
2. dataType []arr; (or)
on syntax 3. dataType arrayRefVar[][]; (or)
3. dataType arr[];
4. dataType []arrayRefVar[];
1. int[][] arr=new int[3][3];
1. arrayRefVar=new datatype[size];
1. int arr[][]={{1,2,3},{2,4,5},{4,4,5
1. int a[]={33,3,4,5};//declaration, instantiatio
example }};
n and
2.
2. initialization
5.

Example program using array:


1.Passing array to methods:
class Testarray2
{
static void min(int arr[])
{
int min=arr[0];
for(int i=1;i<arr.length;i++)
if(min>arr[i])
min=arr[i];
System.out.println(min);
}
public static void main(String args[])
{
int a[]={33,3,4,5};
min(a);//passing array to method
}
}
2.Matrix addition:

class Testarray5{
public static void main(String args[]){
//creating two matrices
int a[][]={{1,3,4},{3,4,5}};
int b[][]={{1,3,4},{3,4,5}};
www.rejinpaul.com
www.rejinpaul.com
//creating another matrix to store the sum of two matrices
int c[][]=new int[2][3];

//adding and printing addition of 2 matrices


for(int i=0;i<2;i++){
for(int j=0;j<3;j++){
c[i][j]=a[i][j]+b[i][j];
System.out.print(c[i][j]+" ");
}
System.out.println();//new line
}

}}
Copying Array:
Syntax:
public static void arraycopy(Object src, int srcPos,Object dest, int destPos, int length )

eg: char[] src = { 'd', 'e', 'c', 'a', 'f', 'f', 'e','i', 'n', 'a', 't', 'e', 'd' };
char[] dest = new char[7];
System.arraycopy(src, 2, dest, 0, 7);

III. Operators:
Operator in java is a symbol that is used to perform operations. There are many types
of operators in java such as unary operator, arithmetic operator, relational operator,
shift operator, bitwise operator, ternary operator and assignment operator.

Operators Precedence
postfix expr++ expr--
unary ++expr --expr +expr -expr ~ !
multiplicative */%
additive +-
shift << >> >>>
relational < > <= >= instanceof
equality == !=
bitwise AND &
bitwise exclusive OR ^
bitwise inclusive OR |
logical AND &&
logical OR ||
ternary ?:
assignment = += -= *= /= %= &= ^= |= <<= >>= >>>=

IV. Classes and Methods:


Class:
A class is a group of objects that has common properties. It is a template or blueprint
from which objects are created.It is the logical entity only.
www.rejinpaul.com
www.rejinpaul.com
A class in java can contain:
Data member, method , constructor , block , class and interface.
Syntax to declare a class:
class <class_name>{
data member;
method;
}
Object:
Object is the physical as well as logical entity. An entity that has state and behavior is
known as an object. Object is an instance of a class. An object has three
characteristics:
 state: represents data (value) of an object.
 behavior: represents the behavior (functionality) of an object such as deposit,
withdraw etc.
 identity: Object identity is typically implemented via a unique ID. The value of the
ID is not visible to the external user. But,it is used internally by the JVM to identify
each object uniquely.
There are many ways to create an object in java. They are:
 By new keyword
 By newInstance() method
 By clone() method
 By factory method etc.
Anonymous object:
Anonymous simply means nameless. An object that has no reference is known as
anonymous object.
If you have to use an object only once, anonymous object is a good approach.
Eg:
class Calculation{
void fact(int n){
int fact=1;
for(int i=1;i<=n;i++){
fact=fact*i;
}
System.out.println("factorial is "+fact);
}
public static void main(String args[]){
new Calculation().fact(5);//calling method with annonymous object
}
}
Methods:
Method Overloading:
Definition: If a class have multiple methods by same name but different parameters, it
is known as Method Overloading.
Method overloading increases the readability of the program.
There are two ways to overload the method in java
1. By changing number of arguments
2. By changing the data type
In java, Method Overloading is not possible by changing the return type of the method.
One type is promoted to another implicitly if no matching data type is found.
www.rejinpaul.com
www.rejinpaul.com

Example Program:

import java.lang.*;
class methodOL
{
void area(int a){System.out.println("square="+a*a);}
void area(double a){System.out.println("circle="+3.14*a*a);}
void area(int a,int b){System.out.println("Rectangle="+a*b);}
public static void main(String args[])
{
char side=12;
methodOL obj=new methodOL();
obj.area(20);
obj.area(20.5);//OL varying type
obj.area(20,10);//OL varying parameter
obj.area(side);//OL and type promotion
}
}
OUTPUT:
square=400
circle=1319.585
Rectangle=200
square=144
Method Constructor:
1. Definition: Constructor in java is a special type of method that is used to initialize the
object.
2. Java constructor is invoked at the time of object creation. It constructs the values i.e.
provides data for the object that is why it is known as constructor.
Rules :
1. Constructor name must be same as its class name
2. Constructor must have no explicit return type. Constructor returns current class
instance (You cannot use return type yet it returns a value).
3. Like object creation, starting a thread, calling method are performed in the
constructor .
There are two types of constructors:
1. Default constructor (no-arg constructor)
A constructor that has no parameter is known as default constructor. syntax
<class_name>(){}
If there is no constructor in a class, compiler automatically creates a default
constructor.
2. Parameterized constructor
A constructor that has parameters is known as parameterized constructor.
www.rejinpaul.com
www.rejinpaul.com
Parameterized constructor is used to provide different values to the distinct objects.
Constructor Overloading:
Constructor overloading is a technique in Java in which a class can have any number
of constructors that differ in parameter lists. The compiler differentiates these
constructors by taking into account the number of parameters in the list and their type.
Difference between constructor and method in java:
There are many differences between constructors and methods. They are given below.

Java Constructor Java Method

Method is used to
Constructor is used to initialize
expose behavior of an
the state of an object.
object.

Constructor must not have return Method must have


type. return type.

Method is invoked
Constructor is invoked implicitly.
explicitly.

The java compiler provides a Method is not


default constructor if you don't provided by compiler
have any constructor. in any case.

Method name may or


Constructor name must be same
may not be same as
as the class name.
class name.
Java Copy Constructor:
There is no copy constructor in java. But, it is possible to copy the values of one
object to another like copy constructor in C++.
There are many ways to copy the values of one object into another in java. They are:
 By constructor
Eg:
class Student{
int id;
String name;
Student(int i,String n){
id = i;
name = n;
}

Student(Student s){
id = s.id;
name =s.name;
}
void display(){System.out.println(id+" "+name);}

public static void main(String args[]){


Student s1 = new Student(111,"Karan");
Student s2 = new Student(s1);
s1.display();
www.rejinpaul.com
www.rejinpaul.com
s2.display();
}
}
 By assigning the values of one object into another
class Student{
int id;
String name;
Student(int i,String n){
id = i;
name = n;
}
Student(){}
void display(){System.out.println(id+" "+name);}

public static void main(String args[]){


Student s1 = new Student(111,"Karan");
Student s2 = new Student();
s2.id=s1.id;
s2.name=s1.name;
s1.display();
s2.display();
}
}
 By clone() method of Object class
The object cloning is a way to create exact copy of an object. For this purpose, clone()
method of Object class is used to clone an object.
The java.lang.Cloneable interface must be implemented by the class whose object
clone is to create. If Cloneable interface is not implemented , clone() method
generates CloneNotSupportedException.
Advantage: Less processing task.
The clone() method is defined in the Object class. Syntax of the clone() method is as
follows:
protected Object clone() throws CloneNotSupportedException

example:
class Student implements Cloneable{
int rollno;
String name;

Student(int rollno,String name){


this.rollno=rollno;
this.name=name;
}

public Object clone() throws CloneNotSupportedException{


return super.clone();
}

public static void main(String args[]){


www.rejinpaul.com
www.rejinpaul.com
try{
Student s1=new Student (101,"amit");

Student s2=(Student )s1.clone();

System.out.println(s1.rollno+" "+s1.name);
System.out.println(s2.rollno+" "+s2.name);

}catch(CloneNotSupportedException c){}

}
}

This keyword:
this is a reference variable that refers to the current object.
Here is given the 6 usage of java this keyword.
1. this keyword can be used to refer current class instance variable.
2. this() can be used to invoke current class constructor.
3. this keyword can be used to invoke current class method (implicitly)
4. this can be passed as an argument in the method call.
5. this can be passed as argument in the constructor call.
6. this keyword can also be used to return the current class instance.
If there is ambiguity between the instance variable and parameter, this keyword
resolves the problem of ambiguity.
Eg:
Class student
{
int id; String name;
student(int id,String name)//ambiquity in (id ,name) parameter and instance
variable.
{
this.id=id;
this.name=name;
}
}
 The this() constructor call can be used to invoke the current class constructor
(constructor chaining). This approach is better if class has many constructors and
wants to reuse that constructor.
Call to this() must be the first statement in constructor.
Eg:
Student(int id,String name){
this.id = id;
this.name = name;
}
Student(int id,String name,String city){
this(id,name);//now no need to initialize id and name
this.city=city;
}
www.rejinpaul.com
www.rejinpaul.com
 The method of the current class can be invoked by using the this keyword. If not used
the this keyword, compiler automatically adds this keyword while invoking the
method.
 The this keyword can also be passed as an argument in the method. It is mainly used
in the event handling.Can pass the this keyword in the constructor also. It is useful if
we have to use one object in multiple classes.
Eg:
class B{
A4 obj;
B(A4 obj){
this.obj=obj;
}
void display(){
System.out.println(obj.data);//using data member of A4 class
}
}

class A4{
int data=10;
A4(){
B b=new B(this);
b.display();
}
public static void main(String args[]){
A4 a=new A4();
}
}
 Can return the this keyword as an statement from the method. In such case, return
type of the method must be the class type (non-primitive).
Eg: class A{
A getA(){
return this;
}
void msg(){System.out.println("Hello java");}
}
class Test1{
public static void main(String args[]){
new A().getA().msg();
}
}
Inheritance:
Inheritance in java is a mechanism in which one object acquires all the properties and
behaviors of parent object. Inheritance represents the IS-A relationship, also known
as parent-child relationship.
Uses:
 For Method Overriding (so runtime polymorphism can be achieved).
 For Code Reusability.
Syntax:
class Subclass-name extends Superclass-name
www.rejinpaul.com
www.rejinpaul.com
{
//methods and fields
}
The extends keyword indicates that you are making a new class that derives from an existing
class.
In the terminology of Java, a class that is inherited is called a super class. The new class is
called a subclass.
Types of inheritance in java:
On the basis of class, there can be three types of inheritance in java: single, multilevel and
hierarchical.
In java programming, multiple and hybrid inheritance is supported through interface only not
by classes.
Reason: To reduce the complexity and simplify the language, multiple inheritances are not
supported in java.
Java wants to handle ambiguity in multiple inheritance during compile time rather than at
run time.

V. Packages and Interfaces:


Abstraction in Java
Abstraction is a process of hiding the implementation details and showing only
functionality to the user. Abstraction let’s focus on what the object does instead of
how it does it. There are two ways to achieve abstraction in java:
1. Abstract class (0 to 100%)
2. Interface (100%)
Abstract class in Java:
A class that is declared with abstract keyword, is known as abstract class in java. It
can have abstract and non-abstract methods (method with body).
A class that is declared as abstract is known as abstract class. It needs to be extended
and its method implemented. It cannot be instantiated.
Eg: abstract class A{}
A method that is declared as abstract and does not have implementation is known as
abstract method.
Eg; abstract void printStatus();//no body and abstract
Rules: If there is any abstract method in a class, that class must be abstract.
If extending any abstract class that has abstract method, either provide the
implementation of the method or make this class abstract.
Eg;
abstract class Bike{
Bike(){System.out.println("bike is created");}
abstract void run();
void changeGear(){System.out.println("gear changed");}
www.rejinpaul.com
www.rejinpaul.com
}

class Honda extends Bike{


void run(){System.out.println("running safely..");}
}
class TestAbstraction2{
public static void main(String args[]){
Bike obj = new Honda();
obj.run();
obj.changeGear();
}
}
The abstract class can also be used to provide some implementation of the interface.
In such case, the end user may not be forced to override all the methods of the
interface.
Eg:
interface A{
void a();
void b();
void c();
}
abstract class B implements A{
public void c(){System.out.println("I am C");}
}
class M extends B{
public void a(){System.out.println("I am a");}
public void b(){System.out.println("I am b");}
}
class Test5{
public static void main(String args[]){
A a=new M();
a.a();
a.b();
a.c();
}}
Interface:
Interface in Java
An interface in java is a blueprint of a class. It has static constants and abstract methods
only.
The interface in java is a mechanism to achieve fully abstraction. There can be only
abstract methods in the java interface not method body. It is used to achieve fully abstraction
and multiple inheritance in Java.
Java Interface also represents IS-A relationship.It cannot be instantiated just like abstract
class.
There are mainly three reasons to use interface. They are given below.
 It is used to achieve fully abstraction.
 By interface, can support the functionality of multiple inheritances.
 It can be used to achieve loose coupling.
www.rejinpaul.com
www.rejinpaul.com
Interface fields are public, static and final by default, and Interface methods are public and
abstract.
Understanding relationship between classes and interfaces:

Example:
interface printable{
void print();
}

class A6 implements printable{


public void print(){System.out.println("Hello");}

public static void main(String args[]){


A6 obj = new A6();
obj.print();
}
}
Multiple inheritance in Java by interface:
If a class implements multiple interfaces, or an interface extends multiple interfaces i.e.
known as multiple inheritance.
What is marker or tagged interface?
An interface that has no member is known as marker or tagged interface. For example:
Serializable, Cloneable, Remote etc. They are used to provide some essential information to
the JVM so that JVM may perform some useful operation.
An interface can have another interface i.e. known as nested interface.
Eg:
interface printable{
void print();
interface MessagePrintable{
void msg();
}
}
Difference between abstract class and interface:
Abstract class and interface both are used to achieve abstraction where can declare the
abstract methods. Abstract class and interface both can't be instantiated.
But there are many differences between abstract class and interface that are given below.
Abstract class Interface
1) Abstract class can have abstract and non- Interface can have only abstract methods.
abstractmethods.

2) Abstract class doesn't support multiple Interface supports multiple inheritance.


www.rejinpaul.com
www.rejinpaul.com
inheritance.

3) Abstract class can have final, non-final, static Interface has only static and final variables.
and non-static variables.

4) Abstract class can have static methods, main Interface can't have static methods, main
method and constructor. method or constructor.

5) Abstract class can provide the implementation Interface can't provide the implementation of
of interface. abstract class.

6) The abstract keyword is used to declare abstract The interface keyword is used to declare
class. interface.

7) Example: Example:
public abstract class Shape{ public interface Drawable{
public abstract void draw(); void draw();
} }

Packages:
Definition: A package is a grouping of related types providing access protection and name
space management. Types refers to classes, interfaces, enumerations, and annotation types.
Suppose write a group of classes that represent graphic objects, such as circles, rectangles,
lines, and points. Also write an interface, Draggable, that classes implement if they can be
dragged with the mouse.
Advantage:
 Can easily determine that these types are related.
 Know where to find types that can provide graphics-related functions.
 The type names won’t conflict with the type names in other packages because the
package creates a new namespace.
 Can allow types within the package to have unrestricted access to one another yet
still restrict access for types outside the package.

Creating a Package:

 To create a package, choose a name for the package and put a package statement
with that name at the top of every source file that contains the types that want to be
included in the package.
 The package statement (for example, package graphics;) must be the first line in the
source file. There can be only one package statement in each source file, and it
applies to all types in the file.

Naming Conventions:
Package names are written in all lower case to avoid conflict with the names of classes or
interfaces.
Companies use their reversed Internet domain name to begin their package names—for
example, com.example.mypackage for a package named mypackage created by a
programmer at example.com.
Packages in the Java language itself begin with java. or javax.
Using Package Members
The types that comprise a package are known as the package members.
To use a public package member from outside its package, do one of the following:
www.rejinpaul.com
www.rejinpaul.com
 Refer to the member by its fully qualified name
To solve ambiguity.
Eg: Rectangle class in user defined package and awt package are differentiated by
using
graphics.Rectangle
 Import the package member
Eg: import graphics.Rectangle;
 Import the member's entire package
Eg: import java.*
The subpackages of packages are imported separately. In java package awt is a package and
color is subpackage both has to be imported.
import java.awt.*
import java.awt.color.*
Static import:static import is a feature that expands the capabilities of import keyword. It is
used to import static member of a class. We all know that static member are referred in
association with its class name outside the class. Using static import, it is possible to refer to
the static member directly without its class name. There are two general form of static import
statement.The first form of static import statement, import only a single static member of a
class

Syntax
import static package.class-name.static-member-name;
Example
import static java.lang.Math.sqrt; //importing static method sqrt of Math class
The second form of static import statement,imports all the static member of a class
Syntax
import static package.class-type-name.*;
Example
import static java.lang.Math.*; //importing all static member of Math class
www.rejinpaul.com
www.rejinpaul.com
VI. EXCEPTION HANDLING:
An exception is a run-time error. A Java exception is an object that describes an exceptional
(that is, error) condition that has occurred in a piece of code.
Java exception handling is managed via five keywords: try, catch, throw, throws, and
finally.
the general form of an exception-handling block:
try {
// block of code to monitor for errors
}
catch (ExceptionType1 exOb) {
// exception handler for ExceptionType1
}
catch (ExceptionType2 exOb) {
// exception handler for ExceptionType2
}
// ...
finally {
// block of code to be executed after try block ends
}
Here, ExceptionType is the type of exception that has occurred.
Exception Types:
All exception types are subclasses of the built-in class Throwable.

throwable

Exceptions error

Important subclass of Exception, called Runtime Exception is automatically defined for the
programs and includes things such as division by zero and invalid array indexing.
Exceptions of type Error are used by the Java run-time system to indicate errors having to do
with the run-time environment, itself created in response to catastrophic failures that cannot
usually be handled by program.
Uncaught Exceptions:
Any exception that is not caught by the program will ultimately be processed by the default
handler provided by the Java run-time system. The default handler displays a string
describing the exception, prints a stack trace from the point at which the exception occurred,
and terminates the program.
Using try and catch:
First, it allows fixing the error. Second, it prevents the program from automatically
terminating.
Example program:
class Exc2 {
public static void main(String args[]) {
int d, a;
try { // monitor a block of code.
d = 0;
a = 42 / d;
System.out.println("This will not be printed.");
} catch (ArithmeticException e) { // catch divide-by-zero error
www.rejinpaul.com
www.rejinpaul.com
System.out.println("Division by zero.");
}
System.out.println("After catch statement.");
}
}
This program generates the following output:
Division by zero.
After catch statement.
A try and its catch statement form a unit. The scope of the catch clause is restricted to those
statements specified by the immediately preceding try statement. A catch statement cannot
catch an exception thrown by another try statement (except in the case of nested try
statements, described shortly). The statements that are protected by try must be surrounded
by curly braces. (That is, they must be within a block.)Don’t use try on a single statement.
The goal of most well-constructed catch clauses should be to resolve the exceptional
condition and then continue on as if the error had never happened.
Displaying a Description of an Exception:
Throwable overrides the toString( ) method (defined by Object) so that it returns a string
containing a description of the exception. Display this description in a println( ) statement by
simply passing the exception as an argument. For example, the catch block in the preceding
program can be rewritten like this:
catch (ArithmeticException e) {
System.out.println("Exception: " + e);
a = 0; // set a to zero and continue
}
Multiple catch Clauses:
In some cases, more than one exception could be raised by a single piece of code. To handle
this type of situation, can able to specify two or more catch clauses, each catching a different
type of exception. When an exception is thrown, each catch statement is inspected in order,
and the first one whose type matches that of the exception is executed. After one catch
statement executes, the others are bypassed, and execution continues after the try/catch block.
When using multiple catch statements, it is important to remember that exception subclasses
must come before any of their super classes. This is because a catch statement that uses a
superclass will catch exceptions of that type plus any of its subclasses. Thus, a subclass
would never be reached if it came after its superclass. Further, in Java, unreachable code is an
compile time error.
Nested try Statements:
The try statement can be nested. That is, a try statement can be inside the block of another
try. Each time a try statement is entered, the context of that exception is pushed on the stack.
If an inner try statement does not have a catch handler for a particular exception, the stack is
unwound and the next try statement’s catch handlers are inspected for a match. This
continues until one of the catch statements succeeds, or until the entire nested try statements
are exhausted. If no catch statement matches, then the Java run-time system will handle the
exception.
Eg:
class NestTry {
public static void main(String args[]) {
try {
int a = args.length;
/* If no command-line args are present,
www.rejinpaul.com
www.rejinpaul.com
the following statement will generate
a divide-by-zero exception. */
int b = 42 / a;
System.out.println("a = " + a);
try { // nested try block
/* If one command-line arg is used,
then a divide-by-zero exception
will be generated by the following code. */
if(a==1) a = a/(a-a); // division by zero
/* If two command-line args are used,
then generate an out-of-bounds exception. */
if(a==2) {
int c[] = { 1 };
c[42] = 99; // generate an out-of-bounds exception
}
} catch(ArrayIndexOutOfBoundsException e) {
System.out.println("Array index out-of-bounds: " + e);
}
} catch(ArithmeticException e) {
System.out.println("Divide by 0: " + e);
}
}
}
www.rejinpaul.com
www.rejinpaul.com
Throw:
The flow of execution stops immediately after the throw statement; any subsequent
statements are not executed. The nearest enclosing try block is inspected to see if it has a
catch statement that matches the type of exception. If it does find a match, control is
transferred to that statement. If not, then the next enclosing try statement is inspected, and so
on. If no matching catch is found, then the default exception handler halts the program and
prints the stack trace.
// Demonstrate throw.
class ThrowDemo {

static void demoproc() {


try {
throw new NullPointerException("demo");
} catch(NullPointerException e) {
System.out.println("Caught inside demoproc.");
throw e; // rethrow the exception
}
}
public static void main(String args[]) {
try {
demoproc();
} catch(NullPointerException e) {
System.out.println("Recaught: " + e);
}
}
}
Throws:
If a method is capable of causing an exception that it does not handle, it must specify this
behavior so that callers of the method can guard themselves against that exception. Do this by
including a throws clause in the method’s declaration. A throws clause lists the types of
exceptions that a method might throw. This is necessary for all exceptions, except those of
type Error or RuntimeException, or any of their subclasses. All other exceptions that a
method can throw must be declared in the throws clause. If they are not, a compile-time error
will result.
This is the general form of a method declaration that includes a throws clause:
type method-name(parameter-list) throws exception-list
{
// body of method
}
Here, exception-list is a comma-separated list of the exceptions that a method can throw.
Finally:
When exceptions are thrown, execution in a method takes a rather abrupt, nonlinear path that
alters the normal flow through the method. Depending upon how the method is coded, it is
even possible for an exception to cause the method to return prematurely. This could be a
problem in some methods. The finally keyword is designed to address this contingency.
finally creates a block of code that will be executed after a try/catch block has completed and
before the code following the try/catch block. The finally block will execute whether or not
an exception is thrown. This can be useful for closing file handles and freeing up any other
resources that might have been allocated at the beginning of a method with the intent of
www.rejinpaul.com
www.rejinpaul.com
disposing of them before returning. The finally clause is optional. However, each try
statement requires at least one catch or a finally clause. If a finally block is associated with a
try, the finally block will be executed upon conclusion of the try.
Java’s Built-in Exceptions:

Creating Your Own Exception Subclasses:


Although Java’s built-in exceptions handle most common errors, probably want to create
exception types to handle situations specific to applications. The Exception class does not
define any methods of its own. It does, of course, inherit those methods provided by
Throwable. Thus, all exceptions, including those that you create, have the methods defined
by Throwable available to them.
www.rejinpaul.com
www.rejinpaul.com

Exception defines four constructors. Exception( ) Exception(String msg) The first form
creates an exception that has no description. The second form lets you specify a description
of the exception.

Chained Exceptions:
The chained exception feature allows to associate another exception with an exception. This
second exception describes the cause of the first exception. For example, imagine a situation
in which a method throws an ArithmeticException because of an attempt to divide by zero.
However, the actual cause of the problem was that an I/O error occurred, which caused the
divisor to be set improperly. To allow chained exceptions, two constructors and two methods
were added to Throwable.
The constructors are shown here:
Throwable(Throwable causeExc)
Throwable(String msg, Throwable causeExc)
In the first form, causeExc is the exception that causes the current exception. That is,
causeExc is the underlying reason that an exception occurred. The second form allows to
specify a description at the same time that you specify a cause exception. These two
constructors have also been added to the Error, Exception, and RuntimeException classes.
The chained exception methods added to Throwable are getCause( ) and initCause( ).
Throwable initCause(Throwable causeExc)
The getCause( ) method returns the exception that underlies the current exception. If there is
no underlying exception, null is returned. The initCause( ) method associates causeExc with
the invoking exception and returns a reference to the exception.
Chained exceptions can be carried on to whatever depth is necessary. Thus, the cause
exception can, itself, have a cause. Be aware that overly long chains of exceptions may
indicate poor design.
www.rejinpaul.com
www.rejinpaul.com
VII. MULTITHREADED PROGRAMMING:
A multithreaded program contains two or more parts that can run concurrently. Each
part of such a program is called a thread, and each thread defines a separate path of
execution. Thus, multithreading is a specialized form of multitasking.
Two distinct types of multitasking: process based and thread-based
properties multithreading multiprocessing
thread defines a
A process is, a program that is
Definition separate path of
executing.
execution
Threads, on the
other hand, are
lightweight. They
share the same
Processes are heavyweight
address space and
Memory space tasks that require their own
cooperatively share
separate address spaces.
the same
heavyweight
process.

Smallest unit
thread process
of code
less overhead than
High overhead than
overhead multitasking
multitasking processes
processes
Context
Low cost. Costly.
Switching
Inter process Inexpensive and
expensive and limited
communication limited
Life cycle of a thread:

New-A new thread begins its life cycle in the new state. It remains in this state until
the program starts the thread. It is also referred to as a born thread.

1-Runnable- After invocation of start() method on new thread, the


thread becomes runnable. After a newly born thread is started, the
thread becomes runnable. A thread in this state is considered to be executing its task.
2-Running-A thread is in running state that means the thread is currently executing.
There are several ways to enter in Runnable state but there is only one way to enter in
Running state: the scheduler select a thread from runnable pool.
3-Blocked- This is the state when a thread is waiting for a lock to access an object.
4-Waiting-Sometimes a thread transitions to the waiting state while the
thread waits for another thread to perform a task.A thread transitions back to the
runnable state only when another thread signals the waiting thread to continue
executing.
www.rejinpaul.com
www.rejinpaul.com

5-Timed waiting- A runnable thread can enter the timed waiting state for a specified
interval of time. A thread in this state transitions back to the runnable state when that
time interval expires or when the event it is waiting for occurs.
6-Not Runnable- after Runnable states these three states are assumed to be in a not
Runnable state. These three states
are waiting, Timed_waiting(sleeping) and Terminated.
7-Terminated- In this state the thread is dead.

Thread Priorities:
Thread priorities are integers that specify the relative priority of one thread to another.
A thread’s priority is used to decide when to switch from one running thread to the
next. This is called a context switch.
Rules that determine when a context switch takes place
1. A thread can voluntarily relinquish control- sleep,I/O
2. A thread can be preempted by a higher-priority thread.
3. two threads with the same priority time-sliced automatically in round-robin
fashion.
JVM selects to run a Runnable thread with the highest priority.
 All Java threads have a priority in the range 1-10.
 Top priority is 10, lowest priority is 1.Default Priority 5
 Thread.MIN_PRIORITY - minimum thread priority
 Thread.MAX_PRIORITY - maximum thread priority
 Thread.NORM_PRIORITY - maximum thread priority
Whenever a new Java thread is created it has the same priority as the thread
which created it.
Thread priority can be changed by the final void setPriority(int level) method , final
int getPriority( ).

Synchronization:
Because multithreading introduces an asynchronous behavior to programs, there must be
a way to enforce synchronicity when needed. Most multithreaded systems expose
monitors as objects that your program must explicitly acquire and manipulate. In Java
each object has its own implicit monitor that is automatically entered when one of the
object’s synchronized methods is called. Once a thread is inside a synchronized method,
no other thread can call any other synchronized method on the same object. When two or
more threads need access to a shared resource, they need some way to ensure that the
resource will be used by only one thread at a time. The process by which this is achieved
is called synchronization. Key to synchronization is the concept of the monitor (also
called a semaphore).
A monitor is an object that is used as a mutually exclusive lock, or mutex. Only one
thread can own a monitor at a given time. When a thread acquires a lock, it is said to have
entered the monitor. All other threads attempting to enter the locked monitor will be
suspended until the first thread exits the monitor. These other threads are said to be
waiting for the monitor. A thread that owns a monitor can reenter the same monitor if it
so desires.
www.rejinpaul.com
www.rejinpaul.com
Achieved in two ways:
1. Using Synchronized Methods
To enter an object’s monitor, just call a method that has been modified with the
synchronized keyword. While a thread is inside a synchronized method, all other threads
that try to call it (or any other synchronized method) on the same instance have to wait.
To exit the monitor and relinquish control of the object to the next waiting thread, the
owner of the monitor simply returns from the synchronized method.
2. The synchronized Statement
calls to the methods defined by this class is kept inside a synchronized block.
This is the general form of the synchronized statement:
synchronized(object) {
// statements to be synchronized
}
Here, object is a reference to the object being synchronized. A synchronized block
ensures that a call to a method that is a member of object occurs only after the current
thread has successfully entered object’s monitor.
Messaging:
After dividing program into separate threads, define how threads will communicate with
each other.
Java provides a way for two or more threads to talk to each other, via calls to predefined
methods that all objects have. Java’s messaging system allows a thread to enter a
synchronized method on an object, and then wait there until some other thread explicitly
notifies it to come out.
Java includes an elegant interprocess communication mechanism via the wait( ), notify( ),
and notifyAll( ) methods. These methods are implemented as final methods in Object, so
all classes have them. All three methods can be called only from within a synchronized
context.
• wait( ) tells the calling thread to give up the monitor and go to sleep until some other
thread enters the same monitor and calls notify( ).
• notify( ) wakes up a thread that called wait( ) on the same object.
• notifyAll( ) wakes up all the threads that called wait( ) on the same object. One of the
threads will be granted access.
These methods are declared within Object, as shown here:
final void wait( ) throws InterruptedException
final void notify( )
final void notifyAll( )
Additional forms of wait( ) exist that allow to specify a period of time to wait.
spurious wakeup:
Although wait( ) normally waits until notify( ) or notifyAll( ) is called, there is a
possibility that in very rare cases the waiting thread could be awakened due to no
apparent reason and called spurious wakeup.
Deadlock:
A special type of error that need to be avoided is deadlock, which occurs when two
threads have a circular dependency on a pair of synchronized objects. Deadlock is a
difficult error to debug for two reasons:
• In general, it occurs only rarely, when the two threads time-slice in just the right way.
• It may involve more than two threads and two synchronized objects.
Creating a Thread:
The Thread Class and the Runnable Interface:
www.rejinpaul.com
www.rejinpaul.com

The Thread class defines several methods that help manage threads:

final void setName(String threadName)


final String getName( )
The Main Thread:
When a Java program starts up, one thread begins running immediately. This is usually
called the main thread of a program, because it is the one that is executed when the
program begins. The main thread is important for two reasons:
• It is the thread from which other “child” threads will be spawned.
• Often, it must be the last thread to finish execution because it performs various
shutdown actions. if the main thread finishes before a child thread has completed, then the
Java run-time system may “hang.”
Although the main thread is created automatically when the program is started, it can be
controlled through a Thread object by knowing the reference to it using the following
method.
static Thread currentThread( )
This method returns a reference to the thread in which it is called.
A thread group is a data structure that controls the state of a collection of threads as a
whole.
Sleep()
The sleep( ) method causes the thread from which it is called to suspend execution for the
specified period of milliseconds.
static void sleep(long milliseconds) throws InterruptedException
static void sleep(long milliseconds, int nanoseconds) throws InterruptedException
To implement Runnable, a class need only implement a single method called run( ),
which is declared like this:
public void run( )
Inside run( ), define the code that constitutes the new thread. After creating a class that
implements Runnable, instantiate an object of type Thread from within that class. Thread
defines several constructor like Thread(Runnable threadOb, String threadName).
start( ) executes a call to run( ). The start( ) method is shown here:
www.rejinpaul.com
www.rejinpaul.com
void start( )
To create a thread is to create a new class that extends Thread, and then to create an
instance of that class. The extending class must override the run( ) method, which is the
entry point for the new thread. It must also call start( ) to begin execution of the new
thread. The call to super( ) inside NewThread. This invokes the following form of the
Thread constructor:
public Thread(String threadName) the child
Thread is created by instantiating an object of New Thread, which is derived from
Thread.
Choice of implementation:
Classes should be extended only when they are being enhanced or modified in some way.
So, if will not
be overriding any of Thread’s other methods, it is probably best simply to implement
Runnable rather than extending threads.
Using isAlive( ) and join( ):
Two ways exist to determine whether a thread has finished.:
1. final boolean isAlive( )-defined by thread.
The isAlive( ) method returns true if the thread upon which it is called is still running. It
returns false otherwise.
2. final void join( ) throws InterruptedException-This method waits until the
thread on which it is called terminates.
3. Additional forms of join( ) allow to specify a maximum amount of time to
wait for the specified thread to terminate.
Suspending, Resuming, and Stopping Threads:
The suspend( ) and stop() method of the Thread class was deprecated by Java 2. This was
done because they can sometimes cause serious system failures.
The resume( ) method is also deprecated. It does not cause problems, but cannot be used
without the suspend( ) method as its counterpart.
A thread must be designed so that the run( ) method periodically checks to determine whether
that thread should suspend, resume, or stop its own execution thus providing the facility of
controlling the thread which was earlier given by the suspend ,resume and stop methods.
This is accomplished by establishing a flag variable that indicates the execution state of the
thread. As long as this flag is set to “running,” the run( ) method must continue to let the
thread execute. If this variable is set to “suspend,” the thread must pause. If it is set to “stop,”
the thread must terminate.
www.rejinpaul.com
www.rejinpaul.com

VIII. INPUT/OUTPUT
Streams:
Java programs perform I/O through streams. A stream is an abstraction that either
produces or consumes information. An input stream can abstract many different kinds
of input: from a disk file, a keyboard, or a network socket. an output stream may refer
to the console, a disk file, or a network connection.
Byte and character Streams: Byte Stream:8-bit,binary data based. Character
Stream:16-bit,Text based.

Hierarchy of classes in byte stream classes:

Hierarchy of classes in Character classes:


www.rejinpaul.com
www.rejinpaul.com

System: The class which encapsulates several aspects of the run-time environment.
System also contains three predefined stream variables: in, out, and err. These fields
are declared as public, static, and final within System.
Reading Console Input:
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
Reading Characters:
int read( ) throws IOException - Each time that read( ) is called, it reads a character
from the input stream and returns it as an integer value else -1.
br.read();
Reading Strings: String readLine( ) throws IOException
Writing Console Output:
void write(int byteval)-This method writes to the stream the byte specified by byteval.
print( ) and println( )- methods are defined by the class PrintStream
The PrintWriter Class:
PrintWriter(OutputStream outputStream, boolean flushOnNewline)
PrintWriter pw = new PrintWriter(System.out, true);
Reading and Writing Files:
FileInputStream(String fileName) throws FileNotFoundException
FileOutputStream(String fileName) throws FileNotFoundException
if the file does not exist, then FileNotFoundException is thrown. For output streams,
if the file cannot be created, then FileNotFoundException is thrown. When an output
file is opened, any preexisting file by the same name is destroyed. File should be
closed by calling close( ). It is defined by both FileInputStream and
FileOutputStream.
void close( ) throws IOException
int read( ) throws IOException
www.rejinpaul.com
www.rejinpaul.com
IX. String Handling:
In the Java programming language, strings are objects. The Java platform provides the
String class to create and manipulate strings. In java, string is an object. String class is
used to create string object.
Creating Strings:
There are two ways to create String object:
1.By String Literal
2. By new keyword
1) String literal
String literal is created by double quote. Example:
String s=”Hello”;
Each time when we create a string literal, the JVM checks the string constant pool
first. If the string already exists in the pool, a reference to the pooled instance returns.
If the string does not exist in the pool, a new String object instantiates, then is placed
in the pool. For example:

1.String s1=”Java”;
2. String s2=”Java”;//no new object will be created

In the above example only one object will be created. First time JVM will find no
string object with the name “Java” in string constant pool, so it will create a new
object. Second time it will find the string with the name “Java” in string constant
pool, so it will not create new object whether will return the reference to the same
instance.
Why java uses concept of string literal? Java uses string literal to make Java more
memory efficient (because no new objects are created if it exists already in string
constant pool).
String objects are stored in a special memory area known as string constant pool
inside the Heap memory. The most direct way to create a string is to write:
String str = “Hello world!”;
Note: The String class is immutable, so that once it is created a String object cannot
be changed. If there is a necessity to make a lot of modifications to Strings of
characters, then use String Buffer & String Builder Classes.
2) By new keyword
String s=new String(“Java”);//creates two objects and one reference variable
In such case, JVM will create a new String object in normal(nonpool) Heap memory
and the literal “Java” will be placed in the string constant pool. The variable s will
refer to the object in Heap(nonpool).
public class StringDemo{
public static void main(String args[])
{
char[] helloArray = { ‘h’, ‘e’, ‘l’, ‘l’, ‘o’, ‘.’};
String helloString = new String(helloArray);
System.out.println( helloString );
}}
String Methods in java:
String method cannot manipulate the string.
www.rejinpaul.com
www.rejinpaul.com

StringBuffer class and its Methods in Java


The StringBuffer class is used to represent characters that can be modified. This is
simply used for concatenation or manipulation of the strings. StringBuffer is mainly
used for the dynamic string concatenation which enhances the performance. A string
buffer implements a mutable sequence of characters. A string buffer is like a String,
but can be modified. At any point in time it contains some particular sequence of
characters, but the length and content of the sequence can be changed through certain
method calls.
www.rejinpaul.com
www.rejinpaul.com

StringBuffer methods:
StringBuffer sb=new StringBuffer(“abc”);
Instance method call Return type Return value

sb.append( “xyz”) StringBuffer abcxyz

sb.insert(3,”d” ) StringBuffer abcdxyz

sb.reverse( ) StringBuffer zyxdcba

sb.setCharAt(2,’q’) void zyqdcba

sb.charAt(1) char y

sb.substring(3) String dcba

sb.deleteCharAt(0) StringBuffer yqdcba

sb.delete(2,4) StringBuffer yqa

sb.length() int 3
19-since room for 16
sb.capacity() int additional char is added
automatically.
sb.replace(0,1,”cb”) StringBuffer cba

StringBuilder
J2SE 5 adds a new string class to Java’s already powerful string handling capabilities.
This new class is called StringBuilder. It is identical to StringBuffer except for one
important difference: it is not synchronized, which means that it is not thread-safe.
The advantage of StringBuilder is faster performance. However, in cases in which you
are using multithreading,you must use StringBuffer rather than StringBuilder.
Difference Between String , StringBuilder and StringBuffer
String StringBuffer StringBuilder
immutable mutable mutable
Storage area: constant
heap heap
pool
- syncronized not synchronized
thread-safe thread-safe not thread-safe
Fast performance Slow Fast
www.rejinpaul.com
www.rejinpaul.com
www.rejinpaul.com
www.rejinpaul.com

UNIT III JDBC 9

JDBC Overview – JDBC implementation – Connection class – Statements - Catching Database

Results, handling database Queries. Networking– InetAddress class – URL class- TCP sockets - UDP

sockets, Java Beans –RMI.

Networking Basics:

Computers running on the Internet communicate to each other using either the Transmission Control
Protocol (TCP) or the User Datagram Protocol (UDP), as this diagram illustrates:

HTTP FTP TELNET SNMP RIP DNS


TCP UDP
NETWORK(IP,…)
LINK(device,drivers)
java.net package classes provide system-independent network communication.

TCP

When two applications want to communicate to each other reliably, they establish a connection and send
data back and forth over that connection. This is analogous to making a telephone call. TCP guarantees that
data sent from one end of the connection actually gets to the other end and in the same order it was sent.
Otherwise, an error is reported.

TCP provides a point-to-point channel for applications that require reliable communications. The Hypertext
Transfer Protocol (HTTP), File Transfer Protocol (FTP), and Telnet are all examples of applications that
require a reliable communication channel. The order in which the data is sent and received over the network
is critical to the success of these applications. When HTTP is used to read from a URL, the data must be
received in the order in which it was sent. Otherwise, it is a jumbled HTML file, a corrupt zip file, or some
other invalid information.

Definition:

TCP (Transmission Control Protocol) is a connection-based protocol that provides a reliable flow of data
between two computers.

UDP

The UDP protocol provides for communication that is not guaranteed between two applications on the
network. UDP is not connection-based like TCP. Rather, it sends independent packets of data,
called datagrams, from one application to another. Sending datagrams is much like sending a letter through
the postal service: The order of delivery is not important and is not guaranteed, and each message is
independent of any other.

Definition:

UDP (User Datagram Protocol) is a protocol that sends independent packets of data, called datagrams, from
one computer to another with no guarantees about arrival. UDP is not connection-based like TCP.
www.rejinpaul.com
www.rejinpaul.com
Consider, for example, a clock server that sends the current time to its client when requested to do so. If the
client misses a packet, it doesn't really make sense to resend it because the time will be incorrect when the
client receives it on the second try. If the client makes two requests and receives packets from the server out
of order, it doesn't really matter because the client can figure out that the packets are out of order and make
another request. The reliability of TCP is unnecessary in this instance because it causes performance
degradation and may hinder the usefulness of the service.

Another example of a service that doesn't need the guarantee of a reliable channel is the ping command. The
purpose of the ping command is to test the communication between two programs over the network. In fact,
ping needs to know about dropped or out-of-order packets to determine how good or bad the connection is.
A reliable channel would invalidate this service altogether.

Note:

Many firewalls and routers have been configured not to allow UDP packets. If you're having trouble
connecting to a service outside your firewall, or if clients are having trouble connecting to your service, ask
your system administrator if UDP is permitted.

Understanding Ports:

Generally speaking, a computer has a single physical connection to the network. All data destined for a
particular computer arrives through that connection. However, the data may be intended for different
applications running on the computer. The computer knows to which application to forward the data through
the use of ports.

Data transmitted over the Internet is accompanied by addressing information that identifies the computer and
the port for which it is destined. The computer is identified by its 32-bit IP address, which IP uses to deliver
data to the right computer on the network. Ports are identified by a 16-bit number, which TCP and UDP use
to deliver the data to the right application.

In connection-based communication such as TCP, a server application binds a socket to a specific port
number. This has the effect of registering the server with the system to receive all data destined for that port.
A client can then rendezvous with the server at the server's port, as illustrated here:

Definition:

The TCP and UDP protocols use ports to map incoming data to a particular process running on a computer.

Port numbers range from 0 to 65,535(216) because ports are represented by 16-bit numbers. The port
numbers ranging from 0 - 1023 are restricted; they are reserved for use by well-known services such as
HTTP and FTP and other system services. These ports are called well-known ports. Your applications
should not attempt to bind to them.

Networking Classes in the JDK

Through the classes in java.net, Java programs can use TCP or UDP to communicate over the Internet.
The URL, URLConnection, Socket, and ServerSocket classes all use TCP to communicate over the network.
The DatagramPacket, DatagramSocket, and MulticastSocket classes are for use with UDP.
www.rejinpaul.com
www.rejinpaul.com

Java.net Package:

Working with URLs:

URL is an acronym for Uniform Resource Locator and is a reference (an address) to a resource on the
Internet. Provide URLs to Web browser so that it can locate files on the Internet.

Java programs that interact with the Internet also may use URLs to find the resources on the Internet they
wish to access. Java programs can use a class called URL in the java.net package to represent a URL
address.

Definition:

A URL has two main components:

 Protocol identifier: For the URL http://example.com, the protocol identifier is http.

 Resource name: For the URL http://example.com, the resource name is example.com.

Note that the protocol identifier and the resource name are separated by a colon and two forward slashes.
The protocol identifier indicates the name of the protocol to be used to fetch the resource. The example uses
the Hypertext Transfer Protocol (HTTP), which is typically used to serve up hypertext documents. HTTP is
just one of many different protocols used to access different types of resources on the net. Other protocols
include File Transfer Protocol (FTP), Gopher, File, and News.

The resource name is the complete address to the resource. The format of the resource name depends
entirely on the protocol used, but for many protocols, including HTTP, the resource name contains one or
more of the following components:

Host Name: The name of the machine on which the resource live.
Filename: The pathname to the file on the machine.
Port Number: The port number to which to connect (typically optional).
www.rejinpaul.com
www.rejinpaul.com
Reference:A reference to a named anchor within a resource that usually identifies a specific location within
a file (typically optional).

Creating a URL

Within Java programs, can create a URL object that represents a URL address. The URL object always
refers to an absolute URL but can be constructed from an absolute URL, a relative URL, or from URL
components.

Four constructors of URL:All throws MalformedURLException:

public URL(String u) throws MalformedURLException


Absolute:

eg: URL myURL = new URL("http://example.com/");

Relative:
two URLs at the site example.com:
http://example.com/pages/page1.html
http://example.com/pages/page2.html
Create URL objects for these pages relative to their common base URL: http://example.com/pages/ like this:
URL myURL = new URL("http://example.com/pages/");
URL page1URL = new URL(myURL, "page1.html");
URL page2URL = new URL(myURL, "page2.html");
public URL(String protocol, String host, String file) throws MalformedURLException
new URL("http", "example.com", "/pages/page1.html");

public URL(String protocol, String host, int port, String file) throws MalformedURLException
URL gamelan = new URL("http", "example.com", 80, "pages/page1.html");

public URL(URL context, String u) throws MalformedURLExceptionMethods of URL class


URL page1BottomURL = new URL(page1URL,"#BOTTOM");

Parsing a URL

Parsing a URL is to find out the host name, filename, and other information. The URL class provides
methods for retrieving individual components of the represented URL (such as the protocol and the host
name). It also provides comparison methods for determining if two URL objects reference the same content.

1. protected void set(String protocol, String host, int port, String file, String ref)
Sets the fields of the URL. This is not a public method so that only URLStreamHandlers can modify URL
fields. URLs are otherwise constant.
2. public int getPort()
Gets the port number. Returns -1 if the port is not set.
3. public String getProtocol()
Gets the protocol name.
4. public String getHost()
Gets the host name.
5. public String getFile()
Gets the file name.
6. public String getRef()
www.rejinpaul.com
www.rejinpaul.com
Gets the ref.
7. public boolean equals(Object obj)
Compares two URLs. Returns true if and only if they are equal, false otherwise.
8. public URLConnection openConnection() throws IOException
Creates (if not already in existance) a URLConnection object that contains a connection to the remote object
referred to by the URL.
9. public final InputStream openStream() throws IOException
Opens an input stream.
10. public final Object getContent() throws IOException
Gets the contents from this opened connection.
Example Program:
import java.net.*;
public class TestURL1
{
public static void main(String args[])throws MalformedURLException
{
URL page1=new URL("https://www.example.com:8080/doc/Notes-on-JavaBeans");
System.out.println("Protocol:"+page1.getProtocol());
System.out.println("HOST:"+page1.getHost());
System.out.println("Port:"+page1.getPort());
System.out.println("FileName:"+page1.getFile());

}
OUTPUT:

D:\subjects\web programming\lab programs>javac TestURL1.java


D:\subjects\web programming\lab programs>java TestURL1
Protocol:https
HOST:www.example.com
Port:8080
FileName:/doc/Notes-on-JavaBeans
Reading Directly from a URL

After successfully created a URL, call the URL's openStream() method to get a stream from which read the
contents of the URL. The openStream() method returns a java.io.InputStream object, so reading from a URL
is as easy as reading from an input stream.

The following small Java program uses openStream() to get an input stream on the
URL http://www.oracle.com/. It then opens a BufferedReader on the input stream and reads from
the BufferedReader thereby reading from the URL. Everything read is copied to the standard output stream:

import java.net.*;
import java.io.*;

public class URLReader {


public static void main(String[] args) throws Exception
{
URL page1 = new URL("www.oracle.com");
www.rejinpaul.com
www.rejinpaul.com
BufferedReader in = new BufferedReader( new InputStreamReader(oracle.openStream()));
String inputLine;
while ((inputLine = in.readLine()) != null)
System.out.println(inputLine);
in.close();
}
Connecting to a URL
If want to do more than just read from a URL, can connect to it by calling openConnection() on the URL.
The openConnection() method returns a URLConnection object that can use for more general
communications with the URL, such as reading from it, writing to it, or querying it for content and other
information.

Reading from and Writing to a URLConnection

Some URLs, such as many that are connected to cgi-bin scripts, allow to (or even require to) write
information to the URL. For example, a search script may require detailed query data to be written to the
URL before the search can be performed.

Reading from a URLConnection

However, rather than getting an input stream directly from the URL, this program explicitly retrieves
a URLConnection object and gets an input stream from the connection. The connection is opened implicitly
by calling getInputStream. Then, like URLReader, this program creates a BufferedReader on the input
stream and reads from it. The bold statements highlight the differences between this example and the
previous program:

import java.net.*;
import java.io.*;

public class URLConnectionReader {


public static void main(String[] args) throws Exception {
URL oracle = new URL("http://www.oracle.com/");
URLConnection yc = oracle.openConnection();
BufferedReader in = new BufferedReader(new InputStreamReader(
yc.getInputStream()));
String inputLine;
while ((inputLine = in.readLine()) != null)
System.out.println(inputLine);
in.close();
}
}
The output from this program is identical to the output from the program that opens a stream directly from
the URL. However, reading from a URLConnection instead of reading directly from a URL might be more
useful. This is because you can use the URLConnection object for other tasks (like writing to the URL) at
the same time.
Writing to a URLConnection

Many HTML pages contain forms — text fields and other GUI objects that let to enter data to send to the
server. After you type in the required information and initiate the query by clicking a button, your Web
browser writes the data to the URL over the network. At the other end the server receives the data, processes
it, and then sends you a response, usually in the form of a new HTML page.
www.rejinpaul.com
www.rejinpaul.com
Many of these HTML forms use the HTTP POST METHOD to send data to the server. Thus writing to a
URL is often called posting to a URL. The server recognizes the POST request and reads the data sent from
the client.

For a Java program to interact with a server-side process it simply must be able to write to a URL, thus
providing data to the server. It can do this by following these steps:

1. Create a URL.

2. Retrieve the URLConnection object.

3. Set output capability on the URLConnection.

4. Open a connection to the resource.

5. Get an output stream from the connection.

6. Write to the output stream.

7. Close the output stream.


www.rejinpaul.com
www.rejinpaul.com

Java InetAddress class


Java InetAddress class represents an IP address. The java.net.InetAddress class provides methods to get the
IP of any host name for example www.javatpoint.com, www.google.com, www.facebook.com etc.

Commonly used methods of InetAddress class

Method Description

public static InetAddress getByName(String host) it returns the instance of InetAddress


throws UnknownHostException containing LocalHost IP and name.

public static InetAddress getLocalHost() throws it returns the instance of InetAdddress


UnknownHostException containing local host name and address.

public String getHostName() it returns the host name of the IP address.

public String getHostAddress() it returns the IP address in string format.

Example program:

import java.net.*;
public class TestInetaddress
{
public static void main(String args[])throws UnknownHostException
{
InetAddress a=InetAddress.getLocalHost();
System.out.println("Localhost:"+a);
InetAddress a1=InetAddress.getByName(args[0]);
System.out.println("hostname:"+a1);
InetAddress a2[]=InetAddress.getAllByName(args[0]);
for(int i=0;i<a2.length;i++)
System.out.println("hostname:"+i+":"+a2[i]);

}
}
OUTPUT:
D:\subjects\web programming\lab programs>javac TestInetaddress.java
D:\subjects\web programming\lab programs>java TestInetaddress www.google.com
Localhost:MSK-PC/192.168.198.1
hostname:www.google.com/74.125.68.106
hostname:0:www.google.com/74.125.68.106
hostname:1:www.google.com/74.125.68.99
hostname:2:www.google.com/74.125.68.147
hostname:3:www.google.com/74.125.68.103
hostname:4:www.google.com/74.125.68.104
hostname:5:www.google.com/74.125.68.105
www.rejinpaul.com
www.rejinpaul.com

TCP Sockets:
URLs and URLConnections provide a relatively high-level mechanism for accessing resources on the
Internet whether lower-level network communication is provided by Socket for example, when you want to
write a client-server application.

Java Socket programming can be connection-oriented or connection-less.

Socket and ServerSocket classes are used for connection-oriented socket programming and DatagramSocket
and DatagramPacket classes are used for connection-less socket programming.

The client in socket programming must know two information:

1. IP Address of Server, and

2. Port number.

Socket class
A socket is simply an endpoint for communications between the machines. The Socket class can be used to
create a socket.
Important methods
Method Description
1) public InputStream getInputStream() returns the InputStream attached with this socket.

2) public OutputStream getOutputStream() returns the OutputStream attached with this socket.

3) public synchronized void close() closes this socket

ServerSocket class
The ServerSocket class can be used to create a server socket. This object is used to establish communication
with the clients.
Important methods
Method Description
1) public Socket accept() returns the socket and establish a connection between server and
client.
2) public synchronized void closes the server socket.
close()

Example Program:
Client Program:
import java.net.*;
import java.io.*;

public class TCPclient


{
public static void main(String args[])throws IOException
{
Socket cs=new Socket(InetAddress.getLocalHost(),9090);
www.rejinpaul.com
www.rejinpaul.com
String date="Hello";
BufferedReader br=new BufferedReader(new InputStreamReader(cs.getInputStream()));
date=br.readLine();
System.out.println(date);
cs.close();

}
}

Server Program:

import java.net.*;
import java.io.*;
import java.util.Date;

public class TCPserver


{
public static void main(String args[])throws IOException
{
ServerSocket ss=new ServerSocket(9090);
Date d=new Date();
String str=d.toString();
Socket s=ss.accept();
PrintWriter out = new PrintWriter(s.getOutputStream());
out.println(str);
out.flush();
s.close();
}
}

UDP Sockets:
Java DatagramSocket and DatagramPacket classes are used for connection-less socket programming.
Java DatagramSocket class:
Java DatagramSocket class represents a connection-less socket for sending and receiving datagram packets.
A datagram is basically an information but there is no guarantee of its content, arrival or arrival time.
Commonly used Constructors of DatagramSocket class
 DatagramSocket() throws SocketException: it creates a datagram socket and binds it with the
available Port Number on the localhost machine.
 DatagramSocket(int port) throws SocketException: it creates a datagram socket and binds it with the
given Port Number.
 DatagramSocket(int port, InetAddress address) throws SocketException: it creates a datagram socket
and binds it with the specified port number and host address.
Java DatagramPacket class
Java DatagramPacket is a message that can be sent or received. If you send multiple packets, it may arrive in
any order. Additionally, packet delivery is not guaranteed.
Commonly used Constructors of DatagramPacket class
www.rejinpaul.com
www.rejinpaul.com
 DatagramPacket(byte[] barr, int length): it creates a datagram packet. This constructor is used to
receive the packets.
 DatagramPacket(byte[] barr, int length, InetAddress address, int port): it creates a datagram packet.
This constructor is used to send the packets.
Example Program:
Client:
import java.net.*;
import java.io.*;

public class UDPclient


{
public static void main(String args[])throws IOException,SocketException
{
DatagramSocket cds=new DatagramSocket();
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
byte[] asendbyte=new byte[1024];
byte[] areceivebyte=new byte[1024];
System.out.println("Enter the comand to be executed:");
String input=br.readLine();
asendbyte=input.getBytes();
DatagramPacket sp=new DatagramPacket (asendbyte, asendbyte.length,
InetAddress.getLocalHost(), 9090);
cds.send(sp);
cds.close();

}
Server:
import java.net.*;
import java.io.*;
import java.lang.Runtime.*;
import java.net.InetAddress.*;

public class UDPserver


{

public static void main(String args[])throws IOException,SocketException


{
DatagramSocket sds=new DatagramSocket(9090);
byte[] rbyte=new byte[1024];
while(true)
{
DatagramPacket dp=new DatagramPacket(rbyte,rbyte.length);
sds.receive(dp);
String cmd=new String(dp.getData());
Runtime r=Runtime.getRuntime();
www.rejinpaul.com
www.rejinpaul.com
Process p=r.exec(cmd);
}
}

RMI:Remote method Invocation:

Java RMI or Remote Method Invocation is an example of Remote Procedure Call (RPC)enabling
client program to locate the server object and remotely invoke the methods from server through server’s stub
and skeleton function. Java RMI is usually referred to Distributed Object rather than RPC. This is because
Java natively is object oriented programming. So we say object as a whole. Moreover, RPC somehow is
mentioned to procedural programming.

 The main Java RMI component consists of 3 elements:


Client
Invoke method on remote object
Server
Process that owns remote object
Registry
Name server that relates objects with unique names
 From the figure above, we can see the process of Java RMI is divided into 4 steps:
1. Instantiate server object and then register it to RMI registry service with unique name
2. Client program locates server object from RMI registry service with associated name
3. Once server object is found in RMI registry, RMI registry returns server stub
4. Server stub handles the data communication with Server skeleton on server side. Be remember that,
server stub and skeleton do marshalling and unmarshalling.
Server Object Interface:
An interface defines the methods for the server object
Server Object:
An instance of the server object interface
Server Stub:
An object that resides on the client host and serves as a representative of the remote server object
Server Skeleton:
An object that resides on the server host. It communicates with the stub and the actual server object
RMI Registry:
It is service to register remote objects and to provide naming services for locating objects
www.rejinpaul.com
www.rejinpaul.com
Client program:
A program that invokes the methods in the remote server object
Steps to write the RMI program:
Following is the 6 steps to write the RMI program.
1. Create the remote interface
2. Provide the implementation of the remote interface
3. Compile the implementation class and create the stub and skeleton objects using the rmic tool
4. Start the registry service by rmiregistry tool
5. Create and start the remote application
6. Create and start the client application
Example RMI Program:
import java.rmi.*;
public interface Computeinterface extends Remote
{
public int add(int a,int b)throws RemoteException;
public int sub(int a,int b)throws RemoteException;
public int mul(int a,int b)throws RemoteException;

}
Rmiserver.java:
import java.rmi.server.*;
import java.rmi.Naming.*;
public class rmiserver extends UnicastRemoteObject implements Computeinterface
{
public rmiserver() throws RemoteException{}
public int add(int a,int b)throws RemoteException
{
return a+b;
}
public int sub(int a,int b)throws RemoteException
{
return a-b;
}
public int mul(int a,int b)throws RemoteException
{
return a*b;
}
public static void main(String args[])throws
RemoteException,MalformedURLException,NotBoundException
{
rmiserver rs=new rmiserver();
Registry r=LocateRegistry.getRegistry();
r.rebind("rmiserver",rs);

}
}
www.rejinpaul.com
www.rejinpaul.com
Rmiclient.java:
import java.io.*;
import java.rmi.*;
import java.rmi.registry.*;
import java.net.*;
import java.rmi.Naming;
public class rmiclient
{
public static void main(String args[])throws IOException,RemoteException,NotBoundException
{

int a,b;
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter the first number");
a=Integer.parseInt(br.readLine());
System.out.println("Enter the second number");
b=Integer.parseInt(br.readLine());
Registry r=LocateRegistry.getRegistry();
Computeinterface ci=(Computeinterface) r.lookup("rmiserver");
System.out.println("sum="+ci.add(a,b));
System.out.println("diff="+ci.sub(a,b));
System.out.println("product="+ci.mul(a,b));
}

}
www.rejinpaul.com
www.rejinpaul.com

JAVA BEANS:
 A “Bean” is a reusable software component model based on sun’s java bean specification that can be
manipulated visually in a builder tool.
 The term software component model describe how to create and use reusable software components
to build an application
 Builder tool is nothing but an application development tool which lets you both to create new beans
or use existing beans to create an application.
 To enrich the software systems by adopting component technology JAVA came up with the concept
called Java Beans.
 Java provides the facility of creating some user defined components by means of Bean programming.
Advantages of Java Beans:
1. The java beans posses the property of “Write once and run anywhere”.
2. Beans can work in different local platforms.
3. Beans have the capability of capturing the events sent by other objects and vice versa enabling object
communication.
4. The properties, events and methods of the bean can be controlled by the application developer.(ex. Add
new properties)
5. Beans can be configured with the help of auxiliary software during design time.(no hassle at runtime)
6. The configuration setting can be made persistent.(reused)
7. Configuration setting of a bean can be saved in persistent storage and restored later.
JavaBeans basic rules:
A Java Bean should:
be public , implements the Serializable interface ,have a no-arg constructor and be derived from
javax.swing.JComponent or java.awt.Component if it is visual.
The classes and interfaces defined in the java.beans package enable you to create JavaBeans.
The Java Bean components can exist in one of the following three phases of development:
• Construction phase
• Build phase
• Execution phase
It supports the standard component architecture features of
Properties
Events
Methods
Persistence.
In addition Java Beans provides support for
Introspection (Allows Automatic Analysis of a java beans)
Customization(To make it easy to configure a java beans component
The JavaBean Component Specification:
Customization: Is the ability of JavaBean to allow its properties to be changed in build and execution phase.
Persistence:- Is the ability of JavaBean to save its state to disk or storage device and restore the saved state
when the JavaBean is reloaded.
Communication:-Is the ability of JavaBean to notify change in its properties to other JavaBeans or the
container.
Introspection:- Is the ability of a JavaBean to allow an external application to query the properties,methods,
and events supported by it.
Features of a JavaBean:
 Support for “introspection” so that a builder tool can analyze how a bean works.
 Support for “customization” to allow the customisation of the appearance and behaviour of a bean.
www.rejinpaul.com
www.rejinpaul.com

 Support for “events” as a simple communication metaphor than can be used to connect up beans.
 Support for “properties”, both for customization and for programmatic use.
 Support for “persistence”, so that a bean can save and restore its customized state.
Steps to Develop a User-Defined JavaBean:
1. Create a directory for the new bean
2. Create the java bean source file(s)
3. Compile the source file(s)
4. Create a manifest file
5. Generate a JAR file
6. Start BDK
7. Load Jar file
8. Test.
Introspection:
Introspection can be defined as the technique of obtaining information about bean properties, events and
methods. Without introspection, the JavaBeans technology could not operate.
Persistence:
Persistence means an ability to save properties and events of user deffined beans to non-volatile storage and
retrieve later.That is the state of the bean is stored and retrived.
Property:
A property is a subset of a Bean’s state. Examples of bean properties include color, label, font, font size, and
display size.
Types of JavaBeans Properties:
 Simple properties:- Simple properties refer to the private variables of a JavaBean that can have only a
single value. Simple properties are retrieved and specified using the get and set methods respectively.
 Boolean properties:- A Boolean property is a property which is used to represent the values True or
False. Let N be the name of the property and T be the type of the value then the methods are
public boolean isN();
public void setN(boolean parameter);
public Boolean getN();
 Indexed properties:- Indexed Properties consists of multiple values.If a simple property can hold an
array of value they are no longer called simple butinstead indexed properties. An indexed property
may expose set/get methods to read/write one element in the array (so-called ’index getter/setter’)
and/or so-called ’array getter/setter’ which read/write the entire array.
 Bound properties:- A bean that has a bound property generates an event when the property is
changed.
 Constrained properties:- It generates an event when an attempt is made to change its value.
Handling Events in JavaBeans:
Enables Beans to communicate and connect together.
Beans generate events and these events can be sent to other objects.
Event means any activity that interrupts the current ongoing activity.
Example: mouse clicks, pressing key…
www.rejinpaul.com
www.rejinpaul.com
JDBC:
JDBC Overview:
The JDBC API is a Java API that can access any kind of tabular data, especially data stored in a Relational
Database.
JDBC helps to write Java applications that manage these three programming activities:
1. Connect to a data source, like a database
2. Send queries and update statements to the database
3. Retrieve and process the results received from the database in answer to the query.
JDBC Product Components
JDBC includes four components:
1. The JDBC API — The JDBC™ API provides programmatic access to relational data from the
Java™ programming language. Using the JDBC API, applications can execute SQL statements,
retrieve results, and propagate changes back to an underlying data source. The JDBC API can also
interact with multiple data sources in a distributed, heterogeneous environment.
The JDBC API is part of the Java platform, which includes the Java™ Standard Edition (Java™ SE
) and the Java™ Enterprise Edition (Java™ EE). The JDBC 4.0 API is divided into two
packages: java.sql and javax.sql. Both packages are included in the Java SE and Java EE platforms.
2. JDBC Driver Manager — The JDBC DriverManager class defines objects which can connect Java
applications to a JDBC driver. DriverManager has traditionally been the backbone of the JDBC
architecture. It is quite small and simple.
The Standard Extension packages javax.naming and javax.sql make to use a DataSource object
registered with a Java Naming and Directory Interface™ (JNDI) naming service to establish a
connection with a data source.
3. JDBC Test Suite — The JDBC driver test suite helps to determine that JDBC drivers will run the
program. i.e to test whether the program runs in the driver or not.
4. JDBC-ODBC Bridge — The Java Software bridge provides JDBC access via ODBC drivers. i.e
connects database drivers to database.
The first two of these four JDBC components are used to connect to a database and then build a java
program that uses SQL commands to communicate with a test Relational Database. The last two
components are used in specialized environments to test web applications, or to communicate with
ODBC-aware DBMSs.
JDBC Architecture:
Two-tier and Three-tier Processing Models
The JDBC API supports both two-tier and three-tier processing models for database access.
Figure 1: Two-tier Architecture for Data Access.
www.rejinpaul.com
www.rejinpaul.com

Figure 2: Three-tier Architecture for Data Access.

JDBC Architectural Diagram:

The JDBC API provides the following interfaces and classes −


 DriverManager: This class manages a list of database drivers. Matches connection requests from
the java application with the proper database driver using communication sub protocol. The first
driver that recognizes a certain subprotocol under JDBC will be used to establish a database
Connection.
 Driver: This interface handles the communications with the database server. The interaction directly
with Driver objects are very rare. Instead, DriverManager objects are used, which manages objects
of this type. It also abstracts the details associated with working with Driver objects.
 Connection: This interface is with all methods for contacting a database. The connection object
represents communication context, i.e., all communication with database is through connection
object only.
 Statement: Use objects created from this interface to submit the SQL statements to the database.
Some derived interfaces accept parameters in addition to executing stored procedures.
 ResultSet: These objects hold data retrieved from a database after executing an SQL query using
Statement objects. It acts as an iterator to allow to move through its data.
 SQLException: This class handles any errors that occur in a database application.
www.rejinpaul.com
www.rejinpaul.com
Packages Used:
Java.sql.* and javax.sql.*

What the java.sql Package Contains


The java.sql package contains API for the following:
 Making a connection with a database via the DriverManager facility
o DriverManager class -- makes a connection with a driver
o SQLPermission class -- provides permission when code running within a Security Manager,
such as an applet, attempts to set up a logging stream through the DriverManager
o Driver interface -- provides the API for registering and connecting drivers based on JDBC
technology ("JDBC drivers"); generally used only by the DriverManager class
o DriverPropertyInfo class -- provides properties for a JDBC driver; not used by the general
user
 Sending SQL statements to a database
o Statement -- used to send basic SQL statements
o PreparedStatement -- used to send prepared statements or basic SQL statements (derived
from Statement)
o CallableStatement -- used to call database stored procedures (derived
from PreparedStatement)
o Connection interface -- provides methods for creating statements and managing connections
and their properties
o Savepoint -- provides savepoints in a transaction
 Retrieving and updating the results of a query
o ResultSet interface
 Standard mappings for SQL types to classes and interfaces in the Java programming language
o Array interface -- mapping for SQL ARRAY
o Blob interface -- mapping for SQL BLOB
o Clob interface -- mapping for SQL CLOB
o Date class -- mapping for SQL DATE
o NClob interface -- mapping for SQL NCLOB
o Ref interface -- mapping for SQL REF
o RowId interface -- mapping for SQL ROWID
o Struct interface -- mapping for SQL STRUCT
o SQLXML interface -- mapping for SQL XML
o Time class -- mapping for SQL TIME
www.rejinpaul.com
www.rejinpaul.com
o Timestamp class -- mapping for SQL TIMESTAMP
o Types class -- provides constants for SQL types
 Custom mapping an SQL user-defined type (UDT) to a class in the Java programming language
o SQLData interface -- specifies the mapping of a UDT to an instance of this class
o SQLInput interface -- provides methods for reading UDT attributes from a stream
o SQLOutput interface -- provides methods for writing UDT attributes back to a stream
 Metadata
o DatabaseMetaData interface -- provides information about the database
o ResultSetMetaData interface -- provides information about the columns of a ResultSet object
o ParameterMetaData interface -- provides information about the parameters
to PreparedStatement commands
 Exceptions
o SQLException -- thrown by most methods when there is a problem accessing data and by
some methods for other reasons
o SQLWarning -- thrown to indicate a warning
o DataTruncation -- thrown to indicate that data may have been truncated
o BatchUpdateException -- thrown to indicate that not all commands in a batch update
executed successfully
Example Program:

d:\subjects\web programming\lab programs>set DERBY_INSTALL=C:\Program Files\Java


\jdk1.7.0_79\db
d:\subjects\web programming\lab programs>set CLASSPATH=%DERBY_INSTALL%\lib\derby
.jar;%DERBY_INSTALL%\lib\derbytools.jar;

d:\subjects\web programming\lab programs>cd %DERBY_INSTALL%\bin

C:\Program Files\Java\jdk1.7.0_79\db\bin>

C:\Program Files\Java\jdk1.7.0_79\db\bin>setEmbeddedCP.bat

C:\Program Files\Java\jdk1.7.0_79\db\bin>SET DERBY_HOME=c:\PROGRA~1\Java\jdk1.8.


0_60\db

C:\Program Files\Java\jdk1.7.0_79\db\bin>set CLASSPATH=c:\PROGRA~1\Java\jdk1.8.0


_60\db\lib\derby.jar;c:\PROGRA~1\Java\jdk1.8.0_60\db\lib\derbytools.jar;c:\PROGR
A~1\Java\jdk1.8.0_60\db\lib\derby.jar;c:\PROGRA~1\Java\jdk1.8.0_60\db\lib\derbyt
ools.jar;C:\Program Files\Java\jdk1.7.0_79\db\lib\derby.jar;C:\Program Files\Jav
a\jdk1.7.0_79\db\lib\derbytools.jar;

program:
import java.sql.*;
public class MYdbase
{
public static void main(String args[])
{
try
{
www.rejinpaul.com
www.rejinpaul.com
Class.forName("org.apache.derby.jdbc.EmbeddedDriver").newInstance();
String path = "d:/subjects/web programming/lab programs/MyDbTest1;";
Connection con = DriverManager.getConnection("jdbc:derby:"+path+"create=true");
Statement s=con.createStatement();
String selTable = "SELECT * FROM emp";
s.execute(selTable);
ResultSet rs = s.getResultSet();
while((rs!=null) && (rs.next()))
{
System.out.println(rs.getString(1) + " : " + rs.getString(2));
}
s.close();
con.close();
}catch(Exception ex){ex.printStackTrace();}
}

}
Output:

d:\subjects\web programming\lab programs>java MYdbase


201 : sai
221 : ksk
222 : kali

d:\subjects\web programming\lab programs>


www.rejinpaul.com
www.rejinpaul.com

UNIT IV APPLETS 9

Java applets- Life cycle of an applet – Adding images to an applet – Adding sound to an applet. Passing
parameters to an applet. Event Handling. Introducing AWT: Working with Windows Graphics and Text. Using
AWT Controls, Layout Managers and Menus. Servlet – life cycle of a servlet. The Servlet API, Handling HTTP
Request and Response, using Cookies, Session Tracking. Introduction to JSP.

Java applets:
Definition:
Applet is a special type of small java program that is embedded in the webpage to generate the dynamic content.
It runs inside the java enabled web browser and works at client side.
Difference between Applet and java application:
 An applet is a Java class that extends the java.applet.Applet class.
 A main method is not invoked on an applet, and an applet class will not define main.
 Applets are designed to be embedded within an HTML page.
 When a user views an HTML page that contains an applet, the code for the applet is downloaded to the
user's machine.
 A JVM is required to view an applet. The JVM can be either a plug-in of the Web browser or a separate
runtime environment. The JVM on the user's machine creates an instance of the applet class and invokes
various methods during the applet's lifetime.
 Applets have strict security rules that are enforced by the Web browser. The security of an applet is
often referred to as sandbox security, comparing the applet to a child playing in a sandbox with various
rules that must be followed.
 Other classes that the applet needs can be downloaded in a single Java Archive JAR file.
 Differences summarized:
Feature Application Applet
Main() method Present Not present

Execution Requires JRE Requires browser


Requires a third party
Nature Runs independently
tool like browser
Can access any data and Cannot access anything
Restrictions software from the except browsers
system. services.
Does not require any Requires high security as
Security
security they are not trusted.

Advantage:
1. Platform Independent.
2. Applets don’t have compatibility issues with different versions of java.
3. Applets cache quickly, that’s why there will be no latency in downloading of them.
4. It can also be used for a real time application.
5. They can pay out different type of action on client-side machine like-
 Playing sound
1

Download Useful Materials from Rejinpaul.com


www.rejinpaul.com
www.rejinpaul.com
 Viewing images
 Get user input
 Get mouse clicks
 Get user keystrokes
6. They increase interactivity for users.
7. Java has constituted security, by this feature of java; an applet doesn’t produce any harmful activity.
8. Database integration is another important advantage of applets.
Disadvantage:
1. Some browsers especially mobile browsers which are running on Apple IOS or Android don’t support
applets run.
2. If a proxy server is applied to web access, than automatically installation and update of Java can be
failed, that’s why applets can’t run with specific requirements unless Java is manually installed or
updated.
3. Applets don’t access client-side resources, like-
 Files
 Operating system
4. Applets have to tag as trusted applets and they must be registered to APS (Applet Security Manager).
5. Applet cannot work with native methods.
6. Applet can only extract information about client-machine is its name, java version, OS, version.
Life Cycle of an applet:

1. init() – Execution of an applet starts from here. It is coequal to born stage of a thread. This is the first
method (it is called before all other methods). A programmer can exploit this method to instantiate
objects, initialize variables, setting background and foreground colors in GUI etc. In this method Applet
is created but remains inactive.
2. start() – In this method Applet become active, and become eligible for processor time. Because an
inactive Applet is not eligible for processor time.
3. paint() – this method is requested instantly after the start () method, this method takes
a java.awt.Graphics object as parameter, this is the only place where a programmer can write his code.
4. stop() – This method makes an Applet inactive temporarily, and it is called directly when the user
moves off the page on which the applet sits.

Download Useful Materials from Rejinpaul.com


www.rejinpaul.com
www.rejinpaul.com
5. destroy() – In this method an Applet become dead, and it’s the best place to have cleanup code.
destroy() method is called when the browser shuts down normally.
First Applet program:

import java.awt.*;
import java.applet.*;
public class applet1 extends Applet
{
public void paint(Graphics g)
{

g.drawString("Hello World",10,30);
}

}
Applet1.html
<html>
<applet code="applet1.class" height=300 width=300>
</applet>
</html>
Steps to execute:

java.awt.Graphics class provides many methods for graphics programming.


Commonly used methods of Graphics class:
1. public abstract void drawString(String str, int x, int y): is used to draw the specified string.
2. public void drawRect(int x, int y, int width, int height): draws a rectangle with the specified width
and height.
3. public abstract void fillRect(int x, int y, int width, int height): is used to fill rectangle with the
default color and specified width and height.

Download Useful Materials from Rejinpaul.com


www.rejinpaul.com
www.rejinpaul.com
4. public abstract void drawOval(int x, int y, int width, int height): is used to draw oval with the
specified width and height.
5. public abstract void fillOval(int x, int y, int width, int height): is used to fill oval with the default
color and specified width and height.
6. public abstract void drawLine(int x1, int y1, int x2, int y2): is used to draw line between the
points(x1, y1) and (x2, y2).
7. public abstract boolean drawImage(Image img, int x, int y, ImageObserver observer): is used draw
the specified image.
8. public abstract void drawArc(int x, int y, int width, int height, int startAngle, int arcAngle): is
used draw a circular or elliptical arc.
9. public abstract void fillArc(int x, int y, int width, int height, int startAngle, int arcAngle): is used
to fill a circular or elliptical arc.
10. public abstract void setColor(Color c): is used to set the graphics current color to the specified color.
11. public abstract void setFont(Font font): is used to set the graphics current font to the specified font.

Adding images to Applet:

 First step is to create the image's URL object by calling either the getDocumentBase() or getCodeBase()
method. The former returns the URL of the directory from which the current HTML file was loaded,
whereas the latter returns the URL of the directory from which the applet was run.
public URL getDocumentBase(): is used to return the URL of the document in which applet is
embedded.
public URL getCodeBase(): is used to return the base URL.
 Create the Object for image using the function public Image getImage(URL u, String image){}
 Load the image in applet . public abstract boolean drawImage(Image img, int x, int y,
ImageObserver observer): is used draw the specified image.
Other drawimage methods:
drawImage(Image img, int x, int y, Color bgcolor, ImageObserver observer)
Draws as much of the specified image as is currently available.
drawImage(Image img, int x, int y, ImageObserver observer)
Draws as much of the specified image as is currently available.
drawImage(Image img, int x, int y, int width, int height, Color bgcolor, ImageObserver observer)
Draws as much of the specified image as has already been scaled to fit inside the specified rectangle.
drawImage(Image img, int x, int y, int width, int height, ImageObserver observer)
Draws as much of the specified image as has already been scaled to fit inside the specified rectangle.
drawImage(Image img, int dx1, int dy1, int dx2, int dy2, int sx1, int sy1, int sx2,
int sy2, Color bgcolor, ImageObserver observer)
Draws as much of the specified area of the specified image as is currently available, scaling it on the fly to fit
inside the specified area of the destination drawable surface.
drawImage(Image img, int dx1, int dy1, int dx2, int dy2, int sx1, int sy1, int sx2,
int sy2, ImageObserver observer)
Draws as much of the specified area of the specified image as is currently available, scaling it on the fly to fit
inside the specified area of the destination drawable surface.
Example program:
import java.applet.Applet;
4

Download Useful Materials from Rejinpaul.com


www.rejinpaul.com
www.rejinpaul.com
import java.awt.Graphics;
import java.awt.Image;
public class AppletImage extends Applet
{
Image img;
public void init()
{
img=getImage(getDocumentBase(),getParameter("img"));
}
public void paint(Graphics g)
{
g.drawImage(img,0,0,this);
g.drawImage(img,150,150,300,140,this);//scaled image.

}
}
Html file
html>
<applet code="AppletImage.class" height=300 width=300>
<param name="img" value="java.png">
</applet>
</html>
Output:

Passing parameter to an Applet:


The Applet.getParameter() method fetches a parameter, given the parameter's name (the value of a parameter is
always a string). If the value is numeric or other non-character data, the string must be parsed.
Example program:
import java.applet.*;
import java.awt.Graphics;
5

Download Useful Materials from Rejinpaul.com


www.rejinpaul.com
www.rejinpaul.com
public class Appletparameter extends Applet
{
int x=0;
int y=0;
String msg="";
public void paint(Graphics g)
{
try
{
x=Integer.parseInt(getParameter("xpos"));
y=Integer.parseInt(getParameter("ypos"));
}catch(NumberFormatException ne)
{}
msg=getParameter("mg");
g.drawString(msg,x,y);

}
}
Html file:
<html>
<applet code="Appletparameter.class" height=500 width= 400>
<param name="xpos" value="30"/>
<param name="ypos" value="40"/>
<param name="mg" value="Hello World"/>
</applet>
</html>
Abstract Windowing Toolkit:(AWT)
The hierarchy of Java AWT classes are given below:

Download Useful Materials from Rejinpaul.com


www.rejinpaul.com
www.rejinpaul.com

Container
The Container is a component in AWT that can contain another components like buttons, textfields, labels etc.
The classes that extends Container class are known as container such as Frame, Dialog and Panel.
Window
The window is the container that have no borders and menu bars. You must use frame, dialog or another
window for creating a window.
Panel
The Panel is the container that doesn't contain title bar and menu bars. It can have other components like button,
textfield etc.
Frame
The Frame is the container that contain title bar and can have menu bars. It can have other components like
button, textfield etc.
Useful Methods of Component class
Method Description
public void add(Component c) inserts a component on this component.
public void setSize(int width,int height) sets the size (width and height) of the component.

Download Useful Materials from Rejinpaul.com


www.rejinpaul.com
www.rejinpaul.com

public void setLayout(LayoutManager m) defines the layout manager for the component.
public void setVisible(boolean status) changes the visibility of the component, by default false.
To create simple awt example, you need a frame. There are two ways to create a frame in AWT.
o By extending Frame class (inheritance)
class First extends Frame
o By creating the object of Frame class (association)
class First2{
First2(){
Frame f=new Frame();

AWT controls:
Controls are components that allow a user to interact with your application.
- A component is a graphical object.
- A few examples of components are:
1. Button
2. Canvas
3. Checkbox, CheckBox Group
4. Choice
5. Container
6. Label
7. List
8. Scrollbar
9. Text Component
10. Image
11. Canvas
12. Dialog
13. File Dialog
Every user interface considers the following three main aspects:
 UI elements : Thes are the core visual elements the user eventually sees and interacts with. GWT
provides a huge list of widely used and common elements varying from basic to complex which we will
cover in this tutorial.
 Layouts: They define how UI elements should be organized on the screen and provide a final look and
feel to the GUI (Graphical User Interface). This part will be covered in Layout chapter.
 Behavior: These are events which occur when the user interacts with UI elements. This part will be
covered in Event Handling chapter.

Download Useful Materials from Rejinpaul.com


www.rejinpaul.com
www.rejinpaul.com

AWT Menu Hierarchy:

Creation of menus involves many steps to be followed in an order. Following are the steps.

1. Create menu bar

2. Add menu bar to the frame

3. Create menus

4. Add menus to menu bar

5. Create menu items

6. Add menu items to menus

7. Event handling
AWT Menu Controls:
1 MenuComponent
It is the top level class for all menu related controls.
2 MenuBar
The MenuBar object is associated with the top-level window.
3 MenuItem
The items in the menu must belong to the MenuItem or any of its subclass.
4 Menu
The Menu object is a pull-down menu component which is displayed from the menu bar.
5 CheckboxMenuItem
CheckboxMenuItem is subclass of MenuItem.
6 PopupMenu
PopupMenu can be dynamically popped up at a specified position within a component.
Graphics controls allows application to draw onto the component or on image.
Example Program:
9

Download Useful Materials from Rejinpaul.com


www.rejinpaul.com
www.rejinpaul.com
import java.awt.*;
import java.io.*;
import java.awt.event.*;
public class MenuDemo extends Frame implements ActionListener
{
TextArea ta;
public MenuDemo()
{ // create menu bar
MenuBar mBar = new MenuBar();
setMenuBar(mBar); // add menu bar to frame
// create menus
Menu files = new Menu("Files");
Menu date = new Menu("Date");
Menu exit = new Menu("Exit");
ta = new TextArea(10, 40);
ta.setBackground(Color.cyan);
// add menus to menu bar
mBar.add(files);
mBar.add(date);
mBar.add(exit);
// create menu items to menus
MenuItem mi1 = new MenuItem("Applet1.java");
files.add(mi1); // using anonymous menu items
files.add(new MenuItem("AppletImage.java"));
files.addSeparator();
files.add(new MenuItem("AppletSound.java"));
files.add(new MenuItem("age.class"));

date.add(new MenuItem("Today"));
exit.add(new MenuItem("Close"));
// linking listener
files.addActionListener(this);
date.addActionListener(this);
exit.addActionListener(this);

add(ta, "Center");

setTitle("Menu Practice");
setSize(400, 400);
setVisible(true);
}
public void actionPerformed(ActionEvent e)
{

10

Download Useful Materials from Rejinpaul.com


www.rejinpaul.com
www.rejinpaul.com
String str = e.getActionCommand();

if(str.equals("Close"))
{
System.exit(0);
}
else if(str.equals("Today"))
{
ta.setText("Today: " + new java.util.Date());
}
else
{
try
{
FileReader fr = new FileReader(str);

ta.setText("Folloiwing are file contents:\n\n");


int temp;
while( (temp = fr.read()) != -1)
{
char ch = (char) temp;
String s1 = String.valueOf(ch);
ta.append(s1);

}
fr.close();
}
catch(IOException e1)
{
ta.setText("Exception: " + e1);
}
}
}
public static void main(String args[])
{
new MenuDemo();
}
}

11

Download Useful Materials from Rejinpaul.com


www.rejinpaul.com
www.rejinpaul.com

AWT Graphics Controls:


Graphics
It is the top level abstract class for all graphics contexts.
Graphics2D
It is a subclass of Graphics class and provides more sophisticated control over geometry, coordinate
transformations, color management, and text layout.
Arc2D
Arc2D is the abstract superclass for all objects that store a 2D arc defined by a framing rectangle, start angle,
angular extent (length of the arc), and a closure type (OPEN, CHORD, or PIE).
CubicCurve2D
The CubicCurve2D class is the abstract superclass fpr all objects which store a 2D cubic curve segment and it
defines a cubic parametric curve segment in (x,y) coordinate space.
Ellipse2D
The Ellipse2D is the abstract superclass for all objects which store a 2D ellipse and it describes an ellipse that is
defined by a framing rectangle.
Rectangle2D
The Rectangle2D class is an abstract superclass for all objects that store a 2D rectangle and it describes a
rectangle defined by a location (x,y) and dimension (w x h).
QuadCurve2D
The QuadCurve2D class is an abstract superclass for all objects that store a 2D quadratic curve segment and it
describes a quadratic parametric curve segment in (x,y) coordinate space.
Line2D
This Line2D represents a line segment in (x,y) coordinate space.
Font
The Font class represents fonts, which are used to render text in a visible way.
Color
12

Download Useful Materials from Rejinpaul.com


www.rejinpaul.com
www.rejinpaul.com
The Color class is used encapsulate colors in the default sRGB color space or colors in arbitrary color spaces
identified by a ColorSpace.
BasicStroke
The BasicStroke class defines a basic set of rendering attributes for the outlines of graphics primitives, which
are rendered with a Graphics2D object that has its Stroke attribute set to this BasicStroke.

Event Handling:
Changing the state of an object is known as an event.
In AWT components, every component (except Panel and Label) generates events when interacted by the user
like clicking over a button or pressing enter key in a text field etc. Listeners handle the events. The style (or
design pattern) Java follows to handle the events are as follows:
The event handling Java involves four types of classes.
1. Event Sources
2. Event classes
3. Event Listeners
4. Event Adapters
1. Event Sources
Event sources are components, subclasses of java.awt.Component, capable to generate events. The event
source can be a button, TextField or a Frame etc.
2. Event classes
Almost every event source generates an event and is named by some Java class. For example, the event
generated by button is known as ActionEvent and that of Checkbox is known as ItemEvent. All the events are
listed in java.awt.event package. Following list gives a few components and their corresponding listeners.

COMPONENT EVENT IT GENERATES

Button, TextField, List, Menu ActionEvent

Frame WindowEvent

Checkbox, Choice, List ItemEvent

Scrollbar AdjustmentEvent

Mouse (hardware) MouseEvent

Keyboard (hardware) KeyEvent

The events generated by hardware components (like MouseEvent and KeyEvent) are known as low-level
events and the events generated by software components (like Button, List) are known as semantic events.
3. Event Listeners
The events generated by the GUI components are handled by a special group of interfaces known as "listeners".
Note, Listener is an interface. Every component has its own listener, say, AdjustmentListener handles the events

13

Download Useful Materials from Rejinpaul.com


www.rejinpaul.com
www.rejinpaul.com
of scrollbar Some listeners handle the events of multiple components. For example, ActionListener handles the
events of Button, TextField, List and Menus. Listeners are from java.awt.event package
Table giving list of few Java AWT Listeners and components whose events the listeners can handle.

LISTENER INTERFACE COMPONENT

WindowListener Frame

ActionListener Button, TextField, List, Menu

ItemListener Checkbox, Choice, List

AdjustmentListener Scrollbar

MouseListener Mouse (stable)

MouseMotionListener Mouse (moving)

KeyListener Keyboard

Adapters make event handling code simple to write. But adapter is an abstract class where as listener is an
interface. Both are from java.awt.event package. Any listener interface containing more than one abstract
method has got corresponding adapter class. But ActionListener, ItemListener and AdjustmentListener do not
have corresponding adapter class as they come with only one abstract method.
4. Event Adapters
When a listener includes many abstract methods to override, the coding becomes heavy to the programmer. For
example, to close the frame, override seven abstract methods of WindowListener, in which, in fact using only
one method. To avoid this heavy coding, the designers come with another group of classes known as
"adapters". Adapters are abstract classes defined in java.awt.event package. Every listener that has more than
one abstract method has got a corresponding adapter class.
When an adapter is used, a separate class is to be created as the main class already extends Frame Since java
does not support multiple inheritances.
Following table gives some important listeners and their corresponding adapter classes.

LISTENER INTERFACE CORRESPONDING ADAPTER

WindowListener (7) WindowAdapter

MouseListener (5) MouseAdapter

MouseMotionListener (2) MouseMotionAdapter

KeyListener (3) KeyAdapter

FocusListener (2) FocusAdapter

14

Download Useful Materials from Rejinpaul.com


www.rejinpaul.com
www.rejinpaul.com
The values in the parentheses indicate the abstract methods available in the listener interface.
Steps to perform Event Handling
Following steps are required to perform event handling:
1. Implement the Listener interface and overrides its methods
2. Register the component with the Listener
For registering the component with the Listener, many classes provide the registration methods. For example:
o Button
o public void addActionListener(ActionListener a){}
o MenuItem
o public void addActionListener(ActionListener a){}
o TextField
o public void addActionListener(ActionListener a){}
o public void addTextListener(TextListener a){}
o TextArea
o public void addTextListener(TextListener a){}
o Checkbox
o public void addItemListener(ItemListener a){}
o Choice
o public void addItemListener(ItemListener a){}
o List
o public void addActionListener(ActionListener a){}
o public void addItemListener(ItemListener a){}
Difference between AWT and Swing:
There are many differences between java awt and swing that are given below.

No. Java AWT(Abstract Window Toolkit) Java Swing

1) AWT components are platform-dependent. Java swing components are platform-


independent.

2) AWT components are heavyweight. Swing components are lightweight.

3) AWT doesn't support pluggable look and feel. Swing supports pluggable look and
feel.

4) AWT provides less components than Swing. Swing provides more powerful
componentssuch as tables, lists,
scrollpanes, colorchooser, tabbedpane
etc.

5) AWT doesn't follows MVC(Model View Controller) Swing follows MVC.


where model represents data, view represents
presentation and controller acts as an interface between
model and view.
awt.event class:
15

Download Useful Materials from Rejinpaul.com


www.rejinpaul.com
www.rejinpaul.com

public abstract interface KeyListener extends java.util.EventListener {


//
Public Instance Methods
public abstract void keyPressed (KeyEvent e);
public abstract void keyReleased (KeyEvent e);
public abstract void keyTyped (KeyEvent e);
}
public abstract interface MouseListener extends java.util.EventListener {
// Public Instance Methods
public abstract void mouseClicked (MouseEvent e);
public abstract void mouseEntered (MouseEvent e);
public abstract void mouseExited (MouseEvent e);
public abstract void mousePressed (MouseEvent e);
public abstract void mouseReleased (MouseEvent e);
}

16

Download Useful Materials from Rejinpaul.com


www.rejinpaul.com
www.rejinpaul.com

public abstract interface MouseMotionListener extends java.util.EventListener {


// Public Instance Methods
public abstract void mouseDragged (MouseEvent e);
public abstract void mouseMoved (MouseEvent e);
}

public abstract interface TextListener extends java.util.EventListener {


// Public Instance Methods
public abstract void textValueChanged (TextEvent e);
}

public abstract interface WindowListener extends java.util.EventListener {


// Public Instance Methods
public abstract void windowActivated (WindowEvent e);
public abstract void windowClosed (WindowEvent e);
public abstract void windowClosing (WindowEvent e);
public abstract void windowDeactivated (WindowEvent e);
public abstract void windowDeiconified (WindowEvent e);
public abstract void windowIconified (WindowEvent e);
public abstract void windowOpened (WindowEvent e);
}
Program for mouselistener:
import java.applet.Applet;
import java.awt.*;
import java.awt.event.*;
/*<applet code="AppletMouseListener.class" width="300" height="300">
</applet>*/
public class AppletMouseListener extends Applet implements MouseListener
{
String str="";
// init() in place of frame constructor
public void init()
{
addMouseListener(this);
}
// override all the 5 abstract methods of MouesListener
public void mousePressed(MouseEvent e)
{
str = "You pressed mouse";

17

Download Useful Materials from Rejinpaul.com


www.rejinpaul.com
www.rejinpaul.com

repaint();
}
public void mouseReleased(MouseEvent e)
{
str = "You released mouse";
repaint();
}
public void mouseClicked(MouseEvent e)
{
str = "You clicked mouse";
repaint();
}
public void mouseEntered(MouseEvent e)
{
str = "Mouse entered frame";
repaint();
}
public void mouseExited(MouseEvent e)
{
str = "Mouse existed frame";
repaint();
}
// write paint() method to draw on applet window
public void paint(Graphics g)
{
g.drawString(str, 75, 150);
}
}
Example Programs:
1.Counter example:
import java.awt.*;
import java.awt.event.*;
public class Countdown extends Frame implements ActionListener
{
TextField tf;
Label l;
Button b;
int count=80;
public void countFrame()
{
tf=new TextField();
tf.setBounds(30,30,30,30);
tf.setEditable(false);
18

Download Useful Materials from Rejinpaul.com


www.rejinpaul.com
www.rejinpaul.com

l=new Label("Counter");
l.setBounds(20,20,20,20);

b=new Button("Count");
b.setBounds(40,40,40,40);
b.addActionListener(this);

add(l);

add(tf);
add(b);
tf.setText(count + "");

setSize(300,200);
setVisible(true);
setLayout(new FlowLayout());
setTitle("AWT Counter");
}
public void actionPerformed(ActionEvent ae)
{
count--;
tf.setText(count + "");
}

public static void main(String args[])


{
Countdown cd=new Countdown();
cd.countFrame();
}
}
Output:

19

Download Useful Materials from Rejinpaul.com


www.rejinpaul.com
www.rejinpaul.com

LayoutManagers:
The LayoutManagers are used to arrange components in a particular manner. LayoutManager is an interface
that is implemented by all the classes of layout managers. There are following classes that represents the layout
managers:
1. java.awt.BorderLayout
2. java.awt.FlowLayout
3. java.awt.GridLayout
4. java.awt.CardLayout
5. java.awt.GridBagLayout
BorderLayout:
The BorderLayout is used to arrange the components in five regions: north, south, east, west and center. Each
region (area) may contain one component only. It is the default layout of frame or window. The BorderLayout
provides five constants for each region:
1. public static final int NORTH
2. public static final int SOUTH
3. public static final int EAST
4. public static final int WEST
5. public static final int CENTER
Constructors of BorderLayout class:
 BorderLayout(): creates a border layout but with no gaps between the components.
 JBorderLayout(int hgap, int vgap): creates a border layout with the given horizontal and
vertical gaps between the components.

Example program:

import java.awt.*;
import javax.swing.*;

public class Border {


JFrame f;
Border(){
f=new JFrame();

JButton b1=new JButton("NORTH");;


JButton b2=new JButton("SOUTH");;
JButton b3=new JButton("EAST");;
JButton b4=new JButton("WEST");;
JButton b5=new JButton("CENTER");;

f.add(b1,BorderLayout.NORTH);
f.add(b2,BorderLayout.SOUTH);
f.add(b3,BorderLayout.EAST);
f.add(b4,BorderLayout.WEST);
f.add(b5,BorderLayout.CENTER);

f.setSize(300,300);
20

Download Useful Materials from Rejinpaul.com


www.rejinpaul.com
www.rejinpaul.com
f.setVisible(true);
}
public static void main(String[] args) {
new Border();
}
}

OUTPUT:

GridLayout
The GridLayout is used to arrange the components in rectangular grid. One component is displayed in each
rectangle.
Constructors of GridLayout class:
1. GridLayout(): creates a grid layout with one column per component in a row.
2. GridLayout(int rows, int columns): creates a grid layout with the given rows and columns but no gaps
between the components.
3. GridLayout(int rows, int columns, int hgap, int vgap): creates a grid layout with the given rows and
columns alongwith given horizontal and vertical gaps.
Example Program:
import java.awt.*;
import javax.swing.*;

public class MyGridLayout{


JFrame f;
MyGridLayout(){
f=new JFrame();

JButton b1=new JButton("1");


JButton b2=new JButton("2");
JButton b3=new JButton("3");
JButton b4=new JButton("4");
JButton b5=new JButton("5");
JButton b6=new JButton("6");
JButton b7=new JButton("7");
21

Download Useful Materials from Rejinpaul.com


www.rejinpaul.com
www.rejinpaul.com
JButton b8=new JButton("8");
JButton b9=new JButton("9");

f.add(b1);f.add(b2);f.add(b3);f.add(b4);f.add(b5);
f.add(b6);f.add(b7);f.add(b8);f.add(b9);

f.setLayout(new GridLayout(3,3));
//setting grid layout of 3 rows and 3 columns

f.setSize(300,300);
f.setVisible(true);
}
public static void main(String[] args) {
new MyGridLayout();
}
}

OUTPUT:

FlowLayout
The FlowLayout is used to arrange the components in a line, one after another (in a flow). It is the default
layout of applet or panel.
Fields of FlowLayout class:
1. public static final int LEFT
2. public static final int RIGHT
3. public static final int CENTER
4. public static final int LEADING
5. public static final int TRAILING
Constructors of FlowLayout class:
22

Download Useful Materials from Rejinpaul.com


www.rejinpaul.com
www.rejinpaul.com

1. FlowLayout(): creates a flow layout with centered alignment and a default 5 unit horizontal and vertical
gap.
2. FlowLayout(int align): creates a flow layout with the given alignment and a default 5 unit horizontal
and vertical gap.
3. FlowLayout(int align, int hgap, int vgap): creates a flow layout with the given alignment and the
given horizontal and vertical gap.
Example program:
import java.awt.*;
import javax.swing.*;

public class MyFlowLayout{


JFrame f;
MyFlowLayout(){
f=new JFrame();

JButton b1=new JButton("1");


JButton b2=new JButton("2");
JButton b3=new JButton("3");
JButton b4=new JButton("4");
JButton b5=new JButton("5");

f.add(b1);f.add(b2);f.add(b3);f.add(b4);f.add(b5);

f.setLayout(new FlowLayout(FlowLayout.RIGHT));
//setting flow layout of right alignment

f.setSize(300,300);
f.setVisible(true);
}
public static void main(String[] args) {
new MyFlowLayout();
}
}
OUTPUT:

23

Download Useful Materials from Rejinpaul.com


www.rejinpaul.com
www.rejinpaul.com

24

Download Useful Materials from Rejinpaul.com


www.rejinpaul.com
www.rejinpaul.com

Servlet – life cycle of a servlet. The Servlet API, Handling HTTP Request and Response, using
Cookies, Session Tracking. Introduction to JSP.

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.)
Application:
 Search Engines
 E-Commerce Applications
 Shopping Carts
 Product Catalogs
 Intranet Applications
 Groupware Applications: – bulletin boards – file sharing
Servlets vs CGI:

Benefits of Java Servlets:


 Performance:–
The performance of servlets is superior to CGI because there is no process creation for
each client request.
1

Download Useful Materials from Rejinpaul.com


www.rejinpaul.com
www.rejinpaul.com

Each request is handled by the servlet container process.


After a servlet has completed processing a request, it stays resident in memory, waiting
for another request.
 Portability:–
Like other Java technologies, servlet applications are portable.
 Rapid development cycle
–As a Java technology, servlets have access to the rich Java library that will help speed
up the development process.
 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.
Servlet Container Architecture:

Servlet Workflow Diagram:

Download Useful Materials from Rejinpaul.com


www.rejinpaul.com
www.rejinpaul.com

Servlet Life Cycle:

 When a servlet is FIRST requested, it is loaded into the servlet engine. The init() method of
the servlet is invoked so that the servlet may initialize itself.
 Once initialization is complete, the request is then forwarded to the appropriate method (ie.
doGet or doPost)
 The servlet is then held in memory. Subsequent requests are simply forwarded to the servlet
object.
 When the engine wishes to remove the servlet, its destroy() method is invoked.
 Servlets can receive multiple requests for multiple clients at any given time. Therefore,
servlets must be thread safe
The life cycle methods are
 void init(ServletConfig config)
–Initializes the servlet.
 void service(ServletRequest req, ServletResponse res)
–Carries out a single request from the client.
 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.
Servlet API:
Every servlet must implement javax.servlet.Servlet interface
 Most servlets implement the interface by extending one of these classes
–javax.servlet.GenericServlet
–javax.servlet.http.HttpServlet

Download Useful Materials from Rejinpaul.com


www.rejinpaul.com
www.rejinpaul.com

Generic Servlet & HTTP Servlet

Interface javax.servlet.Servlet
 The Servlet interface defines methods
–to initialize a servlet
– to receive and respond to client requests
–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.
 Developers need to directly implement this interface only if their servlets cannot (or choose
not to) inherit from GenericServlet or HttpServlet.
GenericServlet – Methods
void init(ServletConfig config)
–Initializes the servlet.
• void service(ServletRequest req, ServletResponse res)
–Carries out a single request from the client.
•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

Download Useful Materials from Rejinpaul.com


www.rejinpaul.com
www.rejinpaul.com

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
Servlet Request Objects:
provides client request information to a servlet.
•the servlet container creates a servlet request object and passes it as an argument to the servlet's
service method.
•the ServletRequest interface define methods to retrieve data sent as client request:
–parameter name and values
– attributes
– input stream
•HTTPServletRequest extends the ServletRequest interface to provide request information for
HTTP servlets
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.
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\this 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.

Servlet Response Objects:


Defines an object to assist a servlet in sending a response to the client.

Download Useful Materials from Rejinpaul.com


www.rejinpaul.com
www.rejinpaul.com

 The servlet container creates a ServletResponse object and passes it as an argument to the
servlet's service method.
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
Example Program for Servlet:
ServletExample.java
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import java.util.*;

public class ServletExample extends HttpServlet


{
public void doGet(HttpServletRequest req,HttpServletResponse res)throws IOException
{
res.setContentType("text/html");
PrintWriter out=res.getWriter();

out.println("<html>");
out.println("<head>");
out.println("<title>Servlet Example</title>");
out.println("</head>");
out.println("<body>");
out.println("<h3>Welcome to Servlet</h3>");
out.println("Time:"+(new Date()).toLocaleString());
out.println("</body>");
out.println("</html>");
}

}
Web.xml
<servlet>
<servlet-name>Example</servlet-name>
<servlet-class>ServletExample</servlet-class>
</servlet>
6

Download Useful Materials from Rejinpaul.com


www.rejinpaul.com
www.rejinpaul.com

<servlet-mapping>
<servlet-name>Example</servlet-name>
<url-pattern>/servletexample</url-pattern>
</servlet-mapping>
OUTPUT:

Web Client Session Tracking:


 The HttpSession object can hold a session id that can be used to identify whether the requests
are within the same session so that they can share the same data.
 Each HttpSession object represents a single user HTTP session.
 Mechanisms for session maintenance:
–Cookies
–URL Rewriting
–Hidden Form fields
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 client’s 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 client’s browser.

 Gmail uses cookies for login


 A cookie has a name, a single value, and optional attributes such as a comment, path and
domain qualifiers, a maximum age, and a version number.

Types of Cookie:

Download Useful Materials from Rejinpaul.com


www.rejinpaul.com
www.rejinpaul.com

There are 2 types of cookies in servlets.


1. Non-persistent cookie-It is valid for single session only. It is removed each time when
user closes the browser.
2. Persistent cookie-It is valid for multiple session . It is not removed each time when user
closes the browser. It is removed only if user logout or signout.

Advantage of Cookies:
1. Simplest technique of maintaining the state.
2. Cookies are maintained at client side.

Disadvantage of Cookies:
1. It will not work if cookie is disabled from the browser.
2. Only textual information can be set in Cookie object.

Cookie class:
javax.servlet.http.Cookie class provides the functionality of using cookies. It provides a
lot of useful methods for cookies.

Constructor of Cookie class:


Constructor Description
Cookie() constructs a cookie.
Cookie(String name, String constructs a cookie with a specified name
value) and value.

Useful Methods of Cookie class:


There are given some commonly used methods of the Cookie class.
Method Description
public void setMaxAge(int Sets the maximum age of the cookie in seconds.
expiry)
public String getName() Returns the name of the cookie. The name cannot be changed
after creation.
public String getValue() Returns the value of the cookie.
public void setName(String changes the name of the cookie.
name)
public void setValue(String changes the value of the cookie.
value)

Download Useful Materials from Rejinpaul.com


www.rejinpaul.com
www.rejinpaul.com

Example Program for cookies:


Myexample.html
<form action="servlet1" method="post">
Name:<input type="text" name="userName"/><br/>
<input type="submit" value="go"/>
</form>
FirstServlet.java

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

public class FirstServlet extends HttpServlet {

public void doPost(HttpServletRequest request, HttpServletResponse response){


try{

response.setContentType("text/html");
PrintWriter out = response.getWriter();

String n=request.getParameter("userName");
out.print("Welcome "+n);

Cookie ck=new Cookie("uname",n);//creating cookie object


response.addCookie(ck);//adding cookie in the response

//creating submit button


out.print("<form action='servlet2'method='get'>");
out.print("<input type='submit' value='go'>");
out.print("</form>");

out.close();

}catch(Exception e){System.out.println(e);}
}
}

Download Useful Materials from Rejinpaul.com


www.rejinpaul.com
www.rejinpaul.com

SecondServlet.java

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

public class SecondServlet extends HttpServlet {

public void doPost(HttpServletRequest request, HttpServletResponse response){


try{

response.setContentType("text/html");
PrintWriter out = response.getWriter();

Cookie ck[]=request.getCookies();
out.print("Hello "+ck[0].getValue());

out.close();

}catch(Exception e){System.out.println(e);}
}

}
web.xml
<web-app>
<servlet>
<servlet-name>s1</servlet-name>
<servlet-class>FirstServlet</servlet-class>
</servlet>

<servlet-mapping>
<servlet-name>s1</servlet-name>
<url-pattern>/servlet1</url-pattern>
</servlet-mapping>

<servlet>
<servlet-name>s2</servlet-name>
<servlet-class>SecondServlet</servlet-class>

10

Download Useful Materials from Rejinpaul.com


www.rejinpaul.com
www.rejinpaul.com

</servlet>

<servlet-mapping>
<servlet-name>s2</servlet-name>
<url-pattern>/servlet2</url-pattern>
</servlet-mapping>

</web-app>

OUTPUT:

11

Download Useful Materials from Rejinpaul.com


www.rejinpaul.com
www.rejinpaul.com

Introduction to JSP

JSP technology is used to create web application. It focuses more on presentation logic of the
web apllication.JSP pages are easier to maintain then a Servlet. JSP pages are opposite of
Servlets. Servlet adds HTML code inside Java code while JSP adds Java code inside HTML.
Everything a Servlet can do, a JSP page can also do it.

JSP enables us to write HTML pages containing tags that run powerful Java programs. JSP
separates presentation and business logic as Web designer can design and update JSP pages
without learning the Java language and Java Developer can also write code without concerning
the web design.
JSP Life Cycle:
JSP pages are converted into Servlet by the Web Container. The Container translates a JSP page
into servletclass source(.java) file and then compiles into a Java Servlet class.

The jspInit() – This method is executed first after the JSP is loaded. – The jspInit() is only called
once during any JSP component life time. –The jspInit() – <%!public void jspinit(){}%>
_jspService() – This method is executed for processing client request and send the response back
to client.
jspDestroy() – This method is executed to destroy the JSP object
JSP Elements:
Besides HTML tag elements, JSP provides four basic categories of constructors (markup tags):
directives, scripting elements, standard actions, and comments.
JSP Syntax

12

Download Useful Materials from Rejinpaul.com


www.rejinpaul.com
www.rejinpaul.com

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.
The page Directive:
<%@ page import="package.class" %>
• <%@ page import="java.util.*" %>
• <%@ page contentType="text/html" %>
– <% response.setContentType("text/html"); %>
The include Directive:
The include directive is used to include a file during the translation phase. This directive tells the
container to merge the content of other external files with the current JSP during the translation
phase. You may include directives anywhere in your JSP page.
The general usage form of this directive is as follows:
<%@ include file="relative url" >
The taglib Directive:
The taglib directive declares that your JSP page uses a set of custom tags, identifies the location
of the library, and provides a means for identifying the custom tags in your JSP page.
The taglib directive follows the following syntax:
<%@ taglib uri="uri" prefix="prefixOfTag" >
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
13

Download Useful Materials from Rejinpaul.com


www.rejinpaul.com
www.rejinpaul.com

<%! Java Code %>


Example:
<%! int i=0; Double d; %>
Expression Element:
expressions are used to display simple values of variables or return values of shared data by
invoking a bean's getter methods.
Syntax : <%= expr %> // No semicolon
<%= i * j + k %>
<%= new java.util.Date() %> // To display Date & Time
Scriptlet Element:
JSP scriptlets are embedded within <% ... %> tags. They are executed at the runtime.
<% Java code %>
<% for (int i=1; i<=4; i++) { %>
The counter is now <% = i %>
• <% } %>

14

Download Useful Materials from Rejinpaul.com


www.rejinpaul.com
www.rejinpaul.com

UNIT V XML AND WEB SERVICES 9


Xml – Introduction-Form Navigation-XML Documents- XSL – XSLT- Web services-UDDI-WSDL-Java
web services – Web resources.

WEB SERVICES:
Definition: Web services are XML-based information exchange systems that use the Internet for direct
application-to-application interaction. These systems can include programs, objects, messages, or
documents.
Properties:
Web service,
 Is available over the Internet or private (intranet) networks
 Uses a standardized XML messaging system
 Is not tied to any one operating system or programming language
 Is self-describing via a common XML grammar
 Is discoverable via a simple find mechanism
Characteristics:
 XML-Based
 Loosely Coupled
 Coarse-Grained
 Ability to be Synchronous or Asynchronous
 Supports Remote Procedure Calls(RPCs)
 Supports Document Exchange
Components of Web Services:
The basic web services platform is XML + HTTP. All the standard web services work using the following
components
 SOAP (Simple Object Access Protocol)
 UDDI (Universal Description, Discovery and Integration)
 WSDL (Web Services Description Language)
Working Steps of Web Service:
A web service enables communication among various applications by using open standards such as HTML,
XML, WSDL, and SOAP. A web service takes the help of:
 XML to tag the data
 SOAP to transfer a message
 WSDL to describe the availability of service.
Can able to build a Java-based web service on Solaris that is accessible from Visual Basic program that runs
on Windows.
www.rejinpaul.com
www.rejinpaul.com

WSDL:
Web Services Description Language (WSDL) is a format for describing a Web Services interface. It is a
way to describe services and how they should be bound to specific network addresses. WSDL has three
parts:
 Definitions
 Operations
 Service bindings
Definitions are generally expressed in XML and include both data type definitions and message definitions
that use the data type definitions. These definitions are usually based upon some agreed upon XML
vocabulary.
Operations describe actions for the messages supported by a Web service. There are four types of
operations:
 One-way: Messages sent without a reply required
 Request/response: The sender sends a message and the received sends a reply.
 Solicit response: A request for a response. (The specific definition for this action is pending.)
 Notification: Messages sent to multiple receivers. (The specific definition for this action is pending.)
Operations are grouped into port types. Port types define a set of operations supported by the Web service.
Service bindings connect port types to a port. A port is defined by associating a network address with a port
type. A collection of ports defines a service. This binding is commonly created using SOAP, but other forms
may be used. These other forms could include CORBA Internet Inter-ORB Protocol (IIOP), DCOM, .NET,
Java Message Service (JMS), or WebSphere MQ to name a few.
The following figure shows the relationship of the basic parts of WSDL:

The following figure illustrates the use of WSDL. At the left is a service provider. At the right is a service
consumer. The steps involved in providing and consuming a service are:
1. A service provider describes its service using WSDL. This definition is published to a repository of
services. The repository could use Universal Description, Discovery, and Integration (UDDI). Other
forms of directories could also be used.
2. A service consumer issues one or more queries to the repository to locate a service and determine
how to communicate with that service.
3. Part of the WSDL provided by the service provider is passed to the service consumer. This tells the
service consumer what the requests and responses are for the service provider.
4. The service consumer uses the WSDL to send a request to the service provider.
5. The service provider provides the expected response to the service consumer.
www.rejinpaul.com
www.rejinpaul.com

UDDI:
UDDI is based on a common set of industry standards, including HTTP, XML, XML Schema, and SOAP. It
provides an infrastructure for a Web Services-based software environment for both publicly available
services and services only exposed internally within an organization. The UDDI Business Registry system
consists of three directories:
 UDDI white pages: basic information such as a company name, address, and phone numbers, as well
as unique identifiers for the company tax IDs. This information allows others to discover web
service based upon business identification.
 UDDI yellow pages: detailed business data, organized by relevant business classifications. Yellow
pages uses commonly accepted industrial categorization schemes, industry codes, product codes,
business identification codes and the like to make it easier for companies to search through the
listings and find exactly what they want
 UDDI green pages: Green pages contain technical information about a web service. A green page
allows someone to bind to a Web service after it's been found. Also information about a company's
key business processes, such as operating platform, supported programs, purchasing methods,
shipping and billing requirements, and other higher-level business protocols.
The figure shows the invocation pattern:
www.rejinpaul.com
www.rejinpaul.com

UDDI Roles and Operations:


Service Registry:
Provides support for publishing and locating services like telephone yellow pages.
Service Provider:
Provides e-business services, and publishes these services through a registry.
Service Requestor:
Finds required services via the service broker. Binds to services via service provider.
The UDDI v3 specification defines 9 APIs:
1. UDDI_Security_PortType, defines the API to obtain a security token. With a valid security token a
publisher can publish to the registry. A security token can be used for the entire session.
2. UDDI_Publication_PortType, defines the API to publish business and service information to the
UDDI registry.
3. UDDI_Inquiry_PortType, defines the API to query the UDDI registry. Typically this API does not
require a security token.
4. UDDI_CustodyTransfer_PortType, this API can be used to transfer the custody of a business from
one UDDI node to another.
5. UDDI_Subscription_PortType, defines the API to register for updates on a particular business of
service.
6. UDDI_SubscriptionListener_PortType, defines the API a client must implement to receive
subscription notifications from a UDDI node.
7. UDDI_Replication_PortType, defines the API to replicate registry data between UDDI nodes.
8. UDDI_ValueSetValidation_PortType, by nodes to allow external providers of value set validation.
Web services to assess whether keyedReferences or keyedReferenceGroups are valid.
9. UDDI_ValueSetCaching_PortType, UDDI nodes may perform validation of publisher references
themselves using the cached values obtained from such a Web service.
www.rejinpaul.com
www.rejinpaul.com
SOAP:
SOAP provides the envelope for sending Web Services messages over the Internet/Internet. It is part of the
set of standards specified by the W3C. SOAP is an alternative to Representational State Transfer (REST)
and JavaScript Object Notation (JSON).
SOAP Building Blocks
A SOAP message is an ordinary XML document containing the following elements:
 An Envelope element that identifies the XML document as a SOAP message
 A Header element that contains header information
 A Body element that contains call and response information
 A Fault element containing errors and status information
SOAP commonly uses HTTP, but other protocols such as Simple Mail Transfer Protocol (SMTP) may be
used. SOAP can be used to exchange complete documents or to call a remote procedure.
 SOAP stands for Simple Object Access Protocol
 SOAP is an application communication protocol
 SOAP is a format for sending and receiving messages
 SOAP is platform independent
 SOAP is based on XML
 SOAP is a W3C recommendation
Why SOAP?
It is important for web applications to be able to communicate over the Internet.
The best way to communicate between applications is over HTTP, because HTTP is supported by all
Internet browsers and servers. SOAP was created to accomplish this.
SOAP provides a way to communicate between applications running on different operating systems,
with different technologies and programming languages.

The SOAP envelope contains two parts:


1. An optional header providing information on authentication, encoding of data, or how a recipient of
a SOAP message should process the message.
2. The body that contains the message. These messages can be defined using the WSDL specification.
SOAP Binding
The SOAP specification defines the structure of the SOAP messages, not how they are exchanged. This gap
is filled by what is called "SOAP Bindings". SOAP bindings are mechanisms which allow SOAP messages
to be effectively exchanged using a transport protocol.
Most SOAP implementations provide bindings for common transport protocols, such as HTTP or SMTP.
HTTP is synchronous and widely used. A SOAP HTTP request specifies at least two HTTP headers:
Content-Type and Content-Length.
SMTP is asynchronous and is used in last resort or particular cases.
Java implementations of SOAP usually provide a specific binding for the JMS (Java Messaging System)
protocol
www.rejinpaul.com
www.rejinpaul.com
Syntax Rules
Here are some important syntax rules:
 A SOAP message MUST be encoded using XML
 A SOAP message MUST use the SOAP Envelope namespace
 A SOAP message MUST use the SOAP Encoding namespace
 A SOAP message must NOT contain a DTD reference
 A SOAP message must NOT contain XML Processing Instructions

<?xml version="1.0"?>

<soap:Envelope
xmlns:soap="http://www.w3.org/2003/05/soap-envelope/"
soap:encodingStyle="http://www.w3.org/2003/05/soap-encoding">
...
Message information goes here
...
</soap:Envelope>
Advantages of Soap Web Services:

WS Security: SOAP defines its own security known as WS Security.


Language and Platform independent: SOAP web services can be written in any programming language
and executed in any platform.

Disadvantages of Soap Web Services:

Slow: SOAP uses XML format that must be parsed to be read. It defines many standards that must be
followed while developing the SOAP applications. So it is slow and consumes more bandwidth and
resource.
WSDL dependent: SOAP uses WSDL and doesn't have any other mechanism to discover the service.

SOAP and Web Services

A SOAP Example Program:


In the example below, a GetStockPrice request is sent to a server. The request has a StockName parameter,
and a Price parameter that will be returned in the response. The namespace for the function is defined in
"http://www.example.org/stock".
www.rejinpaul.com
www.rejinpaul.com
A SOAP request:
POST /InStock HTTP/1.1
Host: www.example.org
Content-Type: application/soap+xml; charset=utf-8
Content-Length: nnn

<?xml version="1.0"?>

<soap:Envelope
xmlns:soap="http://www.w3.org/2003/05/soap-envelope/"
soap:encodingStyle="http://www.w3.org/2003/05/soap-encoding">

<soap:Body xmlns:m="http://www.example.org/stock">
<m:GetStockPrice>
<m:StockName>IBM</m:StockName>
</m:GetStockPrice>
</soap:Body>

</soap:Envelope>

The SOAP response:


HTTP/1.1 200 OK
Content-Type: application/soap+xml; charset=utf-8
Content-Length: nnn

<?xml version="1.0"?>

<soap:Envelope
xmlns:soap="http://www.w3.org/2003/05/soap-envelope/"
soap:encodingStyle="http://www.w3.org/2003/05/soap-encoding">

<soap:Body xmlns:m="http://www.example.org/stock">
<m:GetStockPriceResponse>
<m:Price>34.5</m:Price>
</m:GetStockPriceResponse>
</soap:Body>

</soap:Envelope>
www.rejinpaul.com
www.rejinpaul.com
JAVA WEB SERVICES:

Java web service application perform communication through WSDL (Web Services Description
Language). There are two ways to write java web service application code: SOAP and RESTful.
Java Web Services API
There are two main API's defined by Java for developing web service applications since JavaEE 6.
1) JAX-WS: for SOAP web services. The are two ways to write JAX-WS application code: by RPC style
and Document style.
2) JAX-RS: for RESTful web services. There are mainly 2 implementation currently in use for creating
JAX-RS application: Jersey and RESTeasy.

There are many difference between these two style of web services e.g. SOAP take morebandwidth because
of heavy weight XML based protocol but REST takes less bandwidth because of popular use of JSON as
message protocol and leveraging HTTP method to define action. This also means that REST is faster than
SOAP based web services. You can derive many differences between SOAP and RESTful with the fact that
its HTTP based e.g. REST URLs can be cached or bookmarked.
JAVA-WS API:
There are two ways to develop JAX-WS example.
1. RPC style
2. Document style

Document Style Vs RPC Style


The Document style indicates that the SOAP body contains a XML document which can be validated
against pre-defined XML schema document.
RPC indicates that the SOAP message body contains an XML representation of a method call and uses the
names of the method and its parameters to generate XML structures that represent a method’s call stack. The
document/literal approach is easier because it simply relies on XML Schema to describe exactly what the
SOAP message looks like while transmission.
www.rejinpaul.com
www.rejinpaul.com
What is SOAP Encoding and Literal?
SOAP Encoding indicates how a data value should be encoded in an XML format. SOAP Encoding is an
extension of the SOAP framework. SOAP encoding offers rules to convert any data value defined in SOAP
data model into XML format.

What is Literal?
In simplest definition, literal it means that the data is serialized according to a schema

Different styles of combination:


Document/literal
Document/encoded
RPC/literal
RPC/encoded

JAVA-RS API:

There are two main implementation of JAX-RS API.


1. Jersey
2. RESTEasy

What is REST?
REST is an architectural style of developing web services which take advantage of ubiquity of HTTP
protocol and leverages HTTP method to define actions. REST stands for REpresntational State Transfer.

What is RESTFul Web Service?


There are two popular way to develop web services, using SOAP (Simple Object Access Protocol) which is
XML based way to expose web services and second REST based web services which uses HTTP protocol.
Web services developed using REST style is also known as RESTful web services.

What do you understand by payload in RESTFul?


Payload means data which passed inside request body also payload is not request parameters. So only you
can do payload in POST and not in GET and DELTE method.

Jersey:
Jersey RESTful Web Services framework is open source, production quality, framework for developing
RESTful Web Services in Java that provides support for JAX-RS APIs and serves as a JAX-RS (JSR 311 &
JSR 339) Reference Implementation.
Jersey framework is more than the JAX-RS Reference Implementation. Jersey provides its own API that
extend the JAX-RS toolkit with additional features and utilities to further simplify RESTful service and
client development.
www.rejinpaul.com
www.rejinpaul.com

RESTEasy:

RESTEasy is the JAX-RS implementation provided by JBoss project. Can use RESTEasy to create restful
web services. RESTEasy provides tighter integration with the JBoss Application Server but can deploy it on
any servlet container.

Some of the features of RESTEasy framework are:

 JAX-RS API compliant – so mostly there is a need to plug it with JAX-RS API coding to create rest
web services.

 Runs on almost any servlet container supporting Java 6 or higher

 Provides support for writing client programs using JAX-RS 2.0 client API.

 Rich set of providers – XML, JSON, YAML, Multipart, XOP, Atom, etc.

 OAuth2 and Distributed SSO with JBoss AS7

 EJB, Seam, Guice, Spring, and Spring MVC integration


www.rejinpaul.com
www.rejinpaul.com
XML:
Definition:
XML is a meta-language: a language that allows us to create or define other languages. eg: MathML.
XML stands for EXtensible Markup Language.
XML was designed to store and transport data.
XML was designed to be both human- and machine-readable.
XML was designed to be self-descriptive
XML is a W3C Recommendation
The Difference Between XML and HTML:

Xml html
XML was designed to carry HTML was designed to
data - with focus on what data display data - with focus on
is how data looks
data-description language. presentation language,
self-describing not self-describing
user defined tags no pre
use only pre defined tags
defined tags
tree structured not structured
Extendible Non extendible
XML is case sensitive. HTML is not case sensitive.
HTML does not preserve
XML preserve whitespaces.
whitespaces.
XML provides a framework HTML is a markup
to define markup languages. language itself.
XML makes it mandatory to In HTML, it is not necessary
use a closing tag. to use a closing tag.

The logical structure of an XML document.

Syntax:
<root>
<child>
<subchild>.....</subchild>
</child>
</root>
www.rejinpaul.com
www.rejinpaul.com
A prolog defines the XML version and the character encoding.
<?xml version="1.0" encoding="UTF-8"?> -prolog
<bookstore> -root element
<book category="cooking"> -child of root, Category-attribute of book
<title lang="en">Everyday Italian</title>
<author>Giada De Laurentiis</author>
<year>2005</year>
<price>30.00</price>
</book>
</bookstore>

Syntax Rules:
 XML documents must contain one root element that is the parent of all other elements.
 The XML prolog is optional. If it exists, it must come first in the document.
 The XML prolog does not have a closing tag. This is not an error. The prolog is not a part of the
XML document.
 In XML, it is illegal to omit the closing tag. All elements must have a closing tag.
 XML tags are case sensitive. The tag <Letter> is different from the tag <letter>.
 In XML, all elements must be properly nested within each other. order is important.
 In XML, the attribute values must always be quoted.
 White-space is Preserved in XML.XML does not truncate multiple white-spaces .
 XML Stores New Line as LF
 Comments in XML-<!-- This is a comment -->
 Entity References-Some characters have a special meaning in XML.

 There are 5 pre-defined entity references in XML:



&lt; < less than

&gt; > greater than

&amp; & ampersand

&apos; ' apostrophe

&quot; " quotation mark

Eg: <message>salary &lt; 1000</message>


Well Formed XML:
XML documents that conform to the syntax rules above are said to be "Well Formed" XML documents.

XML Elements:
An XML element is everything from (including) the element's start tag to (including) the element's end tag.
An element can contain:
 text
 attributes
 other elements
 or a mix of the above
Empty XML Elements-An element with no content is said to be empty.<element></element> or</element>.
XML elements must follow these naming rules:
 Element names are case-sensitive
 Element names must start with a letter or underscore
 Element names cannot start with the letters xml (or XML, or Xml, etc)
 Element names can contain letters, digits, hyphens, underscores, and periods
 Element names cannot contain spaces
 no words are reserved (except xml).
www.rejinpaul.com
www.rejinpaul.com
XML Elements are Extensible.eg;<date> extended as <day>,<month>,<year>
XML Attributes
Attributes are designed to contain data related to a specific element. Attribute values must always be quoted.
Either single or double quotes can be used.
Avoid XML Attributes?
Some things to consider when using attributes are:
 attributes cannot contain multiple values (elements can)
 attributes cannot contain tree structures (elements can)
 attributes are not easily expandable (for future changes)

XML Attributes for Metadata- eg: id attribute. ID references are assigned to elements to refer elements.
XML Namespaces:
XML Namespaces provide a method to avoid element name conflicts.
Name Conflicts:
In XML, element names are defined by the developer. This often results in a conflict when trying to mix
XML documents from different XML applications.
Eg:
This XML carries HTML table information:
<table>
<tr>
<td>Apples</td>
<td>Bananas</td>
</tr>
</table>
This XML carries information about a table (a piece of furniture):
<table>
<name>African Coffee Table</name>
<width>80</width>
<length>120</length>
</table>
Name conflicts in XML can easily be avoided using a name prefix.
XML Namespaces - The xmlns Attribute
When using prefixes in XML, a namespace for the prefix must be defined.
The namespace can be defined by an xmlns attribute in the start tag of an element.
The namespace declaration has the following syntax. xmlns:prefix="URI".
Syntax:

Eg:
<root>

<h:table xmlns:h="http://www.w3.org/TR/html4/">
<h:tr>
<h:td>Apples</h:td>
<h:td>Bananas</h:td>
</h:tr>
</h:table>

<f:table xmlns:f="urn:Corp:furniture">
<f:name>African Coffee Table</f:name>
<f:width>80</f:width>
www.rejinpaul.com
www.rejinpaul.com
<f:length>120</f:length>
</f:table>
Default name space:
Defining a default namespace for an element saves us from using prefixes in all the child elements. It has the
following syntax:
xmlns="namespaceURI" i.e without arbitrary text string.
Eg:
<table xmlns="http://www.w3.org/TR/html4/">
<tr>
<td>Apples</td>
<td>Bananas</td>
</tr>
</table>
The purpose of using an URI is to give the namespace a unique name. URI represents nothing more than a
logical namespace name.

What is XML schema?


XML schema is a language which is used for expressing constraint about XML documents. There are so
many schema languages which are used now a day for example DTD,Relax- NG and XSD (XML schema
definition).
An XML schema is used to define the structure of an XML document. It is like DTD but provides more
control on XML structure.
Eg:
employee.xsd
<?xml version="1.0"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"
targetNamespace="http://www.javatpoint.com"
xmlns="http://www.javatpoint.com"
elementFormDefault="qualified">

<xs:element name="employee">
<xs:complexType>
<xs:sequence>
<xs:element name="firstname" type="xs:string"/>
<xs:element name="lastname" type="xs:string"/>
<xs:element name="email" type="xs:string"/>
</xs:sequence>
</xs:complexType>
</xs:element>

</xs:schema>
employee.xml
<?xml version="1.0"?>
<employee
xmlns="http://www.javatpoint.com"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.javatpoint.com employee.xsd">

<firstname>vimal</firstname>
<lastname>jaiswal</lastname>
<email>[email protected]</email>
</employee>
www.rejinpaul.com
www.rejinpaul.com
DTD:

What is DTD?

DTD stands for Document Type Definition. It defines the legal building blocks of an XML document. It is
used to define document structure with a list of legal elements and attributes.

Purpose of DTD:

Its main purpose is to define the structure of an XML document. It contains a list of legal elements and
define the structure with the help of them.

Eg:

employee.xml

<?xml version="1.0"?>

<!DOCTYPE employee SYSTEM "employee.dtd">

<employee>

<firstname>vimal</firstname>

<lastname>jaiswal</lastname>

<email>[email protected]</email>

</employee>

employee

employee.dtd

<!ELEMENT employee (firstname,lastname,email)>

<!ELEMENT firstname (#PCDATA)>

<!ELEMENT lastname (#PCDATA)>

<!ELEMENT email (#PCDATA)>

Description of DTD:

<!DOCTYPE employee : It defines that the root element of the document is employee.

<!ELEMENT employee: It defines that the employee element contains 3 elements "firstname, lastname and
email".

<!ELEMENT firstname: It defines that the firstname element is #PCDATA typed. (parse-able data type).

<!ELEMENT lastname: It defines that the lastname element is #PCDATA typed. (parse-able data type).

<!ELEMENT email: It defines that the email element is #PCDATA typed. (parse-able data type).

The important differences are given below:


www.rejinpaul.com
www.rejinpaul.com

No. DTD XSD


1) DTD stands for Document Type XSD stands for XML Schema Definition.
Definition.

2) DTDs are derived from SGML syntax. XSDs are written in XML.

3) DTD doesn't support datatypes. XSD supports datatypes for elements and attributes.

4) DTD doesn't support namespace. XSD supports namespace.

5) DTD doesn't define order for child XSD defines order for child elements.
elements.

6) DTD is not extensible. XSD is extensible.

7) DTD is not simple to learn. XSD is simple to learn because you don't need to learn
new language.

8) DTD provides less control on XML XSD provides more control on XML structure.
structure.

The difference between well-formed and valid XML is simple: Valid XML has a DTD associated with it
and has been verified against all the rules contained in the DTD in addition to being well-formed.
Merely well-formed XML, on the other hand, is not necessarily valid, although it may be.

CDATA

CDATA: (Unparsed Character data): CDATA contains the text which is not parsed further in an XML
document. Tags inside the CDATA text are not treated as markup and entities will not be expanded.Let's
take an example for CDATA:

<?xml version="1.0"?>

<!DOCTYPE employee SYSTEM "employee.dtd">

<employee>

<![CDATA[

<firstname>vimal</firstname>

<lastname>jaiswal</lastname>

<email>[email protected]</email>

]]>

</employee>

PCDATA

PCDATA: (Parsed Character Data): XML parsers are used to parse all the text in an XML document.
PCDATA stands for Parsed Character data. PCDATA is the text that will be parsed by a parser. Tags inside
the PCDATA will be treated as markup and entities will be expanded.
www.rejinpaul.com
www.rejinpaul.com
www.rejinpaul.com
www.rejinpaul.com

XSLT:
XSLT stands for Extensible Stylesheet Language Transformations. It is both a style sheet specification and a
kind of programming language that allows you to transform an XML document into the format of your
choice: stripped ASCII text, HTML, RTF, and even other dialects of XML.
XSLT transforms an XML source-tree into an XML result-tree.
What is XSLT?
 XSLT stands for XSL Transformations
 XSLT is the most important part of XSL
 XSLT transforms an XML document into another XML document
 XSLT uses XPath to navigate in XML documents
 XSLT is a W3C Recommendation

It Started with XSL


XSL stands for EXtensible Stylesheet Language. CSS is used to add styles to HTML elements. XSL
describes how the XML elements should be displayed.
XSL - More Than a Style Sheet Language
XSL consists of four parts:
 XSLT - a language for transforming XML documents
 XPath - a language for navigating in XML documents
 XSL-FO - a language for formatting XML documents (discontinued in 2013) replaced with CSS3.
 XQuery - a language for querying XML documents
Xpath:
XPath is a language for locating and processing nodes in an XML document. Because each XML document
is, by definition, a hierarchical structure, it becomes possible to navigate this structure in a logical, formal
way (i.e. by following a path).
XPath is used to navigate through elements and attributes in XML documents.

XQuery:
XQuery is designed to query XML data - not just XML files, but anything that can appear as XML,
including databases.

Work of XSLT: How does it Work?


In the transformation process, XSLT uses XPath to define parts of the source document that should match
one or more predefined templates. When a match is found, XSLT will transform the matching part of the
source document into the result document.
Declaration
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">

1. <xsl:template> Element
An XSL style sheet consists of one or more set of rules that are called templates. A template contains rules
to apply when a specified node is matched.
The <xsl:template> element is used to build templates.
The match attribute is used to associate a template with an XML element. The match attribute can also be
used to define a template for the entire XML document. The value of the match attribute is an XPath
expression (i.e. match="/" defines the whole document).
2. <xsl:value-of> Element
The <xsl:value-of> element is used to extract the value of a selected node and add it to the output stream
of the transformation. The value of the select attribute is an XPath expression.
3. The <xsl:for-each> Element
The <xsl:for-each> element allows to do looping in XSLT. The XSL <xsl:for-each> element can be used
to select every XML element of a specified node-set. The value of the select attribute is an XPath
www.rejinpaul.com
www.rejinpaul.com
expression. An XPath expression works like navigating a file system; where a forward slash (/) selects
subdirectories.
It is possible to filter the output from the XML file by adding a criterion to the select attribute in the
<xsl:for-each> element.
<xsl:for-each select="catalog/cd[artist='Bob Dylan']">
Legal filter operators are:
 = (equal)
 != (not equal)
 &lt; less than
 &gt; greater than
4. The <xsl:sort> Element
The <xsl:sort> element is used to sort the output. To sort the output, simply add an <xsl:sort>
element inside the <xsl:for-each> element in the XSL file. The select attribute indicates what XML
element to sort on.
5. The <xsl:if> Element:
To put a conditional if test against the content of the XML file, add an <xsl:if> element to the XSL
document.
Syntax:
<xsl:if test="expression">
...some output if the expression is true...
</xsl:if>
To add a conditional test, add the <xsl:if> element inside the <xsl:for-each> element in the XSL file.
6. The <xsl:choose> Element
Syntax:
<xsl:choose>
<xsl:when test="expression">
... some output ...
</xsl:when>
<xsl:otherwise>
... some output ....
</xsl:otherwise>
</xsl:choose>
To insert a multiple conditional test against the XML file, add the <xsl:choose>, <xsl:when>, and
<xsl:otherwise> elements to the XSL file.

XPATH :
Selecting Nodes
XPath uses path expressions to select nodes in an XML document. The node is selected by following a path
or steps. The most useful path expressions are listed below:
Expression Description

nodename Selects all nodes with the name "nodename"

/ Selects from the root node

// Selects nodes in the document from the current node that match the selection no matter
where they are

. Selects the current node

.. Selects the parent of the current node

@ Selects attributes
www.rejinpaul.com
www.rejinpaul.com
In the table below we have listed some path expressions and the result of the expressions:
Path Expression Result

bookstore Selects all nodes with the name "bookstore"

/bookstore Selects the root element bookstore


Note: If the path starts with a slash ( / ) it always represents an absolute path to an
element!

bookstore/book Selects all book elements that are children of bookstore

//book Selects all book elements no matter where they are in the document

bookstore//book Selects all book elements that are descendant of the bookstore element, no matter
where they are under the bookstore element

//@lang Selects all attributes that are named lang

Predicates:
Predicates are used to find a specific node or a node that contains a specific value.
Predicates are always embedded in square brackets.
In the table below we have listed some path expressions with predicates and the result of the expressions:
Path Expression Result

/bookstore/book[1] Selects the first book element that is the child of the bookstore
element.
Note: In IE 5,6,7,8,9 first node is[0], but according to W3C, it is [1].
To solve this problem in IE, set the SelectionLanguage to XPath:
In JavaScript: xml.setProperty("SelectionLanguage","XPath");

/bookstore/book[last()] Selects the last book element that is the child of the bookstore element

/bookstore/book[last()-1] Selects the last but one book element that is the child of the bookstore
element

/bookstore/book[position()<3] Selects the first two book elements that are children of the bookstore
element

//title[@lang] Selects all the title elements that have an attribute named lang

//title[@lang='en'] Selects all the title elements that have a "lang" attribute with a value of
"en"

/bookstore/book[price>35.00] Selects all the book elements of the bookstore element that have a price
element with a value greater than 35.00

/bookstore/book[price>35.00] Selects all the title elements of the book elements of the bookstore
/title element that have a price element with a value greater than 35.00
www.rejinpaul.com
www.rejinpaul.com
Selecting Unknown Nodes:
XPath wildcards can be used to select unknown XML nodes.
Wildcard Description

* Matches any element node

@* Matches any attribute node

node() Matches any node of any kind


In the table below listed some path expressions and the result of the expressions:
Path Expression Result

/bookstore/* Selects all the child element nodes of the bookstore element

//* Selects all elements in the document

//title[@*] Selects all title elements which have at least one attribute of any
kind

Selecting Several Paths:


By using the | operator in an XPath expression you can select several paths.
In the table below listed some path expressions and the result of the expressions:
Path Expression Result

//book/title | //book/price Selects all the title AND price elements of all book elements

//title | //price Selects all the title AND price elements in the document

/bookstore/book/title | //price Selects all the title elements of the book element of the bookstore
element AND all the price elements in the document

Example program:
First.xml
<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type="text/xsl" href="First.xsl"?>
<catalog>
<cd>
<title>programming languages</title>
<author>Ravi Sethi</author>
<country>India</country>
<company>Pearson</company>
<price>279</price>
<year>2012</year>
</cd>
<cd>
<title>Data mining</title>
<author>Han Kamber</author>
<country>UK</country>
<company>Elsevier</company>
<price>700</price>
<year>2000</year>
</cd>
<cd>
www.rejinpaul.com
www.rejinpaul.com
<title>Operating System</title>
<author>Silberschatz</author>
<country>USA</country>
<company>Wiley</company>
<price>500</price>
<year>2009</year>
</cd>
</catalog>

First.xsl
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">

<xsl:template match="/">
<html>
<body>
<h2>My Book Collection</h2>
<table border="1">
<tr bgcolor="#9acd32">
<th>Title</th>
<th>Author</th>
</tr>
<xsl:for-each select="catalog/cd">
<tr>
<td><xsl:value-of select="title"/></td>
<xsl:choose>
<xsl:when test="price &gt; 300">
<td bgcolor="#ff00ff">
<xsl:value-of select="author"/></td>
</xsl:when>
<xsl:otherwise>
<td><xsl:value-of select="author"/></td>
</xsl:otherwise>
</xsl:choose>
</tr>
</xsl:for-each>
</table>
</body>
</html>
</xsl:template>

</xsl:stylesheet>

You might also like