1.
The CallableStatement object is used to call a stored procedure from within a J2EE object.
2.
A Stored procedure is a block of code and is identified by a unique name.
3.
The type and style of code depends on the DBMS vendor and can be written in PL/SQL, Transact-SQL, C, or other programming languages.
4.
IN, OUT and INOUT are the three parameters used by the CallableStatement object to call a stored procedure.
5.
The IN parameter contains any data that needs to be passed to the stored procedure and whose value is assigned using the setxxx() method.
6.
The OUT parameter contains the value returned by the stored procedures. The OUT parameters must be registered using the registerOutParameter() method, later retrieved by using the getxxx()
7.
The INOUT parameter is a single parameter that is used to pass information to the stored procedure and retrieve information from the stored procedure.
Connection Db; try { String query = "{CALL LastOrderNumber (?))}"; CallableStatement cstatement = Db.prepareCall(qu cstatement.registerOutParameter(1,Types.VARCH cstatement.eqecute(); String lastOrderNumber = cstatement.getString(1); cstatement.close(); } catch (Exception e){} ResultSet
KNSIT
Page 19
1.
The ResultSet object contains methods that are used to copy data from the ResultSet into a Java collection object or variable for further processsing.
2.
Data in a ResultSet is logically organized into a virtual table consisting of rows and columns.
3.
The ResultSet uses a virtual cursor to point to a row of the virtual table.
4.
The virtual cursor is positioned above the first row of data when the ResultSet is returned by the executeQuery(). This means the virtual cursor must be moved to the frist row using the next() method.
5.
The next() returns a boolean true if the row contains data; else false.
6.
Once the virtual cursor points to a row, the getxxx() is used to copy data from the row to a collection, object or a variable.
KNSIT
Page 20
Reading The ResultSet
ResultSet Results; String FirstName, LastName, printrow; boolean Records = Results.next(); if(!Records) { System.out.println("No data returned."); return; } else { while(Results.next()) { FirstName = Results.getString(1); LastName = Results.getString(2); printrow = FirstName + " " + LastName; System.out.println(printrow); } } Scrollable Resultset
1.
In JDBC 2.1 API the virtual cursor can be moved backwards or positioned at a specific row.
2.
Six methods are there for Resultset object. They are first(), last(), previous(), absolute(), relative() and getrow().
3.
first() method moves the virtual cursor to the first row in the Resultset.
4.
last() method positions the virtual cursor at the last r ow in the Resultset
KNSIT
Page 21
5.
previous() method moves the virtual cursor to the previous row.
6.
absolute() method positions the virtual cursor to a specified row by the an integer value passed to the method.
7.
relative() method moves the virtual cursor the specified number of rows contained in the parameter.
1.
The parameter can be positive or negative integer.
2.
The getRow() method returns an integer that represents the number of the current row in the Resultset.
3.
To handle the scrollable ResultSet , a constant value is passed to the Statement object that is created using the createStatement(). Three constants. - TYPE_FORWARD_ONLY - TYPE_SCROLL_INSENSITIVE - TYPE_SCROLL_SENSITIVE
1.
TYPE_FORWARD_ONLY constant restricts the virtual cursor to downward movement(default setting).
The other two allow the virtual cursor to move in both directions Updatable ResultSet
1.
Rows contained in the ResultSet can be updatable similar to how rows in a table can be updated.
2.
This is possible by passing the createStatement() method of the Connection object the CONCUR_UPDATABLE.
3.
CONCUR_READ_ONLY constant can be passed to the createStatement() method to prevent the ResultSet from being updated.
4.
There are three ways in which a ResultSet can be changed.
5.
These are updating values in a row, deleting a row, and inserting a new row.
All are accomplished by using the methods of the Statement object Update ResultSet
1.
Once the executeQuery() of the Statement object returns a ResultSet, the updatexxx() is used to change the value of column in the current row of the ResultSet.
2.
The xxx in the updatexxx() is replaced with the data type of the column that is to be updated.
KNSIT
Page 22
3.
The updatexxx() requires two parameters. The first is either the number or name of the column of the ResultSet that is being updated and the second is the value that will replace the value in the column of the ResultSet.
4.
A value in a column of the ResultSet can be replaced with a NULL value by using the updateNull(). It requires one parameter, which is the number of column in the current row of the ResultSet. The updateNull() don’t accept name of the column as a parameter.
5.
The updateRow() is called after all the updatexxx() are called.
KNSIT
Page 23
try { String query = "SELECT FirstName, LastName FROM 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
m o r f Y L . t e S t l
2.
The deleteRow() is passed an integer that contains the number of the row to be deleted.
3.
First use the absolute() method to move the virtual cursor to the row in the Resultset that should be deleted.
4.
The value of that row should be examined by the program to assure it is the proper row before the deleteRow() is called.
5.
The deleteRow() is then passed a zero integer indicating that the current row must be deleted. Resuts.deleteRow(0);
Insert Row in the ResultSet
1.
Inserting a row into the ResultSet is accomplished using basically the same technique as is used to update the ResultSet.
2.
The updatexxx() is used to specify the column and value that will place into the column of the ResultSet.
3.
The insertRow() is called after the updatexxx(), which causes a new row to be inserted into the ResultSet.
KNSIT
Page 25
try { String query = "SELECT FirstName, LastName FROM Custo DataRequest = Db.createStatement(ResultSet.CONCUR_UP Resulsts = DataRequest.executeQuery(query);
} catch (Exception e){} boolean Records = Results.next(); if(!Records) { System.out.println("No data returned."); System.exit(4); } try { Results.updateString(1, "Smith"); Results.updateString(2, “Tom”); Results.insertRow(); DataRequest.close(); } catch (){} Transaction Processing
1.
A transaction may involve several tasks.
2.
A database transaction consists of a set of SQL statements, each of which must be successfully completed for the transaction to be completed.
KNSIT
Page 26
3.
If any one fails, then the transaction must be rolled back.
4.
The database transaction is not completed until the J2EE component calls the commit() method of the Connection object.
5.
The commit() method must be called regardless if the SQL statement is part of a transaction or not.
6.
The commit() method was automatically called in the previous examples because the DBMS has an AutoCommit feature that is by default set to true.
7.
If a J2EE component is processing a transaction, the AutoCommit feature must be deactivated by calling the setAutoCommit() method and passing it a false parameter.
Once the transaction is completed, the setAutoCommit() method is called again by passing a true parameter
String url = "jdbc:odbc:CustomerInformation"; String userID = "jim"; String password = "keogh"; Statement DataRequest1, DataRequest2; Connection Db; try { Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); Db = DriverManager.getConnection(url,userID,password); }catch(Exception e){}
KNSIT
Page 27
try { Db.setAutoCommit(false); String query1 = "UPDATE Customers SET Street = '5 Main Street'"+ "WHERE FirstName='Bob'"; String query2 = "UPDATE Customers SET Street = '10 Main Street'"+ "WHERE FirstName='Tim'"; DataRequest1=Db.createStatement(); DataRequest2=Db.createStatement(); DataRequest1.executeUpdate(quiery1); DataRequest2.executeUpdate(quiery2); Db.commit(); DataRequest1.close(); DataRequest2.close(); Db.close(); } catch (SQLException ex){ } 1.
The J2EE component can control the number of tasks that are rolled back by using savepoints.
2.
There can be many savepoints used in a transactions. Each savepoint is identified by a unique name.
The savepoint name is then passed to the rollback() method to specify the point within the transaction where the rollback is to stop
KNSIT
Page 28
String url = "jdbc:odbc:CustomerInformation"; String userID = "jim"; String password = "keogh"; Statement DataRequest1, DataRequest2; Connection Db; try { Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); Db = DriverManager.getConnection(url,userID,password); }catch(Exception e){}
KNSIT
Page 29
try { Db.setAutoCommit(false); String query1 = "UPDATE Customers SET Street = '5 Main Street'"+ "WHERE FirstName='Bob'"; String query2 = "UPDATE Customers SET Street = '10 Main Street'"+ "WHERE FirstName='Tim'"; DataRequest1=Db.createStatement(); Savepoint s1 = Db.setSavepoint("sp1"); DataRequest2=Db.createStatement(); DataRequest1.executeUpdate(quiery1); DataRequest2.executeUpdate(quiery2); Db.commit(); DataRequest1.close(); DataRequest2.close(); Db.releaseSavepoint("sp1"); Db.close(); } catch (SQLException ex){ } 1.
Another way to combine SQL statements into a transaction is to batch together these statements into a single transaction and then execute the entire transaction.
2.
This can be done using the addBatch() method of the Statement object.
3.
The addBatch() method receives a SQL statement as a parameter and places the SQL statements in the batch.
4.
Once all the SQL statements ahat comprises the transaction are included in the batch, the executeBatch() method is called to execute the entire batch at the same time.
KNSIT
Page 30
The executeBatch() method returns an int array that contains the number of SQL statements that were executed successfully
String url = "jdbc:odbc:CustomerInformation"; String userID = "jim"; String password = "keogh"; Statement DataRequest, DataRequest1, DataRequest2; Connection Db; try { Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); Db = DriverManager.getConnection(url,userID,password); }catch(Exception e){} try {
KNSIT
Page 31
Db.setAutoCommit(false); String query1 = "UPDATE Customers SET Street = '5 Main Street'"+ "WHERE FirstName='Bob'"; String query2 = "UPDATE Customers SET Street = '10 Main Street'"+ "WHERE FirstName='Tim'"; DataRequest=Db.createStatement(); DataRequest1.addBatch(query1); DataRequest2.addBatch(query2); int[] updated = DataRequest.executeBatch(); Db.commit(); DataRequest1.close(); DataRequest2.close(); Db.close(); } catch (SQLException ex){ } ResultSet Holdability
1.
Whenever the commit() method is called, all ResultSet objects that were created for the transaction are closed.
2.
Sometimes a J2EE component needs to keep the ResultSet open even after the commit() method is called.
3.
We can control whether or not ResultSet objects are closed following the call to the commit() method by passing oen of two constants to the createStatement() method.
4.
These constants are HOLD_CURSORS_OVER _COMMIT and CLOSE_CURSORS_AT_COMMIT.
5.
HOLD_CURSORS_OVER _COMMIT constant keeps ResultSet objects open following a call to the commit() method.
KNSIT
Page 32
6.
CLOSE_CURSORS_AT_COMMIT closes ResultSet objects when the commit() method is called.
RowSets
1.
The JDBC RowSets object is used to encapsulate a ResultSet for use with Enterprise Java Bean(EJB).
2.
A RowSet object contains rows of data from a table(s) that can be used in a disconnected operation.
Auto-Generated Keys
1.
It is common for a DBMS to automatically generate unique keys for a table as rows are inserted into the table.
2.
The getGeneratedKeys() method of the Statement object is called to return keys generated by the DBMS.
3.
The getGeneratedKeys() returns a ResultSet object and can use the ResultSet.getMetaData() to retrieve metadata relating to the automatically generated key.
Metadata
1.
Metadata is data about data. A J2EE component can access metadata using the DatabaseMetaData interface.
2.
The DatabaseMetaData interface is used to retrieve information about database, tables, columns, and indexes among other information about the DBMS.
3.
Some of the commonly used DatabaseMetaData objects methods:
4.
getDatabaseProductName() – returns the product name of the database
5.
getUserName() – returns the URL of the database.
6.
getURL() – returns all the schema names available in this database.
7.
getPrimaryKeys() – returns primary keys
8.
getProcedures() – returns stored procedures names.
9.
getTables() – returns names of the tables in the database.
ResultSet Metadata
1.
KNSIT
There are 2 types of metadata that can be retrieved from the DBMS.
Page 33
2.
These are metadata that describes the database mentioned earlier and metadata that describes the ResultSet.
3.
Metadata describing ResultSet is retrieved by calling the getMetaData() of ResultSet object. 1.
ResultSetMetadata rm = Result.getMetaData()
4.
More commonly called methods are:
5.
getColumnCount() – gets the no. of columns contained in the ResultSet.
6.
getColumnName() – gets the name of the column specified by the column number.
7.
getColumnType(int number) – gets the data type of the column specifed by the column number.
KNSIT
Page 34
Data Types
Table contains a list of data types and their java equivalents. We can use this list to determine the proper data name to use to replace the xxx in the setxxx() and getxxx() methods.
Exceptions
1.
There are three kinds of exceptions that are thrown by JDBC methods.
2.
They are SQLExceptions, SQLWarnings and Data Truncation.
KNSIT
Page 35
3.
SQLExceptions commonly reflect a SQL syntax error in the query and are thrown by many of the methods contained in the java.sql package.
4.
The SQLWarning throws warnings received by the Connection from the DBMS.
5.
The getWarnings() and getNextWarning() methods of Connection object retrieves warnings and subsequent warnings respectively.
6.
DataTruncation exception is thrown whenever data is lost due to truncation of data value.
END OF JDBC
3:4:SERVLETS & SERVLETS-SESSIONS Introduction. 1.
Servlets are small programs that execute on the server side of a Web connection.
2.
Servlets are server side components that provides a powerful mechanism for developing server web applications for server side.
3.
Just as applets dynamically extend the functionality of a Web browser, servlets dynamically extend the functionality of a Web server.
4.
Using servlets web developers can create fast and efficient server side applications and can run it on any servlet enabled web server.
5.
Servlet runs entirely inside the Java Virtual Machine.
6.
Since the servlet runs on server side so it does not depend on browser compatibility.
KNSIT
Page 36
Background • In order to understand the advantages of servlets, a basic understanding of how Web browsers and se to provide content to a user. Webserver map 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.
But the content of the dynamic web pages need to be generated dynamically.
2.
In the early days of the Web, a server could dynamically construct a page by creating a separate process to handle each client request.
3.
The process would open connections to one or more databases in order to obtain the necessary information.
KNSIT
Page 37
4.
It communicated with the Web server via an interface known as the Common Gateway Interface (CGI).
5.
CGI allowed the separate process to read data from the HTTP request and write data to the HTTP response.
6.
However, CGI suffered serious performance problems. It was expensive in terms of processor and memory resources to create a separate process for each client request.
It was also expensive to open and close database connections for each client request. In addition, the CGI programs were not platform-independent. Therefore, other techniques were introduced 1.
Servlets offer several advantages in comparison with CGI.
2.
First, performance is significantly better. It is not necessary to create a separate process to handle each client request.
3.
Second, servlets are platform-independent because they are written in Java.
4.
Third, the Java security manager on the server enforces a set of restrictions to protect the resources on a server machine.
5.
Finally, the full functionality of the Java class libraries is available to a servlet. It can communicate with applets, databases, or other software via the sockets and RMI mechanisms.
The Life Cycle of a Servlet
1.
init( ), service( ), and destroy( ) are the three methods which are central to the life cycle of a servlet.
2.
They are implemented by every servlet and are invoked at specific times by the server.
KNSIT
Page 38
3.
Let us consider a user scenario to understand when these methods are called.
4.
First, user enters URL, browser then generates an HTTP request for this URL, & this request is then sent to the appropriate server.
5.
second, this HTTP request is received by web server, web server maps this request to a particular servlet. The servlet is dynamically retrieved & loaded into the address space of the server.
6.
Third, server invokes init( ) method of the servlet. This method is invoked only when the servlet is first loaded into memory. It is possible to pass initialization parameters to the servlet so it may configure itself.
7.
Fourth, the server invokes the service( ) method of the servlet. This method is called to process the HTTP request. It may also formulate an HTTP response for the client. The service( ) method is called for each HTTP request.
8.
Finally, the server may decide to unload the servlet from its memory.The server calls the destroy( ) method to relinquish any resources such as file handles that are allocated for the servlet.
A Simple Servlet
1.
KNSIT
The basic steps to be followed: 1.
Create and compile the servlet source code.
2.
Start Tomcat.
3.
Start a Web browser and request the servlet.
Page 39
This package contains the interfaces required to buil
A Simple Servlet Code import java.io.*; import javax.servlet.*; public class HelloServlet extends GenericServlet { public void service(ServletRequest request, Servlet response)throws ServletException, { response.setContentType("text/html"); PrintWriter pw = response.getWriter(); pw.println("
Hello!"); pw.close(); } } Enables the servlet to formulat the client.
getWriter() obtains PrintW
written to this stream is sent GRNICA of HTTP res onse. The Servlet API
1.
KNSIT
javax.servlet and javax.servlet.http are the two packages that contains the classes required to build servlet.
Page 40
2.
These packages are not part of Java Java core packages, they are standard extensions provided provided by Tomcat.
3.
The current servlet specification is version 2.4.
4.
The Servlet API is supported supported by most Web servers, such as those those from Sun, Microsoft, and others.
Check at http://java.sun.com for the latest information The javax.servlet Package
1.
The javax.servlet package contains a number of interfaces and classes that establish the framework in which servlets operate.
2.
The following table summarizes summarizes the core interfaces that are provided provided in this package.
GRNICA
The Servlet Interface
1.
All servlets must implement the Servlet interface. The methods defined by Servlet are shown in table below
KNSIT
Page 41
The ServletConfig Interface
1.
It allows a servlet to obtain configuration data when it is loaded.
2.
The methods declared by this interface are summarized here:
The ServletContext Interface
1.
ServletContext is is a interface which helps us to communicate communicate with the servlet container.
2.
It enables servlets to obtain information about their environment.
3.
There is only one ServletContext ServletContext for the entire web application application and the components of the web application can share it.
4.
The information in the the ServletContext will be common common to all the components.
KNSIT
Page 42
5.
Each servlet will have its own ServletConfig. Ser vletConfig.
6.
The ServetContext is created by by the container when the web application is deployed deployed and after that only the context context is available to each servlet in the web application. application. Several of its methods are summarized in table below.
The ServletRequest Interface
1.
It enables a servlet to obtain information about a client request.
2.
Several of its methods are summarized in table below.
KNSIT
Page 43
The ServletResponse Interface
1.
It enables a servlet to formulate a response for a client.
2.
Several of its methods are summarized in table below.
KNSIT
Page 44
The following table summarizes the core classes that are provided in the javax.servlet package.
The GenericServlet Class
1.
The GenericServlet class provides implementations of the basic life cycle methods for a servlet.
2.
GenericServlet implements the Servlet and ServletConfig interfaces.
3.
In addition, a method to append a string to the server log file is available. The signatures of this method are shown here: void log(String s) void log(String s, Throwable e)
1.
Here, s is the string to be appended to the log, and e is an exception that occurred. The ServletInputStream Class
1. 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.
KNSIT
Here, buffer is the array into which size bytes are placed starting at offset . Page 45
The ServletOutputStream Class 1.
The ServletOutputStream class extends OutputStream.
2.
It is implemented by the server and provides an output stream that a servlet developer can use to write data to a client response.
3.
A default constructor is defined. It also defines the print( ) and println( ) methods, which output data to the stream. The Servlet Exception Classes
1.
javax.servlet defines two exceptions.
2.
The first is ServletException, which indicates that a servlet problem has occurred.
3.
The second is UnavailableException, which extends ServletException. It indicates that a servlet is unavailable. Reading Servlet Parameters
1.
The ServletRequest class includes methods that allow you to readthe names and values of parameters that are included in a client request.
2.
The example contains two files. A Web page is defined in PostParameters.htm and a servlet is defined in PostParametersServlet.java.
KNSIT
Page 46