5.1 Java Database Programming: 5.1.1 JDBC Characteristics
5.1 Java Database Programming: 5.1.1 JDBC Characteristics
The JDBC interface provides the application with a set of methods that enable
database connections, queries, and result retrievals. It is the interface between specific
database drivers and the Java user application, applet, or servlet.
• JDBC is a “call-level” SQL interface for Java. This interface is totally independent of
the available database management systems. It is a low-level application programming
interface (API) that allows a Java program to issue SQL statements and retrieve their
results. It also provides methods to handle error and warning messages
• SQL conformance: JDBC does not restrict the type of queries passed to an underlying
DBMS driver. An application may use as much SQL functionality as desired.
• JDBC provides a Java interface that stays consistent with the rest of the Java system.
• JDBC mechanisms are simple to understand and use. This simplicity does not mean that
functionality suffers.
• JDBC uses strong, static typing whenever possible. This approach allows for performing
more error checking at compile time.
5.1.2.1 Application
The user application invokes JDBC methods to send SQL statements to the database and
retrieve results. It performs these tasks:
Page 175
MODULE 5
• Requests results
• Processes errors
• Controls transactions: requests commit or rollback operations
• Closes the connection
5.1.2.3 Driver
The driver is the core component for JDBC. Drivers are written by vendors and must
support the basic features of the JDBC specification.It processes JDBC methods invocations,
sends SQL statements to a specific data source, and returns results back to the application.It
translates and/or optimizes requests so the request conforms to the syntax supported by the
specific DBMS providing database independence.If the back-end database changes, only
JDBC driver need to be replaced.It will:
( Fig: 5.1)
MODULE 5 MCA-404 Java and Web Programming ADMN 2009-‘10
(Fig: 5.2)
Advantage
The JDBC-ODBC Bridge allows access to almost any database, since the database's ODBC
drivers are already available.
Disadvantages
1. Since the Bridge driver is not written fully in Java, Type 1 drivers are not portable.
2. A performance issue is seen as a JDBC call goes through the bridge to the ODBC driver,
then to the database, and this applies even in the reverse process. They are the slowest of all
driver types.
3. The client system requires the ODBC Installation to use the driver.
4. Not good for the Web.
MODULE 5 MCA-404 Java and Web Programming ADMN 2009-‘10
A type 2 JDBC driver is like a type 1 driver, except the ODBC part is replaced with a native
code part instead .The distinctive characteristic of type 2 jdbc drivers are that Type 2 drivers
convert JDBC calls into database-specific calls i.e. this driver is specific to a particular
database. Example: Oracle will have oracle native api.
(Fig: 5.3)
Advantage
The distinctive characteristic of type 2 jdbc drivers are that they are typically offer better
performance than the JDBC-ODBC Bridge as the layers of communication (tiers) are less than
that of Type1 and also it uses Native api which is Database specific.
Disadvantage
1. Native API must be installed in the Client System and hence type 2 drivers cannot be used
for the Internet.
2. Like Type 1 drivers, it’s not written in Java Language which forms a portability issue.
3. If we change the Database we have to change the native api as it is specific to a database
4. Mostly obsolete now
5. Usually not thread safe
A type 3 JDBC driver is an all Java driver that sends the JDBC interface calls to an
intermediate server. The intermediate server then connects to the database on behalf of the
JDBC driver.
MODULE 5 MCA-404 Java and Web Programming ADMN 2009-‘10
(Fig: 5.4)
Advantage
1. This driver is server-based, so there is no need for any vendor database library to be present
on client machines.
2. This driver is fully written in Java and hence Portable. It is suitable for the web.
3. There are many opportunities to optimize portability, performance, and scalability.
4. The net protocol can be designed to make the client JDBC driver very small and fast to
load.
5. The type 3 driver typically provides support for features such as caching (connections,
query results, and so on), load balancing, and advanced
system administration such as logging and auditing.
6. This driver is very flexible allows access to multiple databases using one driver.
7. They are the most efficient amongst all driver types.
Disadvantage
It requires another server application to install and maintain. Transferring data may take
longer, since the data comes through the backend server.
(Fig: 5.5)
Advantage
1. The major benefit of using a type 4 jdbc drivers are that they are completely written in Java
to achieve platform independence and eliminate deployment administration issues. It is most
suitable for the web.
2. Number of translation layers is very less i.e. type 4 JDBC drivers don't have to translate
database requests to ODBC or a native connectivity interface or to pass the request on to
another server, performance is typically quite good.
3. You don’t need to install special software on the client or server. Further, these drivers can
be downloaded dynamically.
Disadvantage
With type 4 drivers, the user needs a different driver for each database.
If you are accessing one type of database, such as Oracle, Sybase, or IBM, the preferred driver
type is 4.
If your Java application is accessing multiple types of databases at the same time, type 3 is the
preferred driver.
Type 2 drivers are useful in situations where a type 3 or type 4 driver is not available yet for
your database.
The type 1 driver is not considered a deployment-level driver and is typically used for
development and testing purposes only.
MODULE 5 MCA-404 Java and Web Programming ADMN 2009-‘10
The java.sql package contains the entire JDBC API that sends SQL (Structured
Query Language) statements to relational databases and retrieves the results of executing
those SQL statements.
(Fig: 5.6)
The cornerstone of the JDBC package is the DriverManager class. This class keeps
track of all the different available database drivers. The DriverManager manages loading and
unloading drivers. The DriverManager maintains a Vector that holds information about all the
drivers that it knows about. The elements in the Vector contain information about the driver
MODULE 5 MCA-404 Java and Web Programming ADMN 2009-‘10
such as the class name of the Driver object, a copy of the actual Driver object, and the Driver
security context. The DriverManager, while not a static class, maintains all static instance
variables with static access methods for registering and unregistering drivers. This allows the
DriverManager never to need instantiation. Its data always exists as part of the Java runtime.
The Driver is the software wedge that communicates with the platform-dependent
database, either directly or using another piece of software. How it communicates really
depends on the database, the platform, and the implementation
jdbc:<sub-protocol>:<sub-name> , where
sub-protocol is the name of the driver set that defines a particular database connectivity
method. This can be represented by several drivers.
sub-name is the additional information necessary to complete the URL. This information is
different depending on the sub-protocol.
Using the getConnection() method, the DriverManager asks each driver that has
registered with it whether the database connection URL is valid. If one driver responds
positively, the DriverManager assumes a match. If no driver responds positively, an
SQLException is thrown. The DriverManager returns the error "no suitable driver," which
means that of all the drivers that the DriverManager knows about, not one of them could
figure out the URL you passed to it.
Statement object encapsulates SQL queries to your database. Using several methods,
these calls return objects that contain the results of your SQL query. When you execute an
SQL query, the data that is returned is commonly called the result set. It is possible to choose
from several result sets, depending on the needs.
The following methods can be used to easily navigate the results a query returns:
• boolean getMoreResults()
This moves to the next result set in the Statement. This, like the execute() method, returns true
if the next result is a result set or false if it is an integer. If you have already retrieved a
ResultSet from the Statement, this method will close it before returning.
• ResultSet getResultSet()
This method returns to you a result set in a ResultSet object. This result set is the current
result set.
• int getUpdateCount()
This method returns to you the integer result that an execute() method returned.
ResultSet class encapsulates the results returned from an SQL query. Normally,
those results are in the form of rows of data. Each row contains one or more columns. The
ResultSet class acts as a cursor, pointing to one record at a time, enabling you to pick out the
data you need.
You can gain access to the data within the ResultSet using many different methods.
These methods are in the form of gettype(), where type is the data type of the column. These
functions return a new instance of the type that contains the data from the result set. If the
column value is NULL, the value returned from these methods is NULL. the column's data
either by column number or name.
The following list presents the gettype() methods provided by the ResultSet class and
their return types:
• String getString()
• boolean getBoolean()
• byte getByte()
MODULE 5 MCA-404 Java and Web Programming ADMN 2009-‘10
• short getShort()
• int getInt()
• long getLong()
float getFloat()
• double getDouble()
• Numeric getNumeric()
• byte[] getBytes()
java.sql.Date getDate()
•
java.sql.Time getTime()
• java.sql.Timestamp getTimestamp()
• java.io.InputStream getAsciiStream()
java.io.InputStream getUnicodeStream()
•
java.io.InputStream getBinaryStream()
•
•
•
When you've retrieved all the data you can from a column, it is time to move on to
the next row. Moving to the next row is done with the next() method. This method returns a
boolean value indicating the status of the row. Internally, it moves the ResultSet's cursor to the
next row, thereby giving access to the data stored in the columns of that row.
When a ResultSet object is created, its position is always before the first row of data
contained within. This makes it necessary to call the next() method before you can access any
column data. The first call to next() makes the first row available to your program. Subsequent
calls to next() make the next rows available. If no more rows are available, next() returns false
In this step of the jdbc connection process, we load the driver class by calling
Class.forName() with the Driver class name as an argument. Once loaded, the Driver class
creates an instance of itself. A client can connect to Database Server through JDBC Driver.
Since most of the Database servers support ODBC driver therefore JDBC-ODBC Bridge
driver is commonly used.The return type of the Class.forName (String ClassName) method is
“Class”. Class is a class in java.lang package.
try
{
Class.forName(”sun.jdbc.odbc.JdbcOdbcDriver”); //Or any other driver
}
catch(Exception x)
{
System.out.println( “Unable to load the driver class!” );
}
MODULE 5 MCA-404 Java and Web Programming ADMN 2009-‘10
The JDBC DriverManager class defines objects which can connect Java applications
to a JDBC driver. DriverManager is considered the backbone of JDBC architecture.
DriverManager class manages the JDBC drivers that are installed on the system. Its
getConnection() method is used to establish a connection to a database. It uses a username,
password, and a jdbc url to establish a connection to the database and returns a connection
object. A jdbc Connection represents a session/connection with a specific database. Within the
context of a Connection, SQL, PL/SQL statements are executed and results are returned. An
application can have one or more connections with a single database, or it can have many
connections with different databases. A Connection object provides metadata i.e. information
about the database, tables, and fields. It also contains methods to deal with transactions.
A statement object is used to send and execute SQL statements to a database.There are three
kinds of Statements
4. Executing a SQL statement with the Statement object, and returning a jdbc resultSet.
Statement interface defines methods that are used to interact with database via the
execution of SQL statements. The Statement class has three methods for executing statements:
executeQuery(), executeUpdate(), and execute(). For a SELECT statement, the method to use
is executeQuery . For statements that create or modify tables, the method to use is
executeUpdate. Note: Statements that create a table, alter a table, or drop a table are all
examples of DDLstatements and are executed with the method executeUpdate. execute()
executes an SQL statement that is written as String object.
ResultSet
ResultSetMetaData
(Fig: 5.7)
import java.sql.*
Page 187
MODULE 5 MCA-404 Java and Web Programming ADMN 2009-‘10
while (rs.next())
System.out.println("Name= " + rs.getString("moviename") + " Date= " +
rs.getString("releasedate");
}
catch (SQLException e) {
e.printStackTrace();
}
catch (Exception e) {
e.printStackTrace();
}
finally {
// Close the connection
con.close();
}
}
}
The essential tags that are required to create a HTML document are:
• <HTML>.............</HTML>
• <HEAD>.............</HEAD>
• <BODY>.............</BODY>
Page 188
MODULE 5 MCA-404 Java and Web Programming ADMN 2009-‘10
The <HTML> tag encloses all other HTML tags and associated text within your
document. It is an optional tag. You can create an HTML document that omits these tags, and
your browser can still read it and display it. But it is always a good form to include the start
and stop tags. The format is:
<HTML>
Your Title and Document (contains text with HTML tags) goes here
</HTML>
Most HTML tags have two parts, an opening tag and closing tag.The closing tag is the same
as the opening tag, except for the slash.
HEAD tag comes after the HTML start tag. It contains TITLE tag to give the
document a title that displays on the browsers title bar at the top.The Format is:
<HEAD>
<TITLE>
Your title goes here
</TITLE>
</HEAD>
The BODY tag contains all the text and graphics of the document with all the HTML
tags that are used for control and formatting of the page.The Format is:
<BODY>
Your Document goes here
</BODY>
Classification of Tags
Container Tags
Tags which have both the opening and closing i.e. <TAG> and </TAG> are called
container tags. They hold the text and other HTML tags in between the tags. The <HTML>,
<HEAD>, <TITLE> and <BODY> tags are all container tags.
Empty Tags
Tags, which have only opening and no ending, are called empty tags. The <HR>,
which is used to draw Horizontal, rule across the width of the document, and line break <BR>
tags are empty tags.
HTML has six header tags <H1>, <H2>...........<H6> used to specify section
headings. Text with header tags is displayed in larger and bolder fonts than the normal body
text by a web browser. Every header leaves a blank line above and below it when displayed in
browser.
Attributes
Page 190
MODULE 5 MCA-404 Java and Web Programming ADMN 2009-‘10
COLOR: Sets the color of the text that will appear on the screen.
SIZE: Sets the size of the text, takes value between 1 and 7, default is 3.
FACE: Sets the normal font type, provided it is installed on the user’s machine.
Comments in HTML
The comment tag is used to insert a comment in the HTML source code. A comment
can be placed anywhere in the document and the browser will ignore everything inside the
brackets. You can use comments to write notes to yourself, or write a helpful message to
someone looking at your source code.
Page 191
MODULE 5 MCA-404 Java and Web Programming ADMN 2009-‘10
5.2.3 List
HTML Supports several ways of arranging items in lists. The most commonly used are:
It is an empty tag (only start tag, no end tag) and is written as:
<IMG SRC = image_URL> where SRC attribute is mandatory
SRC – Source of the image file image
URL – represents the image file with its location.
ALIGN = LEFT - Displays image on left side and the subsequent text flows around the
right hand side of that image
ALIGN = RIGHT - Displays the image on the right side and the subsequent text flows
around the left hand side of that image
ALIGN = TOP - Aligns the text with the top of the image
MODULE 5 MCA-404 Java and Web Programming ADMN 2009-‘10
ALIGN = MIDDLE - Aligns the text with the middle of the image
ALIGN=BOTTOM - Aligns the text with the bottom of the image
VSPACE and HSPACE- White space around an image can be provided by using
HSPACE (Horizontal Space) and VSPACE (Vertical Space) attributes of the <IMG> tag.
ALT- is used to give alternative text that can be displayed in place of the image. This is
required when the user needs to stop display of images while retrieving a document in order
to make the retrieval faster, or when the browser does not support
HREF (Hyper Link Reference) is a mandatory attribute used to refer the URL of the
resource.
URL (Uniform Resource Locator) is an address tells the browser about the file to link to. It
identifies file locations (Addresses) on the web or on the local hard drive. These addresses can
be those of HTML documents or elements such as images, scripts, applets and other files. It is
always enclosed in quotes.
5.2.5 Tables
Tables are used in web pages for two major purposes:
Tables are defined with the <table> tag. A table is divided into rows (with the <tr>
tag), and each row is divided into data cells (with the <td> tag). The letters td stands for table
data, which is the content of a data cell. A data cell can contain text, images, lists, paragraphs,
forms, horizontal rules, tables, etc. Headings in a table are defined with the <th> tag.
The following properties can be added to the <table> tag. Table properties are set for
the entire table. If certain properties are set for single cells, they will have higher priority than
the settings for the table as a whole
Property Description
align=
left left align table
center center table
right right align table
frame=
void, removes all outer borders
above, shows border on top of table
below, shows border on bottom of
lhs, table
rhs, shows border on left side of
hsides, table
vsides, shows border on right side of
MODULE 5 MCA-404 Java and Web Programming ADMN 2009-‘10
box table
shows border on both
horizontal sides
shows border on both vertical
sides
shows border on all sides of
table
valign=
top aligns content to top of cells
bottom aligns content to bottom of
cells
Table: 5.1
5.2.6 HTML FORMS
Html Forms are used to create GUIs on Web pages. Usually the purpose is to ask the
user for information, which is then sent back to the server. A form can contain input elements
like text fields, checkboxes, radio-buttons, submit buttons and more. A form can also contain
select lists, textarea, fieldset, legend, and label elements.
The tag <form> and </form> are used to add a form. All kinds of HTML tags can
be added between the <form> and </form> tags. It informs browser that any thing specified
between these tags belong to form
Attributes
The most important form element is the input element. The input element is used to
select user information. An input element can vary in many ways, depending on the type
attribute. An input element can be of type text field, checkbox, password, radio button, submit
button, and more.<input >is the tag used to create input elements. The attribute type
determines the specific sort of input element to be created.The syntax is:
<input type="text" /> defines a one-line input field that a user can enter text into.
Eg: <form>
First name: <input type="text" name="firstname" /> <br />
Last name: <input type="text" name="lastname" />
</form>
<input type="radio" /> defines a radio button. Radio buttons let a user select ONLY ONE of a
limited number of choices.
Eg:<form>
<input type="radio" name="sex" value="male" /> Male <br />
<input type="radio" name="sex" value="female" /> Female
</form>
5.2.6.4 Checkboxes
<input type="checkbox" /> defines a checkbox. Checkboxes let a user select ONE or MORE
options of a limited number of choices
Eg: form>
Bike: <input type="checkbox" name="vehicle" value="Bike"/> <br />
Car: <input type="checkbox" name="vehicle" value="Car"/><br />
</form>
A submit button is used to send form data to a server. The data is sent to the page specified in
the form's action attribute. The file defined in the action attribute usually does something with
the received input.
Page 196
MODULE 5 MCA-404 Java and Web Programming ADMN 2009-‘10
5.2.7 Frames
Frames allow for multiple ".html" documents to be displayed inside of one browser
window at a time. Each HTML document is called a frame, and each frame is independent of
the others.
The <frameset> tag defines the general layout of a web page that uses frames. Each
frameset defines a set of rows or columns.The values of the rows/columns indicate the amount
of screen area each row/column will occupy
The <frame> tag defines one particular window (frame) within a frameset. It has the SRC
attribute, which indicates the URL of the page that goes in the frame.
Setting the rows attribute defines the number of horizontal subspaces in a frameset.
Setting the cols attribute defines the number of vertical subspaces. Both attributes may be set
simultaneously to create a grid.
If the rows attribute is not set, each column extends the entire length of the page. If
the cols attribute is not set, each row extends the entire width of the page. If neither attribute is
set, the frame takes up exactly the size of the page.
frameset cols="25%,75%">
<frame src="frame_a.htm">
<frame src="frame_b.htm">
</frameset>
In the example above we have a frameset with two columns. The first column is set
to 25% of the width of the browser window. The second column is set to 75% of the width of
the browser window. The HTML document "frame_a.htm" is put into the first column, and
the HTML document "frame_b.htm" is put into the second column.
<html>
<frameset rows="30%,40%,30>
<frame src="frame_a.htm">
<frame src="frame_b.htm">
Page 197
MODULE 5 MCA-404 Java and Web Programming ADMN 2009-‘10
<frame src="frame_c.htm">
</frameset>
</html>
In the example below we have a frameset with three rows. The first row is set to 30%
of the width of the browser window. The second row is set to 40% of the width of the browser
window. The third row is set to 30% browser window. The HTML document "frame_a.htm"
is put into the first row, HTML document "frame_b.htm" is put into the second row and the
HTML document "frame_c.htm" is put into the third row.
Java Script is a scripting language which was designed to add interactivity to HTML
pages. It was released by Netscape and Sun Microsystems in 1995. JavaScript code is
typically embedded in the HTML, to be interpreted and run by the client's browser. JavaScript
was influenced by many languages and was designed to look like Java, but to be easier for
non-programmers to work with.
JavaScript ignores spaces, tabs, and newlines that appear in JavaScript programs.
Because you can use spaces, tabs, and newlines freely in your program so you are free to
format and indent your programs in a neat and consistent way that makes the code easy to
read and understand. Simple statements in JavaScript are generally followed by a semicolon
character, just as they are in C, C++, and Java. JavaScript, however, allows you to omit this
semicolon if your statements are each placed on a separate line. JavaScript is a case-sensitive
language. So identifiers Time, TIme and TIME will have different meanings in JavaScript.
• JavaScript gives HTML designers a programming tool - HTML authors are normally
not programmers, but JavaScript is a scripting language with a very simple syntax! Almost
anyone can put small "snippets" of code into their HTML pages
• JavaScript can put dynamic text into an HTML page - A JavaScript statement like
this: document.write("<h1>" + name + "</h1>") can write a variable text into an HTML
page
• JavaScript can react to events - 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
• JavaScript can read and write HTML elements - A JavaScript can read and change the
content of an HTML element
• JavaScript can be used to validate data - A JavaScript can be used to validate form
data before it is submitted to a server. This saves the server from extra processing
Page 198
MODULE 5 MCA-404 Java and Web Programming ADMN 2009-‘10
• JavaScript can be used to detect the visitor's browser - A JavaScript can be used to
detect the visitor's browser, and - depending on the browser - load another page specifically
designed for that browser
<script ...>
JavaScript code
</script>
• language: This attribute specifies what scripting language you are using. Typically, its
value will be javascript. Although recent versions of HTML (and XHTML, its
successor) have phased out the use of this attribute.
• type: This attribute is what is now recommended to indicate the scripting language in
use and its value should be set to "text/javascript".
JavaScript also defines two trivial data types, null and undefined, each of which defines only a
single value. Page 199
MODULE 5 MCA-404 Java and Web Programming ADMN 2009-‘10
Like many other programming languages, JavaScript has variables. Variables can be
thought of as named containers. You can place data into these containers and then refer to the
data simply by naming the container.In JavaScript you don't have to declare a variable's data
type before using it. Any variable can hold any JavaScript data type
There are rules and conventions in naming variables in any programming language.
It is good practice to use descriptive names for variables. The following are the JavaScript
rules:
• should not use any of the JavaScript reserved keyword as variable name
• The variable name must start with a letter or an underscore.
firstName or _myName
• You can use numbers in a variable name, but not as the first character.
name01 or tuition$
• You can't use space to separate characters.
userName not user Name
Before you use a variable in a JavaScript program, you must declare it. Variables are declared
with the var keyword as follows:
Eg: var userName
When you declare a variable within a function, the variable can only be accessed
within that function. When you exit the function, the variable is destroyed. These variables are
called local variables. You can have local variables with the same name in different functions,
because each is recognized only by the function in which it is declared.
If you declare a variable outside a function, all the functions on your page can access
it. The lifetime of these variables starts when they are declared, and ends when the page is
closed.
5.3.5 Operators
arithmetic
bitwise
relational
logical
Page 200
MODULE 5 MCA-404 Java and Web Programming ADMN 2009-‘10
Operator Description
Table: 5.2
5.3.5.2 Relational operators
Relational operators determine the relationship that one operand has to the other.
Specifically, they determine equality and ordering
Operator Description
Checks if the value of two operands are equal or not, if
== yes then condition becomes true.
Checks if the value of two operands are equal or not, if
values are not equal then condition becomes true.
!= Checks if the value of left operand is greater than the
value of right operand, if yes then condition becomes
true.
> Checks if the value of left operand is less than the value
of right operand, if yes then condition becomes true.
Checks if the value of left operand is greater than or
< equal to the value of right operand, if yes then condition
becomes true.
Checks if the value of left operand is less than or equal to
the value of right operand, if yes then condition becomes
>= true.
<=
Table : 5.3
Page 201
MODULE 5 MCA-404 Java and Web Programming ADMN 2009-‘10
The Boolean logical operators shown here operate only on boolean operands. All of
the binary logical operators combine two boolean values to form a resultant boolean value
Operator Description
Called Logical AND operator. If both the operands are non
&& zero then then condition becomes true.
Called Logical OR Operator. If any of the two operands are
non zero then then condition becomes true.
|| Called Logical NOT Operator. If a condition is true then
Logical NOT operator will make false.
!
Table: 5.4
5.3.5.4 Bitwise Operators
These operators act upon the individual bits of their operands
>>
5.3.6.1 if statement:
The if statement is the fundamental control statement that allows JavaScript to make
decisions and execute statements conditionally
if (expression)
{
Statement(s) to be executed if expression is true
}
The if...else statement is the next form of control statement that allows JavaScript to execute
statements in more controlled way.
if (expression)
{
Statement(s) to be executed if expression is true
}
else
{
Statement(s) to be executed if expression is false
}
The if...else if... statement is the one level advance form of control statement that
allows JavaScript to make correct decision out of several conditions.
if (expression 1)
{
Statement(s) to be executed if expression 1 is true
}
else if (expression 2)
{
Statement(s) to be executed if expression 2 is true
}
else if (expression 3)
{
Statement(s) to be executed if expression 3 is true
}
else
{
Page 203
MODULE 5 MCA-404 Java and Web Programming ADMN 2009-‘10
The basic syntax of the switch statement is to give an expression to evaluate and
several different statements to execute based on the value of the expression. The interpreter
checks each case against the value of the expression until a match is found. If nothing
matches, a default condition will be used.
switch (expression)
{
case condition 1: statement(s)
break;
case condition 2: statement(s)
break;
...
case condition n: statement(s)
break;
default: statement(s)
}
while (expression)
{
Statement(s) to be executed if expression is true
}
do
{
Statement(s) to be executed;
} while (expression);
Page 204
MODULE 5 MCA-404 Java and Web Programming ADMN 2009-‘10
The Array object is used to store a set of values in a single variable name. The syntax is:
var v_name=new Array();
Array Methods
Method Description
Returns a new array comprised of this array joined
concat() with other array(s) and/or value(s).
Joins all elements of an array into a string.
join()
sort()
5.3.7 Objects
JavaScript supports programming with objects.Every object has its own properties
and methods.These properties define the characteristics of an object.Some of the built-in
language objects of JavaScript are:
• Math
• Date
• String
Method Description
abs() Returns the absolute value of
a number.
Returns base to the exponent
pow() power.
Returns a pseudo-random
number between 0 and 1.
random() Returns the value of a
number rounded to the
round() nearest integer
Returns the square root of a
number.
sqrt()
Table: 5.7
new Date( )
new Date(milliseconds)
Page 206
MODULE 5 MCA-404 Java and Web Programming ADMN 2009-‘10
new Date(datestring)
new Date(year,month,date[,hour,minute,second,millisecond ])
Method Description
Table: 5.8
Method Description
charAt() Returns the character at the specified index.
concat() Combines the text of two strings and returns a
new string.
Returns the characters in a string beginning at the
substr() specified location through the specified number
of characters.
valueOf()
toString() Returns the primitive value of the specified
object.
Table: 5.9
Page 207
MODULE 5 MCA-404 Java and Web Programming ADMN 2009-‘10
Document object represents the Web page that is loaded in the browser window, and
the content displayed on that page.Document object methods can be used to work on a Web
page.
Methods
• open([mimeType]) - Opens a new document object with the optional MIME type.
Eg: <html>
<body>
<script type="text/javascript">
document.write("Hello World!")
</script>
</body>
</html>
• close() - Closes an output stream that was used to create a document object.
Properties
Following are some of the properties of Document object.
bgColor- This property defines a document's background color. The "colorinfo" argument is
a string that can contain either the hexadecimal definition of the color or it's literal description.
title -This property returns the document's name as defined between the <TITLE></TITLE>
tags.
Syntax: document.title
Page 208
MODULE 5 MCA-404 Java and Web Programming ADMN 2009-‘10
The window object represents an open window in a browser. You can use it to open a Web
page in a new window and to set the attributes for the window
The window methods are mainly for opening and closing new windows. The following are the
main window methods.
• alert("message") - The string passed to the alert function is displayed in an alert dialog
box. alert confirm(“message”) - Displays a dialog box with the given message and an OK
and a Cancel button
• prompt(msg,defaultText)- Displays a dialog box that prompts the visitor for input. This
method returns the string the visitor has entered. Here msg is the message to display in the
dialog box and defaultText represents the default input value which is optional.
• ("This is a test")
Expressions
An expression is any valid set of literals, variables, operators, and expressions that
evaluates to a single value. The value may be a number, a string, or a logical value.
Conceptually, there are two types of expressions: those that assign a value to a variable, and
thosethatsimplyhaveavalue.Forexample,theexpression
JavaScript has the following kinds of expressions:
Java script Function is a reusable code-block that is execute when the function is called.
Function is defined in the head section of the code. The syntax of JavaScript function is as
follows:
function functionname(var1,var2,...,varX)
{
JavaScript code 1
JavaScript code 2
....
}
Page 209
MODULE 5 MCA-404 Java and Web Programming ADMN 2009-‘10
The parameters var1, var2, etc. are variables or values passed into the function. The {
and the } defines the start and end of the function.While defining JavaScript function its
important to remember that the keyword function should be in lowercase other wise
JavaScript won't understand it as function. If you write function in uppercase the code will
generate error. In the JavaScript semicolon is optional but its better to put semi-colon as part
of best practices. All the java script code are written inside the curly braces. JavaScript
provides many built in functions that ease the development of JavaScript programs
function add(x,y)
{
return(x+y);
The building blocks of an interactive web page is the JavaScript event system. An
event in JavaScript is something that happens with or on the webpage. A few example of
events:
A mouse click
The webpage loading
Mousing over a hot spot on the webpage, also known as hovering
Selecting an input box in an HTML form
A keystroke
Usually, events are used in combination with functions, so that the function does not start until
the event happens. The following are the most important events recognized by javascript:
5.3.8.1 onchange The content of a field changes. This is used frequently to validate the data
that has been entered by the user by calling a specified JavaScript function
this.myForm.userEmail.focus();
this.myForm.userEmail.select();
function validateInput()
{
if (userInput.match("@"))
alert("Thanks for your interest.");
else
alert("Please check your email details are correct before submitting");
}
</script>
5.3.8.2 onclick - This event is triggered when active text or images are clicked on
<form>
</form>
5.3.8.3 onfocus - An element gets focus. often used in combination with validation of
form fields.
5.3.8.4 onload - A This event is triggered when the user enters or leaves the page. The
onload event is often used to check the visitor's browser type and browser version, and
load the proper version of the web page based on the information. used to deal with
cookies that should be set when a user enters or leaves a page.
5.3.8.5 onmouseover – This event is triggered when the mouse is passed over active text
or image.
<A HREF=""onMouseOver="document.bgColor='black'">Black</a>
The code will allow users to pass their mouse over text and change the actual background
color of the page.
5.3.8.6 onsubmit - The onSubmit event is used to validate all form fields before
submitting it.
The checkForm() function will be called when the user clicks the submit button in the form. If
the field values are not accepted, the submit should be cancelled. The function checkForm()
returns either true or false. If it returns true the form will be submitted, otherwise the submit
will be cancelled.
Page 211
MODULE 5 MCA-404 Java and Web Programming ADMN 2009-‘10
Form validation is the process of checking that a form has been filled in correctly
before it is processed. For example, if your form has a box for the user to type their email
address, you might want your form handler to check that they've filled in their address before
you deal with the rest of the form.
There are two main methods for validating forms: server-side (using CGI scripts,
ASP, etc), and client-side (usually done using JavaScript). Server-side validation is more
secure but often more tricky to code, whereas client-side (JavaScript) validation is easier to
do and quicker too (the browser doesn't have to connect to the server to validate the form, so
the user finds out instantly if they've missed out that required field!).
</form>
This is so that we can reference the form by name from our JavaScript validation
function. The form uses the post method to send data. Finally, the form tag includes an
onsubmit attribute to call our JavaScript validation function, validate_form(),when the "Send
Details" button is pressed. The return allows us to return the value true or false from our
function to the browser, where true means "carry on and send the form to the server", and
false means "don't send the form". This means that we can prevent the form from being sent if
the user hasn't filled it in properly. The rest of the form prompts the user to enter their name
into a form field called contact_name, and adds a "Send Details" submit button:
<script type="text/javascript">
<!--
function validate_form ( )
{
valid = true;
if ( document.contact_form.contact_name.value == "" )
{
Page 212
MODULE 5 MCA-404 Java and Web Programming ADMN 2009-‘10
return valid;
}
//-->
</script>
5.4 SERVLET
A servlet is a server-side software program, written in Java code, that handles
messaging between a client and server. Because it is written in Java, it has full access to Java's
advanced features - database connectivity, network awareness, object orientation and built-in
support for multi-threaded processes.. Servlets use the Java Servlet API allowing them to be
used with almost any web server. Servlets can respond to client requests by dynamically
constructing a response that is sent back to the client. Servlets interact with web clients via a
request response paradigm implemented by the servlet container. This request-response model
is based on the behavior of the Hypertext Transfer Protocol (HTTP).
Servlets may be used at different levels on a distributed framework. The following are some
examples of servlet usage:
• In conjunction with applets to provide a high degree of interactivity and dynamic Web
content generation.
The Common Gateway Interface, normally referred to as CGI, was one of the first
practical techniques for creating dynamic content. With CGI, a web server passes certain
requests to an external program. The output of this program is then sent to the client in place
Page 213
MODULE 5 MCA-404 Java and Web Programming ADMN 2009-‘10
of a static file. The advent of CGI made it possible to implement all sorts of new functionality
in web pages.
When a server receives a request that accesses a CGI program, it must create a new
process to run the CGI program and then pass to it, via environment variables and standard
input, every bit of information that might be necessary to generate a response. Creating a
process for every such request requires time and significant server resources, which limits the
numberofrequestsaservercanhandleconcurrently
Java servlets are more efficient, easier to use, more powerful, more portable, safer, and
cheaper than traditional CGI
Efficient
With traditional CGI, a new process is started for each HTTP request. If the CGI
program itself is relatively short, the overhead of starting the process can dominate the
execution time. With servlets, the Java virtual machine stays running and handles each request
with a lightweight Java thread, not a heavyweight operating system process. Similarly, in
traditional CGI, if there are N requests to the same CGI program, the code for the CGI
program is loaded into memory N times. With servlets, however, there would be N threads,
but only a single copy of the servlet class would be loaded.
This approach reduces server memory requirements and saves time by instantiating
fewer objects. Finally, when a CGI program finishes handling a request, the program
terminates. This approach makes it difficult to cache computations, keep database connections
open, and perform other optimizations that rely on persistent data. Servlets,however, remain
in memory even after they complete a response, so it is straightforward to store arbitrarily
complex data between client requests.
Convenient
Powerful
Page 214
MODULE 5 MCA-404 Java and Web Programming ADMN 2009-‘10
similar resource-sharing optimizations. Servlets can also maintain information from request to
request, simplifying techniques like session tracking and caching of previous computations.
Portable
Servlets are written in the Java programming language and follow a standard API.
Servlets are supported directly or by a plug-in on virtually every major Web server.
Secure
One of the main sources of vulnerabilities in traditional CGI stems from the fact that
the programs are often executed by general-purpose operating system shells. So, the CGI
programmer must be careful to filter out characters such as backquotes and semicolons that
are treated specially by the shell
A second source of problems is the fact that some CGI programs are processed by
languages that do not automatically check array or string bounds. So, programmers who forget
to perform this check open up their system to deliberate or accidental buffer overflow attacks.
Servlets suffer from neither of these problems. Even if a servlet executes a system
call (e.g., with Runtime.exec or JNI) to invoke a program on the local operating system,it does
not use a shell to do so. And, of course, array bounds checking and other memory protection
features are a central part of the Java programming language.
The servlet container is a part of a Web server or application server that provides the
network services over which requests and responses are sent. Servlets are managed by the
servlet container, or servlet engine.When the Webserver receives a request that is for a
servlet, the request is passed to the servlet container. The container makes sure the servlet is
loaded and calls it. When the servlet is finished, the. the container reinitializes itself and
returns control to the Webserver.
A servlet container uses a Java Virtual Machine to run servlet code as requested by a
web server. The servlet container is also responsible for managing other aspects of the servlet
lifecycle: user sessions, class loading, servlet contexts (which we will discuss in the next
session), servlet configuration information, servlet persistence, and temporary storage
Eg:Tomcat is the Servlet Engine or servlet container than handles servlet requests for
Apache
Page 215
MODULE 5 MCA-404 Java and Web Programming ADMN 2009-‘10
( Fig:5.8)
The Servlet interface provides the following methods that manage the servlet and its
communications with clients.
• destroy()
Cleans up whatever resources are being held and makes sure that any persistent state is
synchronized with the servlet's current in-memory state.
• getServletConfig()
Returns a servlet config object, which contains any initialization parameters and startup
configuration for this servlet.
• getServletInfo()
Returns a string containing information about the servlet, such as its author, version, and
copyright.
• init(ServletConfig)
Initializes the servlet. Run once before any requests can be serviced.
• service(ServletRequest, ServletResponse)
Carries out a single request from the client.
Servlet writers provide some or all of these methods when developing a servlet.
When a servlet accepts a service call from a client, it receives two objects,
ServletRequest and ServletResponse. The ServletRequest class encapsulates the
communication from the client to the server, while the ServletResponse class encapsulates
the communication from the servlet back to the client.
Page 216
MODULE 5 MCA-404 Java and Web Programming ADMN 2009-‘10
The ServletRequest interface allows the servlet access to information such as the
names of the parameters passed in by the client, the protocol (scheme) being used by the
client, and the names of the remote host that made the request and the server that received it. It
also provides the servlet with access to the input stream, ServletInputStream, through which
the servlet gets data from clients that are using application protocols such as the HTTP POST
and PUT methods. Subclasses of ServletRequest allow the servlet to retrieve more protocol-
specific data. For example, HttpServletRequest contains methods for accessing HTTP-specific
header information.
The ServletResponse interface gives the servlet methods for replying to the client. It
allows the servlet to set the content length and mime type of the reply, and provides an output
stream, ServletOutputStream, and a Writer through which the servlet can send the reply data.
Subclasses of ServletResponse give the servlet more protocol-specific capabilities. For
example, HttpServletResponse contains methods that allow the servlet to manipulate HTTP-
specific header information.
The classes and interfaces described above make up a basic Servlet. HTTP servlets
have some additional objects that provide session-tracking capabilities. The servlet writer can
use these APIs to maintain state between the servlet and the client that persists across multiple
connections during some time period.
(Fig: 5.9)
Page 217
MODULE 5 MCA-404 Java and Web Programming ADMN 2009-‘10
init()
When a server loads a servlet, it runs the servlet's init method. Even though most
servlets are run in multi-threaded servers, there are no concurrency issues during servlet
initialization. This is because the server calls the init method once, when it loads the servlet,
and will not call it again unless it is reloading the servlet. It is possible to pass initialization
parameters to the servlet so it may configure itself. After the init() method runs, the servlet
container marks the servlet as available.
service()
After the server loads and initializes the servlet, the servlet is able to handle client
requests. It processes them in its service method. Each client's request has its call to the
service method. The service( ) method receives the client's request, checks the type of request
(GET, POST, PUT, DELETE, TRACE, OPTION) and call the appropriate method: doGet,
doPost, doPut, doDelete, doTrace, doOption. The service() method can have access to all
the resources created in the init() method
Servlets can run multiple service methods at a time. It is important, therefore, that
service methods be written in a thread-safe manner. If, for some reason, a server should not
run multiple service methods concurrently, the servlet should implement the
SingleThreadModel interface. This interface guarantees that no two threads will execute the
servlet's service methods concurrently.
destroy()
If the Servlet is no longer needed for servicing any request, the servlet container calls
the destroy() method . Like the init() method this method is also called only once throughout
the life cycle of the servlet. Calling the destroy() method indicates to the servlet container not
to sent the any request for service and the servlet releases all the resources associated with it.
Java Virtual Machine claims for the memory associated with the resources for garbage
collection.
The Servlet API consists of two packages, javax.servlet and javax.servlet.http. The
javax is there because servlets are a standard extension to Java, rather than a mandatory part
of the API. This means that while servlets are official Java, Java virtual machine developers
aren’t required to include the classes for them in their Java development and execution
environments
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
Page 218
MODULE 5 MCA-404 Java and Web Programming ADMN 2009-‘10
implement this interface or extend a class that implements the interface.The ServletRequest
and ServletResponse interfaces are also very important.
Interface Description
The following table summarizes the core classes that are provided in the javax.servlet
package.
Class Description
GenericServlet Implements the Servlet and ServletConfig interfaces.
ServletInputStream Provides an input stream for reading requests from a
client.
ServletOutputStream Provides an output stream for writing responses to
a client.
Indicates a servlet error occurred.
ServletException
The javax.servlet.http package contains a number of interfaces and classes that are
commonly used by servlet developers. These classes and interfaces makes it easy to build
servlets that work with HTTP requests and responses.
The following list summarizes the core interfaces that are provided in this package:
Interface Description
from a session.
Page 219
MODULE 5 MCA-404 Java and Web Programming ADMN 2009-‘10
The following list summarizes the core classes that are provided in this package. The
most important of these is HttpServlet. ServletOutputStream Servlet developers typically
extend this class in order to process HTTP requests.
Class Description
Cookie Allows state information to be stored on a client machine.
HttpServlet Provides methods to handle HTTP requests and responses.
HttpSessionEvent Encapsulates a session-changed event.
HttpSessionBindingEvent Indicates when a listener is bound to or unbound from a session
value, or that a session attribute changed.
HttpServlet is an abstract class that simplifies writing HTTP servlets. It extends the
GenericServlet base class and provides a framework for handling the HTTP protocol.
Because it is an abstract class, servlet writers must subclass it and override at least one
method. The methods normally overridden are doGet() and doPost, which respond to
HTTP request types get and post .Depending on the type of request these methods are called
by the HttpServlet class's service method, which is called when a request arrives at the
server. Methods doGet and doPost receive as arguments an HttpServletRequest object
and an HttpServletResponse object that enable interaction between the client and the
server. Important methods of the HttpServlet class are summarized in Table below
Method Description
Table: 5.10
Page 220
MODULE 5 MCA-404 Java and Web Programming ADMN 2009-‘10
This interface gets data from the client to the servlet for use in the
HttpServlet.service method. It allows the HTTP-protocol specified header information to be
accessed from the service method. This interface is implemented by network-service
developers for use within servlets.
Methods
String getParameter( String name ) - Returns the value associated with a parameter sent
to the servlet as part of a GET or POST request
Enumeration getParameterNames() - Returns the names of all the parameters sent to the
servlet as part of a POST request
Cookie[] getCookies() - Returns an array of Cookie objects stored on the client by the
server. Cookies can be used to uniquely identify clients to the servlet
HttpSession getSession(boolean create) - Gets the current valid session associated with
this request, if create is false or, if necessary, creates a new session for the request, if
create is true.
Methods
void addCookie( Cookie cookie ) - Used to add a Cookie to the header of the response to
the client
void setContentType( String type ) =Specifies the MIME type of the response to the
browser. The MIME type helps the browser determine how to display the data (or possibly
what other application to execute to process the data).
Page 221
MODULE 5 MCA-404 Java and Web Programming ADMN 2009-‘10
Eg:MIME type "text/html" indicates that the response is an HTML document, so the
browser displays the HTML
Example: Here we will develop a servlet that handles an HTTP GET request. The servlet is
invoked when a form on a Web page is submitted. The example contains two files. A Web
page is defined in HelloForm.html and a servlet is defined in HelloServlet.java. The HTML
source code for HelloForm.html is shown below. It defines a form that contains a select text
box to enter your name and a submit button. Notice that the action parameter of the form tag
specifies a URL. The URL identifies a servlet to process the HTTP GET request
HelloForm.html
<html><body>
<form method="GET" action="HelloServlet">
Please enter your name:
<input type="text" name="user_name">
<input type="submit" value="OK">
</form>
</body></html>
HelloServlet.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class HelloServlet extends HttpServlet
{
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException
{
response.setContentType("text/html");
ServletOutputStream out = response.getOutputStream();
String userName = request.getParameter("user_name");
out.println("<html><head>");
out.println("\t<title>Hello Servlet</title>");
out.println("</head><body>");
out.println("\t<h1>Hello, " + userName + "</h1>");
out.println("</body></html>");
}
}
Page 222
MODULE 5 MCA-404 Java and Web Programming ADMN 2009-‘10
The source code for HelloServlet.java is shown in the following listing. The
doGet( ) method is overridden to process any HTTP GET requests that are sent to this servlet.
It uses the getParameter( ) method of HttpServletRequest to obtain the the value entered by
the user. 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 getOutputStream() method obtains a
ServletOutputStream. 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.
5.5 Cookies
Cookies serve as a facility for servers to send information to a client. This
information is then housed on the client, from which the server can later retrieve the
information
Java Servlets (which reside on the server) send cookies to clients by adding fields to
their HTTP response headers. Similarly, clients return cookies to servers by adding fields to
HTTP request headers. When a client application (e.g., a Web browser) receives a cookie
from a web server, the client application stores the cookie locally. Upon subsequent request to
the web server, the cookie will be returned.
The content and names of the cookies are opaque to the browser. The browser keeps
the cookies separate for each of the hosts that it is communicating with. In a way, the cookies
belong to the server even though they are stored in the browser. A single browser can store
300 cookies where size of each cookie is limited to 4KB
The cookie mechanism provides a limited amount of storage space which the server
can make use of on each user’s browser. Servers use cookies to mark each user’s browser so
the server can identify which requests are coming from which browser. The browser is very
careful not to mix cookies from different servers. Each cookie is marked with the domain
name of the server that set the cookie and cookies are only sent back on requests destined for
the server that initially set the cookie.
A Java cookie is an object of the javax.servlet.http.Cookie class. Cookies are created with the
Cookie constructor.
Cookie(String name, String value)
Here, the name and value of the cookie are supplied as arguments to the constructor
A servlet can write a cookie to a user’s machine via the addCookie( ) method of the
HttpServletResponse interface. The data for that cookie is then included in the header of the
HTTP response that is sent to the browser.
Page 223
MODULE 5 MCA-404 Java and Web Programming ADMN 2009-‘10
Cookies are passed back to servers using fields added to HTTP request headers. In
this API, HTTP request fields are retrieved using the getCookies method of
HttpServletRequest Interface.This returns all of the cookies found in the request.
Some of the information that is saved for each cookie includes the following:
The expiration date determines when this cookie is deleted from the user’s machine.
If an expiration date is not explicitly assigned to a cookie, it is deleted when the current
browser session ends. Otherwise, the cookie is saved in a file on the user’s machine. The
domain and path of the cookie determine when it is included in the header of an HTTP
request. If the user enters a URL whose domain and path match these values, the cookie is
then supplied to the Web server. Otherwise, it is not.
Method Description
void setComment(String c) Sets the comment to c.
void setDomain(String d) Sets the domain to d.
Sets the maximum age of the cookie to secs
This is the number of seconds after which
the cookie is deleted. Passing –1 causes the
void setMaxAge(int secs) cookie to be removed when the browser is
terminated.
Sets the path to p.
void setPath(String p)
Table: 5.11
Page 224
MODULE 5 MCA-404 Java and Web Programming ADMN 2009-‘10
Method Description
Object getAttribute(String attr) Returns the value associated with the name passed in
attr. Returns null if attr is not found
Enumeration getAttributeNames( ) Returns an enumeration of the attribute names
associated with the session.
Returns the time (in milliseconds since midnight,
long getCreationTime( ) January 1, 1970, GMT) when this session was created
Returns the session ID.
String getId( )
long getLastAccessedTime( ) Returns the time (in milliseconds since midnight,
January 1, 1970, GMT) when the client last made a
request for this session.
Invalidates this session and removes it from the
void invalidate( ) context.
Returns true if the server created the session and it has
boolean isNew( )
Page 225
MODULE 5 MCA-404 Java and Web Programming ADMN 2009-‘10
Table: 5.12
5.7 JSP (Java Server Pages)
JavaServer Pages (JSP) is a technology based on the Java language and enables the
development of dynamic web sites. JSP was developed by Sun Microsystems to allow server
side development. JSP files are HTML files with special tags containing Java source code that
provide the dynamic content. The JSP file extension is .jsp rather than .htm or .html. JSPs run
in a server-side component known as a JSP container, which translates them into equivalent
Java servlets.
• They have built-in support for HTTP sessions, which makes application programming
possible.
• They have full access to Java technology–network awareness, threads, and database
connectivity
• Because JSP pages are HTML-like, they have greater compatibility with Web
development tools
JSP source code :This is the form the developer actually writes. It exists in a text file with an
extension of .jsp, and consists of a mix of HTML template code, Java language statements,
and JSP directives and actions that describe how to generate a Web page to service a
particular request.
Java source code :The JSP container translates the JSP source code into the source code for
an equivalent Java servlet as needed. This source code is typically saved in a work area and is
often helpful for debugging.
Compiled Java class: Like any other Java class, the generated servlet code is compiled into
byte codes in a .class file, ready to be loaded and executed.
Page 226
MODULE 5 MCA-404 Java and Web Programming ADMN 2009-‘10
The JSP container manages each of these forms of the JSP page automatically, based
on the timestamps of each file. In response to an HTTP request, the container checks to see if
the .jsp source file has been modified since the .java source was last compiled. If so, the
container retranslates the JSP source into Java source and recompiles it.
• Directives
• Scripting elements, including expressions, scriptlets, and declarations
• Actions
5.7.1.1 Directives
A JSP directive commands the jsp virtual engine to perform a specific task They have
the general form:
There are three standard directives available in all compliant JSP environments:
• page
• include
• taglib
Page 227
MODULE 5 MCA-404 Java and Web Programming ADMN 2009-‘10
• contentType: This attribute specifies the MIME type and the character encoding i.e.
used for the JSP response
Eg:<%@ page contentType="text/plain" %>
The include directive merges the contents of another file at translation time into the
.jsp source input stream, much like a #include C preprocessor directive. The syntax is
JSP technology supports the development of reusable modules called custom actions.
A custom action is invoked by using a custom tag in a JSP page and tag library is a
collection of custom tags. You declare that a JSP page will use tags defined in a tag library
by including a taglib directive in the page before any custom tag is used. The syntax of the
directive is:
<%@ taglib uri="tagLibraryURI" prefix="tagPrefix" %>
where tagLibraryURI is the URL of a Tag Library Descriptor and tagPrefix is a unique
prefix used to identify custom tags used later in the page.
Eg: <%@ taglib uri="/tlds/FancyTableGenerator.tld" prefix="ft" %>
and if FancyTableGenerator.tld defines a tag named table, then the page can contain tags of
the following type
<ft:table>
...
</ft:table>
5.7.1.2 Comments
The JSP specification provides two means of including comments in a JSP page: one
for hidden comments only visible in the JSP page itself and one for comments included in
the HTML or XML output generated by the page. The former type has the syntax
Page 228
MODULE 5 MCA-404 Java and Web Programming ADMN 2009-‘10
When the JSP compiler encounters the start tag <%- - of a JSP comment, it ignores
everything from that point in the file until it finds the matching end tag - -%>. This means
JSP comments can be used to disable (or "comment out") sections of the JSP page.
The other comment type uses the normal HTML or XML comment tag. Comments
of this type are passed through unaltered to the response output stream and are included in
the generated HTML. They are invisible in the browser window, but can be seen by
invoking the View Source menu option.
5.7.1.3 Expressions
JSP provides a simple means for accessing the value of a Java variable or other
expression and merging that value with the HTML in the page. The syntax is
where exp is any valid Java expression. The expression can have any data value, as long as it
can be converted to a string.
5.7.1.4 Scriptlets
A scriptlet consists of one or more valid Java statements. A scriptlet is a block of
Java code that is executed at request-processing time. A scriptlet is enclosed between "<%"
and "%>". What the scriptlet actually does depends on the code, and it can produce output
into the output stream to the client. Multiple scriptlets are combined in the compiled class in
the order in which they appear in the JSP. Scriptlets like any other Java code block or
method, can modify objects inside them as a result of method invocations.Scriptlets have the
following form:
<% Java Code %>
5.7.1.5 Declarations
A declaration is a block of Java code in a JSP that is used to define class-wide
variables and methods in the generated class file. Declarations are initialized when the JSP
page is initialized and have class scope. Anything defined in a declaration is available
throughout the JSP, to other declarations, expressions or code. It has the following form:
Page 229
MODULE 5 MCA-404 Java and Web Programming ADMN 2009-‘10
Since declarations do not generate any output, they are normally used in conjunction with
JSP expressions or scriptlets
Eg: <%!
private int example = 0 ;
private int test = 5 ;
%>
• <jsp:forward>: Forwards this HTTP request to another JSP page or servlet for processing
Syntax is:
<jsp:forward page="URL">
<jsp:param ... />
<jsp:param ... />
...
<jsp:param ... />
</jsp:forward>
<html>
<head>
<title> Hello JSP </title>
</head>
<body>
<p> Hello World:
<%= new java.util.Date() %>
</p>
</body>
</html>
This extract shows the part of above jsp that produces the output
out = pageContext.getOut();
_jspx_out = out;
out.write("<html>\r\n");
out.write("<head> ");
out.write("<title> Hello JSP ");
out.write("</title> ");
out.write("</head>\r\n");
out.write("<body> \r\n");
out.write("<p> Hello World:\r\n ");
out.print( new java.util.Date() );
out.write("\r\n");
out.write("</p>\r\n");
out.write("</body>\r\n");
out.write("</html>\r\n");
Variable Declaration
It is possible to declare variables in jsp by using the same coding techniques which is
used in java .Declarations can be used to define and initialize variables in jsp. The variables
will be available to scriptlets, expressions, and other declarations.
Page 231
MODULE 5 MCA-404 Java and Web Programming ADMN 2009-‘10
Method Definitions
Declarations can be used to define additional methods. The syntax is no different
than for any other method definitions, except for the <%! and %> delimiters. Once the
method is defined it can be called by using an expression tag.JSP virtual engine resolves the
tag that calls method by replacing tag by result returned by the method.
Eg:<HTML>
<HEAD>
<TITLE>JSP PROGRAMMING</HEAD>
<BODY>
<%! boolean curve(int grade)
{
return 10+grade;
}%>
<P your curved grade is:<%=curve(80)%></P>
</BODY></HTML>
Page 232
MODULE 5 MCA-404 Java and Web Programming ADMN 2009-‘10
boolean isCommitted() : Returns a flag indicating whether the HTTP response has
already been returned to the client.
void setHeader(String name, String value) : Sets an HTTP header with the specified
name and value.
void setStatus(int sc): Sets the HTTP status to the specified value.
Object getAttribute(String name) : Returns the object with the specified name, if it
exists in the session
String getId() : Returns the unique session ID. This ID must be stored by the client (Web
browser) between requests and passed back to the JSP container to identify which session
is required.
5.7.4 Cookies
A cookie is a small, named data element the server passes to a client with a Set-
Cookie header as part of the HTTP response. The client is expected to store the cookie and
return it to the server with a Cookie header on subsequent requests to the same server. Along
with the name and value, the cookie may contain:
• An expiration date, after which the client is no long expected to retain the cookie.
If no date is specified, the cookie expires as soon as the browser session ends.
• A domain name, such as servername.com, which restricts the subset of URLs for which
the cookie is valid. If unspecified, the cookie is returned with all requests to the
originating Web server.
• A secure attribute, which, if present, indicates the cookie should only be returned if the
connection uses a secure channel,
Page 233
MODULE 5 MCA-404 Java and Web Programming ADMN 2009-‘10
Eg: :<html>
<head>
<title>JSP PROGRAMMING</head>
<body>
<%! String MyCookieName=‘userID’;
String MyCookieValue=‘ JK1234’
response.addCookie(new Cookie(,MyCookieName, MyCookieValue); %>
</body>
</html>
A JSP page can indicate that a specific error page should be displayed when it throws an
uncaught exception,by using the errorpage attribute:
<%@ page errorPage="error_url" %> ,where error_url is the URL of another JSP page.
That JSP page must use the following attribute in its page directive:
If any exception is thrown then the control to handle the exception will be passed to
that error page specified by error_url where we can display an information to the user
about what's the reason behind throwing the exception.
An error page has access to the exception through the exception implicit variable. It
can extract the error message text with exception.getMessage(), displaying or logging it as
necessary. It can also generate a stack trace with exception.printStackTrace(). The page need
not be elaborate. It may simply report the exception:
Page 234