You are on page 1of 183

1:JDBC objects

The Concept Of JDBC 1. 2. 3. 4. There are many DBMSs commercially available in the market. These include Oracle, DB2, Sybase etc.. 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. 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. 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. 2. 3. 4. 5. This encouraged third-party vendors & other DBMS suited Suns specifications. manufacturers to build JDBC drivers that

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. 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. Java data objects convert the routine into low-level messages that conform to the JDBC driver specification and send them to the JDBC driver. 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. 2. 3. 4. 5. Open a connection b/n the DBMS and J2EE component. Translate low-level equivalents of SQL statements sent by the j2EE component into messages that can be processed by DBMS. Return data that conforms to the JDBC specification to the JDBC driver. Return info such as error messages that conforms to the JDBC specification to the JDBC driver. 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. 2. 3. Microsoft created ODBC (Open Database Connection), which is the basis from which Sun created JDBC. Both have similar driver specifications and an API. 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. 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. 2. 3. The Java/Native Code driver uses Java classes to generate platform- specific code, that is code only understood by a specific DBMS. The disadvantage of using a Java/Native Code driver is the loss of some portability of code. The API classes for the Java/Native Code driver probably wont work with another manufacturers DBMS.

Type 3 JDBC Driver 1. 2. Also referred to as the Java Protocol, most commonly used JDBC driver. 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. 2. 3. 4. Type 4 JDBC driver is also known as the Type 4 database protocol. The driver is similar to Type 3 JDBC driver except SQL queries are translated into the format required by the DBMS. SQL queries do not need to be converted to JDBC-formatted systems. This is the fastest way to communicated SQL queries to the DBMS.

JDBC Packages
1. 2. The JDBC API is contained in two packages. 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. 4.

These include Java data objects that provide the basic for connecting to the DBMS and interacting with data stored in the DBMS. 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. 2. Though each J2EE component is different, J2EE components use a similar process for interacting with a DBMS. This process is divided into five routines. These are. 1. 2. 3. 4. 5. Loading the JDBC driver Connecting to the DBMS Creating and executing a statement Processing data returned by the DBMS Terminating the connection with the DBMS

Loading the JDBC Driver 1. 2. 3. The JDBC driver must be loaded before the J2EE component can connect to the DBMS. 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. 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. 2. 3. 4. 5. The DriverManager.getConnection() method is passed with the URL of the database, the user ID and the password if required by DBMS. 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. The DriverManager.getConnection() method returns a Connection interface that is used throughout the process to reference the database. The java.sql.Connection is another interface manages communication between the driver and the J2EE component. The java.sql.Connection interface sends statements to the DBMS for processing.

Create and Execute a SQL Statement KNSIT Page 4

1. 2. 3. 4.

Next is we have to send a SQL query to the DBMS for processing. 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. Connection.createStatement() method is used to create a Statement object. 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. Once the ResultSet is received from the DBMS, the close() method is called to terminate the statement.

5.

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

KNSIT

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. 2. A J2EE component does not directly connect to DBMS. Instead, the J2EE component connects with the JDBC driver that is associated with the DBMS. Before the connection is made, the JDBC driver must be loaded and registered with the DriverManager. Page 10

KNSIT

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. 2. After the JDBC driver is loaded & registered, the J2EE component must connect to the database. The data source that the JDBC component will connect to is defined using the URL format. The URL consists of three pats. 1. 2. 3. 3. 4. 1. jdbc which indicates that JDBC protocol is to be used to read the URL. <subprotocol> which is the JDBC driver name. <subname> which is the name of the database.

The connection to the database is established by getConnection(), which requests access to the database from the DBMS. A Connection object is returned by the getConnection() if access is granted; else getConnection() throws a SQLException. 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. 2. The DBMS may not respond quickly for a number of reasons,which might include that database connections are not available. 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. 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. This method returns an int that represents seconds.

4. 5.

Associating the JDBC/ODBC Bridge with the Database 1. 1. 2. 3. 4. We use the ODBC Data Source Administrator to create the association between the database and the JDBC/ODBC bridge. Select Start-> settings and then control panel Select ODBC 32 to display the ODBC Data Source Administrator Add a new user by selecting the Add button. 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. 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. 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. . 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. Since this is our database, we can determine if a login name and the database. If so, then click the Advanced button to display the Set Advanced When the ODBC Microsoft Access Setup dialog box appears, Select Ok to close the ODBC Data Source Administrator dialog 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 password is required to access Options dialog box.

5. 6. 7.

8. 9. 10. 11. 12.

select Ok. box.

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. 2. 3. 4. The Statement object is used whenever J2EE component needs to immediately execute a query without first having the query compiled. The Statement object contains the executeQuery() method, which passes the query as an argument. The query is then transmitted to the DBMS for processing. The executeQuery() method returns one ResultSet object that contains rows, columns, and metadata that represents data requested by query. 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. 2. A SQL query can be precompiled and executed by using the PreparedStatement object. 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. Page 17

KNSIT

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. 2. 3. 4. 5. 6. 7.

The CallableStatement object is used to call a stored procedure from within a J2EE object. A Stored procedure is a block of code and is identified by a unique name. 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. IN, OUT and INOUT are the three parameters used by the CallableStatement object to call a stored procedure. The IN parameter contains any data that needs to be passed to the stored procedure and whose value is assigned using the setxxx() method. 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() 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. 2. 3. 4.

The ResultSet object contains methods that are used to copy data from the ResultSet into a Java collection object or variable for further processsing. Data in a ResultSet is logically organized into a virtual table consisting of rows and columns. The ResultSet uses a virtual cursor to point to a row of the virtual table. 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. The next() returns a boolean true if the row contains data; else false. 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.

5. 6.

KNSIT

Page 20

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. 2. 3. 4. KNSIT In JDBC 2.1 API the virtual cursor can be moved backwards or positioned at a specific row. Six methods are there for Resultset object. They are first(), last(), previous(), absolute(), relative() and getrow(). first() method moves the virtual cursor to the first row in the Resultset. last() method positions the virtual cursor at the last row in the Resultset Page 21

