Sei sulla pagina 1di 60

5.

1 JAVA DATABASE PROGRAMMING

JDBC-Stands for Java Database Connectivity. In today's world the majority of


computer programs need some kind of database connectivity. JDBC is Java's answer to
database connectivity for a Java application or applet. It is an API developed by Sun
Microsystems that defines an interface for accessing various databases. One of JDBC’s
strengths is interoperability — a developer can create JDBC applications without targeting a
specific DBMS. Users can use specific JDBC drivers to target a specific database.

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.

5.1.1 JDBC Characteristics

• 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 JDBC Components

The following are JDBC components:

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:

• Requests a connection with a data source


• Sends SQL statements to the data source
• Defines storage areas and data types for the result sets

Page 175
MODULE 5

• Requests results
• Processes errors
• Controls transactions: requests commit or rollback operations
• Closes the connection

5.1.2.2 Driver Manager


Its primary purpose is to load specific drivers for the user application. It may also
perform the following:
• Locate a driver for a particular database
• Process JDBC initialization calls
• Provide entry points to JDBC functions for each specific driver
• Perform parameter and sequence validation for JDBC calls

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:

• Establish a connection to a data source


• Send requests to the data source
• Perform translations when requested by the user application
• Return results to the user application

5.1.3 JDBC Architecture


JDBC API uses Driver Manager and database specific drivers to provide transparent
connectivity to different databases.

( Fig: 5.1)
MODULE 5 MCA-404 Java and Web Programming ADMN 2009-‘10

There are 4 types of JDBC Drivers:

Type 1 - JDBC-ODBC Bridge


Type 2 - JDBC-Native Bridge
Type 3 - JDBC-Net Bridge
Type 4 - Direct JDBC Driver

5.1.3.1 Type 1 - JDBC-ODBC Bridge


Type 1 JDBC driver consists of a Java part that translates the JDBC interface calls to ODBC
calls. An ODBC bridge then calls the ODBC driver of the given database. Type 1 drivers are
(were) mostly intended to be used in the beginning, when there were no type 4 drivers (all
Java drivers).

