J2EE Full Notes

Embed Size (px)

DESCRIPTION

J2EE Notes

Citation preview

  • KNSIT Page 1

    1:JDBC objects

    The Concept Of JDBC

    1. There are many DBMSs commercially available in the market. These include Oracle, DB2, Sybase etc..

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

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

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

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

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

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

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

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

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

    JDBC drivers created by DBMS manufacturers have to

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

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

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

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

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

    Close the connection b/n DBMS and the J2EE component

    JDBC Driver Types

  • KNSIT Page 2

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

    Type 1 JDBC-to-ODBC Driver

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

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

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

    format & later to the format understood by the DBMS.

    Type 2 Java/Native Code Driver

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

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

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

    Type 3 JDBC Driver

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

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

    Type 4 JDBC Driver

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

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

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

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

    JDBC Packages

    1. The JDBC API is contained in two packages.

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

  • KNSIT Page 3

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

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

    javax.sql includes the data objects that interact with Java Naming and Directory Interface

    (JNDI) and Java data objects that manage connection pooling, among other advanced JDBC

    features

    A Brief Overview of the JDBC Process

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

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

    1. Loading the JDBC driver

    2. Connecting to the DBMS

    3. Creating and executing a statement

    4. Processing data returned by the DBMS

    5. Terminating the connection with the DBMS

    Loading the JDBC Driver

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

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

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

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

    Connect to the DBMS

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

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

    managing driver information

  • KNSIT Page 4

    1. The DriverManager.getConnection() method is passed with the URL of the database, the user ID and the password if required by DBMS.

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

    3. The DriverManager.getConnection() method returns a Connection interface that is used throughout the process to reference the database.

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

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

    Create and Execute a SQL Statement

    String url = "jdbc:odbc:CustomerInformation"; String userID = "jim"; String password = "keogh"; Statement DataRequest; private Connection Db; try { Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); Db = DriverManager.getConnection(url,userID,password); }

  • KNSIT Page 5

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

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

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

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

    J2EE component.

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

    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

    Statement DataRequest; ResultSet Results try { String query = " SELECT * FROM Customers"; DataRequest = Db.createStatement(); Results = DataRequest.executeQuery(query); DataRequest.close(); }

  • KNSIT Page 6

    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.

    16

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

  • KNSIT Page 7

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

    Db.close();

    Example Program : Connecting to MS-Access

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

  • KNSIT Page 8

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

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

  • KNSIT Page 10

    Database Connection

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

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

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

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

    The Connection

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

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

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

    2. which is the JDBC driver name.

    3. which is the name of the database.

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

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

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

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

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

    22

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

  • KNSIT Page 12

    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 13

    TimeOut

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

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

    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.JdbcOdbcDriver"); Db=DriverManager.getConnection(url,props); } catch (Exception e){}

  • KNSIT Page 14

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

    DBMS before timing out.

    4. The public static int DriverManager.getLoginTimeout() is used to retrieve from the DriverManager the max time the DriverManager is set to wait until it times out.

    5. This method returns an int that represents seconds.

    Associating the JDBC/ODBC Bridge with the Database

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

    1. Select Start-> settings and then control panel

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

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

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

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

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

    7. . Click the Select button. We will be prompted to browse the directory of each hard drive connected to our computer in order to define the direct path to the database. Click OK once we

    locate the database. Then directory path and the name of the database will be displayed in the

    ODBC Microsoft Access Setup dialog box.

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

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

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

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

    12. Statement Objects

    Once a connection to the database is opened, the J2EE component creates and sends a query to

    access data contained in the database.

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

  • KNSIT Page 15

    These objects are Statement, which executes a query immediately.

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

    to execute store procedures

    The Statement Object

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

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

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

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

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

    the query.

  • KNSIT Page 16

    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 17

    PreparedStatement Object

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

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

    Next is how to use the executeUpdate() of the Statement object.

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

  • KNSIT Page 18

    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.

    CallableStatement

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

  • KNSIT Page 19

    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.

    ResultSet

    36

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

  • KNSIT Page 20

    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 21

    Scrollable Resultset

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

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

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

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

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

  • KNSIT Page 22

    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 23

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

    column of the ResultSet.

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

    ResultSet. The updateNull() dont accept name of the column as a parameter.

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

  • KNSIT Page 24

    Delete Row in the ResultSet

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

    43

    try { String query = "SELECT FirstName, LastName FROM Customers WHERE FirstName='Mary' and LastName='Smith'"; DataRequest = Db.createStatement(ResultSet.CONCUR_UPDATABLE); 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 (){}

    Helps to update a ResultSet. CONCUR_READ_ONLY prevents the ResultSet from being updated.

  • KNSIT Page 25

    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 26

    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.

    46

    try { String query = "SELECT FirstName, LastName FROM Customers; DataRequest = Db.createStatement(ResultSet.CONCUR_UPDATABLE); 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 (){}

  • KNSIT Page 27

    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 28

    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

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

  • KNSIT Page 29

    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 30

    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.

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

  • KNSIT Page 31

    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 32

    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.

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

  • KNSIT Page 33

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

    RowSets

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

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

    Auto-Generated Keys

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

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

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

    Metadata

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

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

    3. Some of the commonly used DatabaseMetaData objects methods:

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

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

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

    7. getPrimaryKeys() returns primary keys

    8. getProcedures() returns stored procedures names.

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

    ResultSet Metadata

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

  • KNSIT Page 34

    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 35

    Exceptions

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

    2. They are SQLExceptions, SQLWarnings and Data Truncation.

    59

    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.

  • KNSIT Page 36

    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 37

    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.

    Background In order to understand the advantages of servlets, you must have

    a basic understanding of how Web browsers and servers cooperate to provide content to a user.

    Requests for a static web page through web browser & it will generate the HTTP request to appropriate web server.

    Client Server

    Webserver maps this request to a specific file & is returned in a HTTP response to the browser.

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

  • KNSIT Page 38

    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 39

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

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

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

    server.

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

    configure itself.

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

    is called for each HTTP request.

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

    A Simple Servlet

    1. The basic steps to be followed:

    1. Create and compile the servlet source code.

    2. Start Tomcat.

    3. Start a Web browser and request the servlet.

  • KNSIT Page 40

    The Servlet API

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

    GRNICA 9

    A Simple Servlet Code import java.io.*; import javax.servlet.*; public class HelloServlet extends GenericServlet { public void service(ServletRequest request, ServletResponse response)throws ServletException, IOException { response.setContentType("text/html"); PrintWriter pw = response.getWriter(); pw.println("Hello!"); pw.close(); } }

    This package contains the classes and interfaces required to build servlets.

    Enables the servlet to formulate a response for the client.

    getWriter() obtains PrintWriter. Anything written to this stream is sent to the client as part of HTTP response.

  • KNSIT Page 41

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

    3. The current servlet specification is version 2.4.

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

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

    The javax.servlet Package

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

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

    The Servlet Interface

    1. All servlets must implement the Servlet interface.

    The methods defined by Servlet are shown in table below

    GRNICA 11

  • KNSIT Page 42

    The ServletConfig Interface

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

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

    The ServletContext Interface

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

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

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

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

  • KNSIT Page 43

    5. Each servlet will have its own ServletConfig.

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

    Several of its methods are summarized in table below.

    The ServletRequest Interface

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

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

  • KNSIT Page 44

    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 45

    The following table summarizes the core classes that are provided

    in the javax.servlet package.

    The GenericServlet Class

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

    2. GenericServlet implements the Servlet and ServletConfig interfaces.

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

    void log(String s)

    void log(String s, Throwable e)

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

    The ServletInputStream Class

    1. The ServletInputStream class extends InputStream. It is implemented by the server and provides an input stream that a servlet developer can use to read the data from a client request.

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

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

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

  • KNSIT Page 46

    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 47

    GRNICA 24

  • KNSIT Page 48

    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 49

    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

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

  • KNSIT Page 50

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

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

  • KNSIT Page 51

  • KNSIT Page 52

    The HttpServletResponse Interface

    1. The HttpServletResponse interface is implemented by the server. It enables a servlet to formulate an HTTP response to a client.

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

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

  • KNSIT Page 53

    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 54

    The HttpSessionBindingListener Interface

    1. The HttpSessionBindingListener interface is implemented by objects that need to be notified when they are bound to or unbound from an HTTP session.

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

    void

    valueBound(HttpSessionBindingEvent e)

    void

    valueUnbound(HttpSessionBindingEvent e)

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

    The Cookie Class

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

    2. Cookies are valuable for tracking user activities.

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

    visits the store.

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

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

  • KNSIT Page 55

    The name of the cookie

    The value of the cookie

    The expiration date of the cookie

    The domain and path of the cookie

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

    2. If an expiration date is not explicitly assigned to a cookie, it is deleted when the current browser session ends. Otherwise, the cookie is saved in a file on the users machine.

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

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

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

    The methods of the Cookie class are summarized in Table below

  • KNSIT Page 56

    The HttpServlet Class

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

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

  • KNSIT Page 57

    The HttpSessionEvent Class

    1. HttpSessionEvent encapsulates session events. It extents EventObject and is generated when a change occurs to the session.

    2. It defines this constructor: HttpSessionEvent(HttpSession session)

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

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

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

    The HttpSessionBindingEvent Class

  • KNSIT Page 58

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

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

    3. Here are its constructors: HttpSessionBindingEvent(HttpSession session, String name)

    HttpSessionBindingEvent(HttpSession session, String name, Object val)

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

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

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

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

    Object getValue( )

    Handling HTTP Requests and Responses

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

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

    Handling HTTP GET Requests

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

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

    ColorGetServlet.java

  • KNSIT Page 59

    Color: Red Green Blue

  • KNSIT Page 60

    Handling HTTP POST Requests

    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("The selected color is: "); pw.println(color); pw.close(); } }

  • KNSIT Page 61

    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

    Color: Red Green Blue

  • KNSIT Page 62

    Using Cookies

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

    GRNICA 52

    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("The selected color is: "); pw.println(color); pw.close(); } }

  • KNSIT Page 63

    GRNICA 52

    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("The selected color is: "); pw.println(color); pw.close(); } }

  • KNSIT Page 64

    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 65

    // 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("MyCookie has been set to"); pw.println(data); pw.close(); } }

  • KNSIT Page 66

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

  • KNSIT Page 67

    Session Tracking

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

    2. However, in some applications, it is necessary to save state information so that information can be collected from several interactions between a browser and a server. Sessions provide

    such a mechanism.

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

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

    5. The setAttribute( ), getAttribute( ), getAttributeNames( ), and removeAttribute( ) methods of HttpSession manage these bindings.

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

  • KNSIT Page 68

    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 the current session

  • KNSIT Page 69

    // Get writer. response.setContentType("text/html"); PrintWriter pw = response.getWriter(); pw.print(""); // Display date/time of last access. Date date = (Date)hs.getAttribute("date"); if(date != null) { pw.print("Last access: " + date + ""); } // Display current date/time. date = new Date(); hs.setAttribute("date", date); pw.println("Current date: " + date); } }

    Called to obtain the object that is bound

    to the name date.

    This method is called to bind the name

    date to this object.

  • KNSIT Page 70

    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, IOException { response.setContentType("text/html"); PrintWriter pw = response.getWriter(); pw.println("Checking whether the session is new or old"); HttpSession session = request.getSession(); String id = session.getId(); pw.println("Session Id is : " + id);

  • KNSIT Page 71

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

  • KNSIT Page 72

    Servlets reads Username & password as parameters.

    New Page 1 Login Please enter your username and password

  • KNSIT Page 73

    GRNICA 64

    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(""); out.println(""); out.println("Thanks " + " " + name + " " + "for visiting our site...!" ); out.println("Now you can see your password : " + " " + pass + ""); out.println(""); } }

  • KNSIT Page 74

    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 75

    String name = request.getParameter("username"); String password = request.getParameter("password"); if(name.equals("Hemanth")&& password.equals("Kumar")) { response.sendRedirect("/jnnce/ValidUserServlet"); } else { pw.println("u r not a valid user"); } } }

  • KNSIT Page 76

    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 77

    New Page 1 Enter your name Enter your password

  • KNSIT Page 78

    RequestDispatcher

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

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

    import java.io.*; import javax.servlet.*; public class Download extends GenericServlet { public void service(ServletRequest request,ServletResponse response)throws ServletException,IOException { response.setContentType("text/html"); PrintWriter pw=response.getWriter(); pw.println(" click here to download"); pw.close(); } }

    To download a file using servlet

  • KNSIT Page 79

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

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

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

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

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

    io.IOException

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

    signature of the forward method is as follows:

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

    IOException

    1. Use the getRequestDispatcher method of the javax.servlet.ServletRequest interface, passing a String containing the path to the other resource. The path is relative to the current

    HTTP request.

  • KNSIT Page 80

    GRNICA 72

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

  • KNSIT Page 81

    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 82

    if (userName!=null && password!=null && userName.equals("jnnce") && password.equals("mca")) { RequestDispatcher rd = request.getRequestDispatcher("WelcomeServlet1"); rd.forward(request, response); } else { out.println( Not a valid user."); } } }

  • KNSIT Page 83

    Login

  • KNSIT Page 84

    User Name:

    Password:

    Filter API

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

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

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

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

    1. Query the request and act accordingly.

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

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

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

    5. Interact with external resources.

    6. Applications of filters include authentication, logging, image conversion, data compression, encryption, tokenizing streams, and XML transformations.

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

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

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

    This method can perform the following actions:

    10. Examine the request headers.

  • KNSIT Page 85

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

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

    13. Invoke the next entity in the filter chain.

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

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

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

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

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

    An example filter program

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

    implementing "Filter" class.

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

    21. void init(FilterConfig filterConfigObject) throws ServletException

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

    22. void destroy()

    23. void doFilter(ServletRequest request, ServletResponse response, FilterChain filterchainObject) throws IOException, ServletException

    import java.io.*;

    import javax.servlet.*;

    import javax.servlet.http.*;

    public final class LoggingFilterExample implements Filter

    {

    private FilterConfig filterConfigObj = null;

    public void init(FilterConfig filterConfigObj)

    {

    this.filterConfigObj = filterConfigObj;

  • KNSIT Page 86

    }

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

    { }

    }

    LoggingFilterExample

    LoggingFilterExample

    LoggingFilterExample

    /*

    Multi-tier Applications Using Database Connectivity

    EMPLOYEE DETAILS 1

    Enter Name:

    Enter EID:

    Enter ADDRESS :

    package access;

    import java.io.*;

    import java.sql.*;

    import javax.servlet.*;

  • KNSIT Page 87

    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("Record has been inserted");

    }

    else {

    pw.println("failed to insert the data");

    }

    }

    catch (Exception e)

    {

    pw.println(e);

    }

    }

    }

  • KNSIT Page 88

    END OF SERVLETS AND SESSION

    5:JAVA SERVER PAGES

    JSP

    1. Java ServerPages is a server-side program.

    2. A JSP is called by a client to provide a web service.

    3. A JSP processes the request by using logic built into the JSP or by calling other web components built using Java servlet technology or Enterprise Java Bean technology or

    other technology.

  • KNSIT Page 89

    4. A JSP is simple to create, a JSP is written in HTML rather tha with the Java programming language.

    5. A JSP offers basically the same features found in Java servlet because a JSP is converted to a Java servlet the first time that aclient requests the JSP.

    6. JSP pages are translated into servlets, the servlets are compiled, and at request time it is the compiled servlets that execute. So,writing JSP pages is really just another way of

    writing servlets.

    7. jspInt(), jspDestroy() and service() are the three methods that are automatically called when a JSP is requested and terminates normally.

    8. The jspInt() is called first when the JSP is requested and is used to initialize objects and variables that are used throughout the life of JSP.

    9. The jspDestroy() is automatically called when the JSP terminates normally. When JSP abruptly terminated, it is not called.

    10. The service() is automatically called and retrieves a connection to HTTP.

    Advantages of JSP

    11. JSP are translated and compiled into JAVA servlets but are easier to develop than JAVA servlets.

    JSP uses simplified scripting language based syntax for embedding HTML into JSP.

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

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

    developer

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

    JSP Tags

    1. A JSP programs consists of a combination of HTML tags and JSP tags.

    2. JSP tags define Java code that is to be executed before the output of the JSP program is sent to the browser.

  • KNSIT Page 90

    3. Java codes associated with JSP tags in the JSP program is executed when encountered by Tomcat, and the result of that process is sent to the browser.

    4. The browser knows how to display the result because the JSP tag is enclosed within an open and closed HTML tag.

    There are five types of JSP tags.

    5. Comment tag : A comment tag opens with .

    6. Declaration Statement tags : It opens with

  • KNSIT Page 91

    15. request: request represents the clients request and is a subclass of HttpServletRequest. Use this variable to retrieve the data

    submitted along the request.

    16. response: response is subclass of HttpServletResponse.

    17. session: session represents the HTTP session object associated with the request.

    18. out: out is an object of output stream and is used to send any output to the client.

    Expression tags : It opens with .

    Syntax of JSP Expressions are:

    Example JSP Program

    The Page Directives Page directives apply different properties for the page like language support, page

    information and import etc. by using the different attributes of the directives.

    19. There are three types of directives are as follows:

    20. Page Directive

    21. Include Directive

    22. Taglib Directive

    Syntax of the declaration of the page directive with it's attributes is

    Following are name of the attributes of the page directive used in JSP:

    23. Language

    24. extends

    25. import

    26. session

    27. buffer

  • KNSIT Page 92

    28. autoFlush

    29. isThreadSafe

    30. info

    31. errorPage

    32. contentType

    33. isErrorPage

    34. pageEncoding

    35. isELIgnored

    36. language: This attribute of page directive of JSP is used for specifying some other scripting languages to be used in the JSP page.

    37. extends: This is used for specifying some other java classes to be used in the JSP page like packagename.classname. The fully qualified name of the superclass of the Java class

    will be accepted.

    38. import: This attribute imports the java packages and it's classes. We can import more than one java packages and classes by separating with comma (,).

    39. We can set the name of the class with the package name directly like packagename.classname or import all classes of the package by using packagename.*

    40. session: This attribute sets a boolean value to either true or false. If the value of session attribute is true then the session object refers to the current or a new session because the

    client must be in the HTTP session for running the JSP page on the server. If we set the

    value of session object to false then we can not use the session object.

    41. buffer: This attribute sets the buffer size in kilobytes i.e. used by the out object to handle output generated by the JSP page on the client web browser. If we specify the buffer

    size then the output will be buffered with at least 8kb because the default and minimum

    value of the buffer attribute is 8kb.

    42. autoFlush: This attribute of the page directive supports for flushing buffer automatically when the buffer is full. The value of the autoFlush attribute is either true or false. If we

    specify it as true, then buffer will be flushed.

    43. isThreadSafe: This attribute support the facility of maintaining thread for sending multiple and concurrent requests from the JSP container to the JSP page if the value the

    of attribute is set to true, otherwise if we set the value of attribute to false, then the JSP

    container can send only one request at one time. The default value of the attribute is true.

  • KNSIT Page 93

    44. info: This attribute simply sets the information of the JSP page which is retrieved later by using Servlet.getServletInfo() method. The value of the attribute will be a text string.

    45. errorPage: This attribute sets a url. If any exception is generated then the attribute refers to the file which is mentioned in the given url. If no url id specified, then the attribute

    refers to the current page of the JSP application when exception generated

    46. isErrorPage: This attribute sets the boolean value to either true or false. We can use the exception object in the JSP page if we set the attribute value to true, otherwise we cannot

    use the exception object because the default value of the attribute is false.

    47. contentType: This attribute specifies the MIME type and the character encoding used for the JSP response. The default MIME type is "text/html" and the default character set

    is "ISO-88591".

    48. pageEncoding: This attribute specifies the language that the page uses when the page is sent to the browser. This attribute works like the meta tag of the HTML markup

    language.

    49. isELIgnored: This is a boolean attribute that specifies either true or false value. The isELIgnored option gives you the ability to disable the evaluation of Expression

    Language (EL) expressions which has been introduced in JSP 2.0. If we set the attribute

    value to true, then any type of the EL expressions will be ignored in the JSP page.

    Variables & Objects

    1. Order Confirmation

    Your age is :

    2. JSP Programming

    3. JSP Programming

  • KNSIT Page 94

    Methods

    4. JSP offers same functionality for defining methods as done by Java.

    5. In JSP a method definition is placed within a JSP tag.

    6. We can call the method from within the JSP tag once the method is defined.

    7. The JSP tag that calls the method must be a JSP expression tag, which begins with

  • KNSIT Page 95

    Control Statement

    Using JSP it is easy to create dynamic content for a web page based on conditions

    received from the browser.

    9. There are two control statements used to change the flow of a JSP program. These are the if statement and the switch statement, both of which are also used to direct the flow

    of a Java program.

    10. The power of these codes comes from the fact that the code segment that is executed or skipped can consists of HTML tags or a combination of HTML tags and JSP tags.

    JSP Programming

    69 )

    { %> You Passed !

    Better luck next time.

    Your final grade is a A

    Your final grade is a B

    Your final grade is a C

    Your final grade is a D

    Loops

  • KNSIT Page 96

    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

    JSP programming

    First

    Second

    Third

  • KNSIT Page 97

    Second

    Third

  • KNSIT Page 98

    20. Implicit objects in jsp are the objects that are created by the container automatically and the container makes them available to the developers, the developer do not need to

    create them explicitly.

    21. Since these objects are created automatically by the container and are accessed using standard variables; hence, they are called implicit objects.

    22. The implicit objects are parsed by the container and inserted into the generated servlet code.

    23. They are available only within the jspService method and not in any declaration.

    24. Implicit objects are used for different purposes. User defined methods can't access them as they are local to the service method and are created at the conversion time of a jsp into

    a servlet. But we can pass them to our own method if we wish to use them locally in

    those functions.

    25. Application: These objects has an application scope. These objects are available at the widest context level, that allows to share the same information between the JSP page's

    servlet and any Web components with in the same application.

    26. Config: These object has a page scope and is an instance of javax.servlet.ServletConfig class. Config object allows to pass the initialization data to a JSP page's servlet.

    Parameters of this objects can be set in the deployment descriptor (web.xml) inside the

    element . The method getInitParameter() is used to access the initialization

    parameters.

    27. Exception: This object has a page scope and is an instance of java.lang.Throwable class. This object allows the exception data to be accessed only by designated JSP "error

    pages.

    28. Out: This object allows us to access the servlet's output stream and has a page scope. Out object is an instance of javax.servlet.jsp.JspWriter class. It provides the output

    stream that enable access to the servlet's output stream.

    29. Page: This object has a page scope and is an instance of the JSP page's servlet class that processes the current request. Page object represents the current page that is used to call

    the methods defined by the translated servlet class. First type cast the servlet before

    accessing any method of the servlet through the page.

    30. Pagecontext: PageContext has a page scope. Pagecontext is the context for the JSP page itself that provides a single API to manage the various scoped attributes.

    31. This API is extensively used if we are implementing JSP custom tag handlers. PageContext also provides access to several page attributes like including some static

    or dynamic resource.

  • KNSIT Page 99

    32. Request: Request object has a request scope that is used to access the HTTP request data, and also provides a context to associate the request-specific data.

    33. Request object implements javax.servlet.ServletRequest interface. It uses the getParameter() method to access the request parameter. The container passes this object

    to the _jspService() method.

    34. Response: This object has a page scope that allows direct access to the HTTPServletResponse class object.Response object is an instance of the classes that

    implements the javax.servlet.ServletResponse class. Container generates to this object

    and passes to the _jspService() method as a parameter.

    35. Session: Session object has a session scope that is an instance of javax.servlet.http.HttpSession class. Perhaps it is the most commonly used object to

    manage the state contexts. This object

    persist information across multiple user connection.

    36. There are four predefined implicit objects that are in every JSP programs. These are request, response, session and out.

    37. The request object is an instance of the HTTPServletRequest.

    38. The response object is an instance of the HTTPServletResponse.

    39. The session object is an instance of the HTTPSession.

    40. The out object is an instance of the JSPWriter, used to send a response to the client.

    41. getParameterValues() method helps us to copy a value from a multivalued field such as a selection list field.

    42.

    43. Field names in the request string can be parsed by using the getParameterNames() method.

    Order Confirmation

    Order Confirmation

  • KNSIT Page 100

    Thanks for ordering !

    join_email_list.html

    Email List application

    Join our email list

    To join our email list, enter your name and

    email address below.

    Then, click on the Submit button.

    First name:

    Last name:

    Email address:

    Chapter 4 - Email List application

  • KNSIT Page 101

    Thanks for joining our email list

    Here is the information that you entered:

    First name:

    Last name:

    Email address:

    To enter another email address, click on the Back

    button in your browser or the Return button shown

    below.

    Usage of page directives : first.jsp

  • KNSIT Page 102

    return 10*a; }

    %>

    This page is requested by number of times on date

    .

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

    Home.html

    Insert title here

    name:

    Request.jsp

    Implicit Objects

    Hello.

    Your request details are

  • KNSIT Page 103

    NameValue

    request method

    request URI

    request protocol

    Would you like to see use of remaining implicit objects?

    Yes

    No

    pageContext.jsp

    Intermediate

  • KNSIT Page 104

    Parsing Other Information

    44. The request string sent to the JSP by the browser is divided into two general components separated by question mark.

    45. The URL component appears to the left of the question mark and the query string is to the right of the question mark.

    46. The URL is divided into four parts, beginning with the protocol.

    47. The first three parts commonly used protocols like HTTP, HTTPS (secured version of HTTP) and FTP.

    48. Next is host and port combination. The host and port is the virtual path of the JSP programs. The server maps the virtual path to the physical path.

    User Sessions

    49. A JSP program must be able to track a session. There are threecommonly used methods to track a session.

    50. These are by using a hidden field, by a cookier or by Java Bean.

    51. A hidden field is a field in an HTML form whose value isnt displayed on the HTML page.

    Cookies

    52. Cookie is a small piece of information created by a JSP program that is stored on the clients hard disk by the browser.

    53. Cookies are used to store various kinds of information like user preferences and an ID that tracks a session with a JSP database system.

    Addcookie.jsp

    JSP Programming

    MyCookieName is :

  • KNSIT Page 105

    MyCookieValue is :

    getcookie.jsp

    JSP Programming

  • KNSIT Page 106

    getattribute.jsp

    JSP Programming

    Attribute Name is :

    Attribute Value is :

    JSP to print 10 even and 10 odd numbers.

    jsp

    even nos

  • KNSIT Page 107

    odd nos

  • KNSIT Page 108

    pswd

    JSP Standard Actions

    59. JSP Standard action are predefined tags which perform some action based on information that is required at the time the JSP page is requested by a browser.

    60. The action tags are specific to a JSP page.

    61. When the JSP container encounters an action tag while converting a JSP page into a servlet, it generates the java code that corresponds to the required predefined task.

    62. An action can be for instance, access parameters sent with the request to do a database lookup.

    63. It can also dynamically generate HTML, such as a table filled with information retrieved from an external system.

    64. They can be used to include a file at the request time, to find or instantiate a JavaBean, to forward a request to a new page, to generate a browser-specific code, etc.

    65. The JSP standard actions affect the overall runtime behavior of a JSP page and also the response sent back to the client.

    Action element Description

    Makes a JavaBeans component available in a page

  • KNSIT Page 109

    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 browser-dependent elements (OBJECT or EMBED) needed to execute an applet with the Java Plug-in software

    include directive tag include action tag

    1. It inserts the given page and includes the content in the generated servlet page during the translation phase of JSP lifecycle.

    2. In general, the include directive is used to include files, such as HTML, JSP, XML or simple.txt file into JSP page statically.

    3. The include action tag is used to included the response generated by executing the specified JSP page or servlet.

    4. The response is included during the request processing phase, when the page is requested by the user.

    Example for

    Going to include hello.jsp...

    Example for File name : checkmemory.jsp

  • KNSIT Page 110

    One.jsp

    Virtual Memory usage is less than 50 percent

    Two.jsp

    Virtual Memory usage is greater than 50 percent

    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 :

    2. The name Attribute : The name attribute specifies the parameter name and takes a case-sensitive literal string. The parameter name should be unique.

    3. The value Attribute : The value attribute specifies the parameter value and takes either a case-sensitive literal