Reading The ResultSet

5. 6. 7. 1. 2. 3.

previous() method moves the virtual cursor to the previous row. absolute() method positions the virtual cursor to a specified row by the an integer value passed to the method. relative() method moves the virtual cursor the specified number of rows contained in the parameter. The parameter can be positive or negative integer. The getRow() method returns an integer that represents the number of the current row in the Resultset. 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. 2. 3. 4. 5. Rows contained in the ResultSet can be updatable similar to how rows in a table can be updated. This is possible by passing the createStatement() method of the Connection object the CONCUR_UPDATABLE. CONCUR_READ_ONLY constant can be passed to the createStatement() method to prevent the ResultSet from being updated. There are three ways in which a ResultSet can be changed. 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. 2. 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. 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. 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. The updateRow() is called after all the updatexxx() are called.

4.

5.

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) { System.out.println("No data returned."); System.exit(4); } try { Results.updateString("Lastname", "Smith"); Results.updateRow(); DataRequest.close(); } catch (){}

Delete Row in the ResultSet 1. KNSIT The deleteRow() is used to remove a row from a ResultSet. Page 24

ltSet. LY from

2. 3. 4. 5.

The deleteRow() is passed an integer that contains the number of the row to be deleted. First use the absolute() method to move the virtual cursor to the row in the Resultset that should be deleted. The value of that row should be examined by the program to assure it is the proper row before the deleteRow() is called. 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. 2. 3. Inserting a row into the ResultSet is accomplished using basically the same technique as is used to update the ResultSet. The updatexxx() is used to specify the column and value that will place into the column of the ResultSet. 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. 2. KNSIT A transaction may involve several tasks. A database transaction consists of a set of SQL statements, each of which must be successfully completed for the transaction to be completed. Page 26

3. 4. 5. 6. 7.

If any one fails, then the transaction must be rolled back. The database transaction is not completed until the J2EE component calls the commit() method of the Connection object. The commit() method must be called regardless if the SQL statement is part of a transaction or not. The commit() method was automatically called in the previous examples because the DBMS has an AutoCommit feature that is by default set to true. 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. 2. The J2EE component can control the number of tasks that are rolled back by using savepoints. 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. 2. 3. 4. 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. This can be done using the addBatch() method of the Statement object. The addBatch() method receives a SQL statement as a parameter and places the SQL statements in the batch. 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. Page 30

KNSIT

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. 2. 3. 4. 5. Whenever the commit() method is called, all ResultSet objects that were created for the transaction are closed. Sometimes a J2EE component needs to keep the ResultSet open even after the commit() method is called. 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. These constants are HOLD_CURSORS_OVER _COMMIT and CLOSE_CURSORS_AT_COMMIT. 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. 2. The JDBC RowSets object is used to encapsulate a ResultSet for use with Enterprise Java Bean(EJB). A RowSet object contains rows of data from a table(s) that can be used in a disconnected operation.

Auto-Generated Keys 1. 2. 3. It is common for a DBMS to automatically generate unique keys for a table as rows are inserted into the table. The getGeneratedKeys() method of the Statement object is called to return keys generated by the DBMS. The getGeneratedKeys() returns a ResultSet object and can use the ResultSet.getMetaData() to retrieve metadata relating to the automatically generated key.

Metadata 1. 2. 3. 4. 5. 6. 7. 8. 9. Metadata is data about data. A J2EE component can access metadata using the DatabaseMetaData interface. The DatabaseMetaData interface is used to retrieve information about database, tables, columns, and indexes among other information about the DBMS. Some of the commonly used DatabaseMetaData objects methods: getDatabaseProductName() returns the product name of the database getUserName() returns the URL of the database. getURL() returns all the schema names available in this database. getPrimaryKeys() returns primary keys getProcedures() returns stored procedures names. 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. 3.

These are metadata that describes the database mentioned earlier and metadata that describes the ResultSet. Metadata describing ResultSet is retrieved by calling the getMetaData() of ResultSet object. 1. ResultSetMetadata rm = Result.getMetaData()

4. 5. 6. 7.

More commonly called methods are: getColumnCount() gets the no. of columns contained in the ResultSet. getColumnName() gets the name of the column specified by the column number. 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. 2. KNSIT There are three kinds of exceptions that are thrown by JDBC methods. They are SQLExceptions, SQLWarnings and Data Truncation. Page 35

3. 4. 5. 6.

SQLExceptions commonly reflect a SQL syntax error in the query and are thrown by many of the methods contained in the java.sql package. The SQLWarning throws warnings received by the Connection from the DBMS. The getWarnings() and getNextWarning() methods of Connection object retrieves warnings and subsequent warnings respectively. DataTruncation exception is thrown whenever data is lost due to truncation of data value.

END OF JDBC

3:4:SERVLETS & SERVLETS-SESSIONS Introduction.


1. 2. 3. 4. 5. 6. Servlets are small programs that execute on the server side of a Web connection. Servlets are server side components that provides a powerful mechanism for developing server web applications for server side. Just as applets dynamically extend the functionality of a Web browser, servlets dynamically extend the functionality of a Web server. Using servlets web developers can create fast and efficient server side applications and can run it on any servlet enabled web server. Servlet runs entirely inside the Java Virtual Machine. 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 browser & it will generate the HTTP request to appropriate web server.

specific file & i HTTP response

Client The HTTP header in response indicate the type of the content & MIME is used for this purpose.
1. 2. 3. But the content of the dynamic web pages need to be generated dynamically. In the early days of the Web, a server could dynamically construct a page by creating a separate process to handle each client request. The process would open connections to one or more databases in order to obtain the necessary information. Page 37

KNSIT

4. 5. 6.

It communicated with the Web server via an interface known as the Common Gateway Interface (CGI). CGI allowed the separate process to read data from the HTTP request and write data to the HTTP response. 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. 2. 3. 4. 5. Servlets offer several advantages in comparison with CGI. First, performance is significantly better. It is not necessary to create a separate process to handle each client request. Second, servlets are platform-independent because they are written in Java. Third, the Java security manager on the server enforces a set of restrictions to protect the resources on a server machine. 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. 2. KNSIT

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

