You are on page 1of 183

1:JDBC objects

The Concept Of JDBC

1. There are many DBMSs commercially available in the market.


These include Oracle, DB2, Sybase etc..

2. The challenge Sun Microsystems faced in the late 1990s was to develop a way for Java
developers to write high-level code that accesses all popular DBMSs.

3. Language barrier was one of the major obstacle for Sun. Each DBMS defined its own low-level
way to interact with programs to access data stored in its databases.

4. A low-level code written to communicate with an Oracle database might need to be rewritten to
access a DB2 database.

In 1996 Sun developed a JDBC driver, and it wasnt a driver at all

1. This encouraged third-party vendors & other DBMS manufacturers to build JDBC drivers that
suited Suns specifications.

2. The specifications required a JDBC driver to be a translator that converted low-level proprietary
DBMS messages to low-level messages understood by the JDBC API and vice versa.

3. This meant Java programmers could use high-level Java data objects defined in the JDBC API
to write a routine that interacted with the DBMS.

4. Java data objects convert the routine into low-level messages that conform to the JDBC driver
specification and send them to the JDBC driver.

5. The JDBC driver translates the routine into low-level messages that are understood and
processed by the DBMS.

JDBC drivers created by DBMS manufacturers have to

1. Open a connection b/n the DBMS and J2EE component.

2. Translate low-level equivalents of SQL statements sent by the j2EE component into
messages that can be processed by DBMS.

3. Return data that conforms to the JDBC specification to the JDBC driver.

4. Return info such as error messages that conforms to the JDBC specification to the JDBC
driver.

5. Provide transaction management routines that conform to the JDBC specification.

Close the connection b/n DBMS and the J2EE component

JDBC Driver Types

KNSIT Page 1
1. JDBC driver specification classifies JDBC drivers into four groups.
They are

Type 1 JDBC-to-ODBC Driver

1. Microsoft created ODBC (Open Database Connection), which is the basis from which Sun
created JDBC. Both have similar driver specifications and an API.

2. The JDBC-to-ODBC driver, also called the JDBC/ODBC Bridge, is used to translate DBMS
calls between the JDBC specification and the ODBC specification.

3. The JDBC-to-ODBC driver receives messages from a J2EE component that conforms to the
JDBC specification and are translated by the JDBC-to-ODBC driver into the ODBC message
format & later to the format understood by the DBMS.

Type 2 Java/Native Code Driver

1. The Java/Native Code driver uses Java classes to generate platform- specific code, that is code
only understood by a specific DBMS.

2. The disadvantage of using a Java/Native Code driver is the loss of some portability of code.

3. The API classes for the Java/Native Code driver probably wont work with another
manufacturers DBMS.

Type 3 JDBC Driver

1. Also referred to as the Java Protocol, most commonly used JDBC driver.

2. The Type 3 JDBC driver converts SQL queries into JDBC- formatted statements, in-turn they are
translated into the format required by the DBMS.

Type 4 JDBC Driver

1. Type 4 JDBC driver is also known as the Type 4 database protocol.

2. The driver is similar to Type 3 JDBC driver except SQL queries are translated into the format
required by the DBMS.

3. SQL queries do not need to be converted to JDBC-formatted systems.

4. This is the fastest way to communicated SQL queries to the DBMS.

JDBC Packages
1. The JDBC API is contained in two packages.

2. The first package is called java.sql and contains core Java data objects of the JDBC API. java.sql
is part of the J2SE

KNSIT Page 2
3. These include Java data objects that provide the basic for connecting to the DBMS and
interacting with data stored in the DBMS.

4. The second package is javax.sql, which extends java.sql and is in J2EE.

javax.sql includes the data objects that interact with Java Naming and Directory Interface
(JNDI) and Java data objects that manage connection pooling, among other advanced JDBC
features

A Brief Overview of the JDBC Process

1. Though each J2EE component is different, J2EE components use a similar process for interacting
with a DBMS.

2. This process is divided into five routines. These are.

1. Loading the JDBC driver

2. Connecting to the DBMS

3. Creating and executing a statement

4. Processing data returned by the DBMS

5. Terminating the connection with the DBMS

Loading the JDBC Driver

1. The JDBC driver must be loaded before the J2EE component can connect to the DBMS.

2. The developer must write a routine that loads the JDBC/ODBC Bridge driver called
sun.jdbc.odbc.JdbcOdbcDriver to work offline and interact with the Microsoft Access on his PC.

3. The driver is loaded by calling the Class.forName() method and passing it the name of the
driver.

Class.forName( sun.jdbc.odbc.JdbcOdbcDriver);

Connect to the DBMS

1. Once the driver is loaded, the J2EE component must connect to the DBMS using the
DriverManager.getConnection() method.

The java.sql.DriverManager class is the highest class in the java.sql hierarchy and is responsible for
managing driver information