(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

5.1.3.2 Type 2 - JDBC-Native Bridge

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

5.1.3.3 Type 3 - JDBC-Net Bridge

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.

5.1.3.4 Type 4 - Direct JDBC Driver


A type 4 JDBC driver is an all Java driver which connects directly to the database. It
is implemented for a specific database product. Today, most JDBC drivers are type 4 drivers.
MODULE 5 MCA-404 Java and Web Programming ADMN 2009-‘10

(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.

Which Driver should be used?

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

5.1.4 java.sql Package

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)

5.1.4.1 The DriverManager Class

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.

5.1.4.2 The Driver Interface

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

5.1.4.3 The Connection Interface

The Connection interface encapsulates the actual database connection into an


easy-to-use package. It is created by the DriverManager when its getConnection() method is
called. This method accepts a database connection URL and returns a database Connection to
the caller. To connect with a JDBC data source, a uniform resource locator, or URL, is used.
The format follows:

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.

Eg:String url = “jdbc:odbc:mysource”;

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.

5.1.4.4 The Statement Interface

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.

• ResultSet executeQuery( String sqlStatement )


This method sends the SQL query contained in sqlStatement and returns a single set of results.
This method is best used in sending SELECT statements. These statements typically return a
result set.
MODULE 5 MCA-404 Java and Web Programming ADMN 2009-‘10

• int executeUpdate( String sqlStatement )


This method sends the SQL query contained in sqlStatement and returns an integer. This
method is useful when you send SQL INSERTs, DELETEs, and UPDATEs. These commands
return a count of rows that were affected by your query. This statement should not be used for
queries that return result sets.

• boolean execute( String sqlStatement )


This method sends the sqlStatement to the database and returns true if the statement returns a
result set or false if the statement returns an integer. This method is best used when multiple
result sets can be returned.

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.

5.1.4.5 The ResultSet Class

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

5.1.5 Java Database Connectivity Steps

1. Loading a database driver,

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

2. Creating a jdbc Connection

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.

JDBC URL Syntax: jdbc: <subprotocol>: <subname>


try
{
Connection
dbConnection=DriverManager.getConnection(url,”loginName”,”Password”)
}
catch( SQLException x ){
System.out.println( “Couldn’t get connection!” );
}

3. Creating a jdbc Statement object,

Once a connection is obtained we can interact with the database. Connection


interface defines methods for interacting with the database via the established connection. To
execute SQL statements, you need to instantiate a Statement object from your connection
object by using the createStatement() method.

Statement statement = dbConnection.createStatement();

A statement object is used to send and execute SQL statements to a database.There are three
kinds of Statements

• Statement: It executes simple sql queries without parameters.


Statement createStatement() -Creates an SQL Statement object.
eg: Statement stmt = con.createStatement() ;

• Prepared Statement: Execute precompiled sql queries with or without parameters.


PreparedStatement prepareStatement(String sql) returns a new PreparedStatement
MODULE 5 MCA-404 Java and Web Programming ADMN 2009-‘10

object. PreparedStatement objects are precompiled SQL statements.


eg: String insert = “Insert into CS4400 (?,?,?)”;
PreparedStatement stmt2 = con.prepareStatement(insert);
stmt2.setInt(1,123456789);
stmt2.setString(2,abc);
stmt2.setInt(3,100);
stmt2.executeUpdate();

• Callable Statement: Execute a call to a database stored procedure.


CallableStatement prepareCall(String sql) returns a new CallableStatement object.

CallableStatement cs = conn.prepareCall("{call StoreProcedureName}");


ResultSet rs = cs.executeQuery();

eg: CallableStatement cs1 = con.prepareCall("{call HelloWorld}");


ResultSet rs1 = cs1.executeQuery();
returns a new CallableStatement object. CallableStatement objects are SQL stored
procedure call 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

It provides access to a table of data generated by executing a Statement. The table


rows are retrieved in sequence. A ResultSet maintains a cursor pointing to its current row of
data. The next() method is used to successively step through the rows of the tabular results.

ResultSetMetaData

It Interface holds information on the types and properties of the columns in a


ResultSet. It is constructed from the Connection object
MODULE 5 MCA-404 Java and Web Programming ADMN 2009-‘10

(Fig: 5.7)

import java.sql.*

public class JDBCSample {

public static void main( String args[]) {

String userName = "testuser";


String password = "testpass";
String url = "jdbc:mysql://localhost/test";
try {
Class.forName ("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection (url, userName, password);
//Create a Statement class to execute the SQL statement
Statement stmt = con.createStatement();

Page 187
MODULE 5 MCA-404 Java and Web Programming ADMN 2009-‘10

//Execute the SQL statement and get the results in a Resultset


ResultSet rs = stmd.executeQuery("select moviename, releasedate from movies");

// Iterate through the ResultSet, displaying two values


// for each row using the getString method

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();
}
}
}

5.2 Hyper Text MarkUp Lanuage (HTML)

HTML (Hypertext Markup Language) is used to create document on the


World Wide Web. It is simply a collection of certain key words called ‘Tags’ that are helpful
in writing the document to be displayed using a browser on Internet. It is a platform
independent language that can be used on any platform such as Windows, Linux, Macintosh,
and so on. To display a document in web it is essential to mark-up the different elements
(headings, paragraphs, tables, and so on) of the document with the HTML tags. To view a
mark-up document, user has to open the document in a browser. A browser understands and
interpret the HTML tags, identifies the structure of the document (which part are which) and
makes decision about presentation (how the parts look) of the document.

5.2.1 Creating a HTML document

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

5.2.1.1 HTML Tag <HTML>

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.

5.2.1.2 HEAD Tag <HEAD>

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>

5.2.1.3 BODY Tag <BODY>

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>

An HTML document, web page can be created using a text editor,Notepad or


WordPad. All the HTML documents should have the extension .htm or .html. It require a web
browser like Internet Explorer or Netscape Navigator/Communicator to view the document.
Some of the attributes used with body tag are given below:

BGCOLOR: used to set the background color for the document


TEXT: used to set the color of the text of the document
LEFTMARGIN: set the left hand margin of the document
Page 189
MODULE 5 MCA-404 Java and Web Programming ADMN 2009-‘10

TOPMARGIN: set the left hand margin of the document


BACKGROUND: It is used to point to an image file (the files with an extension .gif,
.jpeg) that will be used as the background of the document.

Classification of Tags

There are two types 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.

5.2.2 FORMATTING WEB PAGE


HTML tags used for formatting a web page are:

• Section Heading Tag: <H1>.............<H6>

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.

• Paragraph tag: <P>


This tag <P> indicates a paragraph, used to separate two paragraphs with a blank
line.

• Line Break Tag: <BR>


The empty tag <BR> is used, where the text needs to start from a new line and not
continue on the same line. To get every sentence on a new line, it is necessary to use a line
break.

• Horizontal Rule Tag: <HR>


An empty tag <HR> basically used to draw lines and horizontal rules. It can be used
to separate two sections of text.

Attributes

Page 190
MODULE 5 MCA-404 Java and Web Programming ADMN 2009-‘10

WIDTH: Specifies an exact width of HR in pixels, or a relative width as percentage of the


document width.
ALIGN: Set the alignment of the rule to LEFT, RIGHT and CENTER. It is applicable if it is
not equal to width of the page.
NOSHADE: If a solid bar is required, this attribute is used; it specifies that the horizontal rule
should not be shaded at all.
COLOR: Set the color of the Horizontal rule.

• Character Formatting Tags


The character formatting tags are used to specify how a particular text should be displayed on
the screen to distinguish certain characters within the document.The most common character
formatting tags are:

Boldface <B>: displays text in BOLD


Italics <I>: displays text in Italic
Subscript <SUB>: displays text in Subscript
Superscript <SUP>: displays text in Superscript
Small <SMALL>: displays text in smaller font as compared to normal font
Big <BIG>: displays text in larger font as compared to normal font

• Font Colors and Size:<FONT>


By using <FONT> Tag one can specify the colors, size of the text.
Attributes of <FONT> are:

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.

Eg: <FONT FACE="ARIAL"> the text will be displayed in Arial</FONT>

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.

Syntax : <!-- This is a comment -->

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:

• Ordered List (Numbered List)


• Unordered List (Bulleted List)

5.2.3.1 Ordered List <OL>


Ordered list also called as Numbered list, is used to present a numbered list of item
in the order of importance or the item (paragraph) is marked with a number. An ordered list
starts with the <ol> tag. Each list item starts with the <li> tag.The attribute TYPE : allows
marking list items with different types. By default the list Item markers are set to numbers
1,2,3… so on.

5.2.3.2 Unordered List <UL>


Unordered List also called as bulleted list, used to present list of items marked with
bullets. An unordered list starts with in <UL> followed by <LI> (List Item) tag. Use of <UL>
is very similar to <OL> (ordered list).

5.2.3.3 Definition List


A definition list is not a list of items. This is a list of terms and explanation of the
terms. A definition list starts with the <dl> tag. Each definition-list term starts with the <dt>
tag. Each definition-list definition starts with the <dd> tag.

5.2.4 Using Graphics in Web page <IMG>


Images can be placed in a web page by using <IMG> tag. There are many image
formats available today, but the most widely used among them are gif and jpeg. The gif
format is considered superior to the jpeg format for its clarity and ability to maintain the
originality of an image without lowering its quality.

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.

Attributes used with <IMG This attribute > are: -


ALIGN- used to set the alignment of the text adjacent to the image.

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

HEIGHT AND WIDTH- Controls the Height and Width of an 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

BORDER-Border around the image can be controlled by using BORDER attribute of


<IMG> tag. By default image displays with a thin border.

Anchor Tag: <A> (WORKING WITH LINKS)


Web pages are linked to one another through Hypertext Links. Section of text or
image in the HTML document can be linked to an external document or to a specific place
within the same document. The text or image that provides such linkage is known as
Hypertext.HTML provides <A> Anchor Tag to create links. The format of using anchor tag is
as follows:
<A HREF ="URL"> Make Me The Link </A>

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:

• Arranging information in a table

• Creating a page layout with the use of hidden tables.

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.

Eg: <table border="1">


<tr> <td>row 1, cell 1</td>
MODULE 5 MCA-404 Java and Web Programming ADMN 2009-‘10

<td>row 1, cell 2</td> </tr>


<tr> <td>row 2, cell 1</td>
<td>row 2, cell 2</td>
</tr>
</table>

Above code will create a table with 2 rows and 2 columns

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

image inserted behind the


background=filename table

bgcolor=#rrggbb background color


border=n border thickness
bordercolor=#rrggbb border color
bordercolordark=#rrggbb border shadow
distance between cell and
cellpadding=n content

cellspacing=n space between cells


protects agains linebreaks,
even though the content might
nowrap be wider than the browser
window.

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

• NAME= "..." Name of the form


• ACTION="..." - The address of the script to process this form input.
• METHOD=" " - The method used to send the data from the form to the server. The
options are POST and GET. Normally POST is used.

5.2.6.1 The Input Element

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 =“” specifies type of form element


name =““ specifies name of the control that identifies it.
value =““ default value of control
align =““ align controls w.r.t to form margins
MODULE 5 MCA-404 Java and Web Programming ADMN 2009-‘10

size =““ suggested number of characters for text input


maxlength =“”> maximum number of characters for text input)

The most used input types are described below.

5.2.6.2 Text Fields

<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>

5.2.6.3 Radio Buttons

<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>

5.2.6.5 Submit Button

<input type="submit" /> defines a submit button.

A submit button is used to send form data to a server. The data is sent to the page specified in
the form's action attribute. The file defined in the action attribute usually does something with
the received input.

Page 196
MODULE 5 MCA-404 Java and Web Programming ADMN 2009-‘10

Eg: <form name="input" action="html_form_submit.jsp" method="get">


Username:<input type="text" name="user"/>
<input type="submit" value="Submit" />
</form>

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.

5.2.7.1 The Frameset Tag

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.

5.2.7.2 Vertical & Horizontal Frameset

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.

5.3 JAVA SCRIPT

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.

5.3.1 Uses of 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

5.3.2 JavaScript Syntax:


The HTML <script> tag is used to insert a JavaScript into an HTML page. Scripts
can be in the either <head> section or <body> section. The <script> tag alert the browser
program to begin interpreting all the text between these tags as a script.

<script ...>
JavaScript code
</script>

The script tag takes two important attributes:

• 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".

So your JavaScript segment will look like:

<script language="javascript" type="text/javascript">


JavaScript code
</script>

Eg: <SCRIPT language ="JavaScript"type="text/javascript">


alert("Welcome to the script tag test page.")
</SCRIPT>

5.3.3 JavaScript Data Types

JavaScript allows you to work with three primitive data types:

• Numbers eg. 123, 120.50 etc.


• Strings of text e.g. "This text string" etc.
• Boolean e.g. true or false.

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

5.3.4 JavaScript Variables

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

5.3.4.1 Variable Names

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

5.3.4.2 Lifetime of Variables

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

Java script supports operators that belongs to the following categories:

arithmetic
bitwise
relational
logical
Page 200
MODULE 5 MCA-404 Java and Web Programming ADMN 2009-‘10

5.3.5.1 Arithmetic Operators


Arithmetic operators are used in mathematical expressions in the same way that they
are used in algebra. The operands of the arithmetic operators must be of a numeric type. The
following table lists the arithmetic operators:

Operator Description

+ Adds two operands


Subtracts second operand from
- the first

* Multiply both operands


Divide numerator by
/ denominator
remainder after an integer
% division
Increment operator, increases
integer value by one
++ Decrement operator, decreases
integer value by one
--

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

5.3.5.3 The Logical Operators

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

Called Bitwise AND operator. It performs a Boolean AND


& operation on each bit of its integer arguments.
Called Bitwise OR Operator. It performs a Boolean OR operation
| on each bit of its integer arguments.
Called Bitwise XOR Operator. It performs a Boolean exclusive
OR operation on each bit of its integer arguments. Exclusive OR
means that either operand one is true or operand two is true, but
^ not both.
Called Bitwise NOT Operator. It is a is a unary operator and
operates by reversing all bits in the operand.
Called Bitwise Shift Left Operator. It moves all bits in its first
~ operand to the left by the number of places specified in the
second operand. New bits are filled with zeros. Shifting a value
left by one position is equivalent to multiplying by 2, shifting two
positions is equivalent to multiplying by 4, etc.
Called Bitwise Shift Right with Sign Operator. It moves all bits in
<< its first operand to the right by the number of places specified
inthe second operand. The bits filled in on the left depend on the
sign bit of the original operand, in order to preserve the sign of
the result. If the first operand is positive, the result has zeros
placed in the high bits; if the first operand is negative, the result
has ones placed in the high bits. Shifting a value right one place is
equivalent to dividing by 2 (discarding the remainder), shifting
right two places is equivalent to integer division by 4, and so on.

>>

Table: 5.5 Page 202


MODULE 5 MCA-404 Java and Web Programming ADMN 2009-‘10

5.3.6 Control Structures


Java Script supports the following control structures:

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
}