3. 4. 5.

Let us consider a user scenario to understand when these methods are called. First, user enters URL, browser then generates an HTTP request for this URL, & this request is then sent to the appropriate server. 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. 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. 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. 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.

6.

7.

8.

A Simple Servlet 1. The basic steps to be followed: 1. 2. 3. Create and compile the servlet source code. Start Tomcat. Start a Web browser and request the servlet.

KNSIT

Page 39

A Simple Servlet Code 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.

This package contains the interfaces required to build

getWriter() obtains PrintWr written to this stream is sent t GRNICA of HTTP response.
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. 3. 4.

These packages are not part of Java core packages, they are standard extensions provided by Tomcat. The current servlet specification is version 2.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. 2. The javax.servlet package contains a number of interfaces and classes that establish the framework in which servlets operate. The following table summarizes the core interfaces that are provided in this package.

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. 2. It allows a servlet to obtain configuration data when it is loaded. The methods declared by this interface are summarized here:

The ServletContext Interface 1. 2. 3. 4. KNSIT ServletContext is a interface which helps us to communicate with the servlet container. It enables servlets to obtain information about their environment. There is only one ServletContext for the entire web application and the components of the web application can share it. The information in the ServletContext will be common to all the components. Page 42

5. 6.

Each servlet will have its own ServletConfig. 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. 2. It enables a servlet to obtain information about a client request. Several of its methods are summarized in table below.

KNSIT

Page 43

The ServletResponse Interface 1. 2. It enables a servlet to formulate a response for a client. 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. 2. 3. The GenericServlet class provides implementations of the basic life cycle methods for a servlet. GenericServlet implements the Servlet and ServletConfig interfaces. 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. 2. 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. 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. Page 45

KNSIT

The ServletOutputStream Class 1. 2. 3. The ServletOutputStream class extends OutputStream. It is implemented by the server and provides an output stream that a servlet developer can use to write data to a client response. A default constructor is defined. It also defines the print( ) and println( ) methods, which output data to the stream. The Servlet Exception Classes 1. 2. 3. javax.servlet defines two exceptions. The first is ServletException, which indicates that a servlet problem has occurred. The second is UnavailableException, which extends ServletException. It indicates that a servlet is unavailable. Reading Servlet Parameters 1. 2. The ServletRequest class includes methods that allow you to readthe names and values of parameters that are included in a client request. 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. 2.

The HttpServletRequest interface is implemented by the server. It enables a servlet to obtain information about a client request. Several of its methods are shown in Table below.

KNSIT

Page 50

KNSIT

Page 51

The HttpServletResponse Interface 1. 2. 3. The HttpServletResponse interface is implemented by the server. It enables a servlet to formulate an HTTP response to a client. Several constants are defined. These correspond to the different status codes that can be assigned to an HTTP response. 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. 2. The HttpSessionBindingListener interface is implemented by objects that need to be notified when they are bound to or unbound from an HTTP session. 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. 2. 3. The Cookie class encapsulates a cookie. A cookie is stored on a client and contains state information. Cookies are valuable for tracking user activities. 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. A servlet can write a cookie to a users machine via the addCookie( ) method of the HttpServletResponse interface. 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: Page 54

4. 5. KNSIT

The name of the cookie The value of the cookie The expiration date of the cookie The domain and path of the cookie 1. 2. 3. 4. 5. The expiration date determines when this cookie is deleted from the users machine. If an expiration date is not explicitly assigned to a cookie, it is deleted when the current browser session ends. Otherwise, the cookie is saved in a file on the users machine. The domain and path of the cookie determine when it is included in the header of an HTTP request. There is one constructor for Cookie. It has the signature shown here: Cookie(String name, String value) 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. 2. The HttpServlet class extends GenericServlet. It is commonly used when developing servlets that receive and process HTTP requests. The methods of the HttpServlet class are summarized in Table

KNSIT

Page 56

The HttpSessionEvent Class 1. 2. 3. 4. 5. HttpSessionEvent encapsulates session events. It extents EventObject and is generated when a change occurs to the session. It defines this constructor: HttpSessionEvent(HttpSession session) Here, session is the source of the event. HttpSessionEvent defines one method, getSession( ), which is shown here: HttpSession getSession( ) It returns the session in which the event occurred.

The HttpSessionBindingEvent Class KNSIT Page 57

1. 2. 3.

The HttpSessionBindingEvent class extends HttpSessionEvent. It is generated when a listener is bound to or unbound from a value in an HttpSession object. It is also generated when an attribute is bound or unbound. Here are its constructors: HttpSessionBindingEvent(HttpSession session, String name) HttpSessionBindingEvent(HttpSession session, String name, Object val) 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. The getName( ) method obtains the name that is being bound or unbound. Its is shown here: String getName( ) The getSession( ) method, obtains the session to which the listener is being bound or unbound: HttpSession getSession( ) The getValue( ) method obtains the value of the attribute that is being bound or unbound. It is shown here: Object getValue( )

4. 5. 6. 7.

Handling HTTP Requests and Responses 1. 2. The HttpServlet class provides specialized methods that handle the various types of HTTP requests. 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. 2. HTTP is a stateless protocol. Each request is independent of the previous one. However, in some applications, it is necessary to save state information so that information can be collected from several interactions between a browser and a server. Sessions provide such a mechanism. A session can be created via the getSession( ) method ofHttpServletRequest. An HttpSession object is returned. This object can store a set of bindings that associate names with objects. The setAttribute( ), getAttribute( ), getAttributeNames( ), and removeAttribute( ) methods of HttpSession manage these bindings.

3. 4. 5.

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 { // Get the HttpSession object. HttpSession hs = request.getSession(true);

Gets t sessio

KNSIT

Page 68

// Get writer. response.setContentType("text/html"); PrintWriter pw = response.getWriter(); pw.print("<B>"); // Display date/time of last access. Date date = (Date)hs.getAttribute("date"); if(date != null) { pw.print("Last access: " + date + "<br>"); }

Call obje to th

// Display current date/time. date = new Date(); hs.setAttribute("date", date); pw.println("Current date: " + date);
} }

