Professional Documents
Culture Documents
UNIT-1
HTML
WEB TECHNOLOGIES
INTRODUCTION TO HTML
HTML, or Hyper Text Markup Language is designed to specify the logical organisation of a document,
with important hypertext extensions.
HTML allows you to mark selections of text as titles or paragraphs, and then leaves the interpretation
of these marked elements up to the browser.
For example: one browser may indent the beginning of a paragraph, while another may only leave a
blank line.
HTML instructions divide the text of a document into blocks called elements.
These can be divided into two broad categories -- those that define how the BODY of the document is to
be displayed by the browser, and those that define information `about' the document, such as the title
or relationships to other documents. The detailed rules for HTML (the names of the tags/elements,
how they can be used) are defined using another language known as the standard generalized markup
language, or SGML. SGML is wickedly difficult, and was designed for massive document collections.
Fortunately, HTML is much simpler! However, SGML has useful features that HTML lacks. For this
reason, markup language and software experts have developed a new language, called XML (the
eXtensible markup language) which has most of the most useful features of HTML and SGML.
History of HTML
HTML was originally developed by Tim Berners-Lee while at CERN, and popularized by the Mosaic
browser developed at NCSA. During the course of the 1990s it has blossomed with the explosive growth
of the Web. During this time, HTML has been extended in a number of ways. The Web depends on Web
page authors and vendors sharing the same conventions for HTML. This has motivated joint work on
specifications for HTML.
HTML 2.0 (November 1995) was developed under the aegis of the Internet Engineering Task Force
(IETF) to codify common practice in late 1994.HTML 3.0 (1995) proposed much richer versions of
HTML. Achieving interoperability lowers costs to content providers since they must develop only one
version of a document. If the effort is not made, there is much greater risk that the Web will devolve
into a proprietary world of incompatible formats, ultimately reducing the Web's commercial potential
for all participants. Each version of HTML has attempted to reflect greater consensus among industry
players so that the investment made by content providers will not be wasted and that their documents
will not become unreadable in a short period of time. HTML has been developed with the vision that all
manner of devices should be able to use information on the Web: PCs with graphics displays of varying
resolution and color depths, cellular telephones, hand held devices, devices for speech for output and
input, computers with high or low bandwidth, and so on.
Advantages of HTML:
First advantage it is widely used.
Every browser supports HTML language.
Easy to learn and use.
It is by default in every windows so you don't need to purchase extra software.
Disadvantages of HTML:
It can create only static and plain pages so if we need dynamic pages then HTML is not useful.
Need to write lot of code for making simple webpage.
Security features are not good in HTML.
If we need to write long code for making a webpage then it produces some complexity.
Important points
BRJ002
Besides head and body tag, there are some other tags like title, which is a sub tag of head, that
displays the information in the title bar of the browser. <h1> is used to display the line in its own
format i.e., bold with some big font size. <p> is used to write the content in the form of paragraph.
Comments in HTML documents start with <! and end with >. Each comment can contain as many
lines of text as you like. If comment is having more lines, then each line must start and end with -and must not contain -- within its body.
BRJ003
...
HR TAG:
This tag places a horizontal line across the system.
These lines are used to break the page.
This tag also contains attribute i.e., width which draws the horizontal line with the screen size of the
browser. This tag does not require an end tag.
Example: <hr width=50%>.
FONT TAG: This sets font size, color and relative values for a particular text. <font size=10 color=#f1f2f3>
BOLD TAG: This tag is used for implement bold effect on the text <b> . </b>
ITALIC TAG: This implements italic effects on the text. <i>.</i>
STRONG TAG: This tag is used to always emphasized the text <strong>.</strong>
SUB AND SUP TAG: These tags are used for subscript and superscript effects on the text.
Example: <sub> .</sub> <sup>..</sup>
BREAK TAG: This tag is used to the break the line and start from the next line. <br>
& < >   " These are character escape sequence which are required if you want to display
characters that HTML uses as control sequences. Example: < can be represented as <.
ANCHOR TAG: This tag is used to link two HTML pages, this is represented by <a> .
Example: <a href= path of the file> some text </a> href is an attribute which is used for giving the path of a
file which you want to link.
1) LISTS:
One of the most effective ways of structuring a web site is to use lists.
Lists provides straight forward index in the web site.
HTML provides three types of list i.e., bulleted list, numbered list and a definition list.
Lists can be easily embedded easily in another list to provide a complex but readable
structures.
The different tags used in lists are as follows. <li> ..</li> The ordered(numbered) and
unordered(bulleted) lists are each made up of sets of list items.
Unordered Lists:
This tag is used to write list items <ul type=disc | square | circle > ..</ul>
This tag is used for basic unordered list which uses a bullet in front of each tag, everything
between the tag is encapsulated within <li> tags.
Ordered Lists:
This tag is used to write list items <ol type=1 | a | I start=n>..</ol>
This tag is used for ordered list which uses a number in front of each list item or it uses any
element which is mentioned in the type attribute of the <ol> tag, start attribute is used for
indicating the starting number of the list.
Definition Lists:
This tag is used to write list items <dl>.. </dl> This tag is used for the third category i.e.,
definition list, where numbers or bullet is not used in front of the list item, instead it uses
definition for the items.
<dt>..</dt> This is a sub tag of the <dl> tag called as definition term, which is used for
marking the items whose definition is provided in the next data definition.
<dd> .</dd> This is a sub tag of the <dd> tag, definition of the terms are enclosed within
these tags. The definition may include any text or block.
BRJ004
2) TABLES:
Every thing that we write between these two tags will be within a table.
The attributes of the table will control in formatting of the table.
Cell padding determines how much space there is between the contents of a cell and its border,
cell spacing sets the amount of white space between cells.
Width attribute sets the amount of screen that table will use.
<tr> .. </tr> This is the sub tag of <table> tag, each row of the table has to be delimited by
these tags.
<th></th> This is again a sub tag of the <tr> tag. This tag is used to show the table heading .
<td>..</td> This tag is used to give the content of the table.
BRJ005
3) IMAGES TAG:
The HTML img element inserts an image in the document, which location is set in the "src"
attribute.
Images are great for displaying information that sometimes is hard to explain with text.
by using "alt" attribute which should be used by authors to provide an alternative textual
version for the information displayed in the image.
Img Attributes
src
This attribute contains a URI that is supposed to point to the location of the image resource.
This is the element's most important attribute, and it is mandatory, because without it there
would be no image to display.
<img src="img/treasure-map.jpg" />
alt
The value of this attribute provides a textual alternative for the image's content, and therefore
must describe exactly what the image intends to show.
This is vital when the development of the website needs to reach visually impaired audiences.
<img src="img/treasure-map.jpg" alt="This map displays the route to the treasure. You should
turn right twice and follow straight until you find it." />
5
BRJ006
width
Specifies the width of the image.
This can be different to the real width of the image, and browsers should resize it as needed.
However, specifiyng a different width may cause pixelated images (when bigger) or longer load
periods (when smaller).
<img src="img/treasure-map.jpg" width="100" />
height
Specifies the height of the image.
This can be different to the real height of the image, and browsers should resize it as needed.
However, specifiyng a different height may cause a pixelated images (when bigger) or longer
load periods (when smaller).
<img src="img/treasure-map.jpg" height="50" />
align
This attribute has been deprecated in HTML 4.01.
Therefore its use is no longer recommended.
It specifies the position of the image with respect to the surrounding content.
It can take the following case-insentive values:
top: The top side of the image is vertically aligned with the baseline.
middle: The image is vertically centered with respect to the baseline.
bottom: The bottom side of the image is vertically aligned with the baseline. This is the default
value.
left: The image is floated to the left margin.
right: the image is floated to the right margin.
<img src="img/picture.png" align="center" />
border
This attribute has been deprecated in HTML 4.01.
Therefore its use is no longer recommended.
This attribute sets the border width in number of pixels.
<img src="img/picture.png" border="2" />
Output:-
BRJ007
<p><b>Note:</b> The "usemap" attribute in the img element refers to the "id" or "name" (browser
dependant) <br>attribute inthe map element, therefore we have added both the "id" and "name"
attributes to the map element.</p>
</body>
</html>
Output:-
4)HTML FORMS
A webform on a web page allows a user to enter data that is sent to a server for processing.
Forms can resemble paper or database forms because web users fill out the forms using
checkboxes, radio buttons, or text fields.
Example: forms can be used to enter shipping or credit card data to order a product, or can be used to
retrieve search results from a search engine.
When a visitor reaches the form, he only needs to fill the fields and send the form, usually with a
submit button. The sent form is received and processed by a processing agent (usually a server side
script) specified in the value of the "action" attribute of the form element.
The <form> tag is used to create an HTML form for user input.
Form attributes are:
name: This is the name of the form.
action: Here you will specify any script URL which will receive uploaded data.
method: Here you will specify method to be used to upload data. It can take various values but most
frequently used are GET and POST.
There are different types of form controls that you can use to collect data from a visitor to your site.
Text input controls
Buttons
Checkboxes and radio buttons
Select boxes
File select boxes
Hidden controls
Submit and reset button
HTML Forms - Text Input Controls:
There are actually three types of text input used on forms:
Single-line text input controls: Used for items that require only one line of user input, such as
search boxes or names. They are created using the <input> element.
Password input controls: Single-line text input that mask the characters a user enters.
Multi-line text input controls: Used when the user is required to give details that may be longer
than a single sentence. Multi-line input controls are created with the <textarea> element.
7
BRJ008
The <input> tag specifies an input field where the user can enter data.
An <input> element can vary in many ways, depending on the type attribute.
An <input> element can be of type text field, checkbox, password, radio button, submit button, and
more.
Syntax for Input:
<input type=text/password/submit/button/reset/radio/checkbox name=name value=value
[size=n] [maxlength=n]>
Ex: <input type=text name=ename>
Syntax for Textarea:
<textarea name=textarea name cols=n rows=n>
Ex: <textarea name=description cols=30 rows=5> </textarea>
Radio button
Radio Buttons are used when only one option is required to be selected. They are created using
<input> tag as shown below:
Ex: <input type="radio" name="branch" value="cse" /> cse
<input type="radio" name="branch" value="ece" /> ece
List box
Drop Down Box is used when we have many options available to be selected but only one or two will
be selected..
Syntax: <select name=name multiple size=n >
<option value=value1>
<option value=valuen>
</select>
Ex: <select name="subjects">
<option value="Maths" selected>Maths</option>
<option value="Physics">Physics</option>
</select>
Form for accepting Firstname and Lastname.
<form action="/cgi-bin/hello_get.cgi" method="get">
First name: <input type="text" name="first_name" /><br>
Last name: <input type="text" name="last_name" />
<input type="submit" value="Submit" />
<input type="reset" value="Reset" />
</form>
8
BRJ009
<Html>
<body>
<form action="" method=post name=form1>
<table align="center" border=1 cellpadding=0 cellspacing=5 width="80%">
<tr> <td>Name</td>
<td><input type="text" name="name1" value="John" size="20" maxlength="15" ></td>
</tr>
<tr> <td>Password</td>
<td><input type="password" name="password1" size="20" maxlength="12"></td>
</tr>
<tr> <td>Free Mails for</td>
<td><select name="freestuff" multiple size="3">
<option value="I">Investements
<option value="B"selected>EBusiness
<option value="M">Movies
<option value="U">Music
<option value="T">Technical
</select>
</tr>
</td>
<tr> <td>text area</td>
<td><textarea name="freemails" rows =5 cols= 50> This is free mailing service, you can send your comments by typing in
this text box
</textarea></td>
</tr>
<tr> <td>Information by email</td>
<td><input type="checkbox" name="email" checked></td>
</tr>
<tr> <td>EMails </td>
<td><input type="radio" name="period" value="daily"> daily
<input type="radio" name="period" value="weekly">weekly
<input type="radio" name="period" value="monthly">monthly </td>
</tr>
</tr><tr> <td><input type="submit" name=submit1 value="submit register" id=submit1></td>
<td><input type="reset" name=reset1 value="clear" id=reset1></td>
</tr>
</table>
</form>
</body>
</html>
OUTPUT:
BRJ010
5) FRAMES
Frames allow an author to divide a browser window into multiple (rectangular) regions. Multiple
documents can be displayed in a single window, each within its own frame. Graphical browsers allow
these frames to be scrolled independently of each other, and links can update the document displayed
in one frame without affecting the others. You can't just "add frames" to an existing document. Rather,
you must create a frameset document that defines a particular combination of frames, and then
display your content documents inside those frames. The frameset document should also include
alternative non-framed content in a NOFRAMES element.
Process for coding frames
1. Code the first page with the layout the windows that subdivide your screen (frameset
command)
2. Name each window. This is refered to as a window-target.
3. Code each separate page (individual files) that will be the content of each window. These are
called the source files.
4. Code a "No Frames" option for noframes browsers.
To make a page use frames, add a <frameset> tag immediately after <head> this tag takes two
attributes, cols and rows, which specify the space taken by each frame in the form of a comma
separated list.
You can specify either the number of pixels to use, a percentage, or "*" to mean the rest of the space
once the other values have been worked out. For instance,<frameset rows="40,20%,*"> would divide
the window into three rows, the top-most being 40 pixels deep, the middle one taking 20% of the
window, and the bottom one taking the remainder of the space.
<frameset> has the following attributes
Cols -Specifies no. and size of columns in a frameset either in pixels or % or *
Rows- Specifies no. and size of rows in a frameset either in pixels or % or *
Once you've specified how the window is to be divided up with the <frameset> tag, you then describe
the contents of each frame using <frame>.
This tag takes the following attributes:
src="URL": specifies the URL of the page to be loaded in this frame.
name="name": specifies the name of this window, to be used with <a target>.
marginwidth="value", marginheight="value": sets the size of the margin in the frame. Seriously
optional.
scrolling="yes, no or auto": decides whether the frame will scroll. "Auto" is the default value.
noresize: don't allow the user to resize this frame.
The following special values can also be used as names:
_blank: opens the link in a new unnamed window.
_self: opens the link in the current frame. Useful for overriding a standard target set in <base>
_parent: opens the link in the current frame's parent <frameset>.
_top: gets rid of all frames; the linked page takes up the entire window. Especially appropriate
if the page you're linking to is an external site, and hence nothing to do with your frame
structure.
Frameset which allows a user to see 3 frames at a time.
<html>
Output:
<frameset cols="25%,*,25%">
Frame A
Frame B
Frame C
<frame src="frame_a.htm">
<frame src="frame_b.htm">
<frame src="frame_c.htm">
</frameset></html>
10
BRJ011
<html>
<frameset rows="25%,50%,25%">
<frame src="frame_a.html">
<frame src="frame_b.html">
<frame src="frame_c.html">
</frameset>
</html>
<html>
<frameset cols="25%,50%,25%">
<frame src="frame_a.html">
<frame src="frame_b.html">
<frame src="frame_c.html">
</frameset>
</html>
<html>
<frameset rows="50%,50%">
<frame src="frame_a.html">
<frameset cols="25%,75%">
<frame src="frame_b.html">
<frame src="frame_c.html">
</frameset>
</frameset>
</html>
11
BRJ012
JAVA SCRIPT
DISADVANTAGES OF JAVASCRIPT
Different versions of Netscape will behave differently depending on the language features you use.
It is possible to write JavaScript programs that use advanced JavaScript features but do not cause
problems on older browsers. However, doing this is can be a complex and labour intensive process.
Unfortunately, even the same version of Netscape may behave differently depending on the operating
system it is run on. The language is very new and still evolving. Few software development tools exist
to help you write and debug your scripts. And while you can do a lot with JavaScript, some things like
animation, scrolling/animated banners and notices, and complex programming are often better done
using animated GIFs, Netscape Plugins such as Flash, or Java applets.
JavaScript is used for the following purposes:
JavaScript is also an easy language to get started using.
JavaScript was designed to add interactivity to HTML pages
build small but complete client side programs.
build forms that respond to user input without accessing a server;
validate user input in an HTML form before sending the data to a server;
change the appearance of HTML documents and dynamically write HTML into separate
Windows;
manipulate HTML "layers" including hiding, moving, and allowing the user to drag them
around a browser window;
12
BRJ013
A JavaScript can be set to execute when something happens, like when a page has finished
loading or when a user clicks on an HTML element
A JavaScript can be used to detect the visitor's browser, and - depending on the browser - load
another page specifically designed for that browser
A JavaScript can be used to store and retrieve information on the visitor's computer
Java is loaded from compiled bytecode; JavaScript is loaded as human-readable code. C is their
last common ancestor language.
Nonetheless, JavaScript was designed with Java's syntax and standard library in mind. In
particular, all Java keywords are reserved in JavaScript, JavaScript's standard library follows
Java's naming conventions
Strings
strings can be created by assigning a literal value to a variable or by creating a String object
initialized with a literal string.
msg = "I there is no end to the details I have to remember?"
msg = new String("Is there is not end to the details I have to remember?")
null
null - "special key word denoting a null value"
x = null
BRJ014
if (condition)
{
code to be executed if condition is true
}
else
{
Code to be executed if condtion is not true
}
Ex:
If (a>b)
{ document.writeln(a is greatest);
}
Else
{
Document.writeln(b is greatest);
}
Switch Statement
Use the switch statement to select one of many blocks of code to be executed.
Syntax
switch(n)
{
case 1:
execute code block 1
break;
case 2:
execute code block 2
break;
default:
code to be executed if n is different from case 1 and 2
}
Ex:
var day=new Date().getDay();
switch (day)
{
case 0:
x="Today is Sunday";
break;
case 1:
x="Today is Monday";
break;
-------------default:
x="Today is Saturday";
break;
}
Loops
Loops are handy, if you want to run the same code over and over again, each time with a different
value.
The for loop is often the tool you will use when you want to create a loop.
for (statement 1; statement 2; statement 3)
{
14
BRJ015
For/in Loop
The JavaScript for/in statement loops through the properties of an object:
var txt="";
var person={fname:"John",lname:"Doe",age:25};
for (var x in person)
{
txt=txt + person[x];
}
While loop
The while loop loops through a block of code as long as a specified condition is true.
while (condition)
{
code block to be executed
}
Example
The loop in this example will continue to run as long as the variable i is less than 5:
Example
while (i<5)
{
x=x + "The number is " + i + "<br>";
i++;
}
The do/while loop is a variant of the while loop. This loop will execute the code block once, before
checking if the condition is true, then it will repeat the loop as long as the condition is true.
Syntax
do
{
code block to be executed
}
while (condition);
Example
The example below uses a do/while loop. The loop will always be executed at least once, even if the
condition is false, because the code block is executed before the condition is tested:
15
BRJ016
Example
do
{
x=x + "The number is " + i + "<br>";
i++;
}
while (i<5);
BRJ017
2) Inline code
<html><head>
<title>Java Script</title>
</head>
<body bgcolor=red>
<form>
<script language="JavaScript">
function inline()
{
alert("My First JavaScript Page");
}
</script>
<input type="button" value="Click Me" onclick="inline()">
</form>
</body>
</html>
3) External File
You can utilize the SRC characteristic of the <script> tag to call javascript code from an outside
content record. This is helpful when you want to decrease the length of your code.
Syntax:
<SCRIPT SRC=script.js Language =JavaScript> ....</SCRIPT>
Example:
First open the notepad and write the script content
Alert ("My External Script File");
Save it as script.js
<html><head>
<title>Java Script</title>
</head>
<body bgcolor=red>
<script language="JavaScript" src=script.js>
</script>
</body>
</html>
OBJECTS IN JAVASCRIPT
JavaScript supports programming with objects.
Objects are a way of organizing the variables.
The different screen elements such as Web pages, forms, text boxes, images, and buttons are
treated as objects.
JavaScript code is not compiled, but parsed.
This allows for flexibility when it comes to creating or altering objects.
BRJ018
3. Window objects
OUTPUT
<html><head>
<title>Example on properties</title>
</head>
<body bgcolor=red>
<form name="f1">
<script language="JavaScript">
function calc(txt)
{
var num=txt
round=Math.round(num)
alert("rounded number is: "+round);
}
function calc1(txt)
{
var num=txt
round=Math.sqrt(num)
alert("Square Root of a number is: "+round);
}
</script>
Please Enter the Float Number: <Input type="text" name="t1" id="t1"><br>
<input type="button" value="Round Off" onClick="calc(f1.t1.value)"><br>
<input type="button" value="SquareRoot" onClick="calc1(f1.t1.value)">
</form>
</body>
</html>
Date Object
The Date object provides the day, date, and time information.
Format: dateObject.method()
var today = new Date();
document.write(today);
Produces:
wed Feb 12 09:41 EST 2014
Example:
<html><head>
<title>Example on properties</title>
</head>
<body bgcolor=violet>
<form name="f1">
<script language="JavaScript">
function jsdate()
{
var year=new Date()
alert(year);
}
</script>
<input type="button" value="Show Today's Date and Time"
18
BRJ019
onClick="jsdate()">
</form>
</body>
</html>
String Object
The String object provides methods and properties for string manipulation and formatting.
Format: stringName.method()
Eg, var name = Ruchi;
document.write(name.length);
2) Document Object:
The Document object represents the Web page that is loaded in the browser window, and the
content displayed on that page, including text and form elements.
Document Methods
Here are the most common document methods:
write() - write a string to the Web page
open() - opens a new document
close() - closes the document
3) Window Object:
The window object represents the browser window. You can use it to open a Web page in a
new window and to set the attributes for the window. There are only two main window
properties.
Window Methods
The window methods are mainly for opening and closing new windows.
alert() - to display a message box
confirm() - to display a confirmation box
open() - to open a new window
close() - to close a opened window.
DHTML is differentiated from Ajax by the fact that a DHTML page is still request/reload-based. With
DHTML, there may not be any interaction between the client and server after the page is loaded; all
processing happens in JavaScript on the client side. By contrast, an Ajax page uses features of DHTML
to initiate a request to the server to perform actions such as loading more content.
JavaScript (more on JavaScript in a bit) is a programming language that both Netscape Navigator and
Internet Explorer can understand, making it a good choice for cross-browser DHTML.
DHTML Means showing the dynamic content on the web page rather than the static content.
19
BRJ020
Examples on DHTML:
<html>
<head><title>Dymamic</title></head>
<body bgcolor=red>
<p onclick="this.style.fontSize='90px'">Click me to Increase the size</p>
</body>
</html
<html>
<head><title>Dymamic</title></head>
<body bgcolor=red>
<p onclick="this.style.color='white'">Click me to change the color</p>
</body>
</html>
20
BRJ021
XML can be used to simplify data storage and sharing. With XML, data is separated from HTML. So you
can create HTML layouts for displaying data. When the data changes, you don't have to recreate your
HTML file. With XML, data can also be easily exchanged between computer and database systems;
even they are incompatible in any other ways. Because XML data is stored in text format, this makes it
easier to export data from a system to an XML file, and then import it into another system.
What is XML?
XML stands for EXtensible Markup Language, which became a W3C Recommendation on 10. February
1998. XML is a markup language which is like HTML. XML and HTML both use tags. But there are
some differences between them:
HTML was designed for how to display data. And XML was designed for how to store data.
HTML tags are predefined (for example "<p>", "<table>", etc.). But XML tags are not predefined.
You must define your own tags
The following example is product information, stored as XML:
<product>
<name>
Garmin Oregon 300 3 inch' Touch screen Handheld GPS Unit with a Built-in Base
map and Shaded Relief
</name>
<category>GPS</category>
<brand>Garmin</brand>
<price>529.99</price>
<description>
Handheld GPS navigator for use outdoors, in a car, or on a boat 3 inch LCD touch
screen display (240 x 400 pixels) with built-in picture viewer
</description>
</product>
As you can see, it is just pure information wrapped in tags, which are not like HTML tags ("<table>",
"<tr>", etc.) are predefined. You can create your own tags, like the ones in the above example, for your
XML file.
XML can be used to simplify data storage and sharing. With XML, data is separated from HTML. So you
can create HTML layouts for displaying data. When the data changes, you don't have to recreate your
HTML file. With XML, data can also be easily exchanged between computer and database systems,
even they are incompatible in any other ways. Because XML data is stored in text format, this makes it
easier to export data from a system to an XML file, and then import it into another system. Before we
have XML, the task of exchanging data between incompatible systems was not easier and complicated
due to the different data formats. Now XML greatly reduces this complexity, and we can be easily
expand or upgrade our operating systems and applications without losing data.
A XML document is consist of tags and data. All data in an XML document is wrapped by the tags.
EXAMPLE:
<?xml version="1.0" encoding="ISO-8859-1"?>
<customer>
<firstname>Michael</firstname>
<lastname>Smith</lastname>
<gender>male</gender>
<address>
<street>197 West Park Ave.</street>
<city>New York</city>
21
BRJ022
<state>NY</state>
<zip>11375</zip>
<country>US</country>
</address>
<phone>718-235-5670</phone>
<email>msmith278@yahoo.com</email>
</customer>
The first line is the XML declaration. It defines the XML version (1.0) and the character set (ISO-8859).
The next line uses tag "<customer>". It is the root element of the document. The next four lines
describe the child elements () of the root: Please note that, except the first line, all tags in the
document are used in pair: opening tag and closing tag. You can assume, from the above example, a
pair of tags provide a "container", and data or child tags are stored inside.
Also, you can assume, the structure of an XML document is defined by the relationship between these
"containers": a large container contains smaller containers. Or you can assume the structure of an
XML file as a "tree" that starts at the root tag "customer" and branches to the leaves tags "firstname",
"lastname", "gender", "address", "phone" and "email":
customer ->
firstname
lastname
gender
address ->
street
city
state
zip
country
phone
email
Please note, an XML document must contain a pair of root tags for the "parent" element, whcih
contains all other elements. You cannot have two roots in a single XML document. All elements can
have child elements:
<root>
<child1>......</child1>
<child2>
<subchild1>.....</subchild1>
<subchild2>.....</subchild2>
</child2>
</root>
XML Namespace
An XML namespace is a collection of names that can be used as element or attribute names in an XML
document. The namespace qualifies element names uniquely on the Web in order to avoid conflicts
between elements with the same name. The namespace is identified by some Uniform Resource
22
BRJ023
Identifier (URI), either a Uniform Resource Locator (URL), or a Uniform Resource Number (URN), but
it doesn't matter what, if anything, it points to. URIs is used simply because they are globally unique
across the Internet.
Namespaces can be declared either explicitly or by default. With an explicit declaration, you define a
shorthand, or prefix, to substitute for the full name of the namespace. You use this prefix to qualify
elements belonging to that namespace. Explicit declarations are useful when a node contains elements
from different namespaces. A default declaration declares a namespace to be used for all elements
within its scope, and a prefix is not used.
WHY IS IT NECESSARY?
As an example, let's assume we have an RDB with a table of the following structure (employeeTable,
sectionTable). What kind of SQL statement would you create to obtain a list of Employee ID, Employee
Department Name, and Employee Name? If we merged employeeTable and sectionTable with the
secID column, then we would be able to obtain a list of employee IDs, employee departments and
employee names. However, since the name column and secID column exist in both tables, we would
have to designate the table name before the name and secID columns, or designate the alias of the
table in order to clarify the table of the name and secID columns in question.
So, what happens when this data is expressed in an XML document? Let's take two XML documents,
and see how we can create a list showing employee ID, employee department and employee name
using XML.
First, we will create a root element (employeeList element) and an element (personList element) to
summarize employee information for one individual. You might have thought about creating an
employee ID element (empID element in employeeXML document), department name element (name
element in sectionXML document) and an employee name element (name element in employeeXML
document) as child elements, but there's a problem with this method. The problem is an "element
name conflict." The name element in the employee XML document is defined as an element
representing the employee's name, whereas the name element of the section XML document is
defined as an element representing a department name. In merging these two XML documents, you
will get a name element that has two separate meanings. While a human might be able to tell the
difference between these two "name" elements and what they represent, computer systems cannot
23
BRJ024
determine what these name elements are supposed to mean. The XML 1.0 specification never
considered the merging of different types of XML documents (vocabularies) to create a new XML
document, which led to this type of name conflict problem.
employeeXML Document
<employee>
<personInfo>
<empID>E0000001</empID>
<secID>S001</secID>
<name>John Smith</name>
</personInfo>
<personInfo>
<empID>E0000002</empID>
<secID>S002</secID>
<name>Ichiro Tanaka</name>
</personInfo>
</employee>
sectionXML Document
<section>
<sectionInfo>
<secID>S001</secID>
<name>Sales</name>
</sectionInfo>
<sectionInfo>
<secID>S002</secID>
<name>Development</name>
</sectionInfo>
</section>
employeeListXML Document
<employeeList>
<personList>
<empID>E0000001</empID>
<name>Sales</name>
<name>John Smith</name>
</personList>
<personList>
<empID>E0000002</empID>
<name>Development</name>
<name>Ichiro Tanaka</name>
</personList>
24
BRJ025
</employeeList>
The name element expressing employee name and the name element expressing department
name conflict!
Perhaps some of you out there had the idea that element name conflicts can be avoided by applying
the same type of alias used for RDB table merge explained above to an XML document. The W3C
recommended a specification called "Namespaces in XML," whereby XML vocabularies are mutually
differentiated, allowing for the re-use of a vocabulary. Utilizing this XML namespace allows us to avoid
any element name conflicts.
Here, we will add an XML namespace declaration and description in both the employee data XML
document and section data XML document. Next, we will merge these two XML documents, and create
a new employeeList data XML document. As a result, we can differentiate the "emp:name element" of
the employeeList data XML document as an element representing employee name, and the "sec:name
element" as an element representing department name. It might be easiest to think of one namespace
as an aggregation of elements and attributes.
Employee XML Document
<emp:employee xmlns:emp="urn:corp:emp">
<emp:personInfo>
<emp:empID>E0000001</emp:empID>
<emp:secID>S001</emp:secID>
<emp:name>John Smith</emp:name>
</emp:personInfo>
<emp:personInfo>
<emp:empID>E0000002</emp:empID>
<emp:secID>S002</emp:secID>
<emp:name>Ichiro Tanaka</emp:name>
</emp:personInfo>
</emp:employee>
section XML Document
<sec:section xmlns:sec="urn:corp:sec">
<sec:sectionInfo>
<sec:secID>S001</sec:secID>
<sec:name>Sales</sec:name>
</sec:sectionInfo>
<sec:sectionInfo>
<sec:secID>S002</sec:secID>
<sec:name>Development</sec:name>
</sec:sectionInfo>
</sec:section>
employeeList XML Document
<list:employeeList
xmlns:list="urn:corp:list"
xmlns:emp="urn:corp:emp"
25
BRJ026
xmlns:sec="urn:corp:sec">
<list:personList>
<emp:empID>E0000001</emp:empID>
<sec:name>Sales</sec:name>
<emp:name>John Smith</emp:name>
</list:personList>
<list:personList>
<emp:empID>E0000002</emp:empID>
<sec:name>Development</sec:name>
<emp:name>Ichiro Tanaka</emp:name>
</list:personList>
</list:employeeList>
NAMESPACE DECLARATION
Write a namespace declaration according to the following description method, describing the element
start tag:
If the element and/or attribute belong to a namespace, a colon (":") is placed between the namespace
prefix and the element name/ attribute name.
As a test, let's take the previous employeeList XML document as an example, and provide a namespace
declaration and an element belonging to the namespace.
<emp:employee
xmlns:emp="urn:corp:emp">
<emp:personInfo>
omitted
</emp:personInfo>
</emp:employee>
In this example, we have declared the namespace prefix as "emp", and the namespace identifier (URI)
as "urn:corp:emp". This means that element names and attribute names with the "emp" prefix
(including the employee element) all belong to the urn:corp:emp namespace.
If the namespace prefix is not provided for an element and/ or attribute name, except for cases where
a default namespace is declared (to be discussed later), the element name and/ or attribute name do
not belong to a namespace. While the namespace declaration is described as a start tag attribute, this
is different than a regular attribute. Elements having only an "xmlns:~" description have a namespace
declaration, but no attribute.
26
BRJ027
Any arbitrary text string can be used as a namespace prefix; since there is no special meaning, any text
string will do. However, the URI must be universally unique. Quite often a URL beginning with
"http://~" is used in practice. Since the URL is not actually accessed, it is not a problem if the file, etc.
does not really exist. Understand that a URI represents nothing more than a logical namespace name.
DEFAULT NAMESPACES
A "default namespace" is a namespace declaration that does not use a namespace prefix (See Figure
for notation method). The scope of the default namespace is the element for which the namespace was
declared and the related content, just as with the namespace scope discussed earlier. The benefit of
using a default namespace is that the namespace prefix can be omitted.
For example, when adding a new namespace to an existing XML document, writing a namespace prefix
for each element to which the new namespace will be applied involves a tremendous amount of
tedious work. The larger the XML document, the greater the labor involved, and the greater the
likelihood of notation errors. In this type of situation, adding only a default namespace declaration to
the XML document in question eliminates the need to write a namespace prefix for each and every
element, saving a lot of time.
On the other hand, there are drawbacks. One drawback is that omitting the namespace prefix makes it
more difficult to understand which element belongs to which namespace, and which namespace is
applicable. In addition, programmers should remember that when a default namespace is declared,
the namespace is applied only to the element, and not to any attributes.
27
BRJ028
Even a simple request to create an XML document to serve as a purchase order to be sent to Mr. Y at
Company X can take on a number of different XML document patterns. Any of the three examples
above can be considered to be proper XML documents. As long as the information required for a
purchase order is included, likely any XML document you could create would be a valid XML
document for the purpose.
But what would change if you approached the task from Mr. Y's perspective? Assume that Mr. Y uses
the three XML documents above, or your XML document, for order processing. Having received XML
documents with different element names and hierarchical structures, Mr. Y would have to open each
XML document in an editor, confirm whether all of the required information was present, and then
process the purchase order. In this case, every purchase order would have to be processed by hand,
and the entire system could never be automated.
But what would happen if all XML documents sent had the same element names and hierarchical
structure? With standard element names and structures, a system could be created to handle all
incoming XML documents, and order processing could be automated, without Mr. Y having to verify
the content of each individual document.
28
BRJ029
A "Schema" is what is required to allow the acceptance (or creation) of XML documents with a
standardized element name and hierarchy structure. We know that in the RDB world, a schema is
defined when designing tables to stipulate category (column) data types and data sizes, set the
primary key, associate tables with other tables, etc. Under XML Schema, a user notates element names,
orders of occurrence, and number of occurrences. When XML is used for specific purposes, a schema
will first be defined, and then XML documents will be created in accordance with that schema. In
doing so, anyone can create an XML document having the same exact element names and hierarchical
structure.
Let's take another look at the task for creating an XML document to be used for a purchase order.
Assume that Mr. Y sends to Ms. A, Mr. B, and Ms. C a schema document for purchase orders (XML
document). Ms. A, Mr. B., and Ms. C then each create an XML document based on Mr. Y's schema. The
element names and hierarchical structure of the XML documents they send to Mr. Y are completely
identical.
Mr. Y can now use an XML parser to verify whether the documents have been created according to the
schema, so there is no need to open each file and check element names and hierarchy structures. This
reduces Mr. Y's workload significantly.
TYPES OF XML DOCUMENT SCHEMA
There are many different types of XML document schema. While the following type of narrative
format can be considered a type of schema, there is the chance that different people will interpret the
narrative differently. This is why, in general, XML document schema is created using Schema
Definition Language. Schema Definition Language is specialized definition language for noting schema,
and leaves no room for interpretive differences.
BRJ030
The Content Model is very important in the Element Type Declaration. It defines whether the element
content is a text string or numeric value (character data), whether only child elements occur (element
content), etc.
When there are a multiple number of child elements, you must designate the order of occurrence.
There are two ways to notate the order of occurrence. Using a comma (,) between the child element
name and the next child element name indicates that the child elements will occur in the order given.
Using a vertical line (|) means that either one or the other child element will occur.
","
"|"
In the following example, the content of "product" is the "product_name" and "num" elements,
occurring once each in that order.
<!ELEMENT product (product_name,num)>
30
BRJ031
The following is a valid element description for this type of Element Type Declaration:
<product>
<product_name>television</product_name>
<num>10</num>
</product>
Because "," defines the order of occurrence as the order in which the child element was written, the
following would be examples of invalid notation:
To describe an Element Type Declaration where either the "portable" or "home" element (child
elements of "tel") occurs:
<!ELEMENT tel (portable|home)>
In this case, the following would be an error when describing both the portable and home elements:
tel
portable/portable
home/home
/tel
" "
" "
No designation
One time
Under DTD, a programmer may not designate a specific number of occurrences (e.g. three times,
between two and five times, etc.).
For example, output the "customer" and "product" elements (content of "orderform") in that order.
To describe an Element Type Declaration designating one occurrence for "customer" and zero or
more occurrences for "product", use the following notation:
<!ELEMENT orderform (customer,product*)>
Now, let's describe all of the elements, referencing the notation examples above.
Use the "dtd" extension when actually creating the document. The following shows a file named
"order.dtd", describing the Purchase Order XML schema DTD:
order.dtd
<!ELEMENT orderform (customer,product*)> [1][2]
<!ELEMENT customer (name,address,tel)> [3]
<!ELEMENT name (#PCDATA)>
[4]
<!ELEMENT address (#PCDATA)>
[4]
<!ELEMENT tel (portable | home)>
[5]
31
BRJ032
BRJ033
Entity Name
Symbol Notation
lt
<
&
amp
&
gt
"
quot
'
apos
>
"
'
When using a DTD entity declaration, you can define your own entity references in addition to the five
types above.
BRJ034
This provides us with an understanding of the hierarchical structure of the XML document. Now, we
can provide a schema definition using actual schema definition language.
LIST1 is an example using DTD and providing a schema definition for the content above, while LIST2
is an example using XML Schema to provide a schema definition (employee.xs).
LIST1: Employee Information DTD
<!ELEMENT Employee_Info (Employee)*>
<!ELEMENT Employee (Name, Department, Telephone, Email)>
<!ELEMENT Name (#PCDATA)>
<!ELEMENT Department (#PCDATA)>
<!ELEMENT Telephone (#PCDATA)>
<!ELEMENT Email (#PCDATA)>
<!ATTLIST Employee Employee_Number CDATA #REQUIRED>
BRJ035
(Line numbers have been added for reference, and are not necessary in the actual code.)
As you see, the syntax is completely different between the two. For the DTD, a unique syntax is
written, whereas the XML Schema is written in XML format conforming to XML 1.0 syntax. LIST3 is an
example of a valid XML document for the LIST2 XML Schema (employee.xml).
BRJ036
ELEMENT DECLARATION
When declaring an element, an ELEMENT keyword is used under DTD; however, under XML Schema,
the element element is used. The declaration method is different depending on whether the element
element has a child element or not. When no child element is present, the element name is designated
with the name attribute, and the data type is designated using the type attribute.
Under DTD, not much more than being able to show an optional text string called #PCDATA as the
element content was possible; however, under XML Schema, a variety of data types can be defined.
Data types can be designated using pre-defined embedded simple type (Note), including string type,
int type and date type shown in a table, as well as ID type and NMTOKEN type that are compatible
with DTD. These can be combined and extended or restricted to create new, unique data types.
Table : Main XML Schema Data Types
General Data Types
Name
Explanation
xs:integer
xs:positiveInteger
xs:negativeInteger
including
including
xs:byte
xs:short
xs:unsignedByte
xs:unsignedShort
xs:int
xs:unsignedInt
xs:long
xs:unsignedLong
xs:decimal
xs:float
xs:double
36
(infinite
(infinite
xs:Boolean
xs:string
Boolean value
Explanation
xs:time
Time of day
xs:date
Date
xs:dateTime
xs:gYear
xs:gYearMonth
xs:gMonth
xs:gMonthDay
xs:gDay
DTD-Compatible Types
Name
Explanation
xs:ID
xs:IDREFS
xs:IDREF
xs:ENTITY
xs:ENTITIES
xs:NOTATION
xs:NMTOKEN
xs:NMTOKENS
Meanwhile, if the element has a child element, a new data type must first be designated for the
element (Line 11): <xs:element name="Employee" type="EmployeeType" />
This "EmployeeType type" designated by the type attribute is a Complex Data Type. Lines 11 through
20 are Complex Type declarations. In the actual content of the Complex Type, EmployeeType type is
designated with the name attribute of the complexType element, and the Model Group (settings
method for the occurrence order of the child element) is designated in the child element. In the Model
Group, use the sequence element to output occurrences in the order written (equivalent to the "," in
DTD), and use the choice element to output the occurrence of any given element (equivalent to the "|"
in DTD).
Meaning of the Model Group
XML Schema
DTD
For Model Group element declarations, the most common method is to designate the ref attribute of
the element element, referencing the element declared in a separate location (LIST4).
37
BRJ038
ATTRIBUTE DECLARATIONS
When declaring an attribute, the ATTLIST keyword is used under DTD, while the attribute element is
used under XML Schema. The syntax is as shown below. As mentioned previously in connection with
Complex Type declarations, when describing an attribute, the convention is to describe it after the
Complex Type definition content (after the Model Group) (Line 19).
Designations related to Occurrences
XML Schema
DTD
required
#REQUIRED
optional
prohibited
BRJ039
#IMPLIED
None
XML SCHEMAS
XML schema is an XML based alternative to DTD. Which describes the structure of an XML
document.
The XML schema language is also referred as XML Schema Definition (XSD).
The purpose of an XML schema is to define the legal building blocks of an XML document like a
DTD.
An XML schema defines :
elements and attributes that can appear in a document
which elements are child elements, the order of child elements
the number of child elements and whether an element is empty or can include text
data types for elements and attributes
default and fixed values for elements and attributes
XML Schemas are the Successors of DTDs
XML Schemas will be used in most Web applications as a replacement for DTDs because :
XML Schemas are richer and more powerful than DTDs
XML Schemas are extensible to future additions
XML Schemas are written in XML, also support data types and namespaces
XML Schema is W3c recommendation.
As XML Schemas Support Data Types
It is easier to describe allowable document content
It is easier to validate the correctness of data
It is easier to work with data from a database
It is easier to define restrictions on data
It is easier to define data patterns/formats
It is easier to convert data between different data types
39
BRJ040
Using XML schema we can provide the secured data communication between sender and
receiver.
As XML Schemas use XML Syntax
No need to learn a new language
We can use an XML editor to edit Schema files
we can use XML parser to parse Schema files
we can manipulate Schema with the XML DOM
As XML Schemas are extensible we can reuse the schema in other schemas we can provide
reference of multiple schemas in the same document.
Simple XML Document
<?xml version="1.0"?>
<note>
<to>Tove</to>
<from>Jani</from>
<heading>Reminder</heading>
<body>Don't forget me this weekend!</body>
</note>
Simple DTD Document
<!DOCTYPE note
[<!ELEMENT note (to ,from ,heading ,body)>
<!ELEMENT note (to, from, heading, body)>
<!ELEMENT to (#PCDATA)>
<!ELEMENT from (#PCDATA)>
<!ELEMENT heading (#PCDATA)>
<!ELEMENT body (#PCDATA)> ]>
Reference to DTD
<?xml version="1.0"?>
<!DOCTYPE note SYSTEM http://www.w3schools.com/dtd/note.dtd">
<note>
<to>Tove</to>
<from>Jani</from>
<heading>Reminder</heading>
<body>Don't forget me this weekend!</body>
</note>
40
BRJ041
BRJ042
<author>J K. Rowling</author>
<year>2005</year>
<price>29.99</price>
</book>
<book category="web">
<title lang="en">XQuery Kick Start</title>
<author>James McGovern</author>
<author>Per Bothner</author>
<author>Kurt Cagle</author>
<author>James Linn</author>
<author>Vaidyanathan Nagarajan</author>
<year>2003</year>
<price>49.99</price>
</book>
<book category="web" cover="paperback">
<title lang="en">Learning XML</title>
<author>Erik T. Ray</author>
<year>2003</year>
<price>39.95</price>
</book>
</bookstore>
The root node in the XML above is named <bookstore>. All other nodes in the document are
contained within <bookstore>, which holds four <book> nodes.
The first <book> node holds four nodes: <title>, <author>, <year>, and <price>,which contains
one text node each, "Everyday Italian", "Giada De Laurentiis","2005", and "30.00".
Text is Always Stored in Text Nodes
A common error in DOM processing is to expect an element node to contain text.
However, the text of an element node is stored in a text node.
In this example: <year>2005</year>, the element node <year>, holds a text node with the
value "2005, 2005" is not the value of the <year> element!
XML DOM views an XML document as a tree structure which is called as a nodetree. All the
nodes in the tree have a relationship with each other.
All nodes can be accessed through the tree. Their contents can be modified or deleted, and new
elements can be created.
The node tree shows the set of nodes, and the connections between them. The tree starts at the
root node and branches out to the text nodes at the lowest level of the tree
42
BRJ043
XSL stylesheet are not the same as HTML cascading stylesheets. They create a style for a
specific XML element, with XSL a template is created.
XSL basically transforms one data structure to another i.e., XML to HTML.
Example Here is the XSL file for the XML document of Example
This line must be included in the XML document which reference stylesheet
<?xml:stylesheet type = text/xsl href = student.xsl?>
BRJ044
SAX PARSER
Simple API for XML- SAX
Fast and Efficient
It will Fires Event handlers at Start Tag, Tag Body and End Tag.
e.g: <to> jk </to> respectively.
SAX is Read Only API therefore it cannot be used to Update XML
documents.
It is good for large documents to process as it requires less memory.
It process the document sequentially.
SAX allows us to abort processing at any time.
It is useful to retrieve small amount of information.
<?xml version="1.0" encoding="UTF-8"?>
<parts>
<part> TurboWidget </part>
</parts>
StartDocument( )
StartElement( "parts" )
StartElement( "part" )
Characters( "TurboWidget" )
EndElement( "part" )
EndElement( "parts" )
EndDocument( )
Advantages of SAX:
SAX reduces memory and CPU usage because it only processes one section
of an XML document at a time.
SAX is customizable because when an event is triggered, only the associated
application receives data about the triggering event.
SAX is streamlined, fast, and supports pipelining due to the reason that the
parser can produce output while the document is being parsed.
Drawbacks of SAX:
The SAX parser is unidirectional because It can only parse forwards in
a document.
As it can hold only a portion of the XML document in memory at any
time, it is difficult to add or edit nodes using SAX. If this functionality is
required, then DOM should be considered.
SAX can only work with a fully formed XML document. It cannot be
used to process partial XML documents.
It wont support dynamic access of data in a document.
It is difficult to implement complex searches.
SAX support is not built-in in Microsoft Internet Explorer.
BRJ045
Java developers are kept out of all the hassle and they get the entire tree readily available
whenever they wish.
45
BRJ046
JAVA BEANS
UNIT-II
Sno
Contents
Page No
JAVA BEANS
1
BDK Introspection
2
4
5
6
10
17
BRJ047
13
FEATURES OF JAVABEANS
1 ) Compact and Easy: JavaBeans components are simple to create and easy to use.
This is an important goal of the JavaBeans architecture. It doesn't take very much to write a simple
Bean, and such a Bean is lightweight, it doesn't have to carry around a lot of inherited baggage just
BRJ048
2)
3)
4)
5)
The Bean Developer Kit (BDK), available from the JavaSoft site, is a simple example of a tool that
enables you to create, configure, and connect a set of Beans. There is also a set of sample Beans with
their source code
Installing the BDK
The JDK must be installed on your machine for the BDK to work. Confirm that the JDK tools are
accessible from your environment.
Starting the BDK
To start the BDK, follow these steps:
1. Change to the directory c:\\bdk\\beanbox.
2. Execute the batch file called run.bat. This causes the BDK to display the three windows shown
below . ToolBox lists all of the different Beans that have been included with the BDK. Bean Box provides
an area to lay out and connect the Beans selected from the Toolbox.
Properties provide the ability to configure a selected Bean.
Java Beans by BRJ
BRJ049
BRJ050
4. You can change the molecule that is displayed by changing the selection in the Properties
window. Notice that the Bean display changes immediately when you change the selected
molecule.
5. Go to the menu bar of the BeanBox and select Edit | Events | action |actionPerformed. You should
now see a line extending from the button to the cursor.
Notice that one end of the line moves as the cursor moves.
However, the other end of the line remains fixed at the button.
6. Move the cursor so that it is inside the Molecule Bean display area, and click the left mouse
button. You should see the Event Target Dialog dialog box.
7. The dialog box allows you to choose a method that should be invoked when this button is clicked.
Select the entry labeled "rotateOnX" and click the OK button.
You should see a message box appear very briefly, stating that the tool is
"Generating and compiling adaptor class.
Test the application. Each time you press the button, the molecule should move a few degrees around
one of its axes.
Now create another instance of the OurButton Bean. Label it "Rotate Y" and map its action event to
the "rotateY" method of the Molecule Bean.
The steps to do this are very similar to those just described for the button labeled "Rotate X".
Test the application by clicking these buttons and observing how the molecule moves.
JAR Files
Before developing your own Bean, it is necessary for you to understand JAR (Java Archive) files,
because tools such as the BDK expect Beans to be packaged within JAR files.
A JAR file allows you to efficiently deploy a set of classes and their associated resources.
For example, a developer may build a multimedia application that uses various sound and
image files.
A set of Beans can control how and when this information is presented. All of these pieces can be
placed into one JAR file.
Also, the elements in a JAR file are compressed, which makes downloading a JAR file much faster
than separately downloading several uncompressed files.
Manifest Files
A developer must provide a manifest file to indicate which of the components in a JAR file are
Java Beans.
An example of a manifest file is provided in the following listing. It defines a JAR file that contains
four .gif files and one .class file. The last entry is a Bean.
Name: sunw/demo/slides/slide0.gif
Name: sunw/demo/slides/slide1.gif
Name: sunw/demo/slides/slide2.gif
Name: sunw/demo/slides/slide3.gif
Name: sunw/demo/slides/Slides.class
Java-Bean: True
A manifest file may reference several .class files. If a .class file is a Java Bean, its entry must be
immediately followed by the line "Java-Bean: True".
The JAR Utility
A utility is used to generate a JAR file. Its syntax is shown here:
jar options files
jar -cfm Xyz.jar Yxz.mf *.class *.gif
Java Beans by BRJ
BRJ051
DESCRIPTION
The first element in the file list is the name of the archive that is to be
The second element in the file list is the name of the external manifest file.
Files are to be extracted from the archive. (If there is only one file, that is
created or accessed.
the name of the archive, and all files in it are extracted. Otherwise, the first
element in the file list is the name of the archive, and the remaining
elements in the list are the files that should be extracted from the archive.)
jar cf Xyz.jar *.class *.gif
If a manifest file such as Yxz.mf is available,
it can be used with the following command:
jar cfm Xyz.jar Yxz.mf *.class *.gif
Tabulating the Contents of a JAR File
The following command lists the contents of Xyz.jar:
jar tf Xyz.jar
Extracting Files from a JAR File
The following command extracts the contents of Xyz.jar and places those files in the current
directory:
jar xf Xyz.jar
Recursing Directories
The following command adds all files below
directoryX to Xyz.jar:
jar -uf Xyz.jar -C directoryX *
Java Beans by BRJ
BRJ052
BDK INTROSPECTION
The following sections indicate the design patterns for properties and events that enable the
functionality of a Bean to be determined.
Introspection is the process of exposing the properties, methods, and events that a JavaBeans
component supports.
This process is used at run-time, as well as by a visual development tool at design- time.
The default behavior of this process allows for the automatic introspection of any Bean.
A low-level reflection mechanism is used to analyze the Bean's class to determine its methods.
Next it applies some simple design patterns to determine the properties and events that are
supported.
To take advantage of reflection, you only need to follow a coding style that matches the design
pattern.
This is an important feature of JavaBeans.
It means that you don't have to do anything more than code your methods using a simple
convention.
If you do, your Beans will automatically support introspection without you having to write any
extra code.
appearance of that
public T getN( );
public void setN(T arg);
BRJ053
2) Boolean Properties
A Boolean property has a value of true or false.
It can be identified by the following design patterns,
public boolean isN( );
public boolean getN( );
public void setN(boolean value);
Either the first or second pattern can be used to retrieve the value of a Boolean property.
However, if a class has both of these methods, the first pattern is used.
The following listing shows a class that has one
Boolean property:
public class Line
{
private boolean dotted = false; public boolean isDotted( )
{
return dotted;
}
public void setDotted(boolean dotted)
{
this.dotted = dotted;
}
}
BRJ054
3) Indexed Properties
An indexed property consists of multiple values.
It can be identified by the following design patterns,
public T getN(int index);
public void setN(int index, T value);
public T[ ] getN( );
public void setN(T values[ ]);
The following listing shows a class that has one read/write indexed property:
public class PieChart
{
private double data[ ];
public double getData(int index)
{
return data[index];
}
public void setData(int index, double value)
{
data[index] = value;
}
public double[ ] getData( )
{
return data;
}
public void setData(double[ ] values)
{
data = new double[values.length];
System.arraycopy(values, 0, data, 0, values.length);
}
}
These methods are used by event listeners to register an interest in events of a specific type.
The first pattern indicates that a Bean can multicast an event to multiple listeners.
The second pattern indicates that a Bean can uncast an event to only one listener.
The third pattern is used by a listener when it no lon ge r wishes to receive a specific type of
event notification from a Bean.
The following listing outlines a class that notifies other objects when a temperature value moves
outside a specific range. The two methods indicated here allow other objects that implement the
TemperatureListener interface to r e c e i v e notifications when this occurs.
Java Beans by BRJ
BRJ055
Description
and a
design patterns were used to determine the information that was provided to a Bean user.
This section describes how a developer can use the BeanInfo interface to explicitly control this
process.
This interface defines several methods, including these:
PropertyDescriptor[ ] getPropertyDescriptors( )
EventSetDescriptor[ ] getEventSetDescriptors( )
MethodDescriptor[ ] getMethodDescriptors( )
They return arrays of objects that provide information about the properties, events, and methods
of a Bean.
By implementing these methods, a developer can designate exactly what is presented to a user.
SimpleBeanInfo is a class that provides default implementations of the BeanInfo interface,
including the three methods just shown
Our new component is called the Colors Bean. It appears as either a rectangle or ellipse that
is filled with a color.
A color is chosen at random when the Bean begins execution.
A public method can be invoked to change it. Each time the mouse is clicked on the Bean,
another random color is chosen.
BRJ056
10
Here are the steps that you must follow to create a new Bean:
1. Create a directory for the new Bean.
2. Create the Java source file(s).
3. Compile the source file(s).
4. Create a manifest file.
5. Generate a JAR file.
6. Start the BDK.
7. Test.
STEP: 1 Create a Directory for the New Bean
You need to make a directory for the Bean.
c:\\bdk\\demo\\sunw\\demo\\colors.
Then change to that directory.
BRJ057
11
BRJ058
12
STEP: 7 Test
Create and Configure an Instance of the OurButton Bean
Create an instance of the OurButton Bean in the BeanBox window. Then follow these steps:
1. Go to the Properties window and change the label of the Bean to "Change". You should see that the
button appearance changes immediately when this property is changed.
2. Go to the menu bar of the BeanBox and select Edit | Events | action | actionPerformed.
3. Move the cursor so that it is inside the Colors Bean display area, and click the left mouse button. You
should see the Event Target Dialog dialog box.
4. The dialog box allows you to choose a method that should be invoked when this button is clicked.
Select the entry labeled "change" and click the OK button. You should see a message box appear very
briefly, stating that the tool is "Generating and compiling adaptor class.
5. Click on the button. You should see the color change.
This object maintains the property change listener list and fires property change events. You can
also make your class a PropertyChangeSupport subclass.
BRJ059
13
Modify a property's setter method to fire a property change event when the property is
changed. OurButton's setLabel method looks like this:
public void setLabel(String newLabel)
{
String oldLabel = label;
label = newLabel;
sizeToFit();
changes.firePropertyChange("label", oldLabel, newLabel);
}
Note that setLabel stores the old label value, because both the old and new labels must be passed
to firePropertyChange.
public void firePropertyChange(String propertyName, Object oldValue,Object newValue)
The firePropertyChange method bundles its parameters into a PropertyChangeEvent object,
and calls propertyChange(PropertyChangeEvent pce) on each registered listener.
The old and new values are treated as Object values.
Implementing Bound Property Listeners
So to make your class able to listen and respond to property change events, you must:
1. Implement the PropertyChangeListener interface.
public class MyClass implements java.beans.PropertyChangeListener
java.io.Serializable
BRJ060
14
Now you need to map events generated by the TickTock Bean into method calls on the Colors
Bean.
Follow these steps:
1. Go to the menu bar of the BeanBox and select Edit | Events | propertyChange |
propertyChange.
You should now see a line extending from the button to the cursor.
2. Move the cursor so that it is inside the Colors Bean display area, and click the left
mouse button.
You should see the Event Target Dialog dialog box.
3. The dialog box allows you to choose a method that should be invoked when this event
occurs. Select the entry labeled "change" and click the OK button. You should see a
message box appear very briefly, stating that the tool is "Generating and compiling
adaptor class."
4. You should now see the color of your component change every second
BRJ061
15
Constrained Properties //constrained properties are optional these properties are not in our syllabus
A Bean property is constrained when any change to that property can be vetoed. Usually an
outside object exercises the right to veto, but the Bean itself can also veto a property change.
There are three parts to constrained property implementations:
A source Bean containing one or more constrained properties.
Listener objects that implement the VetoableChangeListener interface. This object accepts
or rejects proposed changes to a constrained property in the source Bean.
A PropertyChangeEvent object containing the property name, and its old and new values.
This is the same class used for bound properties.
Implementing Constrained Property Support Within a Bean
A Bean containing constrained properties must
Allow VetoableChangeListener objects to register and unregister their interest in
receiving notification that a property change is proposed.
Fire property change events at those interested listeners when a property change is
proposed. The event should be fired before the actual property change takes place. This
gives each listener a chance to veto the proposed change. The PropertyChangeEvent is
fired by a call to each listeners vetoableChange method.
If a listener vetoes, then make sure that any other listeners can revert to the old value.
This means reissuing the vetoableChange call to all the listeners, with a
PropertyChangeEvent containing the old value.
The VetoableChangeSupport utility class is provided to implement these capabilities. This class
implements methods to add and remove VetoableChangeListener objects to a listener list, and a
method that fires property change events at each listener in that list when a property change is
proposed. This method will also catch any vetoes, and resend the property change event with the
original property value. Your Bean can either inherit from VetoableChangeSupport, or use an
instance of it.
Note that, in general, constrained properties should also be bound properties. When a
constrained property change does occur, a PropertyChangeEvent can be sent via
PropertyChangeListener.propertyChange to signal all VetoableChangeListener Beans that the
change has taken effect. This lets all the vetoable change listeners know that the change was not
vetoed by any listener.
Here's the steps to implement constrained properties in your Beans:
1) Import the java.beans package. This gives you access to the VetoableChangeSupport class.
2) Instantiate a VetoableChangeSupport object within your Bean:
private VetoableChangeSupport vetos = new VetoableChangeSupport(this);
VetoableChangeSupport manages a list of VetoableChangeListener objects, and fires
property change events at each object in the list when a change occurs to a constrained property.
3) Implement methods to maintain the property change listener list.
public void addVetoableChangeListener( VetoableChangeListener l)
{
vetos.addVetoableChangeListener(l);
}
public void removeVetoableChangeListener( VetoableChangeListener l)
{
vetos.removeVetoableChangeListener(l);
}
4) Write a property's setter method to fire a property change event when the property is
changed.
This includes adding a throws clause to the setter method's signature.
JellyBean's setPriceInCents method looks like this:
BRJ062
16
This section describes how a developer can use the BeanInfo interface to explicitly control this
process.
This interface defines several methods, including these:
PropertyDescriptor[ ] getPropertyDescriptors( )
EventSetDescriptor[ ] getEventSetDescriptors( )
MethodDescriptor[ ] getMethodDescriptors( )
They return arrays of objects that provide information about the properties, events, and methods
of a Bean.
By implementing these methods, a developer can designate exactly what is presented to a user.
// A Bean information class.
package sunw.demo.colors;
import java.beans.*;
public class ColorsBeanInfo extends SimpleBeanInfo {
public PropertyDescriptor[] getPropertyDescriptors() {
try {
PropertyDescriptor rectangular = new
PropertyDescriptor("rectangular", Colors.class);
PropertyDescriptor pd[] = {rectangular};
return pd;
}
catch(Exception e) {
}
return null;
}
}
You must compile this file from the BDK\\demo directory or set CLASSPATH so that it includes
c:\\bdk\\demo. If you don't, the compiler won't find the Colors.class file properly.
After this file is successfully compiled, the colors.mft file can be updated, as shown here:
Name: sunw/demo/colors/ColorsBeanInfo.class
Name: sunw/demo/colors/Colors.class
Java-Bean: True
Use the JAR tool to create a new colors.jar file. Restart the BDK and create an instance of the
Colors Bean in the BeanBox.
Java Beans by BRJ
BRJ063
17
Persistence
Persistence is the ability to save a Bean to nonvolatile storage and retrieve it at a later time.
Let us first see how the BDK allows you to save a set of Beans that have been configured and
connected together to form an application. Recall our previous example involving both the
Colors and TickTock Beans.
The rectangular property of the Colors Bean was changed to true, and the interval property of
the TickTock Bean was changed to one second.
To save the application, go to the menu bar of the BeanBox and select File | Save.
A dialog box should appear, allowing you to specify the name of a file to which the Beans and
their configuration parameters should be saved. Supply a filename and click the OK button on
that dialog box. Exit from the BDK.
Start the BDK again. To restore the application, go to the menu bar of the BeanBox and select File
| Load. A dialog box should appear, allowing you to specify the name of the file from which an
application should be restored.
Supply the name of the file in which the application was saved, and click the OK button. Your
application should now be functioning.
Confirm that the rectangular property of the Colors Bean is true and that the interval property
for the TickTock Bean is equal to one second.
The object serialization capabilities provided by the Java class libraries are used to provide
persistence for Beans.
If a Bean inherits directly or indirectly from java.awt.Component, it is automatically
serializable, because that class implements the java.io.Serializable interface.
If a Bean does not inherit an implementation of the Serializable interface, you must provide this
yourself. Otherwise, containers cannot save the configuration of your component.
The transient keyword can be used to designate data members of a Bean that should not be
serialized. The color variable of the Colors class is an example of such an item.
BRJ064
18
SWINGS
(UNIT-III)
SNO. CONTENTS
PAGE NO.
SWINGS
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
Icons
JApplet
Labels
Buttons
Checkboxes
Text Boxes
Combo Boxes
Tabbed Panes
11
Scroll Panes
12
Trees
14
Tables.
13
1 |B R J
BRJ065
000001
Introduction to swing
Swing is a set of classes that provides more powerful and flexible components than are possible with
the AWT.
Swing provides a set of "lightweight" (all-Java language) components that, to the maximum degree
possible, work the same on all platforms.
The term lightweight is used to describe such elements. The Swing component classes that are used are
shown here:
Class
AbstractButton
ButtonGroup
ImageIcon
JApplet
JButton
JCheckBox
JComboBox
JLabel
JRadioButton
JScrollPane
JTabbedPane
JTable
JTextField
JTree
Description
o
o
o
o
o
In addition to the familiar components, such as buttons, check boxes, and labels, Swing supplies
several exciting additions, including tabbed panes, scroll panes, trees, and tables.
Components such as buttons have more capabilities in Swing. For example, a button may have
both an image and a text string associated with it. Also, the image can be changed as the state of
the button changes.
Swing components are not implemented by platform-specific code. Instead, they are written
entirely in Java and, therefore, are platform-independent.
You can easily add or change the borders drawn around most Swing components. For example,
it's easy to put a box around the outside of a container or label.
You can easily change the behavior or appearance of a Swing component by either invoking
methods on it or creating a subclass of it.
Swing components don't have to be rectangular. Buttons, for example, can be round.
Assistive technologies such as screen readers can easily get information from Swing
components. For example, a tool can easily get the text that's displayed on a button or label.
The biggest difference between the AWT components and Swing components is that the Swing
components are implemented with absolutely no native code. Since Swing components aren't restricted
to the least common denominator -- the features that are present on every platform -- they can have
more functionality than AWT components.
Swing lets you specify which look and feel your program's GUI uses. By contrast, AWT components
always have the look and feel of the native platform.
2 |B R J
BRJ066
000002
AWT
SWING
Heavy weight
Native component
Native look and feel
Does not have complex component
Light weight
Pure java Component
Better look and feel
Has additional components like JTree, JTable,
JProgressBar, JSlider, etc
JApplet can have menu.
JList does not support scrolling but this can be done
using scrollPane
While adding components on Frame or window, they
have to be added on its conetent pane.
Has slidePane or TabbedPane
MDI can be achived using InternalFrame Object
Menu item can have images or radio buttons or
checkboxes.
All swing components have JMV
Default layout is BorderLayout.
JApplet
Fundamental to Swing is the JApplet class, which extends Applet. Applets that use Swing must be
subclasses of JApplet.
JApplet are specialized components that provide a place for other Swing components to paint
themselves.
JApplet supports various "panes," such as the content pane, the glass pane, and the root pane.
When adding a component to an instance of JApplet, do not invoke the add() method of the applet.
Instead, call add() for the content pane of the JApplet object.
The content pane can be obtained via the method shown here:
Container getContentPane( )
The add( ) method of Container can be used to add a component to a content pane. Its form is shown
here:
void add(comp)
Here, comp is the component to be added to the content pane.
Example:-
3 |B R J
BRJ067
000003
In Swing, icons are encapsulated by the ImageIcon class, which paints an icon from an image.
Two of its constructors are shown here:
1. ImageIcon(String filename):- Creates an ImageIcon from the specified file.
ImageIcon(URL url):- Creates an ImageIcon from the specified URL.
The ImageIcon class implements the Icon interface that declares the methods shown here:
Method
1. int getIconHeight( )- Returns the height of the icon in pixels.
2. int getIconWidth( )- Returns the width of the icon in pixels.
3. void paintIcon(Component comp,Graphics g,int x, int y)- Paints the icon at position x, y on the
graphics context g. Additional information about the paint operation can be provided in comp.
Labels
Swing labels are instances of the JLabel class, which extends JComponent.
Labels can display text and/or an icon.
Some of its constructors are shown here:
1. JLabel(Icon i):- Creates a JLabel instance with the specified image.
2. JLabel(String s):- Creates a JLabel instance with the specified text.
3. JLabel(String s, Icon i, int align):- Creates a JLabel instance with the specified text, image, and
horizontal alignment. The align argument is either LEFT, RIGHT, or CENTER. These constants
are defined in the SwingConstants interface, along with several others used by the Swing
classes.
The icon and text associated with the label can be read and written by the following methods:
1. Icon getIcon( ):- Returns the graphic image (glyph, icon) that the label displays.
2. String getText( ):- Returns the text string that the label displays.
3. void setIcon(Icon i):- Defines the icon this component will display.
4. void setText(String s):- Defines the single line of text this component will display.
Example:
The following example illustrates how to create and display a label containing both an icon and a string.
The applet begins by getting its content pane. Next, an ImageIcon object is created for the file
france.gif. This is used as the second argument to the JLabel constructor. The first and last arguments
for the JLabel constructor are the label text and the alignment. Finally, the label is added to the content
pane.
import java.awt.*;
import javax.swing.*;
/*
<applet code="JLabelDemo" width=250 height=150>
</applet>
*/
public class JLabelDemo extends JApplet
{
public void init()
{
// Get content pane
Container contentPane = getContentPane();
// Create an icon
ImageIcon ii = new ImageIcon("france.gif");
// Create a label
JLabel jl = new JLabel("France", ii, JLabel.CENTER);
// Add label to the content pane
contentPane.add(jl);
}
}
4 |B R J
BRJ068
000004
Buttons
Swing buttons provide features that are not found in the Button class defined by the AWT.
For example, you can associate an icon with a Swing button. Swing buttons are subclasses of the
AbstractButton class, which extends JComponent. AbstractButton contains many methods that allow
you to control the behavior of buttons, check boxes, and radio buttons.
For example, you can define different icons that are displayed for the component when it is disabled,
pressed, or selected. Another icon can be used as a rollover icon, which is displayed when the mouse is
positioned over that component.
The following are the methods that control this behavior:
1. void setDisabledIcon(Icon di):-Sets the disabled icon for the button.
2. void setPressedIcon(Icon pi):- Sets the pressed icon for the button.
3. void setSelectedIcon(Icon si):- Sets the selected icon for the button.
4. void setRolloverIcon(Icon ri):- Sets the rollover icon for the button
The text associated with a button can be read and written via the following methods:
1. String getText( ):- Returns the button's text.
2. void setText(String s):- Sets the button's text.
Concrete subclasses of AbstractButton generate action events when they are pressed. Listeners
register and unregistered for these events via the methods shown here:
void addActionListener(ActionListener al)
void removeActionListener(ActionListener al)
Here, al is the action listener.
The JButton class provides the functionality of a push button. JButton allows an icon, a string, or both
to be associated with the push button.
Some of its constructors are shown here:
1. JButton(Icon i):- Creates a button with an icon.
2. JButton(String s):- Creates a button with text.
3. JButton(String s, Icon i):- Creates a button with initial text and an icon.
Example:-The following example displays four push buttons. First button displays only text and other
three buttons display text along with the icon.
5 |B R J
import java.awt.*;
import javax.swing.*;
public class JButtons extends JFrame
{
public static void main(String[] args)
{
new JButtons();
}
public JButtons()
{
super("Using JButton");
//WindowUtilities.setNativeLookAndFeel();
//addWindowListener(new ExitListener());
Container content = getContentPane();
content.setBackground(Color.white);
content.setLayout(new FlowLayout());
JButton button1 = new JButton("Java");
content.add(button1);
ImageIcon cup = new ImageIcon("iso.gif");
JButton button2 = new JButton(cup);
content.add(button2);
JButton button3 = new JButton("Java", cup);
content.add(button3);
JButton button4 = new JButton("Java", cup);
button4.setHorizontalTextPosition
(SwingConstants.LEFT);
content.add(button4);
pack();
setVisible(true);
}
}
BRJ069
000005
Another Example:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
/*
<applet code="JButtonDemo" width=250 height=300>
</applet>
*/
public class JButtonDemo extends JApplet
implements ActionListener {
JTextField jtf;
public void init() {
// Get content pane
Container contentPane = getContentPane();
contentPane.setLayout(new FlowLayout());
// Add buttons to content pane
ImageIcon france = new ImageIcon("france.gif");
JButton jb = new JButton(france);
jb.setActionCommand("France");
jb.addActionListener(this);
contentPane.add(jb);
ImageIcon germany = new ImageIcon("germany.gif");
jb = new JButton(germany);
jb.setActionCommand("Germany");
jb.addActionListener(this);
contentPane.add(jb);
ImageIcon italy = new ImageIcon("italy.gif");
jb = new JButton(italy);
jb.setActionCommand("Italy");
jb.addActionListener(this);
contentPane.add(jb);
ImageIcon japan = new ImageIcon("japan.gif");
jb = new JButton(japan);
jb.setActionCommand("Japan");
jb.addActionListener(this);
contentPane.add(jb);
// Add text field to content pane
jtf = new JTextField(15);
contentPane.add(jtf);
}
public void actionPerformed(ActionEvent ae)
{
jtf.setText(ae.getActionCommand());
}
}
Check Boxes
6 |B R J
The JCheckBox class, which provides the functionality of a check box, is a concrete implementation of
AbstractButton.
This is an implementation of a check box, which is an item that can be selected or deselected, and which
displays its state to the user.
Some of its constructors are shown here:
1. JCheckBox(Icon i):- Creates an initially unselected check box with an icon.
2. JCheckBox(Icon i, boolean state):- Creates a check box with an icon and specifies whether or
not it is initially selected.
3. JCheckBox(String s):- Creates an initially unselected check box with text.
4. JCheckBox(String s, boolean state):- Creates a check box with text and specifies whether or
not it is initially selected.
5. JCheckBox(String s, Icon i):- Creates an initially unselected check box with the specified text
and icon.
6. JCheckBox(String s, Icon i, boolean state):- Creates a check box with text and icon, and
specifies whether or not it is initially selected.
The state of the check box can be changed via the following method:
BRJ070
000006
1. void setSelected(boolean state):- Sets the state of the button. Here, state is true if the check
box should be checked.
Example:
The following example illustrates how to create an applet that displays four check boxes and a text field.
When a check box is pressed, its text is displayed in the text field. When a check box is selected or
deselected, an item event is generated. This is handled by itemStateChanged( ). Inside
itemStateChanged( ), the getItem( ) method gets the JCheckBox object that generated the event. The
getText( ) method gets the text for that check box and uses it to set the text inside the text field.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
/*
<applet code="JCheckBoxDemo" width=400 height=50>
</applet>
*/
public class JCheckBoxDemo extends JApplet
implements ItemListener
{
JTextField jtf;
public void init()
{
// Get content pane
Container contentPane = getContentPane();
contentPane.setLayout(new FlowLayout());
// Create icons
ImageIcon normal = new ImageIcon("normal.gif");
ImageIcon rollover = new ImageIcon("rollover.gif");
ImageIcon selected = new ImageIcon("selected.gif");
// Add check boxes to the content pane
JCheckBox cb = new JCheckBox("C", normal);
cb.setRolloverIcon(rollover);
cb.setSelectedIcon(selected);
cb.addItemListener(this);
contentPane.add(cb);
cb = new JCheckBox("C++", normal);
cb.setRolloverIcon(rollover);
cb.setSelectedIcon(selected);
cb.addItemListener(this);
contentPane.add(cb);
cb = new JCheckBox("Java", normal);
cb.setRolloverIcon(rollover);
cb.setSelectedIcon(selected);
cb.addItemListener(this);
contentPane.add(cb);
cb = new JCheckBox("Perl", normal);
cb.setRolloverIcon(rollover);
cb.setSelectedIcon(selected);
cb.addItemListener(this);
contentPane.add(cb);
// Add text field to the content pane
jtf = new JTextField(15);
contentPane.add(jtf);
}
public void itemStateChanged(ItemEvent ie)
{
JCheckBox cb = (JCheckBox)ie.getItem();
jtf.setText(cb.getText());
}
}
Text Fields
7 |B R J
The Swing text field is encapsulated by the JTextComponent class, which extends JComponent.
It provides functionality that is common to Swing text components.
One of its subclasses is JTextField.
JTextField is a lightweight component that allows the editing of a single line of text.
BRJ071
000007
JTextField components generate ActionEvents whenever the user presses the Return key within the
field. To get these events, implement the ActionListener interface and register your listener using the
addActionListener() method.
Example:
The following example illustrates how to create a text field. The applet begins by getting its content
pane, and then a flow layout is assigned as its layout manager. Next, a JTextField object is created and
is added to the content pane.
import java.awt.*;
import javax.swing.*;
/*
<applet code="JTextFieldDemo" width=300 height=50>
</applet>
*/
public class JTextFieldDemo extends JApplet
{
JTextField jtf;
public void init()
{
// Get content pane
Container contentPane = getContentPane();
contentPane.setLayout(new FlowLayout());
// Add text field to content pane
jtf = new JTextField(15);
contentPane.add(jtf);
}
}
JTextArea
8 |B R J
BRJ072
000008
Combo Boxes
Swing provides a combo box (a combination of a text field and a drop-down list)
Through the JComboBox class, which extends JComponent?
A combo box normally displays one entry.
However, it can also display a drop-down list that allows a user to select a different entry.
Two of JComboBox's constructors are shown here:
JComboBox( )
JComboBox(Vector v)
Here, v is a vector that initializes the combo box.
Items are added to the list of choices via the addItem( ) method,
whose signature is shown here:
void addItem (Object ob)
Here, obj is the object to be added to the combo box.
Example:The following example contains a combo box and a label. The label displays an
icon. The combo box contains entries for France, Germany, Italy, and Japan.
When a country is selected, the label is updated to display the flag for that country.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
/*
<applet code="JComboBoxDemo" width=300 height=100>
</applet>
*/
public class JComboBoxDemo extends JApplet
implements ItemListener {
JLabel jl;
ImageIcon france, germany, italy, japan;
public void init() {
// Get content pane
Container contentPane = getContentPane();
contentPane.setLayout(new FlowLayout());
// Create a combo box and add it
// to the panel
JComboBox jc = new JComboBox();
jc.addItem("France");
jc.addItem("Germany");
jc.addItem("Italy");
jc.addItem("Japan");
jc.addItemListener(this);
contentPane.add(jc);
// Create label
jl = new JLabel(new ImageIcon("france.gif"));
contentPane.add(jl);
}
public void itemStateChanged(ItemEvent ie) {
String s = (String)ie.getItem();
jl.setIcon(new ImageIcon(s + ".gif"));
}
}
Radio Buttons
9 |B R J
Radio buttons are supported by the JRadioButton class, which is a concrete implementation of
AbstractButton.
Some of its constructors are shown here:
1. JRadioButton(Icon i):- Creates an initially unselected radio button with the specified image but
no text.
2. JRadioButton(Icon i, Boolean state):- Creates a radio button with the specified image and
selection state, but no text.
3. JRadioButton(String s):- Creates an unselected radio button with the specified text.
BRJ073
000009
4. JRadioButton(String s, boolean state):- Creates a radio button with the specified text and
selection state.
5. JRadioButton(String s, Icon i):- Creates a radio button that has the specified text and image,
and that is initially unselected.
6. JRadioButton(String s, Icon i, boolean state):- Creates a radio button that has the specified
text, image, and selection state.
Radio buttons must be configured into a group. Only one of the buttons in that group can be selected at
any time.
The ButtonGroup class is instantiated to create a button group. Elements are then added to the button
group via the following method:
void add(AbstractButton ab)
Here, ab is a reference to the button to be added to the group.
Example:
The following example displays three radio buttons and one text field are created. When a radio button
is pressed, its text is displayed in the text field. Radio button presses generate action events that are
handled by actionPerformed( ). The getActionCommand( ) method gets the text that is associated
with a radio button and uses it to set the text field.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
/*
<applet code="JRadioButtonDemo" width=300 height=50>
</applet>
*/
public class JRadioButtonDemo extends JApplet
implements ActionListener
{
JTextField tf;
public void init()
{
// Get content pane
Container contentPane = getContentPane();
contentPane.setLayout(new FlowLayout());
// Add radio buttons to content pane
JRadioButton b1 = new JRadioButton("A");
b1.addActionListener(this);
contentPane.add(b1);
JRadioButton b2 = new JRadioButton("B");
b2.addActionListener(this);
contentPane.add(b2);
JRadioButton b3 = new JRadioButton("C");
b3.addActionListener(this);
contentPane.add(b3);
// Define a button group
ButtonGroup bg = new ButtonGroup();
bg.add(b1);
bg.add(b2);
bg.add(b3);
// Create a text field and add it
// to the content pane
tf = new JTextField(5);
contentPane.add(tf);
}
public void actionPerformed(ActionEvent ae)
{
tf.setText(ae.getActionCommand());
}
}
10 |B R J
BRJ074
000010
Tabbed Panes
A tabbed pane is a component that appears as a group of folders in a file cabinet. Each folder has a title.
Tabbed panes are commonly used for setting configuration options.
Tabbed panes are encapsulated by the JTabbedPane class, which extends JComponent.
Constructor:
o JTabbedPane() :-Creates an empty TabbedPane with a default tab placement of
JTabbedPane.TOP
o JTabbedPane(int tabPlacement) :-Creates an empty TabbedPane with the specified tab
placement of either: JTabbedPane.TOP, JTabbedPane.BOTTOM, JTabbedPane.LEFT, or
JTabbedPane.RIGHT.
o JTabbedPane(int tabPlacement, int tabLayoutPolicy):-Creates an empty TabbedPane with
the specified tab placement and tab layout policy.
Tabs are defined via the following method:
o void addTab(String str, Component comp):- Adds a component represented by a title and no
icon.
Parameters:
Example:
The following example illustrates how to create a tabbed pane. The first tab is titled "Cities" and
contains four buttons. Each button displays the name of a city. The second tab is titled "Colors" and
contains three check boxes. Each check box displays the name of a color. The third tab is titled "Flavors"
and contains one combo box. This enables the user to select one of three flavors.
11 |B R J
import javax.swing.*;
/*
<applet code="JTabbedPaneDemo" width=400 height=100>
</applet>
*/
public class JTabbedPaneDemo extends JApplet
{
public void init()
{
JTabbedPane jtp = new JTabbedPane();
jtp.addTab("Cities", new CitiesPanel());
jtp.addTab("Colors", new ColorsPanel());
jtp.addTab("Flavors", new FlavorsPanel());
getContentPane().add(jtp);
}
}
class CitiesPanel extends JPanel
{
public CitiesPanel()
{
JButton b1 = new JButton("New York");
add(b1);
JButton b2 = new JButton("London");
add(b2);
JButton b3 = new JButton("Hong Kong");
add(b3);
JButton b4 = new JButton("Tokyo");
add(b4);
}
}
class ColorsPanel extends JPanel
BRJ075
000011
{
public ColorsPanel()
{
JCheckBox cb1 = new JCheckBox("Red");
add(cb1);
JCheckBox cb2 = new JCheckBox("Green");
add(cb2);
JCheckBox cb3 = new JCheckBox("Blue");
add(cb3);
}
}
class FlavorsPanel extends JPanel
{
public FlavorsPanel()
{
JComboBox jcb = new JComboBox();
jcb.addItem("Vanilla");
jcb.addItem("Chocolate");
jcb.addItem("Strawberry");
add(jcb);
}
}
Scroll Panes
A scroll pane is a component that presents a rectangular area in which a component may be viewed.
Horizontal and/or vertical scroll bars may be provided if necessary.
Scrollpanes are implemented in Swing by the JScrollPane class, which extends JComponent.
Some of its constructors are shown here:
1. JScrollPane(Component comp):- Creates a JScrollPane that displays the contents of the
specified component, where both horizontal and vertical scrollbars appear whenever the
component's contents are larger than the view.
2. JScrollPane(int vsb, int hsb):- Creates an empty (no viewport view) JScrollPane with specified
scrollbar constants.
3. JScrollPane(Component comp, int vsb, int hsb):- Creates a JScrollPane that displays the view
component in a viewport whose view position can be controlled with a pair of scrollbars.
These constants are defined by the ScrollPaneConstants interface. Some
examples of these constants are described as follows:
Example:The following example illustrates a scroll pane. First, the content pane of the JApplet object is obtained and
a border layout is assigned as its layout manager. Next, a JPanel object is created and four hundred buttons
are added to it, arranged into twenty columns.The panel is then added to a scroll pane, and the scroll pane
is added to the content pane. This causes vertical and horizontal scroll bars to appear.
You can use the scrollbars to scroll the buttons into view.
import java.awt.*;
import javax.swing.*;
/*
<applet code="JScrollPaneDemo" width=300 height=250>
</applet>
*/
public class JScrollPaneDemo extends JApplet
{
12 |B R J
BRJ076
000012
Tables
A table is a component that displays rows and columns of data. You can drag the cursor on column
boundaries to resize columns. You can also drag a column to a new position.
Tables are implemented by the JTable class, which extends JComponent.
Constructors
o JTable(Object data[ ][ ], Object colHeads[ ]):- Constructs a JTable to display the values in the two
dimensional array, rowData, with column names, columnNames.
o JTable(int numRows, int numColumns):-Constructs a JTable with numRows and numColumns of
empty cells using DefaultTableModel.
Here are the steps for using a table in an applet:
1. Create a JTable object.
2. Create a JScrollPane object.
3. Add the table to the scroll pane.
4. Add the scroll pane to the content pane of the applet.
Example:
The following example illustrates how to create and use a table. The content pane of the JApplet object is
obtained and a border layout is assigned as its layout manager. This table has three columns. A twodimensional array of strings is created for the table cells. These arrays are passed to the JTable constructor.
The table is added to a scroll pane and then the scroll pane is added to the content pane.
import java.awt.*;
import javax.swing.*;
/*
<applet code="JTableDemo" width=400 height=200>
</applet>
*/
public class JTableDemo extends JApplet
{
public void init()
{
// Get content pane
Container contentPane = getContentPane();
// Set layout manager
contentPane.setLayout(new BorderLayout());
// Initialize column headings
final String[] colHeads = { "Name", "Roll No", "Address", "Percentage" };
// Initialize data
final Object[][] data = {
{ "Ramesh Shetty","1","kalina","67%" },
13 |B R J
BRJ077
000013
{ "Kapil Varma","2","bandra","45%" },
{ "Ritu Singh", "3","malad","56%" },
{ "Amita Jadhav","4","miraroad","89%" },
{ "Sumit Sahani", "5","mahim","79%" },
Trees
One of Swing's advanced components is JTree. Trees are good for representing hierarchical information, like
the contents of a disk drive or a company's organizational chart.
The classes that support JTree have their own package, javax.swing.tree.
A tree's data model is made up of interconnected nodes. A node has a name, typically, a parent, and some
number of children (possibly 0).
In Swing, a node is represented by the TreeNode interface. Nodes that can be modified are represented by
MutableTreeNode. A concrete implementation of this interface is DefaultMutableTreeNode. One node, called
the root node, usually resides at the top of the hierarchy.
A tree's data model is represented by the TreeModel interface. Swing provides an implementation of this
interface called DefaultTreeModel. You can create a DefaultTreeModel by passing a root TreeNode to its
constructor.
You could create a TreeMdel with just one node like this:
TreeNode root = new DefaultMutableTreeNode("Root node");
TreeModel model = new DefaultTreeModel(root);
The second parameter to the insert() method is the index of the node in the parent.
Once you've got your nodes organized, you can create a TreeModel in the same way as before:
TreeModel model = new DefaultTreeModel(root);
Tree Events
A tree fires several events. You can find out when nodes have been expanded and collapsed, and when
selections occur. Two distinct event listener interfaces handle this information.
TreeExpansionListener
TreeSelectionListener
The following example registers an event listener that prints out the last selected node:
tree.addTreeSelectionListener(new TreeSelectionListener( )
{
public void valueChanged(TreeSelectionEvent e) {
TreePath tp = e.getNewLeadSelectionPath( );
System.out.println(tp.getLastPathComponent( ));
}
});
14 |B R J
BRJ078
000014
JTree(TreeNode root):-Returns a JTree with the specified TreeNode as its root, which displays the
root node.
o JTree(Object [] value):- Returns a JTree with each element of the specified array as the child of a
new root node which is not displayed.
Interfaces associated with the trees are:o MutableTreeNode:-Defines the requirements for a tree node object that can change -- by adding or
removing child nodes, or by changing the contents of a user object stored in the node.
Event class:o TreeExpansionEvent:-An event used to identify a single path in a tree. The source returned by
getSource will be an instance of JTree.
Other Classes associated with the trees are:o DefaultMutableTreeNode :-DefaultMutableTreeNode implements the MutableTreeNode interface A
DefaultMutableTreeNode is a general-purpose node in a tree data structure. A tree node may have at
most one parent and 0 or more children. DefaultMutableTreeNode provides operations for examining
and modifying a node's parent and children and also operations for examining the tree that the
node is a part of.
o TreeModel:- A simple tree data model that uses TreeNodes
o TreePath:- Represents a path to a node. A TreePath is an array of Objects that are taken from a
TreeModel. The elements of the array are ordered such that the root is always the first element
(index 0) of the array.
Methods associated with trees are:o public void add(MutableTreeNode newChild):-Removes newChild from its parent and makes it a
child of this node by adding it to the end of this node's child array.
o public TreeNode[] getPath():-Returns the path from the root, to get to this node. The last element in
the path is this node.
o public Object[] getPath():-Returns an ordered array of Objects containing the components of this
TreePath. The first element (index 0) is the root.
o public void insert(MutableTreeNode newChild,int childIndex):-Removes newChild from its
present parent (if it has a parent), sets the child's parent to this node, and then adds the child to this
node's child array at index childIndex. newChild must not be null and must not be an ancestor of
this node.
Here are the steps that you should follow to use a tree:o Create a JTree object.
o Create a JScrollPane Object.
o Add the tree to the scroll panes.
o Add the scroll to the content pane of the applet.
o
Example:-
import java.awt.*;
import javax.swing.*;
import javax.swing.tree.*;
public class JTreeExample extends JFrame
{
JTreeExample()
{
MutableTreeNode it = new DefaultMutableTreeNode("IT Department");
MutableTreeNode fyit = new DefaultMutableTreeNode("FYIT");
MutableTreeNode syit = new DefaultMutableTreeNode("SYIT");
it.insert(fyit,0);
it.insert(syit,1);
fyit.insert(new DefaultMutableTreeNode("Maths-2"), 0);
fyit.insert(new DefaultMutableTreeNode("DAA"), 1);
fyit.insert(new DefaultMutableTreeNode("ETC"), 2);
fyit.insert(new DefaultMutableTreeNode("PSD"), 3);
fyit.insert(new DefaultMutableTreeNode("CG"), 4);
syit.insert(new DefaultMutableTreeNode("DBMS"), 1);
syit.insert(new DefaultMutableTreeNode("OS"), 2);
syit.insert(new DefaultMutableTreeNode("C++,JAVA"), 3);
syit.insert(new DefaultMutableTreeNode("EComm"), 4);
syit.insert(new DefaultMutableTreeNode("SE"), 5);
15 |B R J
BRJ079
000015
setSize(300,300);
setVisible(true);
This section contains an example that showcases the following tree techniques:
}
public static void main(String[] args)
{
new JTreeExample();
16 |B R J
BRJ080
000016
addPanel.add(button);
// listen for selections
tree.addTreeSelectionListener(new TreeSelectionListener( ) {
public void valueChanged(TreeSelectionEvent e) {
TreePath tp = e.getNewLeadSelectionPath( );
button.setEnabled(tp != null);
}
});
// create a JFrame to hold the tree
JFrame frame = new JFrame("PartsTree v1.0");
frame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
frame.setSize(200, 200);
frame.getContentPane( ).add(new JScrollPane(tree));
frame.getContentPane( ).add(addPanel, BorderLayout.SOUTH);
frame.setVisible(true);
}}
Another Example:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.tree.*;
/*
*/
<applet code="JTreeEvents" width=400 height=200>
</applet>
public class JTreeEvents extends JApplet {
JTree tree;
JTextField jtf;
public void init() {
// Get content pane
Container contentPane = getContentPane();
// Set layout manager
contentPane.setLayout(new BorderLayout());
// Create top node of tree
DefaultMutableTreeNode top = new DefaultMutableTreeNode("Options");
// Create subtree of "A"
DefaultMutableTreeNodea=new DefaultMutableTreeNode("A");
top.add(a);
DefaultMutableTreeNode a1 = new DefaultMutableTreeNode("A1");
a.add(a1);
DefaultMutableTreeNode a2 = new DefaultMutableTreeNode("A2");
a.add(a2);
// Create subtree of "B"
DefaultMutableTreeNodeb=new DefaultMutableTreeNode("B");
top.add(b);
DefaultMutableTreeNode b1 = new DefaultMutableTreeNode("B1");
b.add(b1);
DefaultMutableTreeNode b2 = new DefaultMutableTreeNode("B2");
b.add(b2);
DefaultMutableTreeNode b3 = new DefaultMutableTreeNode("B3");
b.add(b3);
// Create tree
tree = new JTree(top);
// Add tree to a scroll pane
int v = ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED;
int h = ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED;
JScrollPane jsp = new JScrollPane(tree, v, h);
// Add scroll pane to the content pane
contentPane.add(jsp, BorderLayout.CENTER);
}
// Add text field to applet
jtf = new JTextField("", 20);
contentPane.add(jtf, BorderLayout.SOUTH);
// Anonymous inner class to handle mouse clicks
tree.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent me) {
doMouseClicked(me);
}
});
void doMouseClicked(MouseEvent me) {
TreePath tp = tree.getPathForLocation(me.getX(), me.getY());
if(tp != null)
jtf.setText(tp.toString());
else
}
jtf.setText("");
}
17 |B R J
BRJ081
000017
JAVA SERVLETS
JAVA SERVLETS
SNO..
CONTENTS
PAGE NO.,
Simple servlet
2
3
4
5
6
7
8
9
Lifecycle of a servlet
Session tracking.
7
8
9
10
1|BRJ
BRJ082
Java Servlets are programs that run on a Web server or Application server and act as a middle layer between a requests coming
from a Web browser or other HTTP client and databases or applications on the HTTP server.
Using Servlets, you can collect input from users through web page forms, present records from a database or another source, and
create web pages dynamically.
With traditional CGI, a new process is started for the each HTTP request.
If the CGI program does a relatively fast operation, the overhead of starting the process can dominate the execution of time.
With servlets, the Java Virtual Machine stays up, and each request is handled by a lightweight Java thread, not the heavyweight
operating system process.
Similarly, in traditional CGI, if there are N simultaneous request to the same CGI program, then the for the CGI program is
loaded into memory N time.
With servlets, however, there are N threads but only a single copy of the servlets class.
Servlets also have more alternatives than do regular CGI programs for optimizations such as caching previous computations,
keeping the database connections open, and the like.
Convenient
servlets have an extensive infrastructure for automatically parsing and decoding the HTML form data, reading and setting
HTTP headers, handling cookies, tracking sessions, and many other such utilities.
Powerful
Java servlets let you easily do several things that are difficult or impossible with the regular CGI.
servlets can talk directly to Web server (regular CGI programs can't).
This simplifies operations that need to look up images and other data stored in the standard places.
Servlets can also share data among each other, making the useful things like database connection pools easy to implement.
They can also maintain information from request to request, simplifying things like session tracking and caching of previous
computation.
Portable
Server can also run virtually unchanged on Apache, Microsoft IIS, or WebStar.
Servlets are supported directly or via a plug-in on the almost every major Web server.
Inexpensive
There are also a num of free or inexpensive Web servers available that are good for "personal" use or low-volume Web sites.
However, with major exception of Apache, which is free, most commercial-quality Web servers are relatively expensive.
Nevertheless, once you have a Web server, no matter the cost of that server, adding servlets support to it (if it doesn't come
preconfigured to support servlets) is generally free or cheap.
Lifecycle of a servlet
A servlet life cycle can be defined as the entire process from its creation till the destruction.
The following are the paths followed by a servlet
1) The servlet is initialized by calling the init () method.
2) The servlet calls service() method to process a client's request.
3) The servlet is terminated by calling the destroy() method.
4) Finally, servlet is garbage collected by the garbage collector of the JVM.
Now let us discuss the life cycle methods in details.
It is called when the servlet is first created, and not called again for each user request.
So, it is used for one-time initializations, just as with the init method of applets.
The servlet is normally created when a user first invokes a URL corresponding to the servlet, but you can also specify that the
servlet be loaded when the server is first started.
When a user invokes a servlet, a single instance of each servlet gets created, with each user request resulting in a new thread
that is handed off to doGet or doPost as appropriate.
The init() method simply creates or loads some data that will be used throughout the life of the servlet.
2|BRJ
BRJ083
The service () method is called by the container and service method invokes doGet(), doPost(), doPut(), doDelete(), etc..
methods as appropriate.
So you have nothing to do with service() method but you override either doGet() or doPost() depending on what type of
request you receive from the client.
The doGet() and doPost() are most frequently used methods within each service request.
Here are the signature of these two methods.
The doGet() Method
A GET request results from a normal request for a URL or from an HTML form that has no METHOD specified and it should be handled
by doGet() method.
public void doGet(HttpServletRequest request,HttpServletResponse response)throws ServletException, IOException
{
// Servlet code
}
// Finalization code...
Sample Servlet
we will begin by building and testing a simple servlet. The basic steps are the following:
1) Create and compile the servlet source code.
2) Start Tomcat.
3) Start a Web browser and request the servlet.
Let us examine each of these steps in detail.
To begin, create a file named HelloServlet.java that contains the following program:
3|BRJ
BRJ084
import java.io.*;
import javax.servlet.*;
public class HelloServlet extends GenericServlet
{
public void service(ServletRequest request,ServletResponse response)throws ServletException, IOException
{
response.setContentType("text/html");
PrintWriter pw = response.getWriter();
pw.println("<B>Hello!");
pw.close();
}
}
Lets look closely at this program. First, note that it imports the javax.servlet package.
This package contains the classes and interfaces required to build servlets.
the program defines HelloServlet as a subclass of GenericServlet.
The GenericServlet class provides functionality that makes it easy to handle requests and responses.
Inside HelloServet, the service( ) method (which is inherited from GenericServlet) is overridden.
This method handles requests from a client.
Notice that the first argument is a ServletRequest object.
This enables the servlet to read data that is provided via the client request.
The second argument is a ServletResponse object. This enables the servlet to formulate a response for the client.
The call to setContentType( ) establishes the MIME type of the HTTP response.
In this program, the MIME type is text/html. This indicates that the browser should interpret the content as HTML source code.
Next, the getWriter( ) method obtains a PrintWriter.
Anything written to this stream is sent to the client as part of the HTTP response.
Then println( ) is used to write some simple HTML source code as the HTTP response.
Compile this source code and place the HelloServlet.class file in the Tomcat class files directory.
2) Start Tomcat
As explained, to start Tomcat, select Start Tomcat in the Start | Programs menu, or run startup.bat from the
C:\Program Files\Apache Tomcat 4.0\bin\ directory.
http://localhost:8080/examples/servlet/HelloServlet
http://127.0.0.1:8080/examples/servlet/HelloServlet
This can be done because 127.0.0.1 is defined as the IP address of the local machine.
You will observe the output of the servlet in the browser display area. It will contain the string Hello! in bold type.
Two packages contain the classes and interfaces that are required to build servlets.
These packages are javax.servlet and javax.servlet.http.
These constitute the Servlet API.
These packages are not part of the Java core packages. Instead, they are standard extensions.
Therefore, they are not included in the Java Software Development Kit.
You must download Tomcat to obtain their functionality.
The Servlet API has been in a process of ongoing development and enhancement.
The current servlet specification is version is 2.3
The Servlet API is supported by most Web servers, such as those from Sun, Microsoft, and others.
Check at http://java.sun.com for the latest information.
4|BRJ
BRJ085
The javax.servlet package contains a number of interfaces and classes that establish the framework in which servlets operate.
The following table summarizes the core interfaces that are provided in this package.
The most significant of these is Servlet.
All servlets must implement this interface or extend a class that implements the interface.
The ServletRequest and ServletResponse interfaces are also very important.
The following table summarizes the core classes that are provided in the javax.servlet package.
It declares the init( ), service( ), and destroy( ) methods that are called by the server during the life cycle of a servlet.
A method is also provided that allows a servlet to obtain any initialization parameters.
The init( ), service( ), and destroy( ) methods are the life cycle methods of the servlet.
These are invoked by the server ie.. servlet container.
The getServletConfig( ) method is called by the servlet to obtain initialization parameters.
A servlet developer overrides the getServletInfo( ) method to provide a string with useful information
(for example, author, version, date, copyright).
This method is also invoked by the server.
5|BRJ
BRJ086
This interface is used to indicate that only a single thread will execute the service( ) method of a servlet at a given time.
6|BRJ
BRJ087
When a client request arrives, it is sent to an available instance of the servlet.
The GenericServlet class provides implementations of the basic life cycle methods for a servlet and is typically subclassed by
servlet developers.
Here, s is the string to be appended to the log, and e is an exception that occurred.
The ServletInputStream Class
The ServletInputStream class extends InputStream. It is implemented by the server and provides an input stream that a
servlet developer can use to read the data from a client request.
Here, buffer is the array into which size bytes are placed starting at offset.
The method returns the actual number of bytes read or 1 if an end-of-stream condition is encountered.
The ServletOutputStream Class
It is implemented by the server and provides an output stream that a servlet developer can use to write data to a client
response.
A default constructor is defined. It also defines the print( ) and println( ) methods, which output data to the stream.
The Servlet Exception Classes
The first is ServletException, which indicates that a servlet problem has occurred.
The ServletRequest class includes methods that allow you to read the names and values of parameters that are included in a
client request.
We will develop a servlet that illustrates their use.
The example contains two files.
A Web page is defined in PostParameters.htm and a servlet is defined in PostParametersServlet.java.
The HTML source code for PostParameters.htm is shown in the following listing.
It defines a table that contains two labels and two text fields.
One of the labels is Employeeand the other is Phone.
There is also a submit button.
Notice that the action parameter of the form tag specifies a URL.
The URL identifies the servlet to process the HTTP POST request.
<html>
<body>
<center>
<form name="Form1"
method="post"
action="http://localhost:8080/examples/servlet/PostParametersServlet">
<table>
<tr>
<td><B>Employee</td>
<td><input type=textbox name="e" size="25" value=""></td>
</tr>
<tr>
<td><B>Phone</td>
<td><input type=textbox name="p" size="25" value=""></td>
</tr>
</table>
<input type=submit value="Submit">
</body>
</html>
You can see that the parameter name and value are output to the client.
7|BRJ
BRJ088
extends GenericServlet {
public void service(ServletRequest request,
ServletResponse response)
throws ServletException, IOException {
// Get print writer.
PrintWriter pw = response.getWriter();
// Get enumeration of parameter names.
Enumeration e = request.getParameterNames();
// Display parameter names and values.
while(e.hasMoreElements()) {
String pname = (String)e.nextElement();
pw.print(pname + " = ");
String pvalue = request.getParameter(pname);
pw.println(pvalue);
}
pw.close();
}
}
Compile the servlet and perform these steps to test this example:
1) Start Tomcat (if it is not already running).
2) Display the Web page in a browser.
3) Enter an employee name and phone number in the text fields.
4) Submit the Web page.
After following these steps, the browser will display a response that is dynamically generated by the servlet.
The HttpServlet class provides specialized methods that handle the various types of HTTP requests.
A servlet developer typically overrides one of these methods.
These methods are doDelete( ), doGet( ), doHead( ), doOptions( ), doPost( ), doPut( ), and doTrace( ).
the GET and POST requests are commonly used when handling form input.
<html>
<body>
<center>
<form name="Form1"
action="http://localhost:8080/examples/servlet/ColorGetServlet">
<B>Color:</B>
<select name="color" size="1">
<option value="Red">Red</option>
<option value="Green">Green</option>
<option value="Blue">Blue</option>
</select>
<br><br>
<input type=submit value="Submit">
</form>
</body>
</html>
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class ColorGetServlet extends HttpServlet
{
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
String color = request.getParameter("color");
response.setContentType("text/html");
PrintWriter pw = response.getWriter();
pw.println("<B>The selected color is: ");
pw.println(color);
pw.close();
}
}
Compile the servlet and perform these steps to test this example:
1) Start Tomcat, if it is not already running.
2) Display the Web page in a browser.
8|BRJ
BRJ089
3)
4)
Select a color.
Submit the Web page.
After completing these steps, the browser will display the response that is dynamically generated by the servlet.
One other point: Parameters for an HTTP GET request are included as part of the URL that is sent to the Web server.
Assume that the user selects the red option and submits the form.
http://localhost:8080/examples/servlet/ColorGetServlet?color=Red
The characters to the right of the question mark are known as the query string.
Compile the servlet and perform the same steps as described in the previous section to test it.
Note: Parameters for an HTTP POST request are not included as part of the URL that is sent to the Web server.
In this example, the URL sent from the browser to the server is:
http://localhost:8080/examples/servlet/ColorGetServlet
The parameter names and values are sent in the body of the HTTP request.
Using Cookies
9|BRJ
BRJ090
action="http://localhost:8080/examples/servlet/AddCookieServlet">
<B>Enter a value for MyCookie:</B>
<input type=textbox name="data" size=25 value="">
<input type=submit value="Submit">
</form>
</body>
</html>
import javax.servlet.*;
import javax.servlet.http.*;
public class GetCookiesServlet extends HttpServlet
{
public void doGet(HttpServletRequest request,HttpServletResponse response)throws ServletException, IOException
{
// Get cookies from header of HTTP request.
Cookie[] cookies = request.getCookies();
// Display these cookies.
response.setContentType("text/html");
PrintWriter pw = response.getWriter();
pw.println("<B>");
for(int i = 0; i < cookies.length; i++)
{
String name = cookies[i].getName();
String value = cookies[i].getValue();
pw.println("name = " + name + "; value = " + value);
}
pw.close();
}
}
After completing these steps you will observe that a feedback message is displayed by the browser.
http://localhost:8080/examples/servlet/GetCookiesServlet
Observe that the name and value of the cookie are displayed in the browser.
In this example, an expiration date is not explicitly assigned to the cookie via the SsetMaxAge( ) method of Cookie.
Therefore, the cookie expires when the browser session ends.
You can experiment by using setMaxAge( ) and observe that the cookie is then saved to the disk on the client machine.
Session Tracking
10 | B R J
BRJ091
The setAttribute( ), getAttribute( ), getAttributeNames( ), and removeAttribute( ) methods of HttpSession manage these
bindings. It is important to note that session state is shared among all the servlets that are associated with a particular client.
The following servlet illustrates how to use session state.
The getSession( ) method gets the current session.
A new session is created if one does not already exist.
The getAttribute( ) method is called to obtain the object that is bound to the name date.
That object is a Date object that encapsulates the date and time when this page was last accessed.
(Of course, there is no such binding when the page is first accessed.)
A Date object encapsulating the current date and time is then created.
The setAttribute( ) method is called to bind the name date to this object.
import java.io.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class DateServlet extends HttpServlet
{
public void doGet(HttpServletRequest request,HttpServletResponse response)throws ServletException, IOException
{
// Get the HttpSession object.
HttpSession hs = request.getSession(true);
// Get writer.
response.setContentType("text/html");
PrintWriter pw = response.getWriter();
pw.print("<B>");
// Display date/time of last access.
Date date = (Date)hs.getAttribute("date");
if(date != null) {
pw.print("Last access: " + date + "<br>");
}
// Display current date/time.
date = new Date();
hs.setAttribute("date", date);S
pw.println("Current date: " + date);
}
}
When you first request this servlet, the browser displays one line with the current date and time information.
On subsequent invocations, two lines are displayed.
The first line shows the date and time when the servlet was last accessed.
The second line shows the current date and time.
11 | B R J
BRJ092
JSP
JAVA
SNO.,
SERVER
PAGES
(UNIT-V)
CONTENTS
PAGE NO.,
Introduction
Jsp processing
Database access:
Accessing a database from a Jsp
Reading and storing information in a database.
1|BRJ
BRJ094
4
5
6
8
Java Server Pages (JSP) is a technology for developing web pages that support dynamic content which helps developers insert
java code in HTML pages by making use of special JSP tags, most of which start with <% and end with %>.
A Java Server Pages component is a type of Java Servlet that is designed to fulfill the role of a user interface for a Java web
application. Web developers write JSPs as text files that combine HTML or XHTML code, XML elements, and embedded JSP
actions and commands. Using JSP, you can collect input from users through web page forms, present records from a database
or another source, and create web pages dynamically.
JSP tags can be used for a variety of purposes, such as retrieving information from a database or registering user preferences,
accessing JavaBeans components, passing control between pages and sharing information between requests, pages etc.
WHY USE JSP?
1) Java Server Pages often serve the same purpose as programs implemented using the Common Gateway Interface
(CGI). But JSP offer several advantages in comparison with the CGI.
2) Performance is significantly better because JSP allows embedding Dynamic Elements in HTML Pages itself instead of
having a separate CGI files.
3) JSP are always compiled before it's processed by the server unlike CGI/Perl which requires the server to load an
interpreter and the target script each time the page is requested.
4) Java Server Pages are built on top of the Java Servlets API, so like Servlets; JSP also has access to all the powerful
Enterprise Java APIs, including JDBC, JNDI, EJB, JAXP etc.
5) JSP pages can be used in combination with Servlets that handle the business logic, the model supported by Java Servlet
template engines.
6) Finally, JSP is an integral part of Java EE, a complete platform for enterprise class applications. This means that JSP can
play a part in the simplest applications to the most complex and demanding.
ADVANTAGES OF JSP:
Following is the list of other advantages of using JSP over other technologies:
1) Active Server Pages (ASP): The advantages of JSP are twofold. First, the dynamic part is written in Java, not Visual
Basic or other MS specific language, so it is more powerful and easier to use. Second, it is portable to other operating
systems and non-Microsoft Web servers.
2) Pure Servlets: It is more convenient to write (and to modify!) regular HTML than to have plenty of println statements
that generate the HTML.
3) Server-Side Includes (SSI): SSI is really only intended for simple inclusions, not for "real" programs that use form
data, make database connections, and the like.
4) JavaScript: JavaScript can generate HTML dynamically on the client but can hardly interact with the web server to
perform complex tasks like database access and image processing etc.
5) Static HTML: Regular HTML, of course, cannot contain dynamic information.
6) A development environment is where you would develop your JSP programs, test them and finally run them.
In many Java servlet-based applications, processing the request and generating the response
are both handled by a single servlet class.
Example: shows how a servlet class often looks.
saveOrderInfo(request);
out.println("<html>");
out.println(" <head>");
out.println(" <title>Order Confirmation</title>");
out.println(" </head>");
out.println(" <body>");
out.println(" <h1>Order Confirmation</h1>");
renderOrderInfo(request);
out.println(" </body>");
out.println("</html>");
}
If you're not a programmer, don't worry about all the details in this code. The point is that the servlet contains request
processing and business logic (implemented by methods such as isOrderInfoValid( ) and saveOrderInfo( )), and also generates
2|BRJ
BRJ095
the response HTML code, embedded directly in the servlet code using println( ) calls. A more structured servlet application
isolates different pieces of the processing in various reusable utility classes and may also use a separate class library for
generating the actual HTML elements in the response. Even so, the pure servlet-based approach still has a few problems:
Thorough Java programming knowledge is needed to develop and maintain all aspects of the application, since the processing
code and the HTML elements are lumped together.
Changing the look and feel of the application, or adding support for a new type of client (such as a WML client), requires the
servlet code to be updated and recompiled.
It's hard to take advantage of web-page development tools when designing the application interface. If such tools are used to
develop the web page layout, the generated HTML must then be manually embedded into the servlet code, a process which is
time consuming, error prone, and extremely boring. Adding JSP to the puzzle lets you solve these problems by separating the
request processing and business logic code from the presentation, as illustrated in Figure 3-1. Instead of embedding HTML in
the code, you place all static HTML in a JSP page, just as in a regular web page, and add a few JSP elements to generate the
dynamic parts of the page. The request processing can remain the domain of the servlet, and the business logic can be handled
by JavaBeans and EJB components.
Figure 3-1. Separation of request processing, business logic, and presentation
As I mentioned before, separating the request processing and business logic from presentation makes it possible to divide the
development tasks among people with different skills. Java programmers implement the request processing and business logic
pieces, web page authors implement the user interface, and both groups can use best-of-breed development tools for the task
at hand. The result is a much more productive development process. It also makes it possible to change different aspects of the
application independently, such as changing the business rules without touching the user interface.
This model has clear benefits even for a web-page author without programming skills, working alone. A page author can
develop web applications with many dynamic features, using the JSP standard actions and the JSTL libraries, as well as Java
components provided by open source projects and commercial companies.
A JSP page is simply a regular web page with JSP elements for generating the parts that differ for each request, as shown in
Figure Template text and JSP elements
3|BRJ
BRJ096
Everything in the page that isn't a JSP element is called template text. Template text can be any text: HTML, WML, XML, or even
plain text. Since HTML is by far the most common web-page language in use today, most of the descriptions and examples in
this book use HTML, but keep in mind that JSP has no dependency on HTML; it can be used with any markup language.
Template text is always passed straight through to the browser. When a JSP page request is processed, the template text and
dynamic content generated by the JSP elements are merged, and the result is sent as the response to the browser.
JSP Processing
Just as a web server needs a servlet container to provide an interface to servlets, the server needs a JSP container to process
JSP pages. The JSP container is responsible for intercepting requests for JSP pages. To process all JSP elements in the page, the
container first turns the JSP page into a servlet (known as the [JSP page implementation class).
The conversion is pretty straightforward; all template text is converted to println( ) statements similar to the ones in the
handcoded servlet shown in Example 3-1, and all JSP elements are converted to Java code that implements the corresponding
dynamic behavior. The container then compiles the servlet class Converting the JSP page to a servlet and compiling the servlet
form the translation phase.
The JSP container initiates the translation phase for a page automatically when it receives the first request for the page. Since
the translation phase takes a bit of time, the first user to request a JSP page notices a slight delay. The translation phase can
also be initiated explicitly; this is referred to as precompilation of a JSP page.
Precompiling a JSP page is a way to avoid hitting the first user with this delay. The JSP container is also responsible for
invoking the JSP page implementation class (the generated servlet) to process each request and generate the response. This is
called the request processing phase.
The two phases are illustrated in Figure 3-3.
4|BRJ
BRJ097
As long as the JSP page remains unchanged, any subsequent request goes straight to the request processing phase (i.e., the
container simply executes the class file). When the JSPpage is modified, it goes through the translation phase again before
entering the request processing phase.
The JSP container is often implemented as a servlet configured to handle all requests for JSPpages. In fact, these two containers
-- a servlet container and a JSP container -- are often combined in one package under the name web container.
So in a way, a JSP page is really just another way to write a servlet without having to be a Java programming wiz. Except for the
translation phase, a JSP page is handled exactly like a regular servlet: it's loaded once and called repeatedly, until the server is
shut down. By virtue of being an automatically generated servlet, a JSP page inherits all the advantages of a servlet platform
and vendor independence, integration, efficiency, scalability,robustness, and security.
JSP Elements
There are three types of JSP elements you can use: directive, action, and scripting.
3.3.1.1 Directive elements
The directive elements, shown in Table 3-1, specify information about the page itself that remains the same between requests
-- for example, if session tracking is required or not, buffering requirements, and the name of a page that should be used to
report errors, if any.
3.3.1.3 Custom action elements and the JSP Standard Tag Library
In addition to the standard actions, the JSP specification includes a Java API a programmer can use to develop custom actions to
extend the JSP language. The JSP Standard Tag Library (JSTL) is such an extension, with the special status of being defined by a
formal specification from Sun and typically bundled with the JSP container. JSTL contains action elements for processes
needed in most JSP applications, such as conditional processing, database access, internationalization, and more.
3.3.1.4 Scripting elements
Scripting elements, shown in Table 3-3, allow you to add small pieces of code (typically Java code) in a JSP page, such as an if
statement to generate different HTML depending on a certain condition. Like actions, they are also executed when the page is
requested. You should use scripting elements with extreme care: if you embed too much code in your JSP pages, you will end
up with the same kind of maintenance problems as with servlets embedding HTML.
5|BRJ
BRJ098
JSP technology can play a part in everything from the simplest web application, such as an online phone list or an employee
vacation planner, to full-fledged enterprise applications, such as a human-resource application or a sophisticated online
shopping site. How large a part JSP plays differs in each case, of course. In this section, I introduce a design model called
Model-View-Controller (MVC), suitable for both simple and complex applications. MVC was first described by Xerox in a
number of papers published in the late 1980s. The key point of using MVC is to separate logic into three distinct units: the
Model, the View, and the Controller. In a server application, we commonly classify the parts of the application as business
logic, presentation, and request processing. Business logic is the term used for the manipulation of an application's data, such
as customer, product, and order information.
Presentation refers to how the application data is displayed to the user, for example, position, font, and size. And finally,
request processing is what ties the business logic and presentation parts together. In MVC terms, the Model corresponds to
business logic and data, the View to the presentation, and the Controller to the request processing. Why use this design with
JSP? The answer lies primarily in the first two elements. Remember that an application data structure and logic (the Model) is
typically the most stable part of an application, while the presentation of that data (the View) changes fairly often. Just look at
all the face-lifts many web sites go through to keep up with the latest fashion in web design. Yet, the data they present remains
the same. Another common example of why presentation should be separated from the business logic is that you may want to
present the data in different languages or present different subsets of the data to internal and external users. Access to the
data through new types of devices, such as cell phones and personal digital assistants (PDAs), is the latest trend. Each client
type requires its own presentation format. It should come as no surprise, then, that separating business logic from the
presentation makes it easier to evolve an application as the requirements change; new presentation interfaces can be
developed without touching the business logic.
This MVC model is used for most of the examples in this book. In Part II, JSP pages are used as both the Controller and the
View, and JavaBeans components are used as the Model. The examples in Chapter 5 through Chapter 9 use a single JSP page
that handles everything,
Many types of real-world applications can be developed this way, but what's more important is that this approach allows you
to examine all the JSP features without getting distracted by other technologies.
Accessing a Database
Almost all the web applications that you see on the Internet access a database. Databases store customer information,
order information, product information, even discussion forum messages.
in short, all information that needs to survive a server restart and is too complex to handle in plain-text files.
There are many types of databases used in the industry today.
However, relational databases are by far the most common.
A relational database uses tables to represent the information it handles.
A table consists of rows of columns, with each column holding a single value of a predefined data type.
Examples of these data types are text data, numeric data, dates, and binary data such as images and sound.
A specialized language called Structured Query Language (SQL) is used to access the data.
SQL is an ANSI standard and is supported by all major database vendors.
Relational database engines come in all shapes and sizes, from simple one-person databases with limited features, to
sophisticated databases capable of handling large numbers of concurrent users with support for transactions
distributed over multiple servers and extremely optimized search algorithms.
Even though they all use SQL as the data access language, the API used to execute SQL statements is different for each
database engine. To help programmers write code that's portable between database engines, the standard Java
libraries include an API called the Java Database Connectivity (JDBC) API. JDBC defines a set of classes that can execute
SQL statements the same way in any relational database.
The complexity of databases varies extensively. A database for an online discussion forum, for instance, requires only
one or two tables, while a database for a human resources system may contain hundreds of related tables. In this
chapter, we look at a set of JSTL database actions you can use to build any type of database-driven web application.
But if the database is complex, you may want to use another approach: hiding the database behind application specific
beans and custom actions, or moving all database processing to a servlet and using JSP only to show the result.
6|BRJ
BRJ099
JSTL includes a number of actions for database access to make it easy to develop simple database-driven JSP applications.
The actions provide the following features:
we build an employee register application. This application contains functions for adding and changing employee information,
as well as for looking up employees matching a search criterion. The employee information is stored in a relational database
and accessed through the JSTL database access actions.
The employee registration part of the application contains the pages shown in Figure 11-1.
Figure 11-1. Employee registration pages
7|BRJ
BRJ100
The first page the user loads to register an employee in the example application is enter.jsp. This page, which contains a form
for entering all information about an employee, is shown in
Employee information entry form
<%-- See if the employee is already defined. If not, insert the info, else update it. --%>
<sql:query var="empDbInfo">
SELECT * FROM Employee
WHERE UserName = ?
<sql:param value="${param.userName}" />
</sql:query>
<%-- Deal with the date values: parse the employment date and create a Date object from it,
and create a new variable to hold the current date. --%>
<fmt:parseDate value="${param.empDate}" var="parsedEmpDate"
pattern="yyyy-MM-dd" />
<jsp:useBean id="now" class="java.util.Date" />
<c:choose>
<c:when test="${empDbInfo.rowCount == 0}">
<sql:update>
INSERT INTO Employee (UserName, Password, FirstName, LastName, Dept, EmpDate, EmailAddr, ModDate)
VALUES(?, ?, ?, ?, ?, ?, ?, ?)
<sql:param value="${param.userName}" />
<sql:param value="${param.password}" />
<sql:param value="${param.firstName}" />
<sql:param value="${param.lastName}" />
<sql:param value="${param.dept}" />
<sql:dateParam value="${parsedEmpDate}" type="date"/>
<sql:param value="${param.emailAddr}" />
<sql:dateParam value="${now}" />
</sql:update>
</c:when>
<c:otherwise>
<sql:update>
UPDATE Employee SET Password = ?, FirstName = ?, LastName = ?, Dept = ?, EmpDate = ?, EmailAddr = ?, ModDate = ?
WHERE UserName = ?
<sql:param value="${param.password}" />
<sql:param value="${param.firstName}" />
8|BRJ
BRJ101
All JSTL database actions are packaged in their own tag library. At the top of the page in Example 11-1 you'll find the taglib
directive for this library that associates it with the sql prefix, similar to the tag libraries used in the previous examples. Most of
the JSTL database actions are used in this page. Let's look at them one at a time.
The first JSTL action that accesses the database in Example 11-1 is the <sql:query> action, described in Table 11-3.
The <sql:query> action reads information from a database using the SQL SELECT statement, specified in the element's body or
as the sql attribute value. A SELECT statement retrieves data from the database by specifying various clauses that identify the
table to search in, the columns to return, the search criteria, and other options. If you're not familiar with the SELECT
statement, you can read up on it in the documentation for your database.
The SELECT statement in Example 11-1 gets all columns in the Employee table for every row in which the UserName column
has the value specified in the userName field in the entry form. Since the username is unique in our application, either 0 or one
row is returned.
The <sql:query> action in this example gets a connection from the default DataSource specified by the context parameter. It
then executes the SQL SELECT statement and saves the result in the scope specified by the scope attribute, with the name
specified by the var attribute. If no scope is specified, as in this example, the result is saved in the page scope.
Besides the SQL statement, the action element body also contains an <sql:param> action,described in Table 11-4.
9|BRJ
BRJ102
The <sql:param> action replaces a placeholder, marked with a question mark (?), in the SQL statement with a value. In
Example 11-1, the EL expression used for the value attribute gets the userName request parameter value, corresponding to
the form field with the same name in the enter.jsp page:
<sql:query var="empDbInfo">
SELECT * FROM Employee WHERE UserName = ?
<sql:param value="${param.userName}" />
</sql:query>
You could use a <c:out> action in the body instead to insert the userName parameter value directly into the SQL statement,
like this:
<ora:sqlQuery id="empDbInfo">
SELECT * FROM Employee
WHERE UserName = '<c:out value="${params.userName}" />'
</ora:sqlQuery>
but then you run into the problem of string quoting in SQL. Most database engines require a string literal to be enclosed in
single quotes in an SQL statement. That's easy to handle by just putting single quotes around the <c:out> action, like I've done
here. What's not so easy is how to handle quotes within the string value.
Different database engines employ different rules for how to encode embedded quotes. Most require a single quote in a string
literal to be duplicated, while others use a backslash as an escape character or let you enclose the string literal with double
quotes if the value includes single quotes.
When you use the <sql:param> action, you don't have to worry about this type of formatting at all; the value is set directly in
the SQL statement, bypassing all quoting rules.
Another reason for using <sql:param> is that using a <c:out> action to add a dynamic value to an SQL statement is also a
security risk. If a user enters a value such as "foo' OR 1 = 1 -- " in the username field, the SQL statement looks like this after the
<c:out> action is processed:
SELECT * FROM Employee WHERE UserName = 'foo' OR 1 = 1 --'
The "OR 1 = 1" part means that this condition is always true, making the SQL statements returning all rows instead of only one
row matching a specific username. Most databases interpret the " -- " part as the start of a comment, so whatever comes after
these characters is ignored.
Tricks like this can be used to gain access to protected sites or return information that is supposed to be secret. Using
<sql:param> prevents this type of attacks. Instead of merging the dynamic value and the static text to create an SQL statement
that the database then interprets, the <sql:param> action explicitly tells the database to use the provided value in place of the ?
when it has interpreted the statement. Hence, there's no way to fool it.
Only one dynamic value is needed in the query in Example 11-1, but an SQL statement can contain as many placeholders as
you like, matched by the same number of <sql:param> actions in the <sql:query> element body.
The first <sql:param> action replaces the first question mark in the SQL statement with its value, the second replaces the
second question mark, and so on. The result generated by the <sql:query> action is an instance of the
javax.servlet.jsp.jstl.sql.Result class. It's a bean with a number of properties for accessing all rows and their column values, as
well as properties for the column names and number of rows in the result.
We look at most of the Result properties later in this chapter, but the only one used in Example 11-1 is the rowCount property.
It's used to see if the query returned any rows.
The SELECT statement searches the database for information about the employee entered in the form. If the employee is
already registered, the query returns one row; otherwise no rows.
This information is used to decide whether to insert or update the employee information:
<c:choose>
<c:when test="${empDbInfo.rowCount == 0}">
<%-- Insert the employee data --%>
...
</c:when>
<c:otherwise>
<%-- Update the employee data --%>
...
</c:otherwise>
</c:choose>
An SQL INSERT statement is used to insert new rows in a database table. To execute an INSERT statement, use the
<sql:update> action, described in Table 11-5.
10 | B R J
BRJ103
The <sql:update> action executes any SQL statement that doesn't return rows: INSERT, UPDATE, and DELETE, and even socalled Data Definition Language (DDL) statements such as CREATE TABLE. These statements do exactly what it sounds like
they do: insert, update and delete information, and create a new table, respectively. (Refer to your database documentation for
details about the syntax.) For INSERT, UPDATE, and DELETE, the <sql:update> action can optionally save an Integer object,
telling how many rows were affected by the statement. The Integer is saved in the scope specified by the scope attribute using
the name specified by the var attribute. This feature isn't used in Example 11-1, but in some applications it can be used as
feedback to the user or to decide what to do next. The SQL statement can be specified through the sql attribute or the action's
body, and <sql:param> actions can be used to give values to the placeholders in the statement. Multiple <sql:param> actions
are used in Example 11-1:
<sql:update>
INSERT INTO Employee (UserName, Password, FirstName, LastName, Dept, EmpDate, EmailAddr, ModDate)
VALUES(?, ?, ?, ?, ?, ?, ?, ?)
<sql:param value="${param.userName}" />
<sql:param value="${param.password}" />
<sql:param value="${param.firstName}" />
<sql:param value="${param.lastName}" />
<sql:param value="${param.dept}" />
<sql:dateParam value="${parsedEmpDate}" type="date"/>
<sql:param value="${param.emailAddr}" />
<sql:dateParam value="${now}" />
</sql:update>
Most of the placeholders are replaced with request parameter values, just as for the query. The exceptions are the
placeholders for the EmpDate and ModDate columns, which require special attention.
Databases are picky about the format for date and time data types. In Example 11-1 we get the date from the form as a string
in the format yyyy-MM-dd (e.g., 2002-03-06), but the EmpDate column is declared as a DATE column, as shown in Table 11-1.
Some databases accept a string in the format used for this application as a value for a DATE column, but others don't. To be on
the safe side, it's best to convert the string into its native date format, a java.util.Date object, before sending it to the database.
It can be done using a JSTL action from the formatting library, assigned the fmt prefix by the taglib directive at the beginning of
the page:
<fmt:parseDate value="${params.empDate}" var="parsedEmpDate" pattern="yyyy-MM-dd" />
The <fmt:parseDate> action takes the date or time string specified by the value attribute and interprets it according to the
pattern defined by the pattern attribute. The pattern describes the order and format of the year, month, and day parts in the
string representation of the date. We'll return to the <fmt:parseDate> action in Chapter 13 to look at all the details, but for now
it suffices to say that the pattern description is very flexible. For instance, if you want the user to enter dates in a format such
"Tuesday February 19, 2002," you specify the pattern EEEE MMMM dd, yyyy instead of the yyyy-MM-dd pattern used in this
example to tell the action how to interpret the date string. If the string value can be interpreted as a date according to the
pattern, the action saves a java.util.Date object representing the date as a variable with the name specified by the var attribute.
This variable can then replace the placeholder in the SQL statement.
Besides dates, you should also convert numeric values you receive as strings when they are declared as INT, REAL, etc., in the
database, using the JSTL <fmt:parseNumber> action. In this example, there are no columns of this type. The JSTL formatting
actions are very powerful, but let's save the details for Chapter 13.
The Employee table also has a column named ModDate, to hold the date and time the information was last modified. It is
declared as a TIMESTAMP column. To set its value, we need a java.util.Date object that represents the current date and time.
It's easy to create one with the <jsp:useBean> action: <jsp:useBean id="now" class="java.util.Date" />
11 | B R J
BRJ104
The <jsp:useBean> action can create an instance of any class that has a no-arguments constructor, like the java.util.Date class
does. The instance is saved in the variable named by the id attribute.
Finally, we need to use the <sql:dateParam> action, described in Table 11-6, instead of the <sql:param> action to set the date
and timestamp values.
You have to use <sql:dateParam> because of an unfortunate quirk in the JDBC API.
JDBC defines its own classes for date and time values: java.sql.Date, java.sql.Time, and java.sql.Timestamp. These are the only
types accepted for date and time value placeholders. The <sql:dateParam> takes a java.util.Date object and turns it into one of
the JDBC types based on the type attribute value or to a java.sql.Timestamp if no type is specified.
Once you know how to insert information in a database, updating it's a piece of cake. You just use the <sql:update> action with
an SQL UPDATE statement instead of an INSERT statement:
<sql:update>
UPDATE Employee
SET Password = ?,
FirstName = ?,
LastName = ?,
Dept = ?,
EmpDate = ?,
EmailAddr = ?,
ModDate = ?
WHERE UserName = ?
<sql:param value="${param.password}" />
<sql:param value="${param.firstName}" />
<sql:param value="${param.lastName}" />
<sql:param value="${param.dept}" />
<sql:dateParam value="${parsedEmpDate}" type="date" />
<sql:param value="${param.emailAddr}" />
<sql:dateParam value="${now}" />
<sql:param value="${param.userName}" />
</sql:update>
No surprises here. The only difference from how you insert information is the SQL statement. The UPDATE statement sets all
the specified values for rows matching the WHERE clause, in this case the single row for the specified employee.
12 | B R J
BRJ105