5.3.6.2 if...else statement:

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
}

5.3.6.3 else if... statement:

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

Statement(s) to be executed if no expression is true


}

5.3.6.4 switch statement:

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)
}

5.3.6.5 The while Loop


The most basic loop in JavaScript is the while loop

while (expression)
{
Statement(s) to be executed if expression is true
}

5.3.6.6 The do...while Loop:


The do...while loop is similar to the while loop except that the condition check
happens at the end of the loop. This means that the loop will always be executed at least once,
even if the condition is false

do
{
Statement(s) to be executed;

} while (expression);
Page 204
MODULE 5 MCA-404 Java and Web Programming ADMN 2009-‘10

5.3.6.7 The for Loop


The for loop is the most compact form of looping and includes the following three
important parts:
The loop initialization is where we initialize our counter to a starting value. The
initialization statement is executed before the loop begins. The test statement which will test if
the given condition is true or not. If condition is true then code given inside the loop will be
executed otherwise loop will come out. The iteration statement where you can increase or
decrease your counter. You can put all the three parts in a single line separated by a
semicolon.

for (initialization; test condition; iteration statement)


{
Statement(s) to be executed if test condition is true
}

The Arrays Object

The Array object is used to store a set of values in a single variable name. The syntax is:
var v_name=new Array();