This to bi 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. 2. In some circumstances, you may want to include the content from an HTML page or the output from another servlet. Additionally, there are cases that require that you pass the processing of an HTTP request from your servlet to another servlet. Page 78

KNSIT

3. 4. 5. 1.

The current servlet specification responds to these needs with an interface called RequestDispatcher, which is found in the javax.servlet package. This interface has two methods, which allow you to delegate the request-response processing to another resource: include and forward. Both methods accept a javax.servlet.ServletRequest object and a javax.servlet.ServletResponse object as arguments 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. 2. 3. A filter is an object that can transform the header or content or both of a request or response. 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. 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. 2. 3. 4. 5. 6. 7. 8. 9. Query the request and act accordingly. Block the request-and-response pair from passing any further. Modify the request headers and data. It is done by providing a customized version of the request. Modify the response headers and data. It is done by providing a customized version of the response. Interact with external resources. Applications of filters include authentication, logging, image conversion, data compression, encryption, tokenizing streams, and XML transformations. The filtering API is defined by the Filter, FilterChain, and FilterConfig interfaces in the javax.servlet package. We define a filter by implementing the Filter interface. 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. KNSIT Examine the request headers. Page 84

11. 12. 13. 14. 15. 16. 17. 18.

Customize the request object if it wishes to modify request headers or data. Customize the response object if it wishes to modify response headers or data. Invoke the next entity in the filter chain. Examine response headers after it has invoked the next filter in the chain. Throw an exception to indicate an error in processing. In addition to doFilter, we must implement the init and destroy methods. The init method is called by the container when the filter is instantiated. 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. We can create filter class by implementing javax.servlet.Filter, which has three methods as follows: void init(FilterConfig filterConfigObject) throws ServletException 1. 22. 23. It is called once by the server to get prepared for service and then it calls doFilter() a number of times for request processing.

20. 21.

void destroy() 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. 2. 3. Java ServerPages is a server-side program. A JSP is called by a client to provide a web service. 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. 5. 6.

A JSP is simple to create, a JSP is written in HTML rather tha with the Java programming language. 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. 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. jspInt(), jspDestroy() and service() are the three methods that are automatically called when a JSP is requested and terminates normally. 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. The jspDestroy() is automatically called when the JSP terminates normally. When JSP abruptly terminated, it is not called. The service() is automatically called and retrieves a connection to HTTP.

7. 8. 9. 10.

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. 2. A JSP programs consists of a combination of HTML tags and JSP tags. 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. 4.

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. 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. 6. Comment tag : A comment tag opens with <%-- and closes with --%>. 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. 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. The directive tag closes with %>. There are three commonly used directives. They are : import : It is used to import Java packages into the JSP program. <%@ page import = import java.sql.* ; %> include : It inserts a specified file into the JSP program replacing the include tag. <%@ include file=keogh\books.html %> taglib : taglib tag specifies a file that contains a tag library. <%@ taglib url=myTags.tld %> Scriptlet tags : A scriptlet tag opens with <% and contains commonly used Java control statements and loops. Closes with %>. 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

7.

8. 9. 10.

11. 12. 13.

15.

request: request represents the clients request and is a subclass of HttpServletRequest. Use this variable to retrieve the data submitted along the request. response: response is subclass of HttpServletResponse. session: session represents the HTTP session object associated with the request. out: out is an object of output stream and is used to send any output to the client.

16. 17. 18.

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. 20. 21. 22. There are three types of directives are as follows: Page Directive Include Directive Taglib Directive Syntax of the declaration of the page directive with it's attributes is attributeName="values" %> <%@ page

Following are name of the attributes of the page directive used in JSP: 23. 24. 25. 26. 27.
KNSIT

Language extends import session buffer


Page 91

28. 29. 30. 31. 32. 33. 34. 35. 36. 37.

autoFlush isThreadSafe info errorPage contentType isErrorPage pageEncoding isELIgnored language: This attribute of page directive of JSP is used for specifying some other scripting languages to be used in the JSP page. 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. 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 (,). 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.* 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. 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. 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. 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.
Page 92

38. 39. 40.

41.

42.

43.

KNSIT

44. 45.

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

46.

47.

48.

49.

1.

<HTML><HEAD> <TITLE>Order Confirmation</TITLE> </HEAD><BODY> <%! int age=25; %> <p> Your age is : <%=age%> </p> </BODY></HTML> <HTML><HEAD> <TITLE> JSP Programming </TITLE> </HEAD><BODY> <%! int age=25; float salary; int empnumber; %> </BODY></HTML> <HTML><HEAD> <TITLE>JSP Programming </TITLE> </HEAD><BODY>
Page 93

2.

3.

KNSIT

<%! 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. 6. 7. 8. In JSP a method definition is placed within a JSP tag. We can call the method from within the JSP tag once the method is defined. The JSP tag that calls the method must be a JSP expression tag, which begins with <%=. <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. 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

10.

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. 13. 14. 15. 16. 17. 18. Hence there is a need to access to a JSP Virtual Machine to run the JSP programs. One of the most popular JSP Virtual Machines is Tomcat, it is downloadable at free of cost from www.jakarta.apache.org Installing Java is also required. Request String 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. http://www.jimkeogh.com/jsp/myprogram.jsp?fname=bob&lname=smith 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. 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

19.

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. Since these objects are created automatically by the container and are accessed using standard variables; hence, they are called implicit objects. The implicit objects are parsed by the container and inserted into the generated servlet code. They are available only within the jspService method and not in any declaration. 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. 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. 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. 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. 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. 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. 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. 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.
Page 98

21. 22. 23. 24.

25.

26.

27.

28.

29.

30. 31.

KNSIT