KNSIT Page 3
String url =
"jdbc:odbc:CustomerInformation";
String userID = "jim";
String password = "keogh";
Statement DataRequest;
private Connection Db;
try
{
Class.forName("sun.jdbc.odbc.JdbcOdbcD
river");
Db =
DriverManager.getConnection(url,userID,pass
word);
}
1. The DriverManager.getConnection() method is passed with the URL of the database, the user ID
and the password if required by DBMS.

2. The URL is a string object that contains the driver name and the name of the database that is
being accessed by the J2EE component.

3. The DriverManager.getConnection() method returns a Connection interface that is used


throughout the process to reference the database.

4. The java.sql.Connection is another interface manages communication between the driver and
the J2EE component.

5. The java.sql.Connection interface sends statements to the DBMS for processing.

Create and Execute a SQL Statement

KNSIT Page 4
1. Next is we have to send a SQL query to the DBMS for processing.

2. A SQL query consists of a series of SQL commands that direct the DBMS to do something such
as to return a rows of data to the J2EE component.

3. Connection.createStatement() method is used to create a Statement object.

4. The Statement object is then used to execute a query and return a ResultSet object that contains
the response from the DBMS, which is usually one or more rows of information requested by
J2EE component.

5. Once the ResultSet is received from the DBMS, the close() method is called to terminate the
statement.

Statement DataRequest;
ResultSet Results
try
{
String query = " SELECT * FROM
Customers";
DataRequest = Db.createStatement();
Results =
DataRequest.executeQuery(query);
DataRequest.close();
}
Process Data Returned by the DBMS

1. The java.sql.ResultSet object is assigned the result received from the DBMS after the query is
processed.

The java.sql.ResultSet object consists of methods used to interact with data that is returned by the
DBMS to the J2EE component

KNSIT Page 5
ResultSet Results;
String FirstName, LastName, printrow;
boolean Records = Results.next();
if(!Records)
{
System.out.println("No data returned.");
return;
}
else
{
while(Results.next())
{
FirstName = Results.getString(FirstName);
LastName = Results.getString(LastName);
printrow = FirstName + " " + LastName;
System.out.println(printrow);
}
}
Terminate The Connection to the DBMS

1. The connection to the DBMS is terminated by using the close()method of the Connection object
once the J2EE component is finished accessing the DBMS.

KNSIT Page 6
2. The close() method throws an exception if a problem is encountered when disengaging the
DBMS.

Db.close();

Example Program : Connecting to MS-Acces


import java.sql.*;
import java.io.*;
public class DC
{
public static void main (String args[])
{
String url ="jdbc:odbc:access";
String user = " ";
String password = " ";
try
{
// load the driver
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"
// create connection.
Connection c = DriverManager.getConnection(u

KNSIT Page 7
// create statement
Statement s = c.createStatement( );
// execute statement and return resultset &
stored in object
ResultSet r = s.executeQuery("SELECT ename,
eid, addr FROM emp") ;
// iterate the result set
while(r.next())
{
System. out.println (r.getString ("ename")
+"," + r.getString ("eid") +" : "+
r.getString("addr")) ;
}
s.close( ) ;
}catch(Exception e)
{
System.out.println("Could not establish
connection") ;
}
}
}

KNSIT Page 8
Example Program : Connecting to MySql
import java.sql.*;
import java.io.*;
public class DCMysql
{
public static void main (String args[])
{
String url ="jdbc:mysql://localhost:3306/sample";
String user = "root";
String password = "hemanth";
try
{
// load the driver
Class.forName("com.mysql.jdbc.Driver") ;
// create connection.
Connection c = DriverManager.getConnection(url,user,pa

KNSIT Page 9
// create statement
Statement s = c.createStatement( );
// execute statement and return resultset &
stored in object
ResultSet r = s.executeQuery("SELECT
ename, eid, addr FROM emp") ;
// iterate the result set
while(r.next())
{
System. out.println (r.getString ("ename")
+"," + r.getString ("eid") +" : "+
r.getString("addr")) ;
}
s.close( ) ;
}catch(Exception e)
{
System.out.println("Could not establish
connection") ;
}
}
}
Database Connection

1. A J2EE component does not directly connect to DBMS. Instead, the J2EE component connects
with the JDBC driver that is associated with the DBMS.

2. Before the connection is made, the JDBC driver must be loaded and registered with the
DriverManager.

KNSIT Page 10
3. The purpose of loading and registering the JDBC driver is to bring the JDBC driver into the
Java Virtual Machine (JVM).

try
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
}catch (ClassNotFoundException e)
{
System.out.println("Unable to load the JDBC/ODBC
bridge."+e.getMessage());
System.eixt(1);
}
The Connection

1. After the JDBC driver is loaded & registered, the J2EE component must connect to the database.

2. The data source that the JDBC component will connect to is defined using the URL format. The
URL consists of three pats.

1. jdbc which indicates that JDBC protocol is to be used to read the URL.

2. <subprotocol> which is the JDBC driver name.

3. <subname> which is the name of the database.

3. The connection to the database is established by getConnection(), which requests access to the
database from the DBMS.

4. A Connection object is returned by the getConnection() if access is granted; else


getConnection() throws a SQLException.

1. If username & password is required then those information need to be supplied to access the
database.

Connection c = DriverManager.getConnection(url,userID,password) ;

1. Sometimes a DBMS requires extra information besides userID & password to grant access to the
database.

KNSIT Page 11
2. This additional information is referred as properties and must be associated with Properties ob
Sometimes DBMS grants access to a database to anyone without using username or password.

Connection c = DriverManager.getConnection(url) ;

1. ject, which is passed to the DBMS as a getConnection() parameter.

Properties used to access a database are stored in a text file, contents of which are defined by the DBMS
manufacturer

The J2EE component uses a FileInputStream object to open the file and then uses the Properties object
load() method to copy the properties into a Properties object.

KNSIT Page 12
Connection Db;
Properties props = new Properties();
try
{
FileInputStream propFS = new
FileInputStream("DBProps.txt");
props.load(propFS);
}
catch (Exception e){}
try
{
Class.forName("sun.jdbc.odbc.JdbcOdbcD
river");
Db=DriverManager.getConnection(url,pro
ps);
}
catch (Exception e){}
TimeOut

1. The DBMS may not respond quickly for a number of reasons,which might include that database
connections are not available.

2. Rather than waiting for a delayed response from the DBMS, the J2EE component can set a
timeout period after which the DriverManager will cease to attempt to connect to the database.

KNSIT Page 13
3. The public static void DriverManager.setLoginTimeout(int seconds) method can be used by the
J2EE component to establish the maximum time the DriverManager waits for a response from a
DBMS before timing out.

4. The public static int DriverManager.getLoginTimeout() is used to retrieve from the


DriverManager the max time the DriverManager is set to wait until it times out.

5. This method returns an int that represents seconds.

Associating the JDBC/ODBC Bridge with the Database

1. We use the ODBC Data Source Administrator to create the association between the database and
the JDBC/ODBC bridge.

1. Select Start-> settings and then control panel

2. Select ODBC 32 to display the ODBC Data Source Administrator

3. Add a new user by selecting the Add button.

4. Select the driver then select Finish. Use the Microsoft Access Driver if we are using Microsoft
Access; otherwise, select the driver for the DBMS that we are using. If we dont find the driver of
our DBMS on the list, we need to install the driver.

5. Enter the name of the database as the Data Source name in the ODBC Microsoft Access Setup
dialog box. This name will be used within the java database program to connect to the DBMS.

6. Enter a description for the data source. This is optional, but will be a reminder of the kind of data
that is stored in database.

7. . Click the Select button. We will be prompted to browse the directory of each hard drive
connected to our computer in order to define the direct path to the database. Click OK once we
locate the database. Then directory path and the name of the database will be displayed in the
ODBC Microsoft Access Setup dialog box.

8. Since this is our database, we can determine if a login name and password is required to access
the database.

9. If so, then click the Advanced button to display the Set Advanced Options dialog box.

10. When the ODBC Microsoft Access Setup dialog box appears, select Ok.

11. Select Ok to close the ODBC Data Source Administrator dialog box.

12. Statement Objects

Once a connection to the database is opened, the J2EE component creates and sends a query to
access data contained in the database.

One of the three types of Statement objects is used to execute thequery.

KNSIT Page 14
These objects are Statement, which executes a query immediately.

PreparedStatement, which is used to execute a compiled query. CallableStatement, which is used


to execute store procedures

The Statement Object

1. The Statement object is used whenever J2EE component needs to immediately execute a query
without first having the query compiled.

2. The Statement object contains the executeQuery() method, which passes the query as an
argument. The query is then transmitted to the DBMS for processing.

3. The executeQuery() method returns one ResultSet object that contains rows, columns, and
metadata that represents data requested by query.

4. The execute() method is used when there may be multiple results returned.

The executedUpdate() method returns an integer indicating the number of rows that were updated by
the query.

KNSIT Page 15
String url = "jdbc:odbc:CustomerInformation";
String userID = "jim";
String password = "keogh";
Statement DataRequest;
ResultSet Results;
Connection Db;
try
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Db =
DriverManager.getConnection(url,userID,password);
}catch(Exception e){}
Try
{
String query = SELECT * FROM Customers;
DataRequest = Db.createStatement();
Results = DataRequest.executeQuery(query);
// place code here to interact with the Resutls.
DataRequest.close();
}

KNSIT Page 16
Next is how to use the executeUpdate() of the State
String url = "jdbc:odbc:CustomerInformation";
String userID = "jim";
String password = "keogh";
Statement DataRequest;
int rowsUpdated;
Connection Db;
try
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Db = DriverManager.getConnection(url,userID,password);
}catch(Exception e){}
Try
{
String query = UPDATE Customers SET PAID=Y WHERE
BALANCE=0 ;
DataRequest = Db.createStatement();
rowsUpdated = DataRequest.executeUpdate(query);
DataRequest.close();
}
Db.close();
PreparedStatement Object

1. A SQL query can be precompiled and executed by using the PreparedStatement object.

2. Here a query is created as usual, but a question mark is used as a placeholder for a value that is
inserted into the query after the query is compiled.

KNSIT Page 17
3. The preparedStatement() method of Connection object is called to return the PreparedStatement
object. The preparedStatement() method is passed the query, which is then precompiled.

String url = "jdbc:odbc:CustomerInformation";


String userID = "jim";
String password = "keogh";
Statement DataRequest;
ResultSet Results;
Connection Db;
try
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Db =
DriverManager.getConnection(url,userID,password);
}catch(Exception e){}
Try
{
String query = SELECT * FROM Customers
WHERE CustNo = ? ;
PreparedStatement pstatement =
Db.preparedStatement(query);
pstatement.setString(1,123);
Results = pstatement.executeQuery();
// place code here to interact with the ResutlSet.
pstatement.close();
}
CallableStatement

KNSIT Page 18
1. The CallableStatement object is used to call a stored procedure from within a J2EE object.

2. A Stored procedure is a block of code and is identified by a unique name.

3. The type and style of code depends on the DBMS vendor and can be written in PL/SQL,
Transact-SQL, C, or other programming languages.

4. IN, OUT and INOUT are the three parameters used by the CallableStatement object to call a
stored procedure.

5. The IN parameter contains any data that needs to be passed to the stored procedure and whose
value is assigned using the setxxx() method.

6. The OUT parameter contains the value returned by the stored procedures. The OUT parameters
must be registered using the registerOutParameter() method, later retrieved by using the getxxx()

7. The INOUT parameter is a single parameter that is used to pass information to the stored
procedure and retrieve information from the stored procedure.

Connection Db;
try
{
String query = "{CALL LastOrderNumber (?))}";
CallableStatement cstatement = Db.prepareCall(que
cstatement.registerOutParameter(1,Types.VARCHA
cstatement.eqecute();
String lastOrderNumber = cstatement.getString(1);
cstatement.close();
}
catch (Exception e){}
ResultSet

KNSIT Page 19
1. The ResultSet object contains methods that are used to copy data from the ResultSet into a Java
collection object or variable for further processsing.

2. Data in a ResultSet is logically organized into a virtual table consisting of rows and columns.

3. The ResultSet uses a virtual cursor to point to a row of the virtual table.

4. The virtual cursor is positioned above the first row of data when the ResultSet is returned by the
executeQuery(). This means the virtual cursor must be moved to the frist row using the next()
method.

5. The next() returns a boolean true if the row contains data; else false.

6. Once the virtual cursor points to a row, the getxxx() is used to copy data from the row to a
collection, object or a variable.

KNSIT Page 20
Reading The ResultSet
ResultSet Results;
String FirstName, LastName, printrow;
boolean Records = Results.next();
if(!Records)
{
System.out.println("No data returned.");
return;
}
else
{
while(Results.next())
{
FirstName = Results.getString(1);
LastName = Results.getString(2);
printrow = FirstName + " " + LastName;
System.out.println(printrow);
}
}
Scrollable Resultset

1. In JDBC 2.1 API the virtual cursor can be moved backwards or positioned at a specific row.

2. Six methods are there for Resultset object. They are first(), last(), previous(), absolute(),
relative() and getrow().

3. first() method moves the virtual cursor to the first row in the Resultset.

4. last() method positions the virtual cursor at the last row in the Resultset

KNSIT Page 21
5. previous() method moves the virtual cursor to the previous row.

6. absolute() method positions the virtual cursor to a specified row by the an integer value passed
to the method.

7. relative() method moves the virtual cursor the specified number of rows contained in the
parameter.

1. The parameter can be positive or negative integer.

2. The getRow() method returns an integer that represents the number of the current row in the
Resultset.

3. To handle the scrollable ResultSet , a constant value is passed to the Statement object that is
created using the createStatement(). Three constants.

- TYPE_FORWARD_ONLY

- TYPE_SCROLL_INSENSITIVE

- TYPE_SCROLL_SENSITIVE

1. TYPE_FORWARD_ONLY constant restricts the virtual cursor to downward movement(default


setting).

The other two allow the virtual cursor to move in both directions

Updatable ResultSet

1. Rows contained in the ResultSet can be updatable similar to how rows in a table can be updated.

2. This is possible by passing the createStatement() method of the Connection object the
CONCUR_UPDATABLE.

3. CONCUR_READ_ONLY constant can be passed to the createStatement() method to prevent


the ResultSet from being updated.

4. There are three ways in which a ResultSet can be changed.

5. These are updating values in a row, deleting a row, and inserting a new row.

All are accomplished by using the methods of the Statement object

Update ResultSet

1. Once the executeQuery() of the Statement object returns a ResultSet, the updatexxx() is used to
change the value of column in the current row of the ResultSet.

2. The xxx in the updatexxx() is replaced with the data type of the column that is to be updated.

KNSIT Page 22
3. The updatexxx() requires two parameters. The first is either the number or name of the column
of the ResultSet that is being updated and the second is the value that will replace the value in the
column of the ResultSet.

4. A value in a column of the ResultSet can be replaced with a NULL value by using the
updateNull(). It requires one parameter, which is the number of column in the current row of the
ResultSet. The updateNull() dont accept name of the column as a parameter.

5. The updateRow() is called after all the updatexxx() are called.

KNSIT Page 23
try
{
String query = "SELECT FirstName, LastName FROM C
WHERE FirstName='Mary' and LastName='Smith'";
DataRequest = Db.createStatement(ResultSet.CONCUR_
Resulsts = DataRequest.executeQuery(query);
}
catch (Exception e){}
boolean Records = Results.next();
if(!Records) from
{ LY
System.out.println("No data returned."); ltSet.
System.exit(4);
}
try
{
Results.updateString("Lastname", "Smith");
Results.updateRow();
DataRequest.close();
}
catch (){}

Delete Row in the ResultSet

1. The deleteRow() is used to remove a row from a ResultSet.

KNSIT Page 24
2. The deleteRow() is passed an integer that contains the number of the row to be deleted.

3. First use the absolute() method to move the virtual cursor to the row in the Resultset that should
be deleted.

4. The value of that row should be examined by the program to assure it is the proper row before
the deleteRow() is called.

5. The deleteRow() is then passed a zero integer indicating that the current row must be deleted.

Resuts.deleteRow(0);

Insert Row in the ResultSet

1. Inserting a row into the ResultSet is accomplished using basically the same technique as is used
to update the ResultSet.

2. The updatexxx() is used to specify the column and value that will place into the column of the
ResultSet.

3. The insertRow() is called after the updatexxx(), which causes a new row to be inserted into the
ResultSet.

KNSIT Page 25
try
{
String query = "SELECT FirstName, LastName FROM Custo
DataRequest = Db.createStatement(ResultSet.CONCUR_UPD
Resulsts = DataRequest.executeQuery(query);
}
catch (Exception e){}
boolean Records = Results.next();
if(!Records)
{
System.out.println("No data returned.");
System.exit(4);
}
try
{
Results.updateString(1, "Smith");
Results.updateString(2, Tom);
Results.insertRow();
DataRequest.close();
}
catch (){}

Transaction Processing

1. A transaction may involve several tasks.

2. A database transaction consists of a set of SQL statements, each of which must be successfully
completed for the transaction to be completed.

KNSIT Page 26
3. If any one fails, then the transaction must be rolled back.

4. The database transaction is not completed until the J2EE component calls the commit() method
of the Connection object.

5. The commit() method must be called regardless if the SQL statement is part of a transaction or
not.

6. The commit() method was automatically called in the previous examples because the DBMS
has an AutoCommit feature that is by default set to true.

7. If a J2EE component is processing a transaction, the AutoCommit feature must be deactivated by


calling the setAutoCommit() method and passing it a false parameter.

Once the transaction is completed, the setAutoCommit() method is called again by passing a true
parameter

String url = "jdbc:odbc:CustomerInformation";


String userID = "jim";
String password = "keogh";
Statement DataRequest1, DataRequest2;
Connection Db;
try
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Db =
DriverManager.getConnection(url,userID,password);
}catch(Exception e){}

KNSIT Page 27
try
{
Db.setAutoCommit(false);
String query1 = "UPDATE Customers SET Street =
'5 Main Street'"+ "WHERE FirstName='Bob'";
String query2 = "UPDATE Customers SET Street =
'10 Main Street'"+ "WHERE FirstName='Tim'";
DataRequest1=Db.createStatement();
DataRequest2=Db.createStatement();
DataRequest1.executeUpdate(quiery1);
DataRequest2.executeUpdate(quiery2);
Db.commit();
DataRequest1.close();
DataRequest2.close();
Db.close();
}
catch (SQLException ex){ }

1. The J2EE component can control the number of tasks that are rolled back by using savepoints.

2. There can be many savepoints used in a transactions. Each savepoint is identified by a unique
name.

The savepoint name is then passed to the rollback() method to specify the point within the transaction
where the rollback is to stop

KNSIT Page 28
String url = "jdbc:odbc:CustomerInformation";
String userID = "jim";
String password = "keogh";
Statement DataRequest1, DataRequest2;
Connection Db;
try
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Db =
DriverManager.getConnection(url,userID,password);
}catch(Exception e){}

KNSIT Page 29
try
{
Db.setAutoCommit(false);
String query1 = "UPDATE Customers SET Street =
'5 Main Street'"+ "WHERE FirstName='Bob'";
String query2 = "UPDATE Customers SET Street =
'10 Main Street'"+ "WHERE FirstName='Tim'";
DataRequest1=Db.createStatement();
Savepoint s1 = Db.setSavepoint("sp1");
DataRequest2=Db.createStatement();
DataRequest1.executeUpdate(quiery1);
DataRequest2.executeUpdate(quiery2);
Db.commit();
DataRequest1.close();
DataRequest2.close();
Db.releaseSavepoint("sp1");
Db.close();
}
catch (SQLException ex){ }

1. Another way to combine SQL statements into a transaction is to batch together these statements
into a single transaction and then execute the entire transaction.

2. This can be done using the addBatch() method of the Statement object.

3. The addBatch() method receives a SQL statement as a parameter and places the SQL statements
in the batch.

4. Once all the SQL statements ahat comprises the transaction are included in the batch, the
executeBatch() method is called to execute the entire batch at the same time.

KNSIT Page 30
The executeBatch() method returns an int array that contains the number of SQL statements that were
executed successfully

String url = "jdbc:odbc:CustomerInformation";


String userID = "jim";
String password = "keogh";
Statement DataRequest, DataRequest1,
DataRequest2;
Connection Db;
try
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Db =
DriverManager.getConnection(url,userID,password);
}catch(Exception e){}
try
{

KNSIT Page 31
Db.setAutoCommit(false);
String query1 = "UPDATE Customers SET Street =
'5 Main Street'"+ "WHERE FirstName='Bob'";
String query2 = "UPDATE Customers SET Street =
'10 Main Street'"+ "WHERE FirstName='Tim'";
DataRequest=Db.createStatement();
DataRequest1.addBatch(query1);
DataRequest2.addBatch(query2);
int[] updated = DataRequest.executeBatch();
Db.commit();
DataRequest1.close();
DataRequest2.close();
Db.close();
}
catch (SQLException ex){ }

ResultSet Holdability

1. Whenever the commit() method is called, all ResultSet objects that were created for the
transaction are closed.

2. Sometimes a J2EE component needs to keep the ResultSet open even after the commit() method
is called.

3. We can control whether or not ResultSet objects are closed following the call to the commit()
method by passing oen of two constants to the createStatement() method.

4. These constants are HOLD_CURSORS_OVER _COMMIT and


CLOSE_CURSORS_AT_COMMIT.

5. HOLD_CURSORS_OVER _COMMIT constant keeps ResultSet objects open following a call


to the commit() method.

KNSIT Page 32
6. CLOSE_CURSORS_AT_COMMIT closes ResultSet objects when the commit() method is
called.

RowSets

1. The JDBC RowSets object is used to encapsulate a ResultSet for use with Enterprise Java
Bean(EJB).

2. A RowSet object contains rows of data from a table(s) that can be used in a disconnected
operation.

Auto-Generated Keys

1. It is common for a DBMS to automatically generate unique keys for a table as rows are inserted
into the table.

2. The getGeneratedKeys() method of the Statement object is called to return keys generated by the
DBMS.

3. The getGeneratedKeys() returns a ResultSet object and can use the ResultSet.getMetaData() to
retrieve metadata relating to the automatically generated key.

Metadata

1. Metadata is data about data. A J2EE component can access metadata using the
DatabaseMetaData interface.

2. The DatabaseMetaData interface is used to retrieve information about database, tables, columns,
and indexes among other information about the DBMS.

3. Some of the commonly used DatabaseMetaData objects methods:

4. getDatabaseProductName() returns the product name of the database

5. getUserName() returns the URL of the database.

6. getURL() returns all the schema names available in this database.

7. getPrimaryKeys() returns primary keys

8. getProcedures() returns stored procedures names.

9. getTables() returns names of the tables in the database.

ResultSet Metadata

1. There are 2 types of metadata that can be retrieved from the DBMS.

KNSIT Page 33
2. These are metadata that describes the database mentioned earlier and metadata that describes the
ResultSet.

3. Metadata describing ResultSet is retrieved by calling the getMetaData() of ResultSet object.

1. ResultSetMetadata rm = Result.getMetaData()

4. More commonly called methods are:

5. getColumnCount() gets the no. of columns contained in the ResultSet.

6. getColumnName() gets the name of the column specified by the column number.

7. getColumnType(int number) gets the data type of the column specifed by the column number.

KNSIT Page 34
Data Types
Table contains a list of data
types and their java equivalents.
We can use this list to
determine the proper data name
to use to replace the xxx in the
setxxx() and getxxx() methods.

Exceptions

1. There are three kinds of exceptions that are thrown by JDBC methods.

2. They are SQLExceptions, SQLWarnings and Data Truncation.

KNSIT Page 35
3. SQLExceptions commonly reflect a SQL syntax error in the query and are thrown by many of
the methods contained in the java.sql package.

4. The SQLWarning throws warnings received by the Connection from the DBMS.

5. The getWarnings() and getNextWarning() methods of Connection object retrieves warnings and
subsequent warnings respectively.

6. DataTruncation exception is thrown whenever data is lost due to truncation of data value.

END OF JDBC

3:4:SERVLETS & SERVLETS-SESSIONS


Introduction.
1. Servlets are small programs that execute on the server side of a Web connection.

2. Servlets are server side components that provides a powerful mechanism for developing server
web applications for server side.

3. Just as applets dynamically extend the functionality of a Web browser, servlets dynamically
extend the functionality of a Web server.

4. Using servlets web developers can create fast and efficient server side applications and can run
it on any servlet enabled web server.

5. Servlet runs entirely inside the Java Virtual Machine.

6. Since the servlet runs on server side so it does not depend on browser compatibility.

KNSIT Page 36
Background
In order to understand the advantages of servlets,
a
basic understanding of how Web browsers and ser
to
provide content to a user. Webserver maps
Requests for a static web page through web specific file & i
browser & it will generate the HTTP HTTP response
request to appropriate web server.

Client
The HTTP header in response
indicate the type of the content &
MIME is used for this purpose.

1. But the content of the dynamic web pages need to be generated dynamically.

2. In the early days of the Web, a server could dynamically construct a page by creating a separate
process to handle each client request.

3. The process would open connections to one or more databases in order to obtain the necessary
information.

KNSIT Page 37
4. It communicated with the Web server via an interface known as the Common Gateway Interface
(CGI).

5. CGI allowed the separate process to read data from the HTTP request and write data to the
HTTP response.

6. However, CGI suffered serious performance problems. It was expensive in terms of processor
and memory resources to create a separate process for each client request.

It was also expensive to open and close database connections for each client request. In addition, the CGI
programs were not platform-independent. Therefore, other techniques were introduced

1. Servlets offer several advantages in comparison with CGI.

2. First, performance is significantly better. It is not necessary to create a separate process to


handle each client request.

3. Second, servlets are platform-independent because they are written in Java.

4. Third, the Java security manager on the server enforces a set of restrictions to protect the
resources on a server machine.

5. Finally, the full functionality of the Java class libraries is available to a servlet. It can
communicate with applets, databases, or other software via the sockets and RMI mechanisms.

The Life Cycle of a Servlet

1. init( ), service( ), and destroy( ) are the three methods which are central to the life cycle of a
servlet.

2. They are implemented by every servlet and are invoked at specific times by the server.

KNSIT Page 38
3. Let us consider a user scenario to understand when these methods are called.

4. First, user enters URL, browser then generates an HTTP request for this URL, & this request is
then sent to the appropriate server.

5. second, this HTTP request is received by web server, web server maps this request to a
particular servlet. The servlet is dynamically retrieved & loaded into the address space of the
server.

6. Third, server invokes init( ) method of the servlet. This method is invoked only when the servlet
is first loaded into memory. It is possible to pass initialization parameters to the servlet so it may
configure itself.

7. Fourth, the server invokes the service( ) method of the servlet. This method is called to process
the HTTP request. It may also formulate an HTTP response for the client. The service( ) method
is called for each HTTP request.

8. Finally, the server may decide to unload the servlet from its memory.The server calls the destroy(
) method to relinquish any resources such as file handles that are allocated for the servlet.

A Simple Servlet

1. The basic steps to be followed:

1. Create and compile the servlet source code.

2. Start Tomcat.

3. Start a Web browser and request the servlet.

KNSIT Page 39
This package contains the
A Simple Servlet Code interfaces required to build
import java.io.*;
import javax.servlet.*;
public class HelloServlet extends GenericServlet
{
public void service(ServletRequest request, ServletR
response)throws ServletException, I
{
response.setContentType("text/html");
PrintWriter pw = response.getWriter();
pw.println("<B>Hello!");
pw.close();
}
} Enables the servlet to formulate
the client.
getWriter() obtains PrintWr
written to this stream is sent t
of HTTP response.
GRNICA

The Servlet API

1. javax.servlet and javax.servlet.http are the two packages that contains the classes required to
build servlet.

KNSIT Page 40
2. These packages are not part of Java core packages, they are standard extensions provided by
Tomcat.

3. The current servlet specification is version 2.4.

4. The Servlet API is supported by most Web servers, such as those from Sun, Microsoft, and
others.

Check at http://java.sun.com for the latest information

The javax.servlet Package

1. The javax.servlet package contains a number of interfaces and classes that establish the
framework in which servlets operate.

2. The following table summarizes the core interfaces that are provided in this package.

GRNICA

The Servlet Interface

1. All servlets must implement the Servlet interface.

The methods defined by Servlet are shown in table below

KNSIT Page 41
The ServletConfig Interface

1. It allows a servlet to obtain configuration data when it is loaded.

2. The methods declared by this interface are summarized here:

The ServletContext Interface

1. ServletContext is a interface which helps us to communicate with the servlet container.

2. It enables servlets to obtain information about their environment.

3. There is only one ServletContext for the entire web application and the components of the web
application can share it.

4. The information in the ServletContext will be common to all the components.

KNSIT Page 42
5. Each servlet will have its own ServletConfig.

6. The ServetContext is created by the container when the web application is deployed and after
that only the context is available to each servlet in the web application.

Several of its methods are summarized in table below.

The ServletRequest Interface

1. It enables a servlet to obtain information about a client request.

2. Several of its methods are summarized in table below.

KNSIT Page 43
The ServletResponse Interface

1. It enables a servlet to formulate a response for a client.

2. Several of its methods are summarized in table below.

KNSIT Page 44
The following table summarizes the core classes that are provided
in the javax.servlet package.

The GenericServlet Class

1. The GenericServlet class provides implementations of the basic life cycle methods for a servlet.

2. GenericServlet implements the Servlet and ServletConfig interfaces.

3. In addition, a method to append a string to the server log file is available. The signatures of this
method are shown here:
void log(String s)

void log(String s, Throwable e)

1. Here, s is the string to be appended to the log, and e is an exception that occurred.

The ServletInputStream Class

1. The ServletInputStream class extends InputStream. It is implemented by the server and


provides an input stream that a servlet developer can use to read the data from a client request.

2. A method is provided to read bytes from the stream. Its signature isshown here:

int readLine(byte[ ] buffer, int offset, int size) throws IOException

3. Here, buffer is the array into which size bytes are placed starting at
offset.

KNSIT Page 45
The ServletOutputStream Class

1. The ServletOutputStream class extends OutputStream.

2. It is implemented by the server and provides an output stream that a servlet developer can use to
write data to a client response.

3. A default constructor is defined. It also defines the print( ) and println( ) methods, which output
data to the stream.

The Servlet Exception Classes

1. javax.servlet defines two exceptions.

2. The first is ServletException, which indicates that a servlet problem has occurred.

3. The second is UnavailableException, which extends ServletException. It indicates that a servlet


is unavailable.

Reading Servlet Parameters

1. The ServletRequest class includes methods that allow you to readthe names and values of
parameters that are included in a client request.

2. The example contains two files. A Web page is defined in PostParameters.htm and a servlet is
defined in PostParametersServlet.java.

KNSIT Page 46
<html>
<body>
<center>
<form name="Form1" method="post
action="http://localhost:8080/grnica/PostParametersS
<table>
<tr>
<td><B>Employee</td>
<td><input type=textbox name="e" size="25" value=
</tr>
<tr>
<td><B>Phone</td>
<td><input type=textbox name="p" size="25" value
</tr>
</table>
<input type=submit value="Submit">
</body>
</html>

GRNICA

KNSIT Page 47
import java.io.*;
import java.util.*;
import javax.servlet.*;
public class PostParametersServlet extends
GenericServlet
{
public void service(ServletRequest request,
ServletResponse response)
throws ServletException, IOException {
// Get print writer.
PrintWriter pw = response.getWriter();
// Get enumeration of parameter names.
Enumeration e =
request.getParameterNames();

KNSIT Page 48
// Display parameter names and values.
while(e.hasMoreElements())
{
String pname = (String)e.nextElement();
pw.print(pname + " = ");
String pvalue =
request.getParameter(pname);
pw.println(pvalue);
}
pw.close();
}
}
The javax.servlet.http Package

1. The javax.servlet.http package contains a number of interfaces and


classes that are commonly used by servlet developers.

The HttpServletRequest Interface

KNSIT Page 49
1. The HttpServletRequest interface is implemented by the server. It enables a servlet to obtain
information about a client request.

2. Several of its methods are shown in Table below.

KNSIT Page 50
KNSIT Page 51
The HttpServletResponse Interface

1. The HttpServletResponse interface is implemented by the server. It enables a servlet to


formulate an HTTP response to a client.

2. Several constants are defined. These correspond to the different status codes that can be
assigned to an HTTP response.

3. For example, SC_OK indicates that the HTTP request succeeded and SC_NOT_FOUND
indicates that the requested resource is not available.

KNSIT Page 52
The HttpSession Interface

1. The HttpSession interface is implemented by the server. It enables a servlet to read and write the
state information that is associated with an HTTP session.

KNSIT Page 53
The HttpSessionBindingListener Interface

1. The HttpSessionBindingListener interface is implemented by objects that need to be notified


when they are bound to or unbound from an HTTP session.

2. The methods that are invoked when an object is bound or unbound are:

void
valueBound(HttpSessionBindingEvent e)

void
valueUnbound(HttpSessionBindingEvent e)

1. Here, e is the event object that describes the binding.

The Cookie Class

1. The Cookie class encapsulates a cookie. A cookie is stored on a client and contains state
information.

2. Cookies are valuable for tracking user activities.

3. For example, assume that a user visits an online store. A cookie can save the users name,
address, and other information. The user does not need to enter this data each time he or she
visits the store.

4. A servlet can write a cookie to a users machine via the addCookie( ) method of the
HttpServletResponse interface.

5. The names and values of cookies are stored on the users machine. Some of the information that
is saved for each cookie includes the following:

KNSIT Page 54
The name of the cookie

The value of the cookie

The expiration date of the cookie

The domain and path of the cookie

1. The expiration date determines when this cookie is deleted from the users machine.

2. 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 users machine.

3. The domain and path of the cookie determine when it is included in the header of an HTTP
request.

4. There is one constructor for Cookie. It has the signature shown here:
Cookie(String name, String value)

5. Here, the name and value of the cookie are supplied as arguments to the constructor.

The methods of the Cookie class are summarized in Table below

KNSIT Page 55
The HttpServlet Class

1. The HttpServlet class extends GenericServlet. It is commonly used when developing servlets that
receive and process HTTP requests.

2. The methods of the HttpServlet class are summarized in Table

KNSIT Page 56
The HttpSessionEvent Class

1. HttpSessionEvent encapsulates session events. It extents EventObject and is generated when a


change occurs to the session.

2. It defines this constructor:


HttpSessionEvent(HttpSession session)

3. Here, session is the source of the event.

4. HttpSessionEvent defines one method, getSession( ), which is shown here:


HttpSession getSession( )

5. It returns the session in which the event occurred.

The HttpSessionBindingEvent Class

KNSIT Page 57
1. The HttpSessionBindingEvent class extends HttpSessionEvent. It is generated when a listener is
bound to or unbound from a value in an HttpSession object.

2. It is also generated when an attribute is bound or unbound.

3. Here are its constructors:


HttpSessionBindingEvent(HttpSession session, String name)
HttpSessionBindingEvent(HttpSession session, String name, Object val)

4. Here, session is the source of the event and name is the name associated with the object that is
being bound or unbound. If an attribute is being bound or unbound, its value is passed in val.

5. The getName( ) method obtains the name that is being bound or unbound. Its is shown here:
String getName( )

6. The getSession( ) method, obtains the session to which the listener is being bound or unbound:
HttpSession getSession( )

7. The getValue( ) method obtains the value of the attribute that is being bound or unbound. It is
shown here:
Object getValue( )

Handling HTTP Requests and Responses

1. The HttpServlet class provides specialized methods that handle the various types of HTTP
requests.

2. These methods are doDelete( ), doGet( ), doHead( ), doOptions( ), doPost( ), doPut( ), and
doTrace( ).

Handling HTTP GET Requests

The servlet is invoked when a form on a Web page is submitted.


The example contains two files. A Web page is defined in ColorGet.htm and a servlet is defined in
ColorGetServlet.java

KNSIT Page 58
<html>
<body>
<center>
<form name="Form1"
action="http://localhost:8080/jnnce/ColorGetServlet">
<B>Color:</B>
<select name="color" size="1">
<option value="Red">Red</option>
<option value="Green">Green</option>
<option value="Blue">Blue</option>
</select>
<br><br>
<input type=submit value="Submit">
</form>
</body>
</html>

KNSIT Page 59
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class ColorGetServlet extends
HttpServlet {
public void doGet(HttpServletRequest
request,
HttpServletResponse response)
throws ServletException, IOException {
String color =
request.getParameter("color");
response.setContentType("text/html");
PrintWriter pw = response.getWriter();
pw.println("<B>The selected color is: ");
pw.println(color);
pw.close();
}
}
Handling HTTP POST Requests

KNSIT Page 60
1. Here we will develop a servlet that handles an HTTP POST 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 ColorPost.htm and a servlet is defined in
ColorPostServlet.java

<html>
<body>
<center>
<form name="Form1"
method="post"

action="http://localhost:8080/jnnce/ColorPostServlet">
<B>Color:</B>
<select name="color" size="1">
<option value="Red">Red</option>
<option value="Green">Green</option>
<option value="Blue">Blue</option>
</select>
<br><br>
<input type=submit value="Submit">
</form>
</body>
</html>

KNSIT Page 61
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class ColorPostServlet extends HttpServlet {
public void doPost(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
String color = request.getParameter("color");
response.setContentType("text/html");
PrintWriter pw = response.getWriter();
pw.println("<B>The selected color is: ");
pw.println(color);
pw.close();
}
}
GRNICA

Using Cookies

The servlet is invoked when a form on a Web page is submitted

KNSIT Page 62
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class ColorPostServlet extends HttpServlet {
public void doPost(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
String color = request.getParameter("color");
response.setContentType("text/html");
PrintWriter pw = response.getWriter();
pw.println("<B>The selected color is: ");
pw.println(color);
pw.close();
}
}
GRNICA

KNSIT Page 63
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class AddCookieServlet extends HttpServlet {
public void doPost(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
// Get parameter from HTTP request.
String data = request.getParameter("data");

KNSIT Page 64
// Create cookie.
Cookie cookie = new Cookie("MyCookie",
data);
// Add cookie to HTTP response.
response.addCookie(cookie);
// Write output to browser.
response.setContentType("text/html");
PrintWriter pw = response.getWriter();
pw.println("<B>MyCookie has been set
to");
pw.println(data);
pw.close();
}
}

KNSIT Page 65
GetCookiesServlet.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class GetCookiesServlet extends HttpServlet
{
public void doGet(HttpServletRequest request,
HttpServletResponse response) throws
ServletException, IOException
{
// Get cookies from header of HTTP request.
Cookie[] cookies = request.getCookies();
// Display these cookies.
response.setContentType("text/html");
PrintWriter pw = response.getWriter();
pw.println("<B>");

KNSIT Page 66
for(int i = 0; i < cookies.length; i++)
{
String name =
cookies[i].getName();
String value =
cookies[i].getValue();
pw.println("name = " + name + ";
value = " + value);
}
pw.close();
}
}
Session Tracking

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

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

3. A session can be created via the getSession( ) method ofHttpServletRequest.

4. An HttpSession object is returned. This object can store a set of bindings that associate names
with objects.

5. The setAttribute( ), getAttribute( ), getAttributeNames( ), and removeAttribute( ) methods of


HttpSession manage these bindings.

KNSIT Page 67
import java.io.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class DateServlet extends HttpServlet {
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
Gets t
// Get the HttpSession object. sessio
HttpSession hs = request.getSession(true);

KNSIT Page 68
// Get writer. Call
response.setContentType("text/html"); obje
to th
PrintWriter pw = response.getWriter();
pw.print("<B>");
// Display date/time of last access.
Date date = (Date)hs.getAttribute("date");
if(date != null) {
pw.print("Last access: " + date + "<br>");
} This
to bi
// Display current date/time. date
date = new Date();
hs.setAttribute("date", date);
pw.println("Current date: " + date);
}
}

KNSIT Page 69
Servlet to check the session and get the session ID
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class CheckingTheSession extends HttpServlet
{
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException,
{
response.setContentType("text/html");
PrintWriter pw = response.getWriter();
pw.println("Checking whether the session is new or o
HttpSession session = request.getSession();
String id = session.getId();
pw.println("Session Id is : " + id);

KNSIT Page 70
if(session.isNew()){
pw.println("You have created a new
session");
}
else{
pw.println("Session already exists");
}
}
}

KNSIT Page 71
Servlets reads Username & password as parameters
<html>
<head>
<title>New Page 1</title>
</head>
<body>
<h2>Login</h2>
<p>Please enter your username and password</p>
<form method="GET action="http://localhost:8080/jnnce/LoginS
<p> Username <input type="text" name="username" size="20">
<p> Password <input type="password" name="password" size=
<p><input type="submit" value="Submit" name="B1"></p>
</form>
<p>&nbsp;</p>
</body>
</html>

KNSIT Page 72
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class LoginServlet extends HttpServlet
{
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException
{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String name = request.getParameter("username");
String pass = request.getParameter("password");
out.println("<html>");
out.println("<body>");
out.println("Thanks " + " " + name + " " + "for visiting our s
out.println("Now you can see your password : " + " " + pass +
out.println("</body></html>");
}
}

GRNICA

KNSIT Page 73
Usage of sendRedirect()
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class SendRedirectServlet extends HttpServlet
{
protected void doPost(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException
{
response.setContentType("text/html");
PrintWriter pw = response.getWriter();

KNSIT Page 74
String name =
request.getParameter("username");
String password =
request.getParameter("password");
if(name.equals("Hemanth")&&
password.equals("Kumar"))
{

response.sendRedirect("/jnnce/ValidUserServl
et");
}
else
{
pw.println("u r not a valid user");
}
}
}

KNSIT Page 75
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class ValidUserServlet extends
HttpServlet
{
protected void doGet(HttpServletRequest
request,
HttpServletResponse response)
throws ServletException, IOException
{
PrintWriter pw = response.getWriter();
pw.println("Welcome to grnica " + " ");
pw.println("how are you");
}
}

KNSIT Page 76
<html>
<head>
<title>New Page 1</title>
</head>
<body>
<form method="POST"
action="http://localhost:8080/jnnce/SendRedir
ectServlet">
<p>Enter your name
<input type="text" name="username"
size="20"></p>
<p>Enter your password <input
type="password" name="password"
size="20"></p>
<p><input type="submit" value="Submit"
name="B1"></p>
</form>
</body>
</html>

KNSIT Page 77
To download a file using servlet
import java.io.*;
import javax.servlet.*;
public class Download extends GenericServlet
{
public void service(ServletRequest request,ServletR
response)throws ServletException,IOException
{
response.setContentType("text/html");
PrintWriter pw=response.getWriter();
pw.println("<a href=/jnnce/photo.jpg> click he
download</a>");
pw.close();
}
}

RequestDispatcher

1. In some circumstances, you may want to include the content from an HTML page or the output
from another servlet.

2. Additionally, there are cases that require that you pass the processing of an HTTP request from
your servlet to another servlet.

KNSIT Page 78
3. The current servlet specification responds to these needs with an interface called
RequestDispatcher, which is found in the javax.servlet package.

4. This interface has two methods, which allow you to delegate the request-response processing to
another resource: include and forward.

5. Both methods accept a javax.servlet.ServletRequest object and a javax.servlet.ServletResponse


object as arguments

1. As the name implies, the include method is used to include content from another resource, such
as another servlet, a JSP page, or an HTML page. The method has the following signature:

public void include(ServletRequest request, ServletResponse response) throws ServletException,


io.IOException

1. The forward method is used to forward a request from one servlet to another. The original
servlet can perform some initial tasks on the ServletRequest object before forwarding it. The
signature of the forward method is as follows:

public void forward(ServletRequest request, ServletResponse response) throws ServletException,


IOException

1. Use the getRequestDispatcher method of the javax.servlet.ServletRequest interface, passing a


String containing the path to the other resource. The path is relative to the current
HTTP request.

KNSIT Page 79
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import java.util.*;
public class FirstServlet1 extends HttpServlet {
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
RequestDispatcher rd =
request.getRequestDispatcher("/user2.html");
rd.include(request, response);
}
}

GRNICA

KNSIT Page 80
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import java.util.*;
public class LoginServlet3 extends HttpServlet
{
public void doPost(HttpServletRequest
request,HttpServletResponse response)
throws ServletException, IOException
{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String userName =
request.getParameter("userName");
String password =
request.getParameter("password");

KNSIT Page 81
if (userName!=null && password!=null &&
userName.equals("jnnce") &&
password.equals("mca"))
{
RequestDispatcher rd =
request.getRequestDispatcher("WelcomeServl
et1");
rd.forward(request, response);
}
else
{
out.println(<B> Not a valid
user.");
}
}
}

KNSIT Page 82
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
public class WelcomeServlet1 extends HttpServlet {
public void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletExcept
IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<HTML>");
out.println("<BODY>");
out.println("<P>Welcome to the JNNMCA Web Site.
out.println("</BODY>");
out.println("</HTML>");
}
}
GRNICA

<HTML>
<HEAD>
<TITLE>Login</TITLE>
</HEAD><BODY
<p>Please enter your user name and password.
<p><form method="POST" action="http://localhost:8080/jnnce/LoginServlet3">

KNSIT Page 83
<p>User Name: <INPUT TYPE=TEXT
NAME=userName>
<p>Password: <INPUT
TYPE=PASSWORD NAME=password>
<p><INPUT TYPE=SUBMIT
VALUE=Submit>
</form>
</BODY>
</HTML>

Filter API

1. A filter is an object that can transform the header or content or both of a request or response.

2. Filters differ from Web components & in that they usually do not themselves create a response.
Instead, a filter provides functionality that can be "attached" to any kind of Web resource.

3. A filter should not have any dependencies on a Web resource for which it is acting as a filter, so
that it can be composable with more than one type of Web resource.

The main tasks that a filter can perform are as follows:

1. Query the request and act accordingly.

2. Block the request-and-response pair from passing any further.

3. Modify the request headers and data. It is done by providing a customized version of the request.

4. Modify the response headers and data. It is done by providing a customized version of the
response.

5. Interact with external resources.

6. Applications of filters include authentication, logging, image conversion, data compression,


encryption, tokenizing streams, and XML transformations.

7. The filtering API is defined by the Filter, FilterChain, and FilterConfig interfaces in
the javax.servlet package.

8. We define a filter by implementing the Filter interface.

9. The most important method in this interface is the doFilter method, which is passed request,
response, and filter chain objects.

This method can perform the following actions:

10. Examine the request headers.

KNSIT Page 84
11. Customize the request object if it wishes to modify request headers or data.

12. Customize the response object if it wishes to modify response headers or data.

13. Invoke the next entity in the filter chain.

14. Examine response headers after it has invoked the next filter in the chain.

15. Throw an exception to indicate an error in processing.

16. In addition to doFilter, we must implement the init and destroy methods.

17. The init method is called by the container when the filter is instantiated.

18. If we wish to pass initialization parameters to the filter, we retrieve them from
the FilterConfig object passed to init.

An example filter program

19. This example illustrates how one can write Logging Filter servlet to provide control over log
file. We can have additional controls over these log files and these all are available to use by
implementing "Filter" class.

20. We can create filter class by implementing javax.servlet.Filter, which has three methods as
follows:

21. void init(FilterConfig filterConfigObject) throws ServletException

1. It is called once by the server to get prepared for service and then it calls doFilter() a
number of times for request processing.

22. void destroy()

23. void doFilter(ServletRequest request, ServletResponse response, FilterChain


filterchainObject) throws IOException, ServletException

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public final class LoggingFilterExample implements Filter
{
private FilterConfig filterConfigObj = null;
public void init(FilterConfig filterConfigObj)
{
this.filterConfigObj = filterConfigObj;

KNSIT Page 85
}
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException
{
String remoteAddress = request.getRemoteAddr();
String uri = ((HttpServletRequest) request).getRequestURI();
String protocol = request.getProtocol();
chain.doFilter(request, response);
filterConfigObj.getServletContext().log("Logging Filter Servlet called");
filterConfigObj.getServletContext().log("********************************");
filterConfigObj.getServletContext().log("User Logged ! " +
" User IP: " + remoteAddress +" Resource File: " + uri + " Protocol: " + protocol );
}
public void destroy()
{}
}
<web-app>
<filter>
<filter-name>LoggingFilterExample</filter-name>
<filter-class>LoggingFilterExample</filter-class>
</filter>
<filter-mapping>
<filter-name>LoggingFilterExample</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
</web-app>

Multi-tier Applications Using Database Connectivity

<html>
<head>
<title>EMPLOYEE DETAILS 1</title>
</head>
<body>
<form method="GET" action="ServletHtml">
<p>Enter Name: <input type="text" name="ename" size="20"></p>
<p>Enter EID: <input type="text" name="eid" size="20"></p>
<p>Enter ADDRESS : <input type="text" name="eaddr" size="30"></p>
<p><input type="submit" value="Submit" name="B1"></p>
</form>
</body>
</html>

package access;
import java.io.*;
import java.sql.*;
import javax.servlet.*;

KNSIT Page 86
import javax.servlet.http.*;
public class ServletHtml extends HttpServlet
{
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException,
IOException
{
response.setContentType("text/html");
PrintWriter pw = response.getWriter();
String url="jdbc:odbc:html";
Connection con;

try
{
String ename = request.getParameter("ename");
String eid = request.getParameter("eid");
String eaddr = request.getParameter("eaddr");
pw.println(ename);
pw.println(eid);
pw.println(eaddr);
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
con = DriverManager.getConnection(url);
PreparedStatement pst = con.prepareStatement("insert into emp_info values(?,?,?)");
pst.setString(1,ename);
pst.setString(2,eid);
pst.setString(3,eaddr);
int i = pst.executeUpdate();
if(i!=0)
{
pw.println("<br>Record has been inserted");
}
else
{
pw.println("failed to insert the data");
}
}
catch (Exception e)
{
pw.println(e);
}
}
}

KNSIT Page 87
END OF SERVLETS AND SESSION

5:JAVA SERVER PAGES


JSP
1. Java ServerPages is a server-side program.
2. A JSP is called by a client to provide a web service.
3. A JSP processes the request by using logic built into the JSP or by calling other web
components built using Java servlet technology or Enterprise Java Bean technology or
other technology.

KNSIT Page 88
4. A JSP is simple to create, a JSP is written in HTML rather tha with the Java
programming language.
5. A JSP offers basically the same features found in Java servlet because a JSP is converted
to a Java servlet the first time that aclient requests the JSP.
6. JSP pages are translated into servlets, the servlets are compiled, and at request time it is
the compiled servlets that execute. So,writing JSP pages is really just another way of
writing servlets.
7. jspInt(), jspDestroy() and service() are the three methods that are automatically called
when a JSP is requested and terminates normally.
8. The jspInt() is called first when the JSP is requested and is used to initialize objects and
variables that are used throughout the life of JSP.
9. The jspDestroy() is automatically called when the JSP terminates normally. When JSP
abruptly terminated, it is not called.
10. The service() is automatically called and retrieves a connection to HTTP.

Advantages of JSP
11. JSP are translated and compiled into JAVA servlets but are easier to develop than JAVA
servlets.
JSP uses simplified scripting language based syntax for embedding HTML into JSP.

JSP containers provide easy way for accessing standard objects and actions.

JSP reaps all the benefits provided by JAVA servlets and web container environment, but they
have an added advantage of being simpler and more natural program for web enabling enterprise
developer

JSP use HTTP as default request /response communication paradigm and thus make JSP ideal
as Web Enabling Technology.

JSP Tags
1. A JSP programs consists of a combination of HTML tags and JSP tags.
2. JSP tags define Java code that is to be executed before the output of the JSP program is
sent to the browser.

KNSIT Page 89
3. Java codes associated with JSP tags in the JSP program is executed when encountered by
Tomcat, and the result of that process is sent to the browser.
4. The browser knows how to display the result because the JSP tag is enclosed within an
open and closed HTML tag.

There are five types of JSP tags.


5. Comment tag : A comment tag opens with <%-- and closes with --%>.
6. Declaration Statement tags : It opens with <%! and is followed by a Java declaration
statement(s) that define variables, objects, and methods that are available to other
components of the JSP program.
7. Directive tags : A directive tag opens with <%@ and commands the JSP virtual engine
to perform a specific task, such as importing a Java package required by objects and
methods.
8. The directive tag closes with %>. There are three commonly used
directives. They are :
9. import : It is used to import Java packages into the JSP program.
<%@ page import = import java.sql.* ; %>
10. include : It inserts a specified file into the JSP program replacing
the include tag.
<%@ include file=keogh\books.html %>
11. taglib : taglib tag specifies a file that contains a tag library.
<%@ taglib url=myTags.tld %>
12. Scriptlet tags : A scriptlet tag opens with <% and contains
commonly used Java control statements and loops. Closes with %>.
13. We can embed any amount of java code in the JSP Scriptlets. JSP
Engine places these code in the _jspService() method.

Example:
<HTML><HEAD>
<TITLE>Order Confirmation</TITLE>
</HEAD><BODY>
<%String userName=null
userName=request.getParameter("userName");
%>
</BODY></HTML>
14. Variables available to the JSP Scriptlets are:
KNSIT Page 90
15. request: request represents the clients request and is a subclass
of HttpServletRequest. Use this variable to retrieve the data
submitted along the request.
16. response: response is subclass of HttpServletResponse.
17. session: session represents the HTTP session object associated with
the request.
18. out: out is an object of output stream and is used to send any output
to the client.
Expression tags : It opens with <%= and is used for an expression statement. It closes with %>.
Syntax of JSP Expressions are: <%="Any thing" %>
<HTML><HEAD>
<TITLE>Example JSP Program</TITLE>
</HEAD><BODY>
<%="Hello World!" %> </BODY>
</HTML>

The Page Directives


Page directives apply different properties for the page like language support, page
information and import etc. by using the different attributes of the directives.
19. There are three types of directives are as follows:
20. Page Directive
21. Include Directive
22. Taglib Directive
Syntax of the declaration of the page directive with it's attributes is <%@ page
attributeName="values" %>
Following are name of the attributes of the page directive used in JSP:
23. Language
24. extends
25. import
26. session
27. buffer
KNSIT Page 91
28. autoFlush
29. isThreadSafe
30. info
31. errorPage
32. contentType
33. isErrorPage
34. pageEncoding
35. isELIgnored
36. language: This attribute of page directive of JSP is used for specifying some other
scripting languages to be used in the JSP page.
37. extends: This is used for specifying some other java classes to be used in the JSP page
like packagename.classname. The fully qualified name of the superclass of the Java class
will be accepted.
38. 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 (,).
39. We can set the name of the class with the package name directly like
packagename.classname or import all classes of the package by using packagename.*
40. session: This attribute sets a boolean value to either true or false. If the value of session
attribute is true then the session object refers to the current or a new session because the
client must be in the HTTP session for running the JSP page on the server. If we set the
value of session object to false then we can not use the session object.
41. buffer: This attribute sets the buffer size in kilobytes i.e. used by the out object to handle
output generated by the JSP page on the client web browser. If we specify the buffer
size then the output will be buffered with at least 8kb because the default and minimum
value of the buffer attribute is 8kb.
42. autoFlush: This attribute of the page directive supports for flushing buffer automatically
when the buffer is full. The value of the autoFlush attribute is either true or false. If we
specify it as true, then buffer will be flushed.
43. isThreadSafe: This attribute support the facility of maintaining thread for sending
multiple and concurrent requests from the JSP container to the JSP page if the value the
of attribute is set to true, otherwise if we set the value of attribute to false, then the JSP
container can send only one request at one time. The default value of the attribute is true.

KNSIT Page 92
44. info: This attribute simply sets the information of the JSP page which is retrieved later by
using Servlet.getServletInfo() method. The value of the attribute will be a text string.
45. errorPage: This attribute sets a url. If any exception is generated then the attribute refers
to the file which is mentioned in the given url. If no url id specified, then the attribute
refers to the current page of the JSP application when exception generated
46. isErrorPage: This attribute sets the boolean value to either true or false. We can use the
exception object in the JSP page if we set the attribute value to true, otherwise we cannot
use the exception object because the default value of the attribute is false.
47. contentType: This attribute specifies the MIME type and the character encoding used
for the JSP response. The default MIME type is "text/html" and the default character set
is "ISO-88591".
48. pageEncoding: This attribute specifies the language that the page uses when the page is
sent to the browser. This attribute works like the meta tag of the HTML markup
language.
49. isELIgnored: This is a boolean attribute that specifies either true or false value. The
isELIgnored option gives you the ability to disable the evaluation of Expression
Language (EL) expressions which has been introduced in JSP 2.0. If we set the attribute
value to true, then any type of the EL expressions will be ignored in the JSP page.

Variables & Objects


1. <HTML><HEAD>
<TITLE>Order Confirmation</TITLE>
</HEAD><BODY>
<%! int age=25; %>
<p> Your age is : <%=age%> </p>
</BODY></HTML>

2. <HTML><HEAD>
<TITLE> JSP Programming </TITLE>
</HEAD><BODY>
<%! int age=25;
float salary;
int empnumber;
%>
</BODY></HTML>

3. <HTML><HEAD>
<TITLE>JSP Programming </TITLE>
</HEAD><BODY>

KNSIT Page 93
<%! String Name;
String [] Telephone = {"201-555-1212", "201-555-4433"};
String Company = new String();
int[] Grade = {100,82,93};
%>
</BODY></HTML>

Methods
4. JSP offers same functionality for defining methods as done by Java.
5. In JSP a method definition is placed within a JSP tag.
6. We can call the method from within the JSP tag once the method is
defined.
7. The JSP tag that calls the method must be a JSP expression tag,
which begins with <%=.
8. <HTML><HEAD>
<TITLE> JSP Programming </TITLE>
</HEAD><BODY>
<%! int curve (int grade)
{
return 10 + grade;
}
int curve(int grade, int curvevalue)
{<HTML><HEAD>
<TITLE> JSP Programming </TITLE>
</HEAD><BODY>
<%! int curve (int grade)
{
return 10 + grade;
}
%>
<p> Your curved grade is : <%=curve(80)%> </p>
</BODY></HTML>

return curvevalue+grade;
}
%>
<p> Your curved grade is : <%=curve(80,10)%> </p>
<p> Your curved grade is : <%=curve(70)%> </p>
</BODY></HTML>

KNSIT Page 94
Control Statement
Using JSP it is easy to create dynamic content for a web page based on conditions
received from the browser.
9. There are two control statements used to change the flow of a JSP program. These are
the if statement and the switch statement, both of which are also used to direct the flow
of a Java program.
10. The power of these codes comes from the fact that the code segment that is executed or
skipped can consists of HTML tags or a combination of HTML tags and JSP tags.
<HTML>
<HEAD>
<TITLE> JSP Programming </TITLE>
</HEAD>
<BODY>
<%! int grade=70;%>
<% if(grade > 69 )
{ %>
<p> You Passed ! </p>
<% }
else { %>
<p> Better luck next time. </p>
<% } %>
<% switch (grade) {
case 90 : %>
<p> Your final grade is a A </p>
<% break;
case 80 : %>
<p> Your final grade is a B </p>
<% break;
case 70 : %>
<p> Your final grade is a C </p>
<% break;
case 60 : %>
<p> Your final grade is a D </p>
<% break;
}
%>
</BODY>
</HTML>

Loops

KNSIT Page 95
JSP loops are nearly identical to loops used in Java programs.
The for loop, while loop, and do.. While loop are the three loops.
Loops play an important role in JSP database programs
<html>
<head>
<title> JSP programming</title>
</head>
<body>
<center>
<%! int[] Grade = {100,82,93};
int x=0;
%>
<table>
<tr>
<td> First </td>
<td> Second </td>
<td> Third </td>
</tr>
<tr>
<% for(int i=0;i<3;i++) { %>
<td><%=Grade[i]%></td>
<% } %>
</tr>
</table>
<table>
<tr>
<td> First </td>
<td> Second </td>
<td> Third </td>
</tr>

<tr>
<% while(x<3) { %>
<td><%=Grade[x]%></td>
<% x++;
} %>
</tr>
</table>
<table>
<tr>
<td> First </td>

KNSIT Page 96
<td> Second </td>
<td> Third </td>
</tr>
<tr>
<% x=0; %>
<% do{ %>
<td><%=Grade[x]%></td>
<%x++; %>
<% }while(x<3); %>
</tr>
</table>
</center>
</body>
</html>
Tomcat
11. JSP programs are executed by JSP Virtual Machine that runs on a web server.
12. Hence there is a need to access to a JSP Virtual Machine to run the JSP programs.
13. One of the most popular JSP Virtual Machines is Tomcat, it is downloadable at free of
cost from www.jakarta.apache.org
14. Installing Java is also required.
15. Request String
16. The browser generates a user request string whenever the Submit button is selected. The
user request string consists of the URL and the query string.
17. http://www.jimkeogh.com/jsp/myprogram.jsp?fname=bob&lname=smith
18. Your program needs to parse the query string to extract values of fields that are to be
processed by your program. You can parse the query string by using methods of the JSP
request object.
19. The getParameter(Name) is the method used to parse a value of a specific field. The
getParameter() method requires an argument, which is the name of the field whose value
you want to retrieve.

<%! String Firstname = request.getParameter(fname);


String Firstname = request.getParameter(lname); %>

Implicit Variables

KNSIT Page 97
20. Implicit objects in jsp are the objects that are created by the container automatically and
the container makes them available to the developers, the developer do not need to
create them explicitly.
21. Since these objects are created automatically by the container and are accessed using
standard variables; hence, they are called implicit objects.
22. The implicit objects are parsed by the container and inserted into the generated servlet
code.
23. They are available only within the jspService method and not in any declaration.
24. Implicit objects are used for different purposes. User defined methods can't access them
as they are local to the service method and are created at the conversion time of a jsp into
a servlet. But we can pass them to our own method if we wish to use them locally in
those functions.
25. Application: These objects has an application scope. These objects are available at the
widest context level, that allows to share the same information between the JSP page's
servlet and any Web components with in the same application.
26. Config: These object has a page scope and is an instance of javax.servlet.ServletConfig
class. Config object allows to pass the initialization data to a JSP page's servlet.
Parameters of this objects can be set in the deployment descriptor (web.xml) inside the
element <jsp-file>. The method getInitParameter() is used to access the initialization
parameters.
27. Exception: This object has a page scope and is an instance of java.lang.Throwable class.
This object allows the exception data to be accessed only by designated JSP "error
pages.
28. Out: This object allows us to access the servlet's output stream and has a page scope.
Out object is an instance of javax.servlet.jsp.JspWriter class. It provides the output
stream that enable access to the servlet's output stream.
29. Page: This object has a page scope and is an instance of the JSP page's servlet class that
processes the current request. Page object represents the current page that is used to call
the methods defined by the translated servlet class. First type cast the servlet before
accessing any method of the servlet through the page.
30. Pagecontext: PageContext has a page scope. Pagecontext is the context for the JSP page
itself that provides a single API to manage the various scoped attributes.
31. This API is extensively used if we are implementing JSP custom tag handlers.
PageContext also provides access to several page attributes like including some static
or dynamic resource.

KNSIT Page 98
32. Request: Request object has a request scope that is used to access the HTTP request data,
and also provides a context to associate the request-specific data.
33. Request object implements javax.servlet.ServletRequest interface. It uses the
getParameter() method to access the request parameter. The container passes this object
to the _jspService() method.
34. Response: This object has a page scope that allows direct access to the
HTTPServletResponse class object.Response object is an instance of the classes that
implements the javax.servlet.ServletResponse class. Container generates to this object
and passes to the _jspService() method as a parameter.
35. Session: Session object has a session scope that is an instance of
javax.servlet.http.HttpSession class. Perhaps it is the most commonly used object to
manage the state contexts. This object
persist information across multiple user connection.
36. There are four predefined implicit objects that are in every JSP
programs. These are request, response, session and out.
37. The request object is an instance of the HTTPServletRequest.
38. The response object is an instance of the HTTPServletResponse.
39. The session object is an instance of the HTTPSession.
40. The out object is an instance of the JSPWriter, used to send a
response to the client.
41. getParameterValues() method helps us to copy a value from a multivalued field such as a
selection list field.
42. <%! String[] EMAIL = request.getParameterValues(ADDR); %>
<P> <%=EMAIL [O]%> </P>
<P> <%=EMAIL [1]%> </P>
43. Field names in the request string can be parsed by using the
getParameterNames() method.

<HTML>
<HEAD>
<TITLE>Order Confirmation</TITLE>
</HEAD>
<BODY>
<H2>Order Confirmation</H2>
KNSIT Page 99
Thanks for ordering <I><%= request.getParameter("title") %></I>!
</BODY>
</HTML>

join_email_list.html
<html>
<head>
<title> Email List application</title>
</head>
<body>
<h1>Join our email list</h1>
<p>To join our email list, enter your name and
email address below. <br>
Then, click on the Submit button.</p>
<form action="http://localhost:8080/jnnce/email.jsp" method="get">
<table cellspacing="5" border="0">
<tr>
<td align="right">First name:</td>
<td><input type="text" name="firstName"></td>
</tr>
<tr>
<td align="right">Last name:</td>
<td><input type="text" name="lastName"></td>
</tr>
<tr>
<td align="right">Email address:</td>
<td><input type="text" name="emailAddress"></td>
</tr>
<tr>
<td></td>
<td><br><input type="submit" value="Submit"></td>
</tr>
</table>
</form>
</body>
</html>
<html>
<head>
<title>Chapter 4 - Email List application</title>
</head>
<body>
KNSIT Page 100
<%
String firstName = request.getParameter("firstName");
String lastName = request.getParameter("lastName");
String emailAddress = request.getParameter("emailAddress");
%>
<h1>Thanks for joining our email list</h1>
<p>Here is the information that you entered:</p>
<table cellspacing="5" cellpadding="5" border="1">
<tr>
<td align="right">First name:</td>
<td><%= firstName %></td>
</tr>
<tr>
<td align="right">Last name:</td>
<td><%= lastName %></td>
</tr>
<tr>
<td align="right">Email address:</td>
<td><%= emailAddress %></td>
</tr>
</table>
<p>To enter another email address, click on the Back <br>
button in your browser or the Return button shown <br>
below.</p>
<form action=email.html method="post">
<input type="submit" value="Return">
</form>
</body></html>
Usage of page directives : first.jsp

<%@ page import= "java.util.*" language="java" contentType="text/html;


charset=ISO-8859-1 pageEncoding="ISO-8859-1"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<center><h1> using scripting elements</h1></center>
<%! int count,a,b;
int fun(int a)
{

KNSIT Page 101


return 10*a;
}
%>
<% a=1;
count++;
for(int i=0;i<5;i++)
{
out.println("value of i in iteration
no."+i+":&nbsp;&nbsp;<b>"+i+"<b><br/>");
}
b=fun(a);
out.println("value returned by fun():<b>"+b+"</b><br/>");
%>
<b>This page is requested by <b><%=count %></b>number of times on date </b>
<b> <%= new Date() %></b>.
</body>
</html>

Use of Implicit objects: page, session, out & application


Home.html
<html>
<head>
<title>Insert title here</title>
</head>
<body>
<form action="request.jsp">
name: <input type="text" name="name">
<input type="submit" value="Invoke JSP"/>
</form>
</body>
</html>
Request.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"


pageEncoding="ISO-8859-1"%>
<html>
<head>
<title>Implicit Objects</title>
</head>
<body>
Hello. <b> <%=request.getParameter("name") %></b><br/><br/>
Your request details are <br/><br/>
KNSIT Page 102
<table border="1">
<tr><th>Name</th><th>Value</th></tr>
<tr><td>request method</td>
<td><%=request.getMethod() %></td></tr>
<tr><td>request URI</td>
<td><%=request.getRequestURI() %></td></tr>
<tr><td>request protocol</td>
<td><%=request.getProtocol() %></td></tr>
<td><%=request.getHeader("user-agent") %></td></tr>
</table>
<% if (session.getAttribute("sessionVar")==null)
{
session.setAttribute("sessionVar", new Integer(0));
}%>
<table>
<tr><th align=left> Would you like to see use of remaining implicit objects?</th></tr>
<tr>
<form name=form1 action="pageContext.jsp" method="post">
<td><input type="radio" name="other" value="yes">Yes</td>
<td><input type="radio" name="other" value="No">No</td></tr>
<tr><td><input type="submit" value="Submit"></td></tr>
</form>
</table>
</body>
</html>

pageContext.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"


pageEncoding="ISO-8859-1"%>
<html>
<head>
<title>Intermediate</title>
</head>
<body>
<% if ("yes".equals(request.getParameter("other")))
{
pageContext.forward("first.jsp");
}
%>
</body>
</html>
KNSIT Page 103
Parsing Other Information
44. The request string sent to the JSP by the browser is divided into two general components
separated by question mark.
45. The URL component appears to the left of the question mark and the query string is to
the right of the question mark.
46. The URL is divided into four parts, beginning with the protocol.
47. The first three parts commonly used protocols like HTTP, HTTPS
(secured version of HTTP) and FTP.
48. Next is host and port combination. The host and port is the virtual path of the JSP
programs. The server maps the virtual path to the physical path.

User Sessions
49. A JSP program must be able to track a session. There are threecommonly used methods
to track a session.
50. These are by using a hidden field, by a cookier or by Java Bean.
51. A hidden field is a field in an HTML form whose value isnt displayed on the HTML
page.

Cookies
52. Cookie is a small piece of information created by a JSP program that is stored on the
clients hard disk by the browser.
53. Cookies are used to store various kinds of information like user preferences and an ID
that tracks a session with a JSP database system.
Addcookie.jsp
<HTML>
<HEAD>
<TITLE>JSP Programming</TITLE>
</HEAD>
<BODY>
<%! String MyCookieName = "userID";
String MyCookieValue = "HK1917"; %>
<% response.addCookie(new Cookie(MyCookieName, MyCookieValue));
%>
<p> MyCookieName is : <%=MyCookieName%> </p>

KNSIT Page 104


<p> MyCookieValue is : <%=MyCookieValue%> </p>
</BODY>
</HTML>
getcookie.jsp
<HTML>
<HEAD>
<TITLE>JSP Programming</TITLE>
</HEAD>
<BODY>
<%! String CName, CValue;
int found=0; %>
<% Cookie[] cookies = request.getCookies();
for(int i=0; i<cookies.length; i++)
{
CName = cookies[i].getName();
CValue = cookies[i].getValue();
} %>
<p> Cookie name = <%=CName%> </p>
<p> Cookie value = <%=CValue%> </p>
</BODY>
</HTML>

Session Objects
54. Each time a session is created, a unique ID is assigned to the session and stored as a
cookie.
55. The unique ID enables JSP programs to track multiple sessions simultaneously while
maintaining data integrity of each session.
56. The session ID is used to prevent intermingling of information from clients.
57. Along with session ID, a session object is also used to store other types of information,
called attributes.
58. An attribute can be login information, preferences, or even purchases placed in an
electronic shopping cart.

setattribute.jsp
<HTML>
<HEAD>
<TITLE>JSP Programming</TITLE>
</HEAD>
<BODY>

KNSIT Page 105


<%! String AtName = "Product";
String AtValue = "1983"; %>
<% session.setAttribute(AtName, AtValue); %>
</BODY>
</HTML>
getattribute.jsp
<HTML>
<HEAD>
<TITLE>JSP Programming</TITLE>
</HEAD>
<BODY>
<%! Enumeration e = session.getAttributeNames();
while(e.hasMoreElements())
{
String AtName = (String)e.nextElement();
String AtValue =(String)session.getAttribute(AtName);
%>
<p> Attribute Name is : <%=AtName%> </p>
<p> Attribute Value is : <%=AtValue%> </p>
<% } %>
</BODY>
</HTML>

JSP to print 10 even and 10 odd numbers.


<html>
<head>
<title> jsp </title>
</head>
<body>
<%!int i=0;%>
<p> even nos </p>
<table border=2>
<tr>
<%for(i=0;i<20;i++){
if(i%2==0)
{ %>
<td> <%=i%> </td>
<%}%>
<%}%>
</tr>
</table>
<table border=1>

KNSIT Page 106


<p> odd nos </p>
<tr>
<%for(i=1;i<20;i++){
if(i%2!=0)
{ %>
<td> <%=i%> </td>
<%}%>
<%}%>
</tr>
</table>
</body>
</html>

JSP for checking the valid username and password


<html>
<head>
<title> validation </title>
</head>
<body>
<% String username=request.getParameter("uname");
String pssword=request.getParameter("pswd");
if(username.equals("jnnce") && pssword.equals("mca"))
{%>
<p> welcome <%=username%> </p>
<%}
else{%>
<p> invalid usr name </p>
<%}%>
</body>
</html>

HTML file for username and password


<html>
<head>
<title> validation </title>
</head>
<body>
<h2> LOGIN </h2>
<p> enter name n passwd </p>
<form method="GET"
action="http://localhost:8080/jnnce/welcome.jsp">
<p> usrname
<input type="text" name="uname" size="20">

KNSIT Page 107


</p>
<p> pswd
<input type="password" name="pswd" size="20"> </p>
<input type="submit" name="submit">
<input type="reset" name="reset">
</form>
</body>
</html>

JSP Standard Actions


59. JSP Standard action are predefined tags which perform some action based on
information that is required at the time the JSP page is requested by a browser.
60. The action tags are specific to a JSP page.
61. When the JSP container encounters an action tag while converting a JSP page into a
servlet, it generates the java code that corresponds to the required predefined task.
62. An action can be for instance, access parameters sent with the request to do a database
lookup.
63. It can also dynamically generate HTML, such as a table filled with information retrieved
from an external system.
64. They can be used to include a file at the request time, to find or instantiate a JavaBean,
to forward a request to a new page, to generate a browser-specific code, etc.
65. The JSP standard actions affect the overall runtime behavior of a JSP page and also the
response sent back to the client.

Action element Description

<jsp:useBean> Makes a JavaBeans component available in a page

<jsp:getProperty Gets a property value from a JavaBeans component and adds it


to the response

<jsp:setProperty> Sets a JavaBeans component property value

<jsp:include> Includes the response from a servlet or JSP page during


the request processing phase

KNSIT Page 108


<jsp:forward> Forwards the processing of a request to servlet or JSP page

<jsp:param> Allows us to pass a name and value pair as parameter to a


dynamic resource, while including it in a JSP page or forwarding
a request from a JSP page to another JSP page.

<jsp:plugin> Generates HTML that contains the appropriate browser-


dependent elements (OBJECT or EMBED) needed to execute an
applet with the Java Plug-in software

include directive tag include action tag

1. It inserts the given page and includes 3. The include action tag is used to
the content in the generated servlet included the response generated by
page during the translation phase of executing the specified JSP page or
JSP lifecycle. servlet.
2. In general, the include directive is 4. The response is included during the
used to include files, such as HTML, request processing phase, when the
JSP, XML or simple.txt file into JSP page is requested by the user.
page statically.
Example for <jsp:include>
<HTML>
<BODY>
Going to include hello.jsp...<BR>
<jsp:include page="1.jsp"/>
</BODY>
</HTML>

Example for <jsp:forward> File name : checkmemory.jsp

<html>
<%
double freeMemory = Runtime.getRuntime().freeMemory();
double totalMemory = Runtime.getRuntime().totalMemory();
double percent = freeMemory/totalMemory;
if(percent<0.5)
{
%>

KNSIT Page 109


<jsp:forward page="one.jsp"/>
<%
}
else
{
%>
<jsp:forward page="two.html"/>
<% } %>
</html>

One.jsp
<html>
<body>
<font color="red">
Virtual Memory usage is less than 50 percent
</font>
</body>
</html>

Two.jsp
<html>
<body>
<font color="red">
Virtual Memory usage is greater than 50 percent
</font>
</body>
</html>

Jsp:param
1. The jsp:param tag allows us to pass a name and value pair as parameter to a dynamic
resource, while including it in a JSP page or forwarding a request from a JSP page to
another JSP page.
Syntax : <jsp : param attributes />
2. The name Attribute : The name attribute specifies the parameter name and takes a case-
sensitive literal string. The parameter name should be unique.
3. The value Attribute : The value attribute specifies the parameter value and takes either a
case-sensitive literal String or an expression that is evaluated in the request handling
stage of the JSP life cycle.
4. snippet for <jsp:param>

KNSIT Page 110


5. <jsp: include page=/MyPage2.jsp>
6. <jsp:param name=uname value=user1 />
7. <jsp:param name=user_type value=admin />
8. </jsp:include>

jsp:useBean
1. This action allows to use java bean in a JSP page.
2. This action instantiates or locates a Bean with a specific name and scope.
<jsp:useBean attributes>
.
</jsp:useBean>
3. Attributes of <jsp:useBean> tag :
4. Attributes add extra characteristics to a tag.
5. id represents the variable name assigned to the id attribute of the jsp:useBean tag.
6. Used to locate an existing bean instance in the appropriate scope specified in the
jsp:useBean action tag.
7. It is case sensitive.
scope represents the scope in which the bean instance has to be located or created.
1. Scopes can be page, request, session and application. Default scope is page.
2. page scope indicates bean can be used within the JSP page. (stored in
the PageContext of the current page).
3. request scope indicates that the bean can be used from any JSP page that is
processing the same request, until a JSP page sends a respond to the client. (stored in the
ServletRequest object).
4. session scope - A value of session indicates that the object is available to all pages
during the life of the current HttpSession. The page in which we create the bean must
have a page directive with session=true.application scope indicates that the bean can
be used from any JSP
page in the same application as the JSP page that created
KNSIT Page 111
5. class accepts the qualified class name to create a bean instance if the bean instance is
not found in the given scope.
6. beanName accepts a qualified class name or an expression that resolves to a qualified
class name or serialized templets.

<jsp:useBean id="mybean"
class="com.sun.corba.se.spi.activation._ActivatorStub"
scope="session"/>
<jsp:useBean id="mybean"
beanName="com.sun.corba.se.spi.activation._Activato
rImplBase"/>
<jsp:useBean id="mybean"
class="com.sun.corba.se.spi.activation._ActivatorStub"
scope="session"
type="com.sun.corba.se.spi.activation._ActivatorImplB
ase"/>
<jsp:useBean id="mybean"scope="session"
type="com.sun.corba.se.spi.activation._ActivatorImplB
ase"/>
jsp:setProperty
1. This action tag sets the value of a property in a bean, using the beans
setter methods.
2. The bean must be instantiated before using this tag.
3. The name attribute of the bean must be same as the reference variable name of the bean
instance.
1. <jsp:setProperty> tag contains four attributes :
2. name : take the name of the already existing bean as a reference
variable to invoke the setter method.

KNSIT Page 112


3. property : takes property name that has to set, and specifies the setter method that has
to be invoked.
4. usage ->1. * matches all the properties of a bean with the request parameter names.
2. for specific name, specify it with a value for property.
1. value : accepts the value as the string type or as an expression that is evaluated at run
time.
2. param : the param attribute is used to specify the name of the request parameter whose
value we want to assign to a bean property.
<jsp:setProperty property="*" name="name of the reference variable" />
<jsp:setProperty property="property name" name="name of the reerence variable"
value="property value as string"/>
<jsp:setProperty property="property name" name=" reference variable name" param="
request parameter name" />

Jsp:getProperty
3. This tag gets the value of a property in a bean by using the beans
getter methods and writes the value to the current Jsp Writer.
syntax : <jsp:getProperty attributes />
4. name : This attribute takes the reference variable name on which we
want to invoke the getter method.
5. property : This attribute gets the value of a bean property and invokes
the getter method of the bean property.
<jsp:setProperty name=mybean property=uname />

jsp:plugin
1. This action tag provides easy support for including a java applet or bean in the client web
browser, using a built-in or downloaded java plug-in.
2. The attributes of the jsp:plugin action tag perform the following operatins:
1. specify whether the component added in the <object> tag is a bean or an applet.
2. locate the code that needs to be run.

KNSIT Page 113


3. position the object in the browser window
4. specify a URL from which to download the plug-in software.
5. pass parameter names and vales to the object.
<jsp:plugin attributes >
</jsp:plugin>

Attributes Description

Type Specifies the type of the object that needs to be presented to the browser.

Code Takes the qualified class name of the object that has to be presented

Codebase Takes the base URL where the specified class can be located.

Name Specifies the name of the instance of the bean or applet.

Archieve Specifies comma separated list of pathnames, which loctae archive files that are
preloaded with a class loader in the directory named codebase

Width Specifies the initial width, in pixels of the image

Height Specifies the initial height, in pixels of the image

Align Specifies the position of applet : botton, top, middle, left, right

Hspace Amount of space to the left and right of applet in pixels.

Vspace Amount of space to the bottom and top of applet in pixels.

KNSIT Page 114


Jreversion Specifies the version of the JRE

Nspluginurl Specifies the URL where the client can download the JRE plug-in for Netscape
Navigator.

Iepluginurl Specifies the URL where the client can download the JRE plug-in for Inter net
Explorer.

KNSIT Page 115


<jsp:plugin> tag to run a applet
import java.io.*;
import java.awt.*;
import java.util.*;
import java.applet.*;
import java.awt.event.*;
/*<Applet code="ButtonMoveApplet" height=500 width=500> </A
public class ButtonMoveApplet extends Applet {
Button move;
Random r;
public void init()
{
setLayout(null);
move = new Button("Click me");
add(move);
move.reshape(10,10,70,30);
r = new Random();
setBackground(Color.red);
setForeground(Color.yellow);
}
GRNICA

KNSIT Page 116


public void paint(Graphics g)
{
g.drawString("Welcome JSP-
Applet",100,100);
}
public boolean action(Event evt, Object
whatAction)
{
if (!(evt.target instanceof Button))
return false;
String buttonLabel = (String)whatAction;
if (buttonLabel == "Click me")
{

move.reshape(Math.abs(r.nextInt())%(size().width-
70),
Math.abs(r.nextInt())%(size().height-
30),70,30);
repaint();
}
return true;
}
}
Using a Bean in JSP
1. To declare a bean in a JSP, follow these steps

KNSIT Page 117


1. Create a bean
2. Delcare the Bean in a JSP using <jsp:useBean> tag
3. Access the Bean properties.
4. Generate Dynamic Content
5. Deploy and run the application

Creating a Bean : RegForm.java


package com.kogent.jspex;
public class RegForm implements java.io.Serializable {
private String uname, pass, repass, email, fn, ln, address;
public void setUserName(String s){uname=s;}
public void setPassword(String s){pass=s;}
public void setRePassword(String s){repass=s;}
public void setEmail(String s){email=s;}
public void setFirstName(String s){fn=s;}
public void setLastName(String s){ln=s;}
public void setAddress(String s){address=s;}
public String getUserName(){return uname;}
public String getPassword(){return pass;}
public String getRePassword(){return repass;}
public String getEmail(){return email;}
public String getFirstName(){return fn;}
public String getLastName(){return ln;}
public String getAddress(){return address;}
}//class

Declaring the Bean in a JSP : RegProcess.jsp


<%@page errorPage="Registration.html"%>
<html>
<body>
<jsp:useBean id="regform" class="com.kogent.jspex.RegForm" scope="session"/>
<jsp:setProperty name="regform" property="*"/>
<form action="RegProcessFinal.jsp"><pre> <b>
First Name : <input type="text" name="first_name"/>
Last Name : <input type="text" name="last_name"/>
Address : <input type="text" name="address"/>
<input type="submit" value="Register"/>
</b></pre></form>
</body>

KNSIT Page 118


</html>

Accessing the Bean Properties : ViewRegistrationDetails.jsp

<jsp:useBean id="regform" type="com.kogent.jspex.RegForm" scope="session"/>


<%@page errorPage="Registration.html"%>
<html>
<body>
<pre>
<b>User Name :</b> <jsp:getProperty name="regform" property="userName"/>
<b>Password :</b> <jsp:getProperty name="regform" property="password"/>
<b>Email ID :</b> <jsp:getProperty name="regform" property="email"/>
<b>First Name :</b> <jsp:getProperty name="regform" property="firstName"/>
<b>last Name :</b> <jsp:getProperty name="regform" property="lastName"/>
<b>Address :</b> <jsp:getProperty name="regform" property="address"/>
</pre>
<form method=post action="javascript:alert('The remaining process is under development');">
<input type="submit" value="Register"/>
</form>
</body>
</html>

Generating Dynamic Content within a JSP : Registration.html


<html>
<body>
<pre>
<form action="RegProcess.jsp"><pre><b>
UserName : <input type="text" name="userName"/>
Password : <input type="password" name="password"/>
RePassword : <input type="password" name="rePassword"/>
EMail ID : <input type="text" name="email"/>
<input type="submit" value="Register"/>
</b></pre></form>
</pre>
</body>
</html>

RegProcessFinal.jsp
<%@page errorPage="Registration.html"%>
<jsp:useBean id="regform" type="com.kogent.jspex.RegForm" scope="session"/>
<jsp:setProperty name="regform" property="firstName" param="first_name"/>
<jsp:setProperty name="regform" property="lastName" param="last_name"/>
<jsp:setProperty name="regform" property="address"/>

KNSIT Page 119


<html>
<body>
<pre> Your registration details are valid,
<a href="ViewRegistrationDetails.jsp">Click</a> to view Registration Details and confirm.
</pre>
</body>
</html>

Lab List Example : StudentsBean.java


package com.tutorialspoint;
public class StudentsBean implements java.io.Serializable
{
private String firstName, lastName, dept;
private int age = 0;
public StudentsBean()
{
}
public String getFirstName()
{
return firstName;
}
public String getLastName()
{
return lastName;
}
public int getAge()
{
return age;
}
public String getDept()
{
return dept;
}
public void setFirstName(String firstName)
{
this.firstName = firstName;
}
public void setLastName(String lastName)
{
this.lastName = lastName;
}
public void setAge(int age)
{

KNSIT Page 120


this.age = age;
}
public void setDept(String dept)
{
this.dept = dept;
}
}

StudeReg.html
<html>
<body><title>STUDENT'S INFORMATION'</title>
<pre>
<form action="Students.jsp"> <b>
First Name: <input type="text" name="fname"/>
Last Name : <input type="text" name="lname"/>
Age : <input type="text" name="age"/>
Department : <input type="text" name="dept"/>
<input type="submit" value="Register"/>
</b></form>
</pre>
</body>
</html>

Students.jsp
html>
<head>
<title>STUDENT INFORMATION</title>
</head>
<body>
<jsp:useBean id="students" class="com.tutorialspoint.StudentsBean" scope="session"/>
<jsp:setProperty name="students" property="firstName" param="fname" />
<jsp:setProperty name="students" property="lastName" param="lname" />
<jsp:setProperty name="students" property="age" param="age"/>
<jsp:setProperty name="students" property="dept" param="dept"/>
<p>Student First Name:
<jsp:getProperty name="students" property="firstName"/>
</p>
<p>Student Last Name:
<jsp:getProperty name="students" property="lastName"/>
</p>
<p>Student Age:
<jsp:getProperty name="students" property="age"/>
</p>

KNSIT Page 121


<p>
Student Department:
<jsp:getProperty name="students" property="dept"/>
</p>
</body>
</html>

JSP Standard Tag Library (JSTL)


1. JSTL is a collection of custom tag libraries, which provides core functionality used for
JSP documents.
2. JSTL reduces the use of scriptles in a JSP page.
3. The use of JSTL tags allows developers to use predefined tags instead of writing the java
code.
4. JSTL provides four types of tag libraries:
1. The core JSTL - used to process a jsp page in an application
2. The XML tag library used for parsing, selecting and transforming XML data in
a jsp page.
3. The format Tag library used for formatting the data used in jsp page.
4. The SQL Tag library used to access the database in a jsp page.

The Core JSTL tags:


1. The core tags are used to perform iteration, conditional processing, and also provide
support of expression language for the tags in jsp pages.
2. The core tag library can be used in a JSP page by accessing the following tag library :
<%@ taglib prefix =c uri=http://java.sun.com/jstl/core %>
1. The core tags in jsp can be accessed by using prefix c, a preferred prefix for core tab
libraries.
2. The JSTL core tags are divided into 3 categories :
1. General-purpose Tags
2. Conditional and Looping Tags
3. Networking Tags

KNSIT Page 122


General-purpose Tags:
1. It includes tags for writing the values to the output stream, retrieving, setting and
removing attributes and for catching exceptions.
2. General-purpose tags contains four tags :
1. <c:out>
2. <c:set>
3. <c:remove>
<c:catch>

<c:out > tag


1. It evaluates an expression that may be given in its value attribute or in its tag body and
the resulting value is written in the output.
Syntax : <c:out attributes> [body content] </c:out>
Attributes are:
2. value specifies the output data to be displayed.
3. escapeXml specifies whether or not the tag should ignore XML
characters.
1. If boolean escapeXML is true, then tag converts XML special characters <,>,&
to &lt, &gt, and &amp.
2. If boolean escapeXML is false, then it does not convert XML special characters.
The default value is true.
4. default takes the value to be written to output if the given value resolves to null. If
value does not resolve to null, the value specified in the value attribute is displayed.

KNSIT Page 123


Using <c:out> Tag : GetRequestData.jsp
<%@taglib uri="http://java.sun.com/jstl/core"prefix="c"%
<html>
<body>
<b>Requested URL:&nbsp;&nbsp;</b><br/>
<c:out value="${pageContext.request.requestURL}"/><b
<br/><h4>Request Path information:</h4>
<table border='1'>
<tr><th>Name</th><th>Value</th></tr>
<tr><td>HTTP Request method</td>
<td><c:out value="${pageContext.request.method}"/></t
<tr><td>Request URI</td>
<td><c:out value="${pageContext.request.requestURI}"/>
<tr><td>Context Path</td>
<td><c:out value="${pageContext.request.contextPath}"/

GRNICA

KNSIT Page 124


<tr><td>Servlet path</td>
<td><c:out value="${pageContext.request.servletPath}"/>
<tr><td>Path info</td>
<td><c:out value="${pageContext.request.pathInfo}"/><
<tr><td>Path translated</td>
<td><c:out
value="${pageContext.request.pathTranslated}"/></td><
</table><br/>
<h4>Accessing Request Parameter value:</h4>
Value of parameter <b>uname</b> is:
<b><c:out value="${param.uname}"/></b>
</body>
</html>

GRNICA

<c:set> tag
1. It allows us to set the value of a variable or property into the given scope. Syntax:
<c:set attribute> [body content ] </c:set>

KNSIT Page 125


Attributes are :
1. value specifies the value being set.
2. var specifies the name of the variable to store.
3. scope specifies the scope of the variable defined in the var
attribute. Scope can be page, request, session or application.
4. target specifies the name of the variable whose property is to be set.
5. property specifies the name of the property to be set.

<c:remove> tag
1. It allows us to remove a variable from the specified scope.
Syntax : <c:remove attributes/>
The attributes are:
1. var name of the variable to be removed
2. scope scope of the variable, scope can be page, request, session or application.
<c:catch> tag
1. It allows jsp pages tohandle exceptions that might be raised to any of the tag inside the
body of the <c:catch> tag.
syntax : <c:catch attributes> body content </c:catch>
The attributes :
1. var takes the name of the variables that stores the exception thrown.

Conditional and Looping Tags


1. It includes tags for writing if conditions, switch cases and loops.

The <c:if> tag


1. It evaluates an expression that is given in its test attribute.
2. If true, body of <c:if> is evaluated, otherwise not.
syntax <c:if attributes> body content </c:if>
The attributes are:
1. test boolean variable or expression resolving to boolean value.
2. var name of the variable to store the conditions result.
<c:if test="${param.uname==''}">

KNSIT Page 126


username cannot be empty
</c:if>

The <c:choose> tag


1. It acts like a switch statement.
2. It encloses one or more <c:when> and <c:otherwise> tag.
syntax : <c:choose> body content </c:choose>

The <c:when> tag


1. It encloses a single case within the <c:choose> tag.
2. <c:when> tag must appear inside the <c:choose> element.
syntax : <c:when attribute> body content </c:when>
Attribute:
1. test takes a boolean value. If true, the body content of <c:when> is evaluated,
otherwise skipped.

The <c:otherwise> tag


1. It is equivalent to default case in java switch statement.
2. The body content of the <c:otherwise> tag is evaluated if none of the
<c:when> conditions in the <c:choose> tag are resolved to true.
syntax : <c:otherwise> body content </c:otherwise>

The <c:forEach> tag


1. It is used to iterate over a collection of objects or as a fixed over a range of numbers.
2. A common use of <c:forEach> is to produce a HTML table containing data gathered
from a SQL query or other data source.
syntax : <c:forEach attributes > body content </c: forEach>
3. The attributes :
1. items specifies the collection (ArrayList, Map or List.var) to iterate over.
2. varStatus specifies the name of the variable that defines the status of the
variable given in the var attribute. Its optional one.

KNSIT Page 127


3. begin takes the starting index for the loop, optional one.
4. end takes the ending index for the loop, optional one.
5. step an optional increment for the loop, default value is 1.

The <c:forTokens> tag


1. It is used for looping over tokenized elements of a string.
Syntax : <c: forTokens attributes> body content </c:forTokens>
Attributes are:
1. items specifies the string to be tokenized.
2. var specifies the name of the variable into which the current iteration item has
to be set.
3. delims specifies the delimiter or delimiters which are to be tokenized.
4. varStatus defines the status of the variable given in var attributes, it is optional.
5. begin takes the starting index for the loop, optional one.
6. end - takes the ending index for the loop, optional one.
7. step provides optional increment for the loop; default value is 1.
2. Example for forEach tag
3. <%@ page contentType="text/html" %>
4. <%@ taglib prefix="c" uri="http://java.sun.com/jstl/core" %>
5. <c:forEach var="n" begin="3" end="8" >
6. <c:out value="${n}" /> <br>
7. </c:forEach>

KNSIT Page 128


Example for forTokens tag
<%@ page contentType="text/html" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jstl/core" %>
<c:set var="s" value="HK,SMG,MCA,28,70" />
<html>
<body>
<table border="1">
<tr>
<th>Name</th>
<th>Place</th>
<th>Degree</th>
<th>Age</th>
<th>Mark</th>
</tr>
<tr>
<c:forTokens items="${s}"
delims="," var="token" >
<td><c:out value="${token}" /></td>
</c:forTokens>
</tr>
</table>
<br>
</font>
</body>
</html>
GRNICA

Networking Tags
It contain tags that perform certain operations on URLs, such as
including some other web pages, encoding the URL, and redirecting
the client request.
KNSIT Page 129
1. Networking tags of JSTL contains four tags:
1. <c:import>
2. <c:url>
3. <c:redirect>
4. <c:param>

<c:import> Tag
1. This tag is used to include another resource such as another JSP or HTML page in a JSP
page.
2. The resource can either be static or dynamic.
syntax : <c: import attributes > </c:import>
Attributes are:
1. url specifies the url of the resource to include.
2. context specifies the context name in which the page has to be located, its
optional one.
3. var specifies the name of the variable into which the result has to be stored, if
specified.
4. scope specifies the scope into which the variable has to be stored.
Example for <c:import> tag : import.jsp
<%@ taglib prefix="c" uri="http://java.sun.com/jstl/core" %>
<c:import url="foreach.jsp"/>
<c:out value="Welcome to our web-site!" />

<c:url> Tag
1. It creates a URL and is added with a session ID if the user session needs to be
maintained.
syntax : <c:url attributes> [ zero or more <c:param> tags] </c:url>
Attributes are:
1. url specifies the URL to be written if required added with session ID.

KNSIT Page 130


2. context specifies the context name of another web application, required if the
URL refers to the resource in another servlet context.
3. var specifies the name of the variable into which the new rewritten URL has
to be stored.
4. scope specifies the scope of the variable defined in var attribute.
Example for <c:url> tag : url.jsp
<%@ taglib prefix="c" uri="http://java.sun.com/jstl/core" %>
<a href="<c:url value="http://localhost:8000/fortokens.jsp/>">
send</a>

<c:redirect> Tag
2. It is used to redirect a client request.
3. It is similar to sendRedirect() method.
syntax : <c:redirect attributes> [ zero or more <c:param> tag </c:redirect>
Attributes are:
4. value specifies the URL of the resource to which the request has to be redirected.
5. context specifies the context name of another web application, required if the URL
refers to the resource in another servlet context.
Example for <c:redirect> tag : redirect.jsp
6. <%@ page contentType="text/html" %>
7. <%@ taglib prefix="c" uri="http://java.sun.com/jstl/core" %>
8. <c:redirect value="http://localhost:8000/index1.html> </c:redirect>

<c:param> Tag
1. It is used to add a request parameter to the URL.
2. It also can be used in <c:url> and <c:redirect> tags.
syntax: <c:param attributes />

KNSIT Page 131


Attributes are:
1. name specifies the name of the parameter.
value specifies the parameter value
Example for <c:param> tag : params.jsp
<%@ page contentType="text/html" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jstl/core" %>
<c:redirect url="http://localhost:8000/hemanth/sample.jsp" >
<c:param name="name1" value=HK/>
</c:redirect>
sample.jsp
<%@ taglib prefix="c" uri="http://java.sun.com/jstl/core" %>
<c:out value="${param.name1}"/>

JSTL XML Tags


1. The XML tag library is used to work with XML data used in JSP pages.
2. It helps to parse and transform data used in JSP page.
3. These operations can be done by using the Xpath expression associated with an XML
document.
4. An Xpath expression includes both the relative and absolute path of XML element.
5. XML tags can be used with JSP pages after importing the following tag library by using
the following code snippet.
<%@ taglib prefix=x uri=http://java.sun.com/jsp/jstl/xml%>
1. JSTL XML tags can be categorized into following categories:
1. XML core tags
2. XML Flow Control tags
3. XML Transformation tags

KNSIT Page 132


XML core tags
1. It includes the tags for parsing XML document and performing Xpath operations.
2. XML core tags are of three types :
1. <x:parse>
2. <x:out>
3. <x:set>

The <x:parse> tag


1. This tag parses the given XML document and stores the resulted XML Document
Object Model (DOM) into the specified variable.
syntax : <x:parse attributes> [ body content] </x:parse>
Attributes are:
1. doc accepts an XML document to be parsed in the form of a string or Reader
object that locates the XML document to be parsed.
2. systemId accepts the system identifier (URI) for parsing the XML document.
3. filter accepts an org.xml.sax.XMLFilter object to be applied for the XML
document.
4. var specifies the variable name to which the parsed XML
document has to be set.
5. scope specifies the scope of the attribute.
6. varDom specifies the variable name to which the org.w3c.dom.Document
object of the parsed XML document has to be set.
7. scopeDom specifies the scope of the varDom attribute.

The <x:set> tag


1. It evaluates an XML Xpath expression and stores the result of the evaluation in a scoped
variable.
syntax : <x:set attributes/>
Attributes are:
1. select accepts an XML Xpath expression to be evaluated.

KNSIT Page 133


2. var specifies the name of the scooped variable to hold the result.
3. scope specifies the scope of the var attribute.

The <x:out> tag


1. It evaluates an XML Xpath expression and writes the result of the evaluation to the
current JspWriter.
syntax : <x:out attributes />
Attributes are:
1. select accepts an XML Xpath expression to be evaluated.
2. escapeXML accepts boolean value which describes whether the characters like
>,<, & , in the result string has to be converted to their corresponding character
entity codes. Default value is true.

XML Flow Control Tags


1. It helps to parse, access XML data, iterate over elements in an XML document, and
conditionally process JSP code fragment.
2. XML flow control tags of JSTL contains five tags:
1. <x:if>
2. <x:choose>
3. <x:when>
4. <x:otherwise>
<x:forEach>

<x:if> tag
1. It evaluates an XPath expression that is given in its select attribute.
2. If the reslting value is true, then the body of the <x:if> tag is evaluated, otherwise not.
syntax : <x:if attributes > body content </x:if>
Attributes are:
1. select takes an Xpath expression that resolves to a Boolean value
2. var takes the name of the scoped variable to store the conditions result.

KNSIT Page 134


3. scope specifies the scope of a variable.

<x:choose> tag
1. It acts similar to java switch statement.
2. It encloses one or more <x:when> tag and a <x:otherwise> tag.
syntax : <x:choose> body content </x:choose>

<x:when> tag
1. It encloses a single case within the <x:choose> tag.
syntax : <x:when attribute> body content </x:when>
Attributes :
1. select takes an Xpath expression resolving to boolean value.
2. If boolean value is true, <c:when> tags body is evaluated.

<x:otherwise> tag
1. It is equivalent to default case in java switch statement.
2. The body content of this tag is evaluated if none of the <x:when> conditions in the
<x:choose> tag are resolved to true.
Syntax : <x:otherwise> body content </x:otherwise>

<x:forEach> tag
1. It is used for looping over a list of elements obtained after obtaining
the given Xpath expression.
Syntax : <x:forEach attributes > body content </x:forEach>

Attributes are
1. select takes an Xpath expression that results a node list.
2. var specifies the name of the variable into which the current iteration item has
to be set.
3. varStatus specifies the name of the variable that lets us to know the
information about where are we in the overall iteration such as getting count,
index, knowing isFirst, isLast etc, this is optional.

KNSIT Page 135


4. begin takes the starting index for the loop, this is optional.
5. end takes the end index for the loop, optional one.
6. step specifies an optional increment for the loop, default is 1.

XML Transformation Tags


1. It provides support to transform the XML document with the given XSL stylesheet.
<x:transform > tag
1. It transforms an XML document using given XSL stylesheet.
Syntax : <x:transform attributes > [body content] </x:transform>
Attributes are :
1. doc takes an XML doc to be parsed in the form of a string or a Reader object.
2. xslt takes an XSLT stylesheet doc for transformation in the form of a string or a
Reader object.
3. docSystemId takes the system identifier for parsing XML doc.
4. xsltSystemId takes the system identifies for parsing XSLT doc.
1. var takes the variable name to which the transformed XML doc
has to be set.
2. scope specifies the scope of the var attribute.
3. result the javax.xml.transform.Result object that captures or processes the
transformation result.

<x:param> tag
1. It is used to set transformation parameters.
2. It should be used within the body of the <x:transform> tag.
syntax : <x:param attributes> [body content] </x:param>
Attributes are :
1. name takes the name of the transformation parameter.
2. value specifies the value of the transformation parameter. It is optional. Value
of the param tag can also be specified.

KNSIT Page 136


3. To use XML tags in your program you have to firstly download these jar files in your
Tomcat's "lib"folder.
4. These jar files are:
1. jstl.jar
2. resolver.jar
3. serializer.jar
4. standard.jar
5. xercesImpl.jar
6. xercesSamples.jar
7. xml-apis.jar
xalan.jar

KNSIT Page 137


user.xml
<?xml version="1.0"?>
<user>
<information>
<fname>Hemanth</fname>
<mname>kumar</mname>
<lname>M L</lname>
<age>29</age>
</information>
<information>
<fname>Sudeep</fname>
<mname>Manohar</mname>
<lname>R</lname>
<age>29</age>
</information>
</user>

KNSIT Page 138


xmlinjsp.jsp
<%@ taglib uri="http://java.sun.com/jstl/xml" prefix="
<%@ taglib uri="http://java.sun.com/jstl/core" prefix="
<html>
<head><title>Use of Core XML tags</title></head>
<body>
<h2>Example of using Core XML tags</h2>
<c:import url="http://localhost:8000/hemanth/user.xml
<x:parse xml="${user}" var="doc" />
<h3>Information of user.xml file</h3>
<x:forEach select="$doc/user/information" var="n">
First Name:<x:out select="$n/fname"/><br>
Middle Name:<x:out select="$n/mname"/><br>
Last Name:<x:out select="$n/lname"/><br>
Age: <x:out select="$n/age"/><br>
</x:forEach>
</body>
</html> GRNICA

JSTL Formatting Tags


1. It provides the support for internationalization.

KNSIT Page 139


2. It provides the formatting of data in different domains.
3. The data can be date, numbers or the time specifications in different domains.
4. The format tag library can be used in a JSP page by using the following specification:
<%@ taglib prefix=fmt uri=http://java.sun.com/jsp/jstl/fmt %>
5. Formatting tags are divided into four categories :
1. Basic Formatting tags
2. Number formatting tags
3. Date formatting tags
Time Zone tags

Basic Formatting tags


1. They are used to format the data of a jsp page.
2. These tags parse the data based on the current locale and provide support for
internationalization.

Types of basic formatting tags


1. <fmt:setLocale>
2. <fmt:setBundle>
3. <fmt:bundles>
4. <fmt:message>
5. <fmt:param>
6. <fmt:requestEncoding>

fmt:setLocale> tag
1. It stores the given locale in the locale configuration variable of the given scope.
syntax : <fmt:setLocale attributes/>
The attributes are :

KNSIT Page 140


1. value specifies the locale, which contains a string value that
contains a two-letter language code and may contain a two-letter
country code.
2. variant specifies the locale variant of the language referenced
by value attribute.
3. scope the scope into which this object has to be set.

<fmt:setBundle> tag
1. It creates a ResourceBundle object using the Locale object in the locale configuration
variable and the given base name.
2. It stores ResourceBundle object into the given variable and scope.
syntax : <fmt:setBundle attributes />
Attributes are:
1. basename specifies the resource bundle name
2. var specifies the variable name to which this resource bundle object has to be
set.
3. scope specifies the scope of the variable defined in var attribute.

<fmt:bundle> tag
1. It creates a ResourceBundle object by using the Locale object in the locale configuration
variable and the given base name.
2. It then applies to the formatting actions in its body content.
syntax : <fmt:bundle attributes> body content </fmt:bundle>
Attributes are :
1. basename specifies the resource bundle name
2. prefix specifies prefix that has to be used for the messages in this elements
body content.

<fmt:message> tag
1. It maps key to localized message and performs parameter replacements using the
resource bundle specified in bundle attribute.
Syntax : <fmt:message attributes> body content </fmt:message>
KNSIT Page 141
2. Attributes are:
1. key specifies the key that whose value has to be retrieved.
2. bundle specifies the resource bundle that has to be used to get the value of the
specified key.
3. var specifies the variable to which the retrieved message has to be stored.
4. scope specifies the scope of the variable defined in var attribute.

<fmt:param> tag
1. It is used within the <fmt:message> element.
2. This tag supplies the argument for the parametric replacement in a message.
syntax : <fmt:param attributes/>
Attributes are:
1. value specifies the value of the parameter to be passed.

<fmt:requestEncoding> tag
1. It allows to set the character encoding of a request.
2. It invokes the setCharacterEncoding() method of the ServletRequest interace to set the
character encoding of a request.
3. syntax : <fmt:requestEncoding attributes/>
4. Attributes are:
1. value represents the character encoding to be set.Character encoding is further
used to decode the request parameters.

KNSIT Page 142


Using Basic JSTL Formatting Tags
<%@taglib uri="http://java.sun.com/jstl/fmt" prefix="fm
<%@taglib uri="http://java.sun.com/jstl/core" prefix="c
This example demonstrates the basic JSTL formatting ta
<br/><br/>
Locale from client :
<b><c:out value="${pageContext.request.locale}"/></b
<fmt:setBundle basename="ApplicationResources" var=
<fmt:message key="welcome.message" bundle="${myb
<fmt:param value="${param.uname}"/>
</fmt:message> <br/></br>
<b>Now testing &lt;fmt:setLocale&gt; tag:</b><br/>
<br/><br/>

GRNICA

KNSIT Page 143


Creating a ResourceBundle with client locale and
setting it to <i>mybundle1</i> variable.<br/>
<fmt:setBundle basename="ApplicationResources"
var="mybundle1"/>
Setting the locale to <i>it</i> (italian). <br/>
<fmt:setLocale value="it"/>
Creating a ResourceBundle with <i>it</i> (italian)
locale and setting it to <i>mybundle2</i> variable.
<br/><br/>
<fmt:setBundle basename="ApplicationResources"
var="mybundle2"/>
<b>Message using <i>mybundle1</i>:</b> <br/>
<pre>
<fmt:message bundle="${mybundle1}"
key="welcome.message">
<fmt:param value="${param.uname}"/>
</fmt:message>
</pre>
<br/>

KNSIT Page 144


<b>Message using <i>mybundle2</i>:</b> <br/>
<pre>
<fmt:message bundle="${mybundle2}" key="welcome.messa
<fmt:param value="${param.uname}"/>
</fmt:message>
</pre>

ApplicationResources_en.properties
welcome.message=Welcome to internationalization <b>{0}</b> (E

ApplicationResources_en_US.properties
welcome.message=Welcome to internationalization <b>{0}</b> (U

ApplicationResources_it.properties
welcome.message=Welcome to internationalization <b>{0}</b> (I

Save these ApplicationResources.properties files u


folder.
Number Formatting Tags
1. They are used to format the number data.
2. Number Formatting includes the currency-related formatting, number parsing and
formatting and formatting percentages.

KNSIT Page 145


Types of number formatting tags
1. <fmt:formatNumber>
2. <fmt:parseNumber>

<fmt:formatNumber> tag
1. It allows us to format numbers, currencies, and percentages according to the locale or
customized formatting pattern.
syntax : <fmt:formatNumber attributes > body content </fmt:formatNumber>

Attributes are :
1. value specifies the numeric value that has to be formatted to the locale or
given pattern. It is optional.
2. type specifies the value type, accepted values are number, currency, and
percent. If not specified, takes number as default.
3. pattern specifies custom pattern to which the given value has to be formatted.
4. currencyCode specifies the currency code as per ISO 4217 that has to be used
in formatting.
5. currencySymbol specifies the currency symbol that has to be included into the
formatted number, used as type=currency.
6. groupingUsed specifies whether the formatted output should contain any
grouping separators. It is a boolean, default is true.
7. maxIntegerDigits specifies max number of digits in integer portion of
formatted output.
8. minIntegerDigits - specifies min number of digits in integer portion of formatted
output.
9. maxFractionDigits specifies max number of digits in fractional portion of the
formatted output.
10. minFractionDigits - specifies min number of digits in fractional portion of
formatted output.
11. var specifies the variable name to which the formatted value has to be stored, if
not specified, formatted value is written to JspWriter
12. scope specifies the scope of the variable defined in var attribute.

KNSIT Page 146


<fmt:parseNumber> tag
1. It allows us to parse the string representations of numbers, currencies, and percentages
formatted according to the locale or customised formatting pattern.
syntax : <fmt:parseNumber attributes > body content </fmt:parseNumber>

Attributes are:
1. value specifies the string value that has to be parsed according to the locale or
given pattern. It is optional.
2. type specifies the value type, accepted values are number, currency and
percent. Default is number.
3. pattern specifies the custom formatting pattern that determines how the given
value is to be parsed.
parseLocale specifies the Locale whose default formatting pattern is to be
used during the parse operation.
1. integerOnly specifies whether just the integer portion of the given value should
be parsed. Default is false.
2. var specifies the variable name to which the parsed value has to be stored.
3. scope specifies the scope of the variable defined in var attribute.

index.html
<html> <body>
<form method=post action="TestApp.jsp"> <pre> <b>
Number : <input type="text" name="mynumber"/>
<input type="submit" value="Format Number"/>
</b> </pre> </form>
</body> </html>

KNSIT Page 147


TestApp.jsp
<%@taglib uri="http://java.sun.com/jstl/fmt" prefix="fmt"%>
<%@taglib uri="http://java.sun.com/jstl/core" prefix="c"%>
<html> <body>
My Number:
<b><c:out value="${param.mynumber}"/></b> </br>
Formatting My Number: <br/><br/>
<fmt:setLocale value="it"/>
In Italy:
<pre>
Default pattern:<b>
<fmt:formatNumber type="currency" value="${param.mynum
Using pattern (0,00,00.0000): <b>
<fmt:formatNumber type="currency" value="${param.mynumber}
pattern="00,0,00.0000"/> </b>
</pre>
<br/>

KNSIT Page 148


In US:
<fmt:setLocale value="en_US"/>
<pre>
Default pattern:<b>
<fmt:formatNumber type="currency"
value="${param.mynumber}"/></b>
Using pattern (0,00,00.0000):<b>
<fmt:formatNumber type="currency"
value="${param.mynumber}" currencySymbol="$"
pattern="0,00,00.0000" var="fmt_mynumber"/>
<c:out value="${fmt_mynumber}"/></b>
</pre>
<br/>
After parsing the formatted mynumber:
<fmt:parseNumber value="${fmt_mynumber}"
type="currency" pattern="0,00,00.0000"/>
</body></html>
Date Formatting Tags
1. It is used to format the date type of data.
2. Types of date formatting tags
1. <fmt:formatDate>
2. <fmt:parseDate>

<fmt:formatDate> tag
1. It allows us to format dates and times according to the locale or
customized formatting pattern.

KNSIT Page 149


syntax : <fmt:formatDate attributes/>

Attributes are:
1. value specifies the java.util.Date object whose date and or time to be formatted.
2. pattern specifies the custom pattern to which the given value has to be
formatted.
3. type specifies the components of the given date object which has to be
formatted, accepted values are date, time and both.
4. dateStyle specifies the predefined formatting style for dates. Applicable only if
type is both date and time.
5. timeStyle specifies the predefined formatting style for time. Accepted values
are default, short, medium, long and full.
6. timeZone specifies a string value that may be one of the time zone IDs
supported by the java platform or a custom time zone ID, in which to represent
the formatted time.
7. var specifies the variable name to which the formatted value has to be stored.
8. scope specifies the scope of the variable defined in var attribute

<fmt:parseDate> tag
1. It allows us to parse and format the string representation of dates and times according to
the locale or customized formatting pattern.
syntax : <fmt:parseDate attributes/>

Attributes are:
1. value specifies the Date string to be parsed.
2. type specifies whether the given value contains date or time or both. Default is
date.
3. pattern specifies the custom pattern to which the given value has to be
formatted.
4. dateStyle specifies the predefined formatting style for dates. Accepted values
are default, short, medium, long and full.
5. timeStyle specifies the predefined style for times. Accepted values are default,
short, medium, long and full.

KNSIT Page 150


6. timeZone specifies a string value that may be one of the time zone IDs
supported by the java platform or a custom time zone ID
7. parseLocale specifies the Locale whose default formatting pattern is to be used
during the parse operation
8. var specifies the variable name to which the formatted value has to be stored.
If not specified, written to current JspWriter.
9. scope specifies the scope of the variable defined in var attribute.

Fmtdate.jsp
<%@taglib uri="http://java.sun.com/jstl/fmt" prefix="fmt"%>
<%@taglib uri="http://java.sun.com/jstl/core" prefix="c"%>
<html> <body>
<%pageContext.setAttribute("mydate",new java.util.Date(),PageContext.P
Current Date and Time:
<b><c:out value="${mydate}"/></b> </br>
Formatting Date: <br/><br/>
<fmt:setLocale value="it"/>
In Italy:
<pre>
Default pattern:<b>
<fmt:formatDate type="both" value="${mydate}"/></b>
Using pattern (dd-MMM-yyyy hh:mm:ss): <b>
<fmt:formatDate type="both" value="${mydate}" pattern="dd-MMM-yyy
</b>
</pre>
<br/>

KNSIT Page 151


In US:
<fmt:setLocale value="en_US"/>
<pre>
Default pattern:<b>
<fmt:formatDate type="both" value="${mydate}"/></b>
Using pattern (dd-MMM-yyyy hh:mm:ss): <b>
<fmt:formatDate type="both" value="${mydate}"
pattern="dd-MMM-yyyy hh:mm:ss"
var="fmt_mydate"/> </b>
<c:out value="${fmt_mydate}"/></b>
</pre>
<br/>
After parsing the formatted mydate: <fmt:parseDate
value="${fmt_mydate}" type="both"
pattern="dd-MMM-yyyy hh:mm:ss"/>
</body></html>
Time Zone Formatting Tags
1. They are used to format the time zone type of data.

Types of Time Zone Formatting Tags


1. <fmt:timeZone>
2. <fmt:setTimeZone>

<fmt:timeZone> Tag
1. The body content of this tag specifies the tags that will be controlled by the time zone
specified in <fmt:timeZone> tag.
Syntax : <fmt:timeZone attributes > body content </fmt:timeZone>
Attributes are:

KNSIT Page 152


value specifies the java.util.TimeZone object or a string that Represents a time
zone ID.

<fmt:setTimeZone> tag
1. This tag stores the given time zone in time zone configuration variable of the
given scope.
syntax : <fmt:setTimeZone attributes/>
Attributes are:
2. value specifies a string value that may be one of the time zone IDs supported
by the java platform or a custom time zone ID.
3. var specifies the variable name.
4. scope specifies the scope into which this object has to be set.
5. represents a time zone ID.

KNSIT Page 153


Fmttime.jsp
<%@taglib uri="http://java.sun.com/jstl/fmt" prefix="fmt"%>
<%@taglib uri="http://java.sun.com/jstl/core" prefix="c"%>
<html> <body>
<%pageContext.setAttribute("mydate",new
java.util.Date(),PageContext.PAGE_SCOPE);%>
Current Date and Time:
<b><c:out value="${mydate}"/></b> </br>
Formatting Date based on Time Zone: <br/><br/>
GMT:
<pre>
<b><fmt:timeZone value="GMT">
<fmt:formatDate type="both" value="${mydate}"/>
</fmt:timeZone></b>
</pre>
<br/>

KNSIT Page 154


6 hours 30 minutes ahead of GMT :
<pre>
<b><fmt:timeZone value="GMT+06:30">
<fmt:formatDate type="both"
value="${mydate}"/>
</fmt:timeZone></b>
</pre>
<br/>
10 hours 30 minutes behind the GMT :
<pre>
<b><fmt:timeZone value="GMT-10:30">
<fmt:formatDate type="both"
value="${mydate}"/>
</fmt:timeZone></b>
</pre>
</body></html>

JSTL SQL Tags


1. The SQL tag library is used to access the relational database used in the JSP pages.
2. SQL tag libraries can be accessed in a jsp page by importing the following tag library in
JSP page :
1. <%@ taglib prefix=sql uri=http://java.sun.com/jsp/jstl/sql%>

The <sql:query> Tag


1. The <sql:query> tag executes the query specified in the sql attribute or in the tag body.
Then result is stored in variable specified in var attribute.
2. Syntax : <sql:query attributes >[body content] </sql:query>
Attributes are:

KNSIT Page 155


1. sql specifies the sql query that has to be executed, optional, can be executed in tag
body. SQL query can be parameterized.
2. var sepcifies the variable to wich result of query is set.
3. scope specifies the scope of the variable.
4. dataSource specifies the datasource JNDI name or java.sql.DataSource object.
5. maxRows specifies the max number of rows that has to be included in result.
6. startRow specifes the starting row number.

The <sql:update> Tag


1. The <sql:update> tag executes a SQL statement specified in the sql attribute for in the
tag body.
1. Syntax : <sql:update attributes > [body content] </sql:update>
Attribute are:
1. sql specifies the update SQL statement that has to be executed.
2. var specifies the variable name to which the result has to be set.
3. scope specifies the scope of the variable.
4. dataSource specifies the datasource JNDI name or java.sql.DataSource object.

The <sql:param> Tag


1. This tag is used to set a parameter in the SQL statement.
2. Syntax : <sql:param attributes> [parameter value] </sql:param>
3. Attributes are :
1. value specifies the parameter value that has to be substituted in the SQL
statement.

The <sql:dateParam> Tag


1. This tag is used to set a Date parameter in the SQL statement.
2. Syntax : <sql:dateParam attributes/>
3. Attributes are :
1. value specifies the date parameter value that has to be
substituted in the SQL statement.
2. type takes either date or time or timestamp.

The <sql:setDataSource> Tag


1. This tag binds a datasource to the specified variable.
2. Syntax : <sql:setDataSource attributes/>
3. Attributes are :
1. dataSource specifes the datasource JNDI name or
java.sql.DataSource object.
2. driver specifies the JDBC driver class name
3. url specifies the JDBC URL referring to database
4. user specifies the database username

KNSIT Page 156


5. password specifies the database password
6. var specifies the name of the variable to which the DataSource
object has to be set.
7. scope specifies the scope of the variable.

The <sql:transaction> Tag


1. This tag is used to specify a data source that we can use with the
transaction.
2. The <sql:transaction> tag groups <sql:update> and <sql:query> in its
body part into a transaction.
3. Syntax : <sql:transaction attributes>
[<sql:query> | <sql:update>] + </sql:transaction>
1. Attributes are :
1. dataSource specifes the datasource JNDI name or java.sql.DataSource object
to be used with this transaction.
2. isolation specifes the possible values for isolation attribute are
READ_COMMITTED, READ_UNCOMMITTED,
REPEATABLE_READ, or SERIALIZABLE.

Using SQL Tags : GetEmpDetails.jsp


<%@taglib uri="http://java.sun.com/jstl/sql" prefix="sql"%>
<%@taglib uri="http://java.sun.com/jstl/core" prefix="c"%>
<sql:setDataSource driver="com.mysql.jdbc.Driver"
url="jdbc:mysql://localhost:3306/sample"
user="root"
password="hemanth" var="myds" scope="request"/>
<sql:query sql="select * from emp" var="result" scope="page"
dataSource="${requestScope.myds}"/>
<html> <body>
<table border="1">
<tr>
<c:forEach items="${pageScope.result.columnNames}" var="colname">
<th><c:out value="${colname}"/></th>
</c:forEach>
<th>&nbsp;</th>
</tr>
<c:forEach items="${pageScope.result.rows}" var="row">
<tr> <td>
<c:out value="${row.empno}"/>
</td> <td>
<c:out value="${row.deptno}"/>
</td> <td>
<c:out value="${row.ename}"/>

KNSIT Page 157


</td> <td>
<c:out value="${row.sal}"/>
</td> <td>
<a href= "RemoveEmp.jsp?empno=<c:out
value="${row.empno}"/>">
Remove</a> </td> </tr>
</c:forEach>
</table>
</body> </html>

Using SQL Tags : RemoveEmp.jsp


<%@taglib uri="http://java.sun.com/jstl/core" prefix="c"%>
<%@taglib uri="http://java.sun.com/jstl/sql" prefix="sql"%>
<sql:setDataSource driver="com.mysql.jdbc.Driver"
url="jdbc:mysql://localhost:3306/sample"
user="root"
password="root" var="myds" scope="request"/>
<sql:update dataSource="${requestScope.myds}" sql="delete from emp where empno=?"
var="count">
<sql:param value="${param.empno}"/>
</sql:update>
<c:if test="${count eq 1}">
<b>Employee Removed</b>
</c:if>
<c:if test="${count ne 1}">
<b>Problem in removing Employee</b>
</c:if>
<br/>
<a href="GetEmpDetails.jsp">View Employees</a>

JSP Custom Tags


1. A custom tag is a user-defined JSP language element.
2. JSP tag extensions lets us to create new tags that we can insert directly into a Java
Server Page.
3. The JSP 2.0 specification introduced Simple Tag Handlers for writing these custom
tags.
4. To write a custom tag we can simply extend SimpleTagSupport class and override the
doTag() method, where we can place our code to generate content for the tag.
5. JSP custom tags enable you to perform various functions, such as:
1. Accessing all implicit variables of a JSP page, such as request,
response, in, and out.
2. Modifying the response generated by a calling JSP page.
3. Initializing and instantiating a JavaBean component.

KNSIT Page 158


Types of Custom Tags
1. The various types of custom tags that you can develop in JSP are :
2. Empty tags:
1. Refer to the custom tags that do not have any attribute or
body. The following code snippet shows an empty custom tag:
<td:welcome />

1. Tags with a body:


1. Refer to the custom tag within which you can define nested custom tags,
scripting elements, actions, HTML text, and JSP directives.
<td: welcome>
<%=today_date%>
</td:welcome>

1. Tags with attributes:


1. Refer to custom tags for which you can define attributes to customize the
behavior of the custom tag.
<td: welcome color=?blue?> </td:welcome>

1. Nested tags:
1. Refer to the set of custom tags in which one custom tag
encloses one or more custom tags. The following code snippet
shows a nested custom tag:
<td1:ifTag condition ?<%=eval>? >
<td2:valueTrue>
The expression evaluates to true
</td2:valueTrue>
</td1:ifTag>/font>

Development of Custom Tag :


1. To develop a custom tag, you need to perform following steps:
1. Develop a tag handler or class file(.java)
2. Develop the Tag Library Descriptor (TLD) file
3. Include the Tag Library in a JSP page
4. Deploy the application

Empty Tag:
1. Assume we want to define a custom tag named <ex:Hello> and we
want to use it in the following fashion without a body:
1. <ex:Hello />
2. To create a custom JSP tag, we must first create a Java class that acts
as a tag handler.

KNSIT Page 159


package com.jnnce;
import javax.servlet.jsp.tagext.*;
import javax.servlet.jsp.*;
import java.io.*;
public class HelloTag extends SimpleTagSupport
{
public void doTag() throws JspException, IOException {
JspWriter out = getJspContext().getOut();
out.println("Hello Custom Tag!");
}
}

Create following tab library file: \tomcat\webapps\<directory>\WEB-


INF\custom.tld.
<taglib>
<tlib-version>1.0</tlib-version>
<jsp-version>2.0</jsp-version>
<short-name>Example TLD</short-name>
<tag>
<name>Hello</name>
<tag-class>com.jnnce.HelloTag</tag-class>
<body-content>empty</body-content>
</tag>
</taglib>

Use the defined custom tab in a jsp file.


<%@ taglib prefix="ex" uri="WEB-INF/custom.tld"%>
<html>
<head>
<title>A sample custom tag</title>
</head>
<body>
<ex:Hello/>
</body>
</html>

Accessing the Tag Body:


1. You can include a message in the body of the tag like standard tags.
2. Assume you want to define a custom tag named <ex:Hello> and
you want to use it in the following fashion with a body:

KNSIT Page 160


<ex:Hello>
This is message body
</ex:Hello>

package com.jnnce;
import javax.servlet.jsp.tagext.*;
import javax.servlet.jsp.*;
import java.io.*;
public class HelloTag1 extends SimpleTagSupport
{
StringWriter sw = new StringWriter();
public void doTag() throws JspException, IOException
{
getJspBody().invoke(sw);
getJspContext().getOut().println(sw.toString());
}
}
<taglib>
<tlib-version>1.0</tlib-version>
<jsp-version>2.0</jsp-version>
<short-name>Example TLD with Body</short-name>
<tag>
<name>Hello</name>
<tag-class>com.jnnce.HelloTag1</tag-class>
<body-content>scriptless</body-content>
</tag>
</taglib>
<%@ taglib prefix="ex" uri="WEB-INF/custom1.tld"%>
<html>
<head>
<title>A sample custom tag</title>
</head>
<body>
<ex:Hello>
This is message body
</ex:Hello>
</body>
</html>

Custom Tag Attributes


1. You can use various attributes along with your custom tags.
2. To accept an attribute value, a custom tag class needs to implement
setter methods, identical to JavaBean setter methods.

KNSIT Page 161


package com.jnnce;
import javax.servlet.jsp.tagext.*;
import javax.servlet.jsp.*;
import java.io.*;
public class HelloTag2 extends SimpleTagSupport
{
private String message;
public void setMessage(String msg)
{
this.message = msg;
}
StringWriter sw = new StringWriter();
public void doTag() throws JspException, IOException
{
if (message != null)
{
/* Use message from attribute */
JspWriter out = getJspContext().getOut();
out.println( message );
}
else
{
/* use message from the body */
getJspBody().invoke(sw);
getJspContext().getOut().println(sw.toString());
}
}
}
<taglib>
<tlib-version>1.0</tlib-version>
<jsp-version>2.0</jsp-version>
<short-name>Example TLD with Body</short-name>
<tag>
<name>Hello</name>
<tag-class>com.jnnce.HelloTag2</tag-class>
<body-content>scriptless</body-content>
<attribute>
<name>message</name>
</attribute>
</tag>
</taglib>
<%@ taglib prefix="ex" uri="WEB-INF/custom2.tld"%>
<html>

KNSIT Page 162


<head>
<title>A sample custom tag</title>
</head>
<body>
<ex:Hello message="This is custom tag" />
</body>
</html>

Nested Custom Tags in JSP


package mca;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.tagext.SimpleTagSupport;
public class MenuTag extends SimpleTagSupport
{
private List<MenuItemTag> menuItems = new ArrayList<MenuItemTag>();
private String prefix;
public String getPrefix()
{
return this.prefix;
}
public void setPrefix(String prefix)
{
this.prefix = prefix;
}
public void addMenuItem(MenuItemTag tag)
{
menuItems.add(tag);
}
public void doTag() throws JspException, IOException
{
getJspBody().invoke(null);
JspWriter out = getJspContext().getOut();
out.println("<table border='1'>");
for(MenuItemTag tag : menuItems)
{
out.println(String.format("<tr><td>%s==%s</td></tr>", this.getPrefix(),
tag.getValue()));

KNSIT Page 163


}
out.println("</table>");
}
}
package mca;
import java.io.IOException;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.tagext.SimpleTagSupport;
public class MenuItemTag extends SimpleTagSupport
{
private String value;
public void setValue(String value)
{
this.value = value;
}
public String getValue() {
return this.value;
}
public void doTag() throws JspException, IOException
{
MenuTag parent = (MenuTag)getParent();
if(parent != null) {
parent.addMenuItem(this);
}
}
}

JSP file
<%@ taglib uri="WEB-INF/menus.tld" prefix="myTags" %>
<html>
<head>
<title>Nested Custom Tags</title>
</head>
<body>
<myTags:Menu prefix="Out">
<myTags:MenuItem value="01" />
<myTags:MenuItem value="02" />
<myTags:MenuItem value="03" />
<myTags:MenuItem value="04" />
</myTags:Menu>
</body>
</html>
.tld file : menus.tld

KNSIT Page 164


<taglib>
<tlib-version>1.2</tlib-version>
<jsp-version>2.0</jsp-version>
<tag>
<name>Menu</name>
<tag-class>mca.MenuTag</tag-class>
<body-content>scriptless</body-content>
<attribute>
<name>prefix</name>
<required>true</required>
<rtexprvalue>true</rtexprvalue>
</attribute>
</tag>
<tag>
<name>MenuItem</name>
<tag-class>mca.MenuItemTag</tag-class>
<body-content>empty</body-content>
<attribute>
<name>value</name>
<required>true</required>
<rtexprvalue>true</rtexprvalue>
</attribute>
</tag>
</taglib>

END OF JSP

KNSIT Page 165


6:Java Beans
What is a Java Bean?
1. A Java Bean is a software component that has been designed to be reusable in variety of
different environments.
2. There is no restriction on the capability of a Bean. It may perform a simple function,
such as spelling check of a document, or a complex function such as forecasting the
performance of a stock portfolio.
3. A Bean may be visible to an end user (ex. A button)
4. A Bean may be invisible to a user (ex. Software to decode a stream of multimedia
information in a real time)
5. A Bean may be designed to work autonomously on a users workstation or to work in
cooperation with a set of other distributed components.

Advantages of Java Beans


1. A Bean obtains all the benefits of Javas write-once, run-anywhere paradigm.
2. The properties, events, and methods of a Bean that are exposed to an application
builder tool can be controlled.
KNSIT Page 166
3. A Bean may be designed to operate correctly in different locales, which makes it useful
in global markets.
4. Auxiliary software can be provided to help a person configure a Bean. This software is
only needed when the design-time parameters for that component are being set.
5. The configuration settings of a Bean can be saved in persistent storage and restored at a
later time.
A Bean may register to receive events from other objects and can generate events that are sent
to other objects

The Java Beans API


1. The Java Beans functionality is provided by a set of classes and interfaces in the
java.beans package.
Class Introspector
2. The Introspector class provides a standard way for tools to learn about the properties,
events, and methods supported by a target Java Bean.
3. For each of those three kinds of information, the Introspector will separately analyze the
bean's class and superclasses looking for information and use that information to build a
BeanInfo object that describes the target bean.
For each class "Foo", explicit information may be available if there exists a
corresponding "FooBeanInfo" class that provides a non-null value when queried for the
information.
1. If a class provides explicit BeanInfo about itself then we add that to the BeanInfo
information we obtained from analyzing any derived classes.
2. We then proceed to analyze the class's superclass and add in the information from it.
3. decapitalize(String name) : Utility method to take a string and convert it to normal Java
variable name.
4. flushCaches() : Flush all of the Introspector's internal caches.
5. flushFromCaches(Class classname) : Flush the Introspector's internal cached
information for a given class.
6. getBeanInfo(Class beanClass) : Introspect on a Java Bean and learn about all its
properties, exposed methods, and events.

KNSIT Page 167


7. getBeanInfo(Class beanClass, Class stopClass) : Introspect on a Java bean and learn all
about its properties, exposed methods, below a given "stop" point.
8. getBeanInfo(Class beanClass, int flags) : Introspect on a Java bean and learn about all
its properties, exposed methods, and events, subject to some control flags.
9. getBeanInfoSearchPath() : Gets the list of package names that will be used for finding
BeanInfo classes.
10. setBeanInfoSearchPath(String[] path) : Change the list of package names that will be
used for finding BeanInfo classes.

Class PropertyDescriptor
1. A PropertyDescriptor describes one property that a Java Bean exports via a pair of
accessor methods.
2. createPropertyEditor(Object bean) : Constructs an instance of a property editor using
the current property editor class.
3. equals(Object obj) : Compares this PropertyDescriptor against the specified object.
4. getPropertyEditorClass() : Gets any explicit PropertyEditor Class that has been
registered for this property.
5. getPropertyType() : Gets the Class object for the property.
6. getReadMethod() : Gets the method that should be used to read the property value.
7. getWriteMethod() : Gets the method that should be used to write the property value.
8. hashCode() : Returns a hash code value for the object.
9. isBound() : Updates to "bound" properties will cause a "PropertyChange" event to get
fired when the property is changed.
10. isConstrained() : Attempted updates to "Constrained" properties will cause a event to
get fired when the property is changed.
11. setBound(boolean bound) : Updates to "bound" properties will cause a
"PropertyChange" event to get fired when the property is changed.
12. setConstrained(boolean constrained) : Returns the class for the desired PropertyEditor.
Normally, property editors will be found using the property editor manager.

KNSIT Page 168


13. setPropertyEditorClass(Class propertyEditorClass) : Normally PropertyEditors will be
found using the PropertyEditorManager.
14. setReadMethod(Method readMethod) : Sets the method that should be used to read the
property value.
15. setWriteMethod(Method writeMethod) : Sets the method that should be used to write
the property value.

Class EventSetDescriptor
1. An EventSetDescriptor describes a group of events that a given Java bean fires.
2. getAddListenerMethod() : Gets the method used to add event listeners.
3. getGetListenerMethod() : Gets the method used to access the registered event listeners.
4. getListenerMethodDescriptors() : Gets the MethodDescriptors of the target listener
interface.
5. getListenerMethods() : Gets the methods of the target listener interface.
6. getListenerType() : Gets the Class object for the target interface.
7. getRemoveListenerMethod() : Gets the method used to remove event listeners.
8. isInDefaultEventSet() : Reports if an event set is in the "default set.
9. isUnicast() : Normally event sources are multicast.
10. setInDefaultEventSet(boolean inDefaultEventSet) : Marks an event set as being in the
"default" set (or not).
11. setUnicast(boolean unicast) : Mark an event set as unicast (or not)

Class MethodDescriptor
1. A MethodDescriptor describes a particular method that a Java Bean supports for
external access from other components.
2. getMethod() : Gets the method that this MethodDescriptor encapsualtes.
3. getParameterDescriptors() : Gets the ParameterDescriptor for each of this
MethodDescriptor's method's parameters.

A Bean Example

KNSIT Page 169


import java.beans.BeanInfo;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
public class IntrospectorTest
{
private static final String PROP_NAME = "testProperty";
public static void main(String[] args)
{
try
{
Introspector.flushCaches();
BeanInfo beanInfo = Introspector.getBeanInfo(TestSubclass.class);
PropertyDescriptor[] propDescriptors =
beanInfo.getPropertyDescriptors();
for (PropertyDescriptor descr : propDescriptors)
{
if (descr.getDisplayName().contains(prop_name))
{
System.out.println("Getter for property: " + descr.getName() + " =
" + descr.getReadMethod());
System.out.println("Setter for property :" + descr.getName() + " =
" + descr.getWriteMethod());
System.out.println("Property Type:" + descr.getName()+ " = " +
descr.getPropertyType());
System.out.println("Property Editor Class:" + descr.hashCode());
System.out.println("Property Editor Class:" +
descr.isConstrained());
System.out.println("Property Editor Class:" + descr.isBound());
}

}
} catch (Exception e)
{

e.printStackTrace();
}
}

public class TestSubclass extends TestSuperclass


{
private boolean testProperty;
public boolean isTestProperty()
{

KNSIT Page 170


return testProperty;
}
public void setTestProperty(boolean testProperty)
{
this.testProperty = testProperty;
}
}

public class TestSuperclass


{
private boolean testProperty;
public boolean getTestProperty()
{
return testProperty;
}
public void setTestProperty(boolean testProperty)
{
this.testProperty = testProperty;
}
}
}

JSP with Java beans

<html>
<head>
<title>Login</title>
</head>
<body>
<P>
<form action="Welcome.jsp" method=Post>
Enter Login ID: <input type=Text name="id" >
<P>
Enter Password: <input type=Password name="pwd"">
<P>
<input type="Submit" value="Login">
<input type="Reset" >
</form>
</body>
</html>
<jsp:useBean id="login" class="jnnce.Login" scope="session"/>
<jsp:setProperty name="login" property="*"/>
<html>

KNSIT Page 171


<head>
<title>WELCOME</title>
<body>
<% if (login.checkCredentials())
{ %>
Welcome <%=request.getParameter("id") %> !
<% } else { %>
Invalid credentials.
<% } %>
</body></html>
package jnnce;
public class Login
{
private String id;
private String password;
public void setId(String value)
{
id=value;
}
public void setPwd(String value)
{
password=value;
}
public boolean checkCredentials()
{
if("hemanth".equalsIgnoreCase(id) &&
"kumar".equalsIgnoreCase(password))
{
return true;
}
else
{
return false;
}
}
}
END OF JAVA BEANS
7:ENTERPRISE JAVA BEANS
The J2EE architecture consists of components that together enable developers to build
a robust,industrial-strength application.

KNSIT Page 172


1. JSP, Java Servlets and EJB form the nucleus of J2EE application.
2. A J2EE application uses a browser-based user interface composed of a web page.
3. An HTML form collects information from a user and formulates a request for web
services, which is passed to the server-side component.
4. The server side component is written in either Java servlet or JSP.
A java servlet or JSP perform a intermediary function, a Java servlet or JSP receive a request
for web service from a client and fulfil the request by calling other server-side components that
contain the business logic needed to comply with part or all of the request

Enterprise JavaBeans
1. An EJB is a component of the J2EE architecture that primarily provides business logic
to a J2EE application and interacts with other server-side J2EE components.
2. The nature of the business logic and the interactions with other| server-side J2EE
components are dependent on the J2EE application.
3. An EJB is written in the Java programming language.

The EJB Container


1. An EJB container is a vendor-provided entity located on the EBJ server that manages
system-level services for EJB.
2. The EJB container is one of several containers, each of which handles a J2EE
component such as a Java servlets or JSP.
An EJB container provides a reusable pool of distributed components. Each EJB must be
installed in an EJB container
EJB Classes
1. Types of EBJ
1. Entity JavaBean class (entity bean) : used to represent business data.
2. Session JavaBean class (session bean) : used to model a business process.
Message-Driven JavaBean class ( message-driven bean) : used to receive messages from a JMS
(Java
Message Service) resource

EJB Interface

KNSIT Page 173


1. The session and entity beans must have two interfaces.
2. These are Home interface and the Remote interface.
3. Both interfaces are declared by the developer of the EJB and are implemented by the
EJB container.
4. The Home interface must extend the EJBHome interface.

When to Use Enterprise Beans


1. You should consider using enterprise beans if your application has any of the following
requirements:
The application must be scalable. To accommodate a growing number of users,
you may need to distribute an application's components across multiple
machines. Not only can the enterprise beans of an application run on different
machines, but their location will remain transparent to the clients.
1. Transactions are required to ensure data integrity. Enterprise beans support
transactions, the mechanisms that manage the concurrent access of shared
objects.
2. The application will have a variety of clients. With just a few lines of code, remote
clients can easily locate enterprise beans. These clients can be thin, various, and
numerous.

Deployment Descriptors
1. A deployment descriptor describes how EJBs are managed at runtime and enables the
customization of EJB behavior without modification to the EJB code.
2. A deployment descriptor is written in a file using XML syntax.
3. A dd file is packed in the Java Archive (JAR) file along with the other files that are
required to deploy the EJB. It includes classes and component interfaces that are
necessary for each EJB in the package.
4. An EJB container references the deployment descriptor file to understand how to deploy
and manage EJBs contained in package.
5. The dd identifies the types of EJBs that are contained in the package as well as other
attributes, such as how transactions aremanaged.
Dd are used in EJB1.1 and EJB2.0 are nearly same with two changes. (<local> & <local-home>
not found in EJB1.1)

KNSIT Page 174


<!DOCTYPE ejb-jar PUBLIC "~//Sun Microsystems, Inc. //DTD EnterpriseJavaBeans 2.0//EN"
"http://java/sun/com/dtd/ejb-jar_2_0/dtd">

<ejb-jar>
<enterprise-beans>
<entity>
<ejb-name>myEJB</ejb-name>
<home>com.jimkeogh.ejb.MyEJBHome</home>
<remote>com.jimkeogh.ejb.MyEJBRemote</remote>
<local-home>com.jimkeogh.ejb.MyEJBHomeLocal</local-home>
<local>com.jimkeogh.ejb.MyEJBLocal</local>
<ejb-class>com.jimkeogh.ejb.MyEJB</ejb-class>
<peristence-type>Container</persistence-type>
<prim-key-class>java.lang.String</prim-key-class>
<reentrant>False</reentrant>
</entity>
</enterprise-beans>
</ejb-jar>

Session Java Bean

1. A Session bean contains business logic used to provide a service to a client and exists
for the duration of the client server session.
2. A session bean terminates once the session with the client server terminates.
3. A session bean can be stateless or stateful. A stateless session bean doesnt retain state
between method calls and typically performs business logic that doesnt require data to
be maintained during the session.
4. A stateful session bean retains data(state) between method calls with a client during a
session.
When calls are made to multiple methods, the stateful session bean is able to retain state
between calls
1. The session bean can implement the SessionSynchronization interface, which makes the
container notify the session bean of transaction-related events.
2. If implemented, the container will notify the bean of three transactional events:
beforeBegin(), beforeCompletion(), and aferCompletion(boolean committed).

KNSIT Page 175


Though a stateful bean retains state during a session, a session bean by its nature is not
persistent, transitional state is maintained for the life of the session

KNSIT Page 176


Data flow
KNSIT Page 177
Application component

When to Use Session Beans


1. In general, you should use a session bean if the following circumstances hold:
At any given time, only one client has access to the bean instance.

2. The state of the bean is not persistent, existing only for a short period of time (perhaps a few
hours).
3. Stateful session beans are appropriate if any of the following conditions are true:
The bean's state represents the interaction between the bean and a specific client.

4. The bean needs to hold information about the client across method invocations.
5. The bean mediates between the client and the other components of the application, presenting
a simplified view to the client.
6. Behind the scenes, the bean manages the work flow of several enterprise beans.
7. Stateless session beans are appropriate if any of the following conditions are true:
8. The bean's state has no data for a specific client.
9. In a single method invocation, the bean performs a generic task for all clients. For example, you
might use a stateless session bean to send an e-mail that confirms an online order.
10. The bean fetches from a database a set of read-only data that is often used by clients. Such a
bean, for example, could retrieve

KNSIT Page 178


the table rows that represent the products that are on sale this
month.
Creating a Session Java Bean
1. A session bean in a java class implements the SessionBean interface
2. The SessionBean interface requires five methods to be defined in the session bean class.
3. They are : ejbActive(), ejbPassive(), ejbRemove(), setSessionContext(SessionContext),
ejbCreate()
4. The EJB container calls each of these methods at an appropriate time during the life of
the session bean.

import javax.ejb.*;
public class MyEJBBean implements SessionBean
{
public void ejbActivate()
{
System.out.println("Called ejbActivate()");
}
public void ejbRemove()
{
System.out.println("Called ejbRemove()");
}
public void ejbPassivate()
{
System.out.println("Called ejbPassivate()");
}
public void setSessionContext(SessionContext ctx)
{
System.out.println("Called setSessionContext()");
}
public void ejbCreate ()
{
System.out.println("Called ejbCreate()");
}
public String myMethod ()
{
return("Called myMethod()");
KNSIT Page 179
}
}

Entity Java Bean

1. An entity bean is considered the powerhouse of a J2EE application because an entity


bean is used to manage a collection of data retrieved from a database and stored in
memory.
2. An entity bean inserts, updates, and removes data while maintaining the integrity of
data.
3. Data collected and managed by an entity bean is referred to as persistent data and is
managed in one of two ways:
using Bean-Managed Persistence (BMP) ( it requires the bean to manage persistence)
using Container-Managed Persistence (CMP) (it requires the container to
managepersistence)
4. An entity bean can have a remote interface, a local interface or both interfaces.
5. A remote interface enables remote clients to access the entity bean.
6. A remote interface is used by a client not located in the EJB container.
7. A local interface provides access to clients running within the same environment.
8. A local interface is used by clients within the same EJB container.

Container-Managed Persistence
1. The term container-managed persistence means that the EJB container handles all
database access required by the entity bean.
2. The bean's code contains no database access (SQL) calls.
3. As a result, the bean's code is not tied to a specific persistent storage mechanism.
4. Because of this flexibility, even if you redeploy the same entity bean on
different J2EE servers that use different databases, you won't need to modify or
recompile the bean's code.
5. There are 3 groups of methods that are contained in an entity bean.

KNSIT Page 180


6. These are creation methods, business methods and callback methods.
7. ejbCreate() : EJB container calls this method when a client calls the EJBHome client
method.
8. ejbPostCreate() : Called by EJB container after performing the wrapper operation
(creating a representation in database and creating a new Remote object.)
9. There are two general types of business methods in an entity bean.
10. They are getxxx() and setxxx(), xxx refers to the type of object that is either being
retrieved from a database or written to a database.
11. Callback methods are invoked in response to events that occur.
12. There are seven callback methods : ejbLoad(), ejbStore(),
setEntityContext(EntityContext), unsetEntityContext(), ejbActivate(), ejbPassivate() and
ejbRemote().

Bean-Managed Persistence
1. A bean-managed persistence (BMP) bean uses the JDBC API or another appropriate
database API to interface with the database.
2. The EJB container tells the BMP bean when to insert a new record, retrieve data,
modify data, or delete data.
3. There are five methods defined in a BMP bean.
4. They are : ejbLoad(), ejbStore(), ejbCreate(), ejbRemote() and findxxx().

Message-Driven Bean
1. A message-driven bean MDB is designed for clients to invoke server-side business logic
using asynchronous communication.
2. MDB monitors Java Message Service (JMS) communications and reacts to messages
sent by clients.
3. Clients dont directly access a MDB. Instead, the MDB interacts and processes requests
anonymously.
4. The EJB container handles the responsibility for creating and removing an MDB.
5. Requests from clients are sent via JMS.
6. The EJB container listens for messages in the JMS service that MDBs are registered to
receive.

KNSIT Page 181


7. The developer provide all the logic to process a message in the onMessage() method.
8. The JMS service enables the client and MDB to work independently and without having
to wait until the other is finished processing.
The MDB doesnt know anything about the client

Creating an MDB
1. An MDB defines four methods :
2. ejbCreate() : called when the MDB is created by the container.
3. ejbRemove() : called by the EJB container when the container terminates the instance of
the MDB.
4. setMessageDrivenContext() : creates the context for the MDB.
5. onMessage() : called each time when the EJB container receives a JMS message from a
client.

The JAR File


1. EJB classes and related files are packaged together into a Java Archive (JAR) file for
deployment.
2. The JAR file is a compressed file format that was originally designed to reduce the size
of software to transport it easily.
3. The JAR file used to package an EJB must contain the following:
1. EJB classes
2. Dependent classes
3. Remote interfaces
4. Home interfaces
5. Dependent interfaces
6. Primary key class
Deployment Descriptor
1. In addition to this, the deployment descriptor must be located in META-INF/ejb-
jar.xml

KNSIT Page 182


END OF EJB

KNSIT Page 183

You might also like