Eg: var mycars=new Array();


mycars[0]=“Xy”;
mycars[1]=“YY”;
mycars[2]=“ZZ”;
OR
var mycars=new Array(" Xy” , “YY” ,“ZZ");

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()

Removes the last element from an array and returns


pop() that element
Adds one or more elements to the end of an array
push() and returns the new length of the array.
Reverses the order of the elements of an array -- the
first becomes the last, and the last becomes the first.
reverse() Sorts the elements of an array.

sort()

Table: 5.6 Page 205


MODULE 5 MCA-404 Java and Web Programming ADMN 2009-‘10

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

5.3.7.1 Math Object


The math object provides you properties and methods for mathematical constants
and functions. Unlike the other global objects, Math is not a constructor. All properties and
methods of Math are static and can be called by using Math as an object without creating it.

Eg: var pi_val = Math.PI;


var sine_val = Math.sin(30);

Important Methods are:

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

5.3.7.2 Date Object


The Date object is a data type built into the JavaScript language. Date objects are
created with the new Date( ). Once a Date object is created, a number of methods allow you
to operate on it. Most methods simply allow you to get and set the year, month, day, hour,
minute, second, and millisecond fields of the object, using either local time or GMT.
The Syntax is:

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

Date() Returns today's date and time

getDate() Returns the day of the month for