32. 33.

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. 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. 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. 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. There are four predefined implicit objects that are in every JSP programs. These are request, response, session and out. The request object is an instance of the HTTPServletRequest. The response object is an instance of the HTTPServletResponse. The session object is an instance of the HTTPSession. The out object is an instance of the JSPWriter, used to send a response to the client. getParameterValues() method helps us to copy a value from a multivalued field such as a selection list field. <%! String[] EMAIL = request.getParameterValues(ADDR); %> <P> <%=EMAIL [O]%> </P> <P> <%=EMAIL [1]%> </P> Field names in the request string can be parsed by using the getParameterNames() method.

34.

35.

36. 37. 38. 39. 40. 41. 42.

43.

<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. 45. 46. 47. 48. The request string sent to the JSP by the browser is divided into two general components separated by question mark. The URL component appears to the left of the question mark and the query string is to the right of the question mark. The URL is divided into four parts, beginning with the protocol. The first three parts commonly used protocols like HTTP, HTTPS (secured version of HTTP) and FTP. 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. 50. 51. A JSP program must be able to track a session. There are threecommonly used methods to track a session. These are by using a hidden field, by a cookier or by Java Bean. A hidden field is a field in an HTML form whose value isnt displayed on the HTML page.

Cookies 52. 53. Cookie is a small piece of information created by a JSP program that is stored on the clients hard disk by the browser. 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. 55. 56. 57. 58. Each time a session is created, a unique ID is assigned to the session and stored as a cookie. The unique ID enables JSP programs to track multiple sessions simultaneously while maintaining data integrity of each session. The session ID is used to prevent intermingling of information from clients. Along with session ID, a session object is also used to store other types of information, called attributes. 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. 60. 61. 62. 63. 64. 65. 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. The action tags are specific to a JSP page. 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. An action can be for instance, access parameters sent with the request to do a database lookup. It can also dynamically generate HTML, such as a table filled with information retrieved from an external system. 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. The JSP standard actions affect the overall runtime behavior of a JSP page and also the response sent back to the client. Description Makes a JavaBeans component available in a page Gets a property value from a JavaBeans component and adds it to the response Sets a JavaBeans component property value Includes the response from a servlet or JSP page during the request processing phase

Action element <jsp:useBean> <jsp:getProperty

<jsp:setProperty> <jsp:include>

KNSIT

Page 108

<jsp:forward> <jsp:param>

Forwards the processing of a request to servlet or JSP page 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. Generates HTML that contains the appropriate browserdependent elements (OBJECT or EMBED) needed to execute an applet with the Java Plug-in software

<jsp:plugin>

include directive tag 1. It inserts the given page and includes the content in the generated servlet page during the translation phase of JSP lifecycle. In general, the include directive is used to include files, such as HTML, JSP, XML or simple.txt file into JSP page statically.

include action tag 3. The include action tag is used to included the response generated by executing the specified JSP page or servlet. The response is included during the request processing phase, when the page is requested by the user.

2.

4.

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. 3. The name Attribute : The name attribute specifies the parameter name and takes a casesensitive literal string. The parameter name should be unique. 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. snippet for <jsp:param>
Page 110

4.
KNSIT

5. 6. 7. 8.

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

jsp:useBean 1. 2. This action allows to use java bean in a JSP page. This action instantiates or locates a Bean with a specific name and scope. <jsp:useBean attributes> . </jsp:useBean> 3. 4. 5. 6. 7. Attributes of <jsp:useBean> tag : Attributes add extra characteristics to a tag. id represents the variable name assigned to the id attribute of the jsp:useBean tag. Used to locate an existing bean instance in the appropriate scope specified in the jsp:useBean action tag. It is case sensitive. scope represents the scope in which the bean instance has to be located or created. 1. 2. 3. Scopes can be page, request, session and application. Default scope is page. page scope indicates bean can be used within the JSP page. (stored in the PageContext of the current page). 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). 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
Page 111

4.

KNSIT

5. 6.

class accepts the qualified class name to create a bean instance if the bean instance is not found in the given scope. 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. 2. 3. 1. 2. This action tag sets the value of a property in a bean, using the beans setter methods. The bean must be instantiated before using this tag. The name attribute of the bean must be same as the reference variable name of the bean instance. <jsp:setProperty> tag contains four attributes : name : take the name of the already existing bean as a reference variable to invoke the setter method.
Page 112

KNSIT

3. 4.

property : takes property name that has to set, and specifies the setter to be invoked.

method that has

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

value : accepts the value as the string type or as an expression that is evaluated at run time. 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. 5. name : This attribute takes the reference variable name on which we want to invoke the getter method. 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. 2. 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. The attributes of the jsp:plugin action tag perform the following operatins: 1. 2.
KNSIT

specify whether the component added in the <object> tag is a bean or an applet. locate the code that needs to be run.
Page 113

3. 4. 5.

position the object in the browser window specify a URL from which to download the plug-in software. pass parameter names and vales to the object.

<jsp:plugin attributes > </jsp:plugin> Attributes Type Code Codebase Name Archieve Description Specifies the type of the object that needs to be presented to the browser. Takes the qualified class name of the object that has to be presented Takes the base URL where the specified class can be located. Specifies the name of the instance of the bean or applet. Specifies comma separated list of pathnames, which loctae archive files that are preloaded with a class loader in the directory named codebase Specifies the initial width, in pixels of the image Specifies the initial height, in pixels of the image Specifies the position of applet : botton, top, middle, left, right Amount of space to the left and right of applet in pixels. Amount of space to the bottom and top of applet in pixels.

Width Height Align Hspace Vspace

KNSIT

Page 114

Jreversion Nspluginurl

Specifies the version of the JRE Specifies the URL where the client can download the JRE plug-in for Netscape Navigator. Specifies the URL where the client can download the JRE plug-in for Inter net Explorer.

Iepluginurl

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 JSPApplet",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().width70), Math.abs(r.nextInt())%(size().height30),70,30); repaint(); } return true; } }
Using a Bean in JSP 1.
KNSIT

To declare a bean in a JSP, follow these steps


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

The Core JSTL tags: 1. 2. The core tags are used to perform iteration, conditional processing, and also provide support of expression language for the tags in jsp pages. 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. 2. The core tags in jsp can be accessed by using prefix c, a preferred prefix for core tab libraries. The JSTL core tags are divided into 3 categories : 1. 2. 3.
KNSIT

General-purpose Tags Conditional and Looping Tags Networking Tags


Page 122

General-purpose Tags: 1. 2. It includes tags for writing the values to the output stream, retrieving, setting and removing attributes and for catching exceptions. General-purpose tags contains four tags : 1. 2. 3. <c:out> <c:set> <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. 3. value specifies the output data to be displayed. escapeXml specifies whether or not the tag should ignore XML characters. 1. 2. 4. If boolean escapeXML is true, then tag converts XML special characters <,>,& to &lt, &gt, and &amp. If boolean escapeXML is false, then it does not convert XML special characters. The default value is true.

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

KNSIT

Attributes are : 1. 2. 3. 4. 5. value specifies the value being set. var specifies the name of the variable to store. scope specifies the scope of the variable defined in the var attribute. Scope can be page, request, session or application. target specifies the name of the variable whose property is to be set. 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. 2. It evaluates an expression that is given in its test attribute. If true, body of <c:if> is evaluated, otherwise not. syntax <c:if attributes> body content </c:if> The attributes are: 1. 2. test boolean variable or expression resolving to boolean value. 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. 2. It acts like a switch statement. It encloses one or more <c:when> and <c:otherwise> tag. syntax : <c:choose> body content </c:choose> The <c:when> tag 1. 2. It encloses a single case within the <c:choose> tag. <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. 2. It is equivalent to default case in java switch statement. 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. 2. It is used to iterate over a collection of objects or as a fixed over a range of numbers. 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. 2.
KNSIT

items specifies the collection (ArrayList, Map or List.var) to iterate over. varStatus specifies the name of the variable that defines the status of the variable given in the var attribute. Its optional one.
Page 127

3. 4. 5.

begin takes the starting index for the loop, optional one. end takes the ending index for the loop, optional one. 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. 2. 3. 4. 5. 6. 7. 2. 3. 4. 5. 6. 7. items specifies the string to be tokenized. var specifies the name of the variable into which the current iteration item has to be set. delims specifies the delimiter or delimiters which are to be tokenized. varStatus defines the status of the variable given in var attributes, it is optional. begin takes the starting index for the loop, optional one. end - takes the ending index for the loop, optional one. step provides optional increment for the loop; default value is 1.

Example for forEach tag <%@ page contentType="text/html" %> <%@ taglib prefix="c" uri="http://java.sun.com/jstl/core" %> <c:forEach var="n" begin="3" end="8" > <c:out value="${n}" /> <br> </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. 2. 3. 4. <c:import> <c:url> <c:redirect> <c:param>

<c:import> Tag 1. 2. This tag is used to include another resource such as another JSP or HTML page in a JSP page. The resource can either be static or dynamic. syntax : <c: import attributes > </c:import> Attributes are: 1. 2. 3. 4. url specifies the url of the resource to include. context specifies the context name in which the page has to be located, its optional one. var specifies the name of the variable into which the result has to be stored, if specified. 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.
KNSIT

url specifies the URL to be written if required added with session ID.
Page 130

2. 3. 4.

context specifies the context name of another web application, URL refers to the resource in another servlet context. var specifies the name of the variable into which the new to be stored.

required if the

rewritten URL has

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. 3. It is used to redirect a client request. It is similar to sendRedirect() method. </c:redirect>