the specified date according to
Returns the day of the week for
getDay() the specified date according to
local time.
Returns the year of the specified
date according to local time.
getFullYear() Returns the hour in the specified
date according to local time.
getHours() Returns the numeric value of the
specified date as the number of
milliseconds since January 1,
getTime() 1970, 00:00:00 UTC.

Table: 5.8

5.3.7.3 The String Object


The String object provides methods and properties for string manipulation and
formatting.

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

5.3.7.4 Document Object

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.

• write(expr1[,expr2...exprN]) - Add data to a document. Writes the values passed to


the write function to the document.

Eg: <html>
<body>
<script type="text/javascript">
document.write("Hello World!")
</script>
</body>
</html>

It is possible to including some formatting in "document.write" statement


Eg: document.write("<H3>") document.writeln("This is a Header")
document.write("</H3>")

• 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.

Syntax: document.bgColor = "colorinfo"

URL- This property is used to retrieve the document's full URL


Syntax: document.URL

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

5.3.7.4 Window Object

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

Window Object Methods

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:

• Arithmetic: evaluates to a number


• String: evaluates to a character string, for example "Fred" or "234"
• Logical: evaluates to true or false

5.3.8 JavaScript Functions

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);

5.3.9 JavaScript Events

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

<INPUT TYPE="text" VALUE="Enter email address" NAME="userEmail"


onChange=validateInput(this.value)>

<script type="text/javascript" language="JavaScript">

this.myForm.userEmail.focus();
this.myForm.userEmail.select();
function validateInput()
{

userInput = new String();


userInput = this.myForm.userEmail.value;
Page 210
MODULE 5 MCA-404 Java and Web Programming ADMN 2009-‘10

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>

<input type=button Value="Don't Press Me"

onClick="alert('now you are in trouble!')“ >

</form>

This will display an alert window when the button is clicked.

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.

<form method="post" action="xxx.html"


onsubmit="return checkForm()">

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

5.3.9 Form Field Validation

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 name="contact_form" method="post"


action=" form_2.jsp"
<h1>Please Enter Your Name</h1>

<p>Your Name: <input type="text" name="contact_name"></p>


<p><input type="submit" name="send" value="Send Details"></p>

</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:

The validate_form() function


The form validation function, validate_form(), is embedded in the head element near the
top of the page:

<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

alert ( "Please fill in the 'Your Name' box." );


valid = false;
}

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).

A servlet runs in a Java virtual machine managed by a servlet engine. It is invoked to


handle a request from a Web client. Each new request uses the same copy of the servlet in
memory while running in its own thread of execution for optimal performance.

Servlets may be used at different levels on a distributed framework. The following are some
examples of servlet usage:

• To accept form input and generate HTML Web pages dynamically.


• As part of middle tiers in enterprise networks by connecting to SQL databases via
JDBC.

• In conjunction with applets to provide a high degree of interactivity and dynamic Web
content generation.

• For collaborative applications such as online conferencing.


• A community of servlets could act as active agents which share data with each other.
• Servlets could be used for balancing load among servers which mirror the same
content.

5.4.1 Common Gateway Interface

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

5.4.1.1 Servlets vs. CGI scripts

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

Servlets have an extensive infrastructure for automatically parsing and decoding


HTML form data, reading and setting HTTP headers, handling cookies, tracking sessions, and
many other such high-level utilities.

Powerful

Servlets support several capabilities that are difficult or impossible to accomplish


with regular CGI. Servlets can talk directly to the Web server, whereas regular CGI programs
cannot, at least not without using a server-specific API. Communicating with the Web server
makes it easier to translate relative URLs into concrete path names, for instance. Multiple
servlets can also share data, making it easy to implement database connection pooling and

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.

5.4.2 Servlet Container

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

5.4.3 Servlet Architecture


A servlet is any class that either implement the Servlet interface or extend a class that
implements the Servlet interface. Most user-written servlet classes are extensions to
HttpServlet (which is an extension of GenericServlet, which implements the Servlet
Interface).Servlets, like applets, usually lack a main method, but must implement or override
certa in other methods.