syntax : <c:redirect attributes> [ zero or more <c:param> tag Attributes are: 4. 5.

value specifies the URL of the resource to which the request

has to be redirected.

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

<%@ page contentType="text/html" %> <%@ taglib prefix="c" uri="http://java.sun.com/jstl/core" %> <c:redirect value="http://localhost:8000/index1.html> </c:redirect>

<c:param> Tag 1. 2. It is used to add a request parameter to the URL. 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. 2. 3. 4. 5. The XML tag library is used to work with XML data used in JSP pages. It helps to parse and transform data used in JSP page. These operations can be done by using the Xpath expression associated with an XML document. An Xpath expression includes both the relative and absolute path of XML element. 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. 2. 3.
KNSIT

XML core tags XML Flow Control tags XML Transformation tags
Page 132

XML core tags 1. 2. It includes the tags for parsing XML document and performing Xpath operations. XML core tags are of three types : 1. 2. 3. <x:parse> <x:out> <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. 2. 3. 4. 5. 6. 7. 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. systemId accepts the system identifier (URI) for parsing the XML document. filter accepts an org.xml.sax.XMLFilter object to be applied for the XML document. var specifies the variable name to which the parsed XML document has to be set. scope specifies the scope of the attribute. varDom specifies the variable name to which the org.w3c.dom.Document object of the parsed XML document has to be set. 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.
KNSIT

select accepts an XML Xpath expression to be evaluated.


Page 133

2. 3.

var specifies the name of the scooped variable to hold the result. 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. 2. select accepts an XML Xpath expression to be evaluated. 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. 2. It helps to parse, access XML data, iterate over elements in an XML document, and conditionally process JSP code fragment. XML flow control tags of JSTL contains five tags: 1. 2. 3. 4. <x:if> <x:choose> <x:when> <x:otherwise> <x:forEach> <x:if> tag 1. 2. It evaluates an XPath expression that is given in its select attribute. 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. 2.
KNSIT

select takes an Xpath expression that resolves to a Boolean value var takes the name of the scoped variable to store the conditions result.
Page 134

3.

scope specifies the scope of a variable.

<x:choose> tag 1. 2. It acts similar to java switch statement. 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. 2. select takes an Xpath expression resolving to boolean value. If boolean value is true, <c:when> tags body is evaluated.

<x:otherwise> tag 1. 2. It is equivalent to default case in java switch statement. 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. 2. 3. select takes an Xpath expression that results a node list. var specifies the name of the variable into which the current iteration item has to be set. 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.
Page 135

KNSIT

4. 5. 6.

begin takes the starting index for the loop, this is optional. end takes the end index for the loop, optional one. 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. 2. 3. 4. 1. 2. 3. doc takes an XML doc to be parsed in the form of a string or a Reader object. xslt takes an XSLT stylesheet doc for transformation in the form of a string or a Reader object. docSystemId takes the system identifier for parsing XML doc. xsltSystemId takes the system identifies for parsing XSLT doc. var takes the variable name to which the transformed XML doc has to be set. scope specifies the scope of the var attribute. result the javax.xml.transform.Result object that captures or processes the transformation result.

<x:param> tag 1. 2. It is used to set transformation parameters. It should be used within the body of the <x:transform> tag. syntax : <x:param attributes> [body content] </x:param> Attributes are : 1. 2.
KNSIT

name takes the name of the transformation parameter. value specifies the value of the transformation parameter. It is optional. Value of the param tag can also be specified.
Page 136

3. 4.

To use XML tags in your program you have to firstly download these jar files in your Tomcat's "lib"folder. These jar files are: 1. 2. 3. 4. 5. 6. 7. jstl.jar resolver.jar serializer.jar standard.jar xercesImpl.jar xercesSamples.jar 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> GRNICA </html>
JSTL Formatting Tags 1.
KNSIT

It provides the support for internationalization.


Page 139

2. 3. 4.

It provides the formatting of data in different domains. The data can be date, numbers or the time specifications in different domains. 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. 2. 3. Basic Formatting tags Number formatting tags Date formatting tags Time Zone tags

Basic Formatting tags 1. 2. They are used to format the data of a jsp page. These tags parse the data based on the current locale and provide support for internationalization. Types of basic formatting tags 1. 2. 3. 4. 5. 6. <fmt:setLocale> <fmt:setBundle> <fmt:bundles> <fmt:message> <fmt:param> <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. variant specifies the locale variant of the language referenced by value attribute. scope the scope into which this object has to be set.

2. 3.

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

<fmt:bundle> tag 1. 2. It creates a ResourceBundle object by using the Locale object in the locale configuration variable and the given base name. It then applies to the formatting actions in its body content. syntax : <fmt:bundle attributes> body content </fmt:bundle> Attributes are : 1. 2. basename specifies the resource bundle name 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. 2. 3. 4. key specifies the key that whose value has to be retrieved. bundle specifies the resource bundle that has to be used to get the value of the specified key. var specifies the variable to which the retrieved message has to be stored. scope specifies the scope of the variable defined in var attribute.

<fmt:param> tag 1. 2. It is used within the <fmt:message> element. 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. 2. 3. 4. It allows to set the character encoding of a request. It invokes the setCharacterEncoding() method of the ServletRequest interace to set the character encoding of a request. syntax : <fmt:requestEncoding attributes/> 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
ApplicationResources_it.properties

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

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

Save these ApplicationResources.properties files u folder.


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

KNSIT

Types of number formatting tags 1. 2. <fmt:formatNumber> <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. 2. 3. 4. 5. 6. 7. 8. 9. 10. 11. 12.
KNSIT

value specifies the numeric value that has to be formatted to the locale or given pattern. It is optional. type specifies the value type, accepted values are number, currency, and percent. If not specified, takes number as default. pattern specifies custom pattern to which the given value has to be formatted. currencyCode specifies the currency code as per ISO 4217 that has to be used in formatting. currencySymbol specifies the currency symbol that has to be included into the formatted number, used as type=currency. groupingUsed specifies whether the formatted output should contain any grouping separators. It is a boolean, default is true. maxIntegerDigits specifies max number of digits in integer portion of formatted output. minIntegerDigits - specifies min number of digits in integer portion of formatted output. maxFractionDigits specifies max number of digits in fractional portion of the formatted output. minFractionDigits - specifies min number of digits in fractional portion of formatted output. var specifies the variable name to which the formatted value has to be stored, if not specified, formatted value is written to JspWriter scope specifies the scope of the variable defined in var attribute.
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. 2. 3. value specifies the string value that has to be parsed according to the locale or given pattern. It is optional. type specifies the value type, accepted values are number, currency and percent. Default is number. 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 the parse operation. integerOnly specifies whether just the integer portion of the given value should be parsed. Default is false. var specifies the variable name to which the parsed value has to be stored. scope specifies the scope of the variable defined in var attribute.

used during 1. 2. 3.

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. 2. It is used to format the date type of data. Types of date formatting tags 1. 2. <fmt:formatDate> <fmt:parseDate>

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

KNSIT

syntax : <fmt:formatDate attributes/> Attributes are: 1. 2. 3. 4. 5. 6. value specifies the java.util.Date object whose date and or time to be formatted. pattern specifies the custom pattern to which the given value has to be formatted. type specifies the components of the given date object which has to be formatted, accepted values are date, time and both. dateStyle specifies the predefined formatting style for dates. Applicable only if type is both date and time. timeStyle specifies the predefined formatting style for time. Accepted values are default, short, medium, long and full. 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. var specifies the variable name to which the formatted value has to be stored. scope specifies the scope of the variable defined in var attribute

7. 8.

<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. 2. 3. 4. 5.
KNSIT

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

6. 7. 8. 9.

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 parseLocale specifies the Locale whose default formatting pattern is to be used during the parse operation var specifies the variable name to which the formatted value has to be stored. If not specified, written to current JspWriter. 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. 2. <fmt:timeZone> <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. 3. 4. 5. 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. var specifies the variable name. scope specifies the scope into which this object has to be set. 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. 2. The SQL tag library is used to access the relational database used in the JSP pages. 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. 2. 3. 4. 5. 6.

sql specifies the sql query that has to be executed, optional, can be executed in tag body. SQL query can be parameterized. var sepcifies the variable to wich result of query is set. scope specifies the scope of the variable. dataSource specifies the datasource JNDI name or java.sql.DataSource object. maxRows specifies the max number of rows that has to be included in result. 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. 6. 7.

password specifies the database password var specifies the name of the variable to which the DataSource object has to be set. 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> 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> 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>

1.

1.

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>\WEBINF\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: You can include a message in the body of the tag like standard tags. Assume you want to define a custom tag named <ex:Hello> and you want to use it in the following fashion with a body:
Page 160

1. 2.

KNSIT

<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. 2. A Java Bean is a software component that has been designed to be reusable in variety of different environments. 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. A Bean may be visible to an end user (ex. A button) A Bean may be invisible to a user (ex. Software to decode a stream of multimedia information in a real time) A Bean may be designed to work autonomously on a users workstation or to work in cooperation with a set of other distributed components.

3. 4. 5.

Advantages of Java Beans 1. 2.


KNSIT

A Bean obtains all the benefits of Javas write-once, run-anywhere paradigm. The properties, events, and methods of a Bean that are exposed to an application builder tool can be controlled.
Page 166

3. 4. 5.

A Bean may be designed to operate correctly in different locales, which makes it useful in global markets. 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. 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. 3. The Introspector class provides a standard way for tools to learn about the properties, events, and methods supported by a target Java Bean. 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. 2. 3. 4. 5. 6. If a class provides explicit BeanInfo about itself then we add that to the BeanInfo information we obtained from analyzing any derived classes. We then proceed to analyze the class's superclass and add in the information from it. decapitalize(String name) : Utility method to take a string and convert it to normal Java variable name. flushCaches() : Flush all of the Introspector's internal caches. flushFromCaches(Class classname) : Flush the Introspector's internal cached information for a given class. getBeanInfo(Class beanClass) : Introspect on a Java Bean and learn about all its properties, exposed methods, and events.
Page 167

KNSIT

7. 8. 9. 10.

getBeanInfo(Class beanClass, Class stopClass) : Introspect on a Java bean and learn all about its properties, exposed methods, below a given "stop" point. 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. getBeanInfoSearchPath() : Gets the list of package names that will be used for finding BeanInfo classes. setBeanInfoSearchPath(String[] path) : Change the list of package names that will be used for finding BeanInfo classes.

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

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

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

Class MethodDescriptor 1. 2. 3. A MethodDescriptor describes a particular method that a Java Bean supports for external access from other components. getMethod() : Gets the method that this MethodDescriptor encapsualtes. 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. 2. 3. 4.

JSP, Java Servlets and EJB form the nucleus of J2EE application. A J2EE application uses a browser-based user interface composed of a web page. An HTML form collects information from a user and formulates a request for web services, which is passed to the server-side component. 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. 2. 3. 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. The nature of the business logic and the interactions with other| server-side J2EE components are dependent on the J2EE application. An EJB is written in the Java programming language.

The EJB Container 1. 2. An EJB container is a vendor-provided entity located on the EBJ server that manages system-level services for EJB. 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. 2. Entity JavaBean class (entity bean) : used to represent business data. 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. 2. 3. 4.

The session and entity beans must have two interfaces. These are Home interface and the Remote interface. Both interfaces are declared by the developer of the EJB and are implemented by the EJB container. 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. 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.

2.

Deployment Descriptors 1. 2. 3. A deployment descriptor describes how EJBs are managed at runtime and enables the customization of EJB behavior without modification to the EJB code. A deployment descriptor is written in a file using XML syntax. 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. An EJB container references the deployment descriptor file to understand how to deploy and manage EJBs contained in package. The dd identifies the types of EJBs that are contained in the package as well as other attributes, such as how transactions aremanaged.

4. 5.

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. 2. 3. A Session bean contains business logic used to provide a service to a client and exists for the duration of the client server session. A session bean terminates once the session with the client server terminates. 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. A stateful session bean retains data(state) between method calls with a client during a session.

4.

When calls are made to multiple methods, the stateful session bean is able to retain state between calls 1. 2. The session bean can implement the SessionSynchronization interface, which makes the container notify the session bean of transaction-related events. 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. 5. 6. 7. 8. 9. 10. The bean needs to hold information about the client across method invocations. The bean mediates between the client and the other components of the application, presenting a simplified view to the client. Behind the scenes, the bean manages the work flow of several enterprise beans. Stateless session beans are appropriate if any of the following conditions are true: The bean's state has no data for a specific client. 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. 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 Page 178

KNSIT

the table rows that represent the products that are on sale this month.

Creating a Session Java Bean 1. 2. 3. 4. A session bean in a java class implements the SessionBean interface The SessionBean interface requires five methods to be defined in the session bean class. They are : ejbActive(), ejbPassive(), ejbRemove(), setSessionContext(SessionContext), ejbCreate() 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. An entity bean inserts, updates, and removes data while maintaining the integrity of data. 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. 5. 6. 7. 8. An entity bean can have a remote interface, a local interface or both interfaces. A remote interface enables remote clients to access the entity bean. A remote interface is used by a client not located in the EJB container. A local interface provides access to clients running within the same environment. A local interface is used by clients within the same EJB container.

2. 3.

Container-Managed Persistence 1. 2. 3. 4. The term container-managed persistence means that the EJB container handles all database access required by the entity bean. The bean's code contains no database access (SQL) calls. As a result, the bean's code is not tied to a specific persistent storage mechanism. 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. There are 3 groups of methods that are contained in an entity bean.
Page 180

5.
KNSIT

6. 7. 8. 9. 10. 11. 12.

These are creation methods, business methods and callback methods. ejbCreate() : EJB container calls this method when a client calls the EJBHome client method. ejbPostCreate() : Called by EJB container after performing the wrapper operation (creating a representation in database and creating a new Remote object.) There are two general types of business methods in an entity bean. 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. Callback methods are invoked in response to events that occur. There are seven callback methods : ejbLoad(), ejbStore(), setEntityContext(EntityContext), unsetEntityContext(), ejbActivate(), ejbPassivate() and ejbRemote().

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

Message-Driven Bean 1. 2. 3. 4. 5. 6.
KNSIT

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

7. 8.

The developer provide all the logic to process a message in the onMessage() method. 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. 2. 3. 4. 5. An MDB defines four methods : ejbCreate() : called when the MDB is created by the container. ejbRemove() : called by the EJB container when the container terminates the instance of the MDB. setMessageDrivenContext() : creates the context for the MDB. onMessage() : called each time when the EJB container receives a JMS message from a client.

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

KNSIT

Page 182

END OF EJB

KNSIT

Page 183

You might also like