( 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.

5.4.4 Servlet Life cycle


Three methods are central to the life cycle of a servlet. These are init( ), service( ),
and destroy( ). They are implemented by every servlet and are invoked at specific times by the
server

(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.

5.4.5 The Servlet API

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

5.4.5.1 The javax.servlet Package

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

Servlet Declares life cycle methods for a servlet.

ServletConfig Allows servlets to get initialization parameters.

ServletContext Enables servlets to log events and access information

about their environment.

ServletRequest Used to read data from a client request.

ServletResponse Used to write data to a client response.

SingleThreadModel Indicates that the servlet is thread safe

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

5.4.5.2 The javax.servlet.http Package

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

HttpServletRequest Enables servlets to read data from an HTTP request.

HttpServletResponse Enables servlets to write data to an HTTP response.

HttpSession Allows session data to be read and written.

HttpSessionBindingListener Informs an object that it is bound to or unbound

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.

5.4.5.3 HttpServlet class

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

void doGet(HttpServletRequest req,


HttpServletResponse res) Performs an HTTP GET.
throws IOException, ServletException

void doPost(HttpServletRequest req,


HttpServletResponse res) Performs an HTTP POST.
throws IOException, ServletException

Called by the server when an HTTP


void service(HttpServletRequestreq, request arrives for this servlet. The
HttpServletResponse res) arguments provide access to the HTTP
throws IOException, ServletException request and
response, respectively.
Returns the time (in milliseconds since
midnight, January 1, 1970, GMT)
when
the requested resource was last
long getLastModified(HttpServletRequest modified.
req)

Table: 5.10
Page 220
MODULE 5 MCA-404 Java and Web Programming ADMN 2009-‘10

5.4.5.4 HttpServletRequest Interface

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

String[] getParameterValues( String name ) -Returns a String array containing the


values for a specified servlet parameter.

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.

5.4.5.5 HttpServletResponse Interface

This interface allows a servlet's service method to manipulate HTTP-protocol


specified header information and return data to its client. It is implemented by network service
developers for use within servlets.

Methods

void addCookie( Cookie cookie ) - Used to add a Cookie to the header of the response to
the client

ServletOutputStream getOutputStream() – Obtains a byte-based output stream


enabling binary data to be sent to the client

PrintWriter getWriter() -Obtains a character-based output stream enabling text data to


be sent 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

void sendRedirect()-Redirect an HTTP request to another URL

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.

5.5.1 The Cookie Class

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 name of the cookie

■ The value of the cookie

■ The expiration date of the cookie

■ The domain and path of the cookie

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.

The methods of the Cookie class are summarized in Table

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)

void setValue(String v) Sets the value to v.


Sets the cookie protocol version to v, which
will be 0 or 1.
void setVersion(int v)

Returns the maximum specified age of the


cookie. If none was specified, a negative
int getMaxAge() value is returned, indicating the default
behaviour described with setMaxAge
Returns the name of the cookie.
String getName() Returns the value of the cookie.
String getValue()

Table: 5.11
Page 224
MODULE 5 MCA-404 Java and Web Programming ADMN 2009-‘10

5.6 Session Tracking

HTTP is a stateless protocol. Each request is independent of the previous one.


However, in some applications, it is necessary to save state information so that information
can be collected from several interactions between a browser and a server. Sessions provide
such a mechanism.A session is the time span during which a browser interacts with a
particular server .A session ends when the browser is terminated or the server terminates it
because of inactivity

A session can be created via the getSession( ) method of HttpServletRequest. An


HttpSession object is returned. This object can store a set of bindings that associate names
with objects. 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.

5.6.1 HttpSession Interface

The HttpSession interface is implemented by services to provide an association


between an HTTP client and HTTP server. This association, or session, persists over multiple
connections and/or requests during a given time period. Sessions are used to maintain state
and user identity across multiple page requests. A session can be maintained either by using
cookies or by URL rewriting.

HttpSession defines methods which store standard session properties, such as an


identifier for the session, and the context for the sessionSeveral of its methods are summarized
in the table below. All of these methods throw an IllegalStateException if the session has
already been invalidated.

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

not yet been accessed by the client.


void removeAttribute(String attr) Removes the attribute specified by attr from the
session
Associates the value passed in val with the attribute
void setAttribute(String attr, name passed in attr.
Object val)

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.

JSP pages have the following advantages:

• 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

• They are automatically recompiled when necessary.


• Because they exist in the ordinary Web server document space, addressing JSP pages
is simpler than addressing servlets.

• Because JSP pages are HTML-like, they have greater compatibility with Web
development tools

A JSP page exists in three forms:

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.

5.7.1 Components of a JSP Page


A .jsp file can contain JSP elements, fixed template data(HTML), or any
combination of the two.JSP elements are instructions to the JSP container about what code to
generate and how it should operate. These elements have specific start and end tags that
identify them to the JSP compiler. Template data is everything else that is not recognized by
the JSP container. Template data (usually HTML) is passed through unmodified, so the
HTML that is ultimately generated contains the template data exactly as it was coded in the
.jsp file.

Three types of JSP elements exist. They are:

• 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:

<%@ directive-name [attribute="value" attribute="value" ...] %>

There are three standard directives available in all compliant JSP environments:
• page
• include
• taglib

The page Directive


The page directive apply different properties for the page like language support, page
information and import etc. by using the different attributes of the directives It has the
following syntax:
<%@ page [attribute="value" attribute="value" ...] %>
Following are names of some of important the attributes of the page directive used in JSP
• import: : This attribute imports the java packages and it's classes .We can import
more than one java packages and classes by separating with comma (,)
Eg: <%@ page import="java.util.*" %>

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" %>

• isThreadSafe="true|false":‘true’ indicated that multiple requests can be processed


simultaneously with a single servlet instance .‘false’ indicates that only one request
can be processed at a time.
Eg: <%@page isThreadSafe=”false”/>

The include Directive

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

<%@ include file="filename" %>

where filename is an absolute or relative pathname interpreted according to the current


servlet context.

Eg: <%@ include file="/doc/legal/disclaimer.html" %>

The taglib Directive

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

<%- - This is a hidden JSP comment - -%>

and the latter looks like this:

<!- - This is included in the generated HTML - ->

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

<%= expression %>

where exp is any valid Java expression. The expression can have any data value, as long as it
can be converted to a string.

Eg:<%= new java.util.Date() %>

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 %>

Eg: <% System.out.println( "Evaluating date now);


java.util.Date date = new java.util.Date(); %>

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

<%!//start of declaration tag


statement1;
statement2; //variables or methods declaration
..........;
..........;
%>//end of declaration tag

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 ;
%>

5.7.2 Standard Actions


Standard actions are specific tags that affect the runtime behavior of the JSP and
affect the response sent back to the client. The JSP specification lists some standard action
types to be provided by all containers, irrespective of the implementation. Standard actions
provide page authors with some basic functionality to exploit; the vendor is free to provide
other actions to enhance .The Syntax is:

<tagname [attr="value" attr="value" ...] > ... </tag-name>


or, if the action has no body, an abbreviated form:

<tagname [attr="value" attr="value" ...] />

Following are some of the important actions available in jsp


• <jsp:include>:Invokes another resource and merges its output stream with the JSP page
output stream.
Syntax is:
<jsp:include page="URL" flush="true" />

or, if parameters need to be passed:

<jsp:include page="URL" flush="true">


<jsp:param … />
<jsp:param … />
...
<jsp:param ... />
</jsp:include>

• <jsp:forward>: Forwards this HTTP request to another JSP page or servlet for processing
Syntax is:

<jsp:forward page="URL" />


or, if parameters need to be passed:
Page 230
MODULE 5 MCA-404 Java and Web Programming ADMN 2009-‘10

<jsp:forward page="URL">
<jsp:param ... />
<jsp:param ... />
...
<jsp:param ... />
</jsp:forward>

Sample JSP Code

<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.

Eg: <%! int age=29;%>


your age is:<%=age%>

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>

5.7.3 Implicit Objects


JSP container provides a list of instantiated objects for you to access different kind of
data in a web application. These objects are called implicit objects because they are
automatically instantiated. These objects are implicitly available inside scriptlets and
expressions (but not declarations).
e.g. request, response, session etc

5.7.3.1 Request object


The request object. contains a reference to the HttpServletRequest object.This object
encapsulates the details of the HTTP request generated by the Web browser or other
Client - its parameters, attributes, headers, and data.

Following are some useful methods of the request Object:

String getParameter(String name): Given the name of a single-valued form parameter,


returns its value.

Enumeration getParameterNames() : Returns an enumeration of the names of all form


parameters passed to this request.

HttpSession getSession(boolean create) : Returns the current HttpSession object. If one


does not exist, either creates a new one or returns null, depending on the create flag.

5.7.3.2 Response object


This object encapsulates the output returned to the HTTP client, providing the page
auth or with a means for setting response headers and the status code. It also has methods for
accessing the response output stream, but the JSP specification prohibits directly accessing
this stream.

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.

5.7.3.3 Session object


HTTP is a stateless protocol, which means it doesn’t remember from one request to
the next anything about previous requests. In any web application user moves from one page
to another and it becomes necessary to track the user data and objects throughout the
application. JSP provide an implicit object "session", which can be use to save the data
specific to a particular user. It persists between HTTP requests and can store named objects of
any kind. By default, the JSP container creates an HttpSession object or accesses the currently
active one. If you do not need to retain objects between requests, you can turn off automatic
session creation by specifying session="false" in the page directive.

Object getAttribute(String name) : Returns the object with the specified name, if it
exists in the session

Enumeration getAttributeNames() : Returns an enumeration of the names of all the


objects stored 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 path name that further restricts the URL subset.

• 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

A cookie can be created and read by using methods of Cookie class.

Eg: :<html>
<head>
<title>JSP PROGRAMMING</head>
<body>
<%! String MyCookieName=‘userID’;
String MyCookieValue=‘ JK1234’
response.addCookie(new Cookie(,MyCookieName, MyCookieValue); %>
</body>
</html>

5.7.5 Error Handling


An exception is an event that occurs during the execution of a program and it
disrupts the normal working of the instructions in the program. JSP offers a simple and
convenient solution for handling exceptions that requires the coordinated use of two
attributes: errorPage and isErrorPage.

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:

<%@ page isErrorPage="true" %>.

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 isErrorPage="true" session="false"%>


<H3>Application Error</H3>
The error message is:
<B><%= exception.getMessage() %></B>

Page 234

Potrebbero piacerti anche