Sub : J2EE Chapter – 1 The J2EE platform B.C.A. Sem -5
1 The J2EE Platform,JDBC(Java Database
Connectivity)
Topics Covered 1. Introduction to J2EE 2. Enterprise Architecture Style.
3. Enterprise Architecture
4. J2EE Platform. 5. J2EE API’s. 6. Introduction to J2EE APIs 7. introduction to container 8. Tomcat as a web container 9. Introduction. 10. JDBC Architecture
11. Datatypes in JDBC 12. Processing Queries 13. Database exception handling 14. Database Driver 15. JDBC API for connectivity 16. Connection 17. Driver Manager class
18. Statement
19. Prepared Statement 20. Callable Statement 21. ResultSet 22. Other JDBC API 23. Database Meta Data 24. Result set Meta Data 25. Connecting with Databses(MySQL,Oracle,Access)
Page 1 of 24
Sub : J2EE Chapter – 1 The J2EE platform B.C.A. Sem -5
Introduction to J2EE Core java application only provides facility to work with windows based applications. If we required developing the enterprise level application, it will not work. Advance java programming provides the facility to develop the Enterprise based and Internet based Application. The J2EE is an open source. It reduces the cost of developing multi-tier applications. It provides a number of APIs to develop the different types of applications, such as JDBC(Java Database Connectivity) used for making connection between the java programs and database, JSP and servlets to create the dynamic web page, RMI(Remote Method Invocation) to create the remote objects. J2EE platforms also include concept of containers to provide the interface between the clients, server and the database. J2EE provides many framework such as JSF, spring, structs, hibernate to develop very attractive, secure, user-friendly, database driven enterprise application.
1. Introduction The Tier A tier is an abstract concept that defines a group of technologies that provides one or more services to its clients. In simplest words, tier is collection of similar technologies in a group.
Introduction to Enterprise Application Design Framework Enterprise Application is divided in to following six (6) logical layers which are related to the client tier, middle tier, and database tier. It defines which layer belongs to which tier. Presentation Manager . It defines User interface . It is located on the client tier. . Manages the information displayed to the user. Presentation Logic . Defines the Navigation system of the user interface . Focused on how and what will be displayed to the user. . It may locate with the client tier or business tier or the database tier, based on thin client and thick client. Application Logic . Defines the actual application logic with it. . It may be, connectivity with the database, validation over the various inputs etc. . It may locate with the client tier or business tier or the database tier, based on thin client and thick client. Business Logic . Contains business rules of applications. . Should be shared with whole application.
Page 2 of 24
Sub : J2EE Chapter – 1 The J2EE platform B.C.A. Sem -5
. It may located with business tier or the database tier, based on thin client and thick client. Database Logic . Defines the table structure and relation among the tables of database . Includes various constraints of the table. . Located with the database tier. Database Manager . Stores the persistent (constant) data. . Always located with the database tier.
Enterprise Architecture Style Single tier Architecture When User inputs, its verifications, business logic, and data access all these are combined together in a single computer such kind of architecture is known as Single tier architecture. In this all layers are located on a single machne. Advantages . Easy to manage . Data consistency is simple due to data stored at single location. Disadvantages . Single storage is not sufficient due to large number of data . Sharing of data in large amount is not possible. . Multiple user can’t be handled
Two tier Architecture Two tier architecture is divided into two separate tiers, client machine and database server machine (server). The application includes the presentation and business logic. Data accessed by connecting client machine to a database which is lying on another machine (i.e. server) In this architecture there are various types of clients which are discussed below. Advantages . Any changes made in data access logic will not affect the presentation and the business logic . Using this type of architecture it is easy to develop an application.
Page 3 of 24
Sub : J2EE Chapter – 1 The J2EE platform B.C.A. Sem -5
Disadvantages . Only supports limited number of users. . Because each client requires its own connections and each connection requires CPU and memory. . So, when number of connection increases the database performance decreases. Thin Client . In two tier architecture, presentation manager resides only with the client tier then such client is called Thin client, while other presentation logic, application logic, business logic, data logic and database manager reside with the server side.
Thick Client . In two tier architecture, presentation manager, presentation logic and application logic are resides in client tier then such architecture is called thick client. . Other like business logic, data logic and database manager resides with the server side
Page 4 of 24
Sub : J2EE Chapter – 1 The J2EE platform B.C.A. Sem -5
Normal Client . In two tier architecture, if the presentation manager and presentation logic resides in the client tier then the client is called Normal Client. . Other like application logic, business logic, data logic and database manager resides with the server side.
Three tier Architecture Applications which are divided into three tiers client tier, middle tier (business tier) and database tier is known as three tier architecture application. Logic is physically divided into separate tier. The presentation layer and logic runs on the client machine. Application and business logic runs on J2EE server and database logic is there with database layer.
Thin Client Page 5 of 24
Sub : J2EE Chapter – 1 The J2EE platform B.C.A. Sem -5
. In three tier architecture if the presentation manager is resides only with the client tier then client is called as thin client. . Presentation logic, application logic and business logic are with the business tier . Database logic and database manager are with the database tier (EIS – Enterprise Information System.) Thick Client . In three tier architecture if the presentation manager ,presentation logic, application logic resides with the client tier then client is called as thick client. . Business logic only with the business tier . Database logic and database manager are with the database tier (EIS – Enterprise Information System.) Advantages . Improves scalability since application server are deployed on many machines. . Database connection not required longer from each and every client, only requires connections from a smaller number of application server. . Better reusability due to same logic can be initiated from many clients. . Security is ensured because not direct access to the database. Disadvantages . Increases complexity
N-tier architecture Application divided into more than three tier can be called as N-tier architecture. In N-tier architecture it is not decided how many tier can be present. Number of tiers in application is depends on the computing and network hardware on which application is to be deployed. Basically divided into client tier, web tier, business (EJB) tier and database tier (EIS). Client tier . Collection of user interface for user request and the print the response . Runs on the client machine. . Uses browser or applet as client side application. Web tier . Collection of JSP and servlet dynamic webpages to handle the HTTP specific request logons, session , accesses the business services and response back to the client. Business tier . Collection of business logic for J2EE application. For example EJB (Enterprise JavaBeans) . Using such business tier, same business logic can support different types of client like browser, WAP, other stand-alone application. Database (EIS) tier . EIS tier consist of the DBMS/RDBMS.
Page 6 of 24
Sub : J2EE Chapter – 1 The J2EE platform B.C.A. Sem -5
. Handles User SQL requests and generates appropriate response based on the queries. . Stores all persistent data in database Advantages . Separation of User interface logic, business logic is done . Business logic resides on small number of centralized machines. . Easy to maintain, to manage, to scale, loosely coupled etc., Modification is easy Disadvantages . More complex structure . Difficult to setup and maintain all separated layers
Enterprise Architecture Java 2 Enterprise edition is basically developed for commercial project and web- solution. Business solution for commercial project solved using multi-tier architecture. The J2EE platform use multi-tier distributed application model for enterprise application. By dividing application logic into various component according to its tasks or functions and various application components that are gathered J2EE application are installed on different machine depending on the tier.
Page 7 of 24
Sub : J2EE Chapter – 1 The J2EE platform B.C.A. Sem -5
Following tiers are available for J2EE. . Client tier (Client machine) . Web tier (J2EE server) . Business tier ( J2EE server) . EIS tier (database server)
J2EE Platform Introduction to editions of Java. . J2SE – Java 2 standard edition normally used for developing desktop application. . J2EE – Java 2 enterprise edition used for applications which are run on server example websites. . J2ME – Java 2 Micro Edition (mobile) used for developing small scale device like mobile, PDA What is J2EE ? . J2EE is an open standard which is provided by Sun micro system (now Oracle) for applications which runs on server. . Provides Multi-tier architecture. . Includes J2SE + most of other java technologies. . (JavaMail, Servlet, EJB, JMS, JSF)
Page 8 of 24
Sub : J2EE Chapter – 1 The J2EE platform B.C.A. Sem -5
J2EE as a multi-tier architecture.
J2EE has following tiers in its architecture . Client tier . Web tier . Business tier (EJB tier) . Database tier (EIS tier)
J2EE API’s JDBC (Java Database Connectivity) Used to connect Java Database application with any relational database. Can access well know database like MySQL, Oracle, MS – access. RMI (Remote Method Invocation) Used to access object method running on different machine RPC (Remote Procedure Call) EJB (Enterprise JavaBeans) Used to server side components Consisting business logic for J2EE application JS (Java Servlet) Object oriented abstraction for building dynamic web application. JSP (Java Server Pages) Provides easy way for building dynamic web-applications JMS (Java Message Service) Provides Java API for message passing , publish and subscribe the types of message oriented middleware service. JNDI (Java Naming and Directory Interface) Provides different types of naming and directory service. JTA (Java Transaction API) Used for Implementing distributed transaction application Page 9 of 24
Sub : J2EE Chapter – 1 The J2EE platform B.C.A. Sem -5
JM (Java Mail) Provides platform independent and protocol independent framework to build java based mail application
Introduction to Container Container . They are interface between a component and Client (lower level code) or platform oriented functionality which supports component. . Container provides communication between client and components. Types of Container . Applet Container . Application Container . EJB Container . Web Container
Page 10 of 24
Sub : J2EE Chapter – 1 The J2EE platform B.C.A. Sem -5
Applet Container . One kind of client container which is used to manage execution of the applet on the browser. Application Container . It is client container which is used to manage application client and their component EJB Container . It is one kind of server container. . Used to manage enterprise beans components. Web container . It is also sever container which is used to manage execution of JSP pages and servlet components
Tomcat as a web container Tomcat is a one type of server container which is used to manage and execute the JSP pages and servlet components. Tomcat is a powerful web container provided by Apache Using Tomcat we can develop servlet and JSP application. Tomcat is free web container that can be used to run code of JSP servlet. We can debug JSP and servlet pages using Tomcat before deploying on the server. Using JSP and servlets we can develop dynamic web pages. Apache most common HTTP web server on the internet which is use Tomcat is chosen to be official sun web container.
Basic Requirements . Sun Java JDK 5.0 or higher . Tomcat 6.0 or higher . Eclipse or Netbeans (Editor) . We can use any editor like notepad, wordpad, notepad++ and Dreamweaver to create, edit webpage’s coding
Tomcat Directory Structure . Bin All the scripts and batch files are stored in this folder which are used to startup a tomcat server. . Conf All the configuration file for a global and server configuration and it is also contains user authentication settings. . Log All the server logs resides in this folder . Lib JAR files resides in this folder which is used by tomcat . Webapps All the JSP and servlet application folders are stored in this folder. Page 11 of 24
Sub : J2EE Chapter – 1 The J2EE platform B.C.A. Sem -5
. Work All the temporary and precompiled files are stored in this folder. 1. Introduction JDBC stands for Java Database Connectivity. The java provides JDBC API to create java application that is capable of interacting with a database. As we know that java is an ideal language for persistent data storage. By using class inheritance and data encapsulation, a java application developed to work with one type of data storage can be ported or extended to work with another. An example for that is an application currently working with a RDBMS (Relational Database Management System) that is extended to use RMI to store data in file. A general misunderstanding with java is that database access is possible only with the JDBC API. Even though the JDBC provides the lower level classes to manage database connections and transaction, it is not compulsory component. JDBC Vs ODBC ODBC can not directly used with java because it uses a C interface. Calls From java to native C code have number of drawbacks in the security, implementation, robustness, and automatic portability of application. ODBC makes use of pointers which have been totally removed from java. ODBC mixes simple advance feature of ODBC driver manager and driver on all client machines. JDBC drivers are written in java and JDBC code is automatically installable secure and portable on all java platforms from network computers to mainframes. JDBC API is an natural java interface and is built on ODBC retain some of the basic features of ODBC like X/Open SQL call level interface JDBC API The JDBC API is collection of methods, classes and interface that enable java application to communicate with database. For this, database should be installed on the computer and the RDBMS should provide a driver. JDBC classes and interface defined in the package java.sql constitute the JDBC API. The Java program invokes the method of the JDBC API. The JDBC API then calls the JDBC driver and submits the queries to the SQL statements that a database can understand. After the query has been performed, the JDBC driver retrieves the result of the query form the database. The result is converted into the JDBC API classes that are used by the java Program. Then the java program obtain the result of the query.
JDBC Architecture The JDBC architecture describes the interaction of JDBC API with java application and java applet. JDBC API consists of several call level interface with JDBC Driver Manager and JDBC drivers for defining database. JDBC API is responsible for transferring data between an application and a database.
Page 12 of 24
Sub : J2EE Chapter – 1 The J2EE platform B.C.A. Sem -5
Datatypes in JDBC The following table summarizes the default JDBC data type that the java data type is converted when you call the setXXX() method of preparedStatement and CallableStatement.
SQL JDBC/Java setXXX() VARCHAR Java.lang.String setString() CHAR Java.lang.String setString() LONGVARCHAR Java.lang.String setString() BIT Boolean setBoolean() NUMERIC Java.math.BigDecimal setBigDecimal() TINYINT Byte setByte() SMALLINT Short setShort() INTEGER Int setInt() BIGINT Long setLong() REAL Float setFloat FLOAT Float setFloat() DOUBLE Double setDouble() DATE Java.sql.Date setDate() ARRAY Java.sql.Array setArray() Page 13 of 24
Sub : J2EE Chapter – 1 The J2EE platform B.C.A. Sem -5
STRUCT Java.sql.Struct setStruct() TIME Java.sql.Time setTime()
Types of Database Driver JDBC Driver Type
JDBC Driver is a software component that enables java application to interact with the database. Database vendor provide a driver along with the database. These database driver are used to communicate with java programs. There are 4 types of JDBC drivers: . JDBC-ODBC bridge driver . Native-API driver (partially java driver) . Network Protocol driver (fully java driver) . Thin driver (fully java driver) 1. JDBC-ODBC Bridge The JDBC-ODBC bridge driver converts all JDBC call into ODBC calls and send them to the ODBC driver. The ODBC driver then forwards the call to the database server. Figure shows communication between java application and Database using JDBC- ODBC Bridge. E.g. MS Access do not provide JDBC driver. Instead they provide Open Database Connectivity(ODBC) drivers. One can access such databases by using the ODBC-JDBC Bridge.
Advantages . easy to use. . can be easily connected to any database. Disadvantages . Performance degraded because JDBC method call is converted into the ODBC funcion calls. . The ODBC driver needs to be installed on the client machine. 2. Native-API / Partly-Java driver
Page 14 of 24
Sub : J2EE Chapter – 1 The J2EE platform B.C.A. Sem -5
This driver communicates directly the database server. Therefore the vendor database library needs to be loaded on each client computer. The type 2 driver converts JDBC calls into database-specific calls for databases. Example: Oracle will have oracle native API.
Advantage: . Performance upgraded than JDBC-ODBC bridge driver. Disadvantage: . The Native driver needs to be installed on the each client machine. . The Vendor client library needs to be installed on client machine.
3. Net-Protocol / all-Java Driver The JDBC Type 3 driver, or the net-protocol/all-java driver, follows a three-tiered approach. In the three-tiered approach, JDBC database requests are passed to a middle-tier server. The middle-tier server then translates the requests and passes to the database- specific native-connectivity interface and forward the requests to the database server. If the middle-tier server is written in Java, it can use the Type 1 or Type 2 drivers to forward the requests to the database server.
Page 15 of 24
Sub : J2EE Chapter – 1 The J2EE platform B.C.A. Sem -5
Advantage: . No client side library is required because of application server that can perform many tasks like auditing, load balancing, logging etc. Disadvantages: . Network support is required on client machine. . Requires database-specific coding to be done in the middle tier. . Maintenance of Network Protocol driver becomes costly because it requires database-specific coding to be done in the middle tier. 4. Native-Protocol / All-Java Driver
These drivers are commonly implemented in java to achieve platform independence. These drivers convert JDBC calls into vendor specific DBMS protocol. Therefore client applications can communicate directly with the database server when Type 4 driver are used.
Page 16 of 24
Sub : J2EE Chapter – 1 The J2EE platform B.C.A. Sem -5
Advantage: . Better performance than all other drivers. . No software is required at client side or server side. Disadvantage: . Drivers depend on the Database.
JDBC API for database connectivity 1 Connection A Connection is the session between java application and database. The Connection interface is a factory of Statement, PreparedStatement, and DatabaseMetaData i.e. object of Connection can be used to get the object of Statement and DatabaseMetaData. The Connection interface provide many methods for transaction management like commit(),rollback() etc. Methods 1) public Statement createStatement(): creates a statement object that can be used to execute SQL queries. 2)public Statement createStatement(int resultSetType,int resultSetConcurrency): Creates a Statement object that will generate ResultSet objects with the given type and concurrency. 3) public void setAutoCommit(boolean status): is used to set the commit status.By default it is true. 4) public void commit(): saves the changes made since the previous commit/rollback permanent. 5) public void rollback(): Drops all changes made since the previous commit/rollback. 6) public void close(): closes the connection and Releases a JDBC resources immediately.
2. Driver Manager Class The DriverManager Class belongs to java.sql package. It consists of the static methods to manage the JDBC Driver must register with the DriverManager class. Page 17 of 24
Sub : J2EE Chapter – 1 The J2EE platform B.C.A. Sem -5
There are many JDBC Driver for Oracle. In short DriverManager class controls the interface between the application and JDBC Driver. In DriverManager class important methos is getConnection() method which is used to establish the connection with the different database servers. It has three overloaded signatures (parameters) Syntax:- public static Connection getConnection(String url) throws SQLException public static Connection getConnection(String url,Properties Info) throws SQLException public static Connection getConnection(String url,String username,String Password) throws SQLException
3 Statement The interface object is used to execute the SQL statement and obtain the result produced after executing the statement. It is having following different types of methods to execute the different types of SQL Statements. Methods executeQuery(): This method is used to fetch the records from the database by using select query. It can be only return the single ResultSet object at a time. It passed a parameter with it which is SQL statement which selects the records from the database. This method throws SQLException. Syntax :- public ResultSet executeQuery(String sql) throws SQLException executeUpdate() : This methods is used to perform the insert, update, delete operation on the records of the database. It returns the integer value which indicates no. of records updated the records in the database. It passes a SQL statement as a parameter which updates the records of the database. This method throws SQLException. Syntax :- Public int executeUpdate(String sql) throws SQLException execute() : It is used to execute the SQL statements which returns the multiple results. It returns the boolean indicating value if it returns true that the next result is ResultSet object and if it returns false then defines no. of records updated or no more result is there. This method throws SQLException. Syntax :- Public boolean execute(String sql) throws SQLException
4 Prepared Statement PrepareStatement Interface is derived from the Statement Interface. Disadvantages of Statement object are that it executes a simple SQL statement with no parameters and the SQL statement is not precompiled. But PreparedStatement object uses a template to create a SQL request and use a PreparedStatement to send precompiled SQL statements with one or more parameters, So sometimes it is more convenient to use a PreparedStatment object for sending SQL statements to database. If you want to execute a SQL statements many times, PreparedStatement object reduces execution time in comparison to Statement object.
Page 18 of 24
Sub : J2EE Chapter – 1 The J2EE platform B.C.A. Sem -5
Examples :- String sql = “insert into data(ID, Name) values (?,?)”; PreparedStatement ps = con.preparedStatement(sql); ps.setInt(1,10); ps.setString(2,”ABC”); SetXXX Methods : (1) setInt(int parameterIndex, int x) (2) setChar(int parameterIndex, Char x) (3) setString(int parameterIndex, String x) (4) setFloat(int parameterIndex, float x) (5) setDouble(int parameterIndex, double x) (6) setLong(int parameterIndex, long x) (7) setShort(int parameterIndex, short x) (8) setDate(int parameterIndex, Date x) (9) setByte(int parameterIndex, byte x) (10)setBlob(int parameterIndex, Blob x) Methods: Same as Statement . executeQuery() . executeUpdate . execute()
5 Callable Statement A CallableStatement object provides a way to call stored procedure in a standard way for all DBMSs. A stored procedure is stored in a database; the call to the stored procedure is what a CallableStatement object contains. This call is written in an escape syntax that may take one of two forms: one form with a result parameter, and the order without one. A result parameter, a kind of OUT parameter, is the return value for the stored procedure. Both forms may have a variable number of parameters used for IN parameters, OUT parameters or both IN OUT parameters. A question mark serves as a placeholder for a parameter. Syntax for Stored Procedure with IN parameters { call procedure_name[(?,?,...)] } Syntax for Stored Procedure with IN and OUT parameters { ? = call procedure_name[(?,?,...)] } Syntax for Stored Procedure with no parameters { call procedure_name }
6 ResultSet It is used to access the data of the table from database. Result Set object stores the data of the table by executing the query. It also maintains the cursor position for navigation of the data. Cursor can move on first, next, previous and last position from the current row position. It also fetch the data from the table using getXXX methods depends on column type. Page 19 of 24
Sub : J2EE Chapter – 1 The J2EE platform B.C.A. Sem -5
It can fetch the data either passing column name or index number with getXXX methods. Index number always starts with one. Fields of ResultSet Interface CONCUR_READ_ONLY It defines the ResultSet object can not be modified. CONCUR_UPDATEBLE It defines the ResultSet object can be modified. TYPE_FORWARD_ONLY It defines the cursor from the current row can move forward only. TYPE_SCROLL_INSENSITIVE It defines that cursor can scroll but can not be modified or updated TYPE_SCROLL_SENSITIVE It defines that cursor can scroll and also can be modified or updated. getXXX Method getString() getInt() getBoolean() getDouble() getFloat() getDate() getLong() getShort() getByte() getBlob() Navigation Methods . first(): It is used to move the cursor at the first record of the table. . last(): It is used to move the cursor at the last record of the table. . previous(): It is used to move the cursor at the previous record from the current position of the table. . next():It is used to move the cursor at the next record from the current position of the table. . afterLast(): It is used to move the cursor after the last record of the table. . beforeFirst(): It is used to move the cursor before the first record of the table. . relative(int row): It is used to move the cursor on the relative no. of rows . . absolute(int row): It is used to move the cursor on the absolute row.
Other JDBC API 1Database Meta Data DatabaseMetaData interface provides methods to get meta data of a database such as database product name, database product version, driver name, name of total number of tables, name of total number of views etc. Database Metadata is used to store following information of Database Metadata object and information as below. . What tables are available ? . What is our user name as known to the databse?
Page 20 of 24
Sub : J2EE Chapter – 1 The J2EE platform B.C.A. Sem -5
. Is the database in read only mode ? Commonly used methods of DatabaseMetaData interface public String getDriverName()throws SQLException: it returns the name of the JDBC driver. public String getDriverVersion()throws SQLException: it returns the version number of the JDBC driver. public String getUserName()throws SQLException: it returns the username of the database. public String getDatabaseProductName()throws SQLException: it returns the product name of the database. public String getDatabaseProductVersion()throws SQLException: it returns the product version of the database.
2Result set Meta Data This interface provides methods for obtaining information about the types and properties of the columns in a ResultSet object. ResultSet MetaData is used to store following information of ResultSet object and information as below. . What is the number of columns in the Result Set? . What is a column’s name? . What is column’s SQL type? . What is the column’s normal maximum width in chars? . What is column’s number of decimal digits? . Can you put a NULL in this column? . Can column can be use in a where clause? The metadata means data about data i.e. we can get further information from the data. If you have to get metadata of a table like total number of column, column name, column type etc. , ResultSetMetaData interface is useful because it provides methods to get metadata from the ResultSet object. Commonly used methods of ResultSetMetaData interface public int getColumnCount()throws SQLException: it returns the total number of columns in the ResultSet object. public String getColumnName(int index)throws SQLException: it returns the column name of the specified column index. public String getColumnTypeName(int index)throws SQLException: it returns the column type name for the specified index. public String getTableName(int index)throws SQLException: it returns the table name for the specified column index.
Extra (asked in last exam) Difference between Statement and Prepared Statement
1. The PreparedStatement is a slightly more powerful version of a Statement, and should always be at least as quick and easy to handle as a Statement. 2. The PreparedStatement may be parametrized while statement is not 3. PreparedStatement is sub interface of statement inferface
Page 21 of 24
Sub : J2EE Chapter – 1 The J2EE platform B.C.A. Sem -5
4. A Statement will always proceed through the steps for each SQL query sent to the database while prepared statement pre-executes some of those steps.
Connecting with other databases(Mysql,Access,Oracle) Connect with Access As shown in ch-5
Connect with Oracle To connect with oracle data base first of all create oracle procedure. First of all start oracle database. start sql*plus enter scott as username and tiger as password. Then create std table and enter data in a table. . Create table std(id number(3), name varchar2(30)); . Insert into table values(1,’AAAAA’); . Insert into table values(1,’BBBBB’); Then write procedure create or replace PROCEDURE SearchStudent(name1 in varchar2,name2 in varchar2) is BEGIN Update Std SET name=name2 where name=name1; END; Now, create a DSN for oracle 1) click on control panel 2) select administrative tools 3) select data sources(ODBC) 4) click on add button 5) select odbc driver for oracle 6) click on finish button 7) give data source name 8) click on ok button write the java program import java.sql.*; public class Pro34 { public static void main(String[] args) { Connection con; CallableStatement cst; ResultSet rs; Try { Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); con = DriverManager.getConnection("jdbc:odbc:std","scott","tiger"); cst=con.prepareCall("{call SearchStudent('AAAAA','Ashish')}"); cst.executeUpdate(); con.close(); System.out.println("\n \t Procedure Successfully compiled..."); } catch (Exception e) {
Page 22 of 24
Sub : J2EE Chapter – 1 The J2EE platform B.C.A. Sem -5
System.out.println(e); } } } now run the java program javac Pro34.java java Pro34 O/P procedure successfully compiled
and see the output in oracle table. Select * from std;
Connect with mysql To connect with mysql data base first of all create table in mysql. And start apache server. Then create employee table and enter data in a table. . Create table std(id number(3), name varchar2(30)); . Insert into table values(1,’AAAAA’); . Insert into table values(1,’BBBBB’); Now, create a DSN for oracle 9) click on control panel 10) select administrative tools 11) select data sources(ODBC) 12) click on add button 13) select mysql odbc driver 3.51 14) click on finish button 15) give data source name and database name 16) click on ok button write the java program import java.sql.*; public class ex { public static void main(String[] args) { try { Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); Connection con= DriverManager.getConnection("jdbc:odbc:stud","root",""); try { Statement st = con.createStatement(); ResultSet rs = st.executeQuery("SELECT * FROM employee"); System.out.println("Emp_code: " + "\t" + "Emp_name: "); while (rs.next()) { int i = rs.getInt("id"); String s = rs.getString("name"); System.out.println(i + "\t\t" + s); } con.close(); Page 23 of 24
Sub : J2EE Chapter – 1 The J2EE platform B.C.A. Sem -5
} catch (SQLException se) { System.out.println(se); } } catch (Exception e) { System.out.println(e); } } } now run the java program javac ex.java java ex O/P Emp_code Emp_name 1 AAAAA 2 BBBBB
Page 24 of 24
J2EE 2. RMI,Servlet B.C.A. SEM -5
2 RMI,Servlet
Topics Covered 1. Introduction to RMI. 2. RMI Architecture. 3. Stub and Skeleton. 4. Developing and Executing RMI application 5. Introduction. 6. Servlet implementation 6.1. The Servlet interface 6.2. The Generic Servlet class 6.3. The single thread model 6.4. The Http Servlet class 7. Servlet Exception 8. Servlet Life Cycle 9. Servlet Request and Response 9.1. HttpServletRequest interface 9.2. HttpServletResponse interface 10. Session Tracking Approaches 10.1. URL Rewriting 10.2. Hidden Form Fields 10.3. Cookies 11. Servlet collaboration
1. Introduction to RMI We are going to discuss what distributed application is. Distributed application is an application which is divided into more than one machine and machines are attached using Network. So whole application is distributed within two or more machines. DCE(Distributed Computing Environment),DCOM (Distributed Components Object Model), CORBA (Common Object Request Broker Architecture) are not compatible for J2EE environment. RMI is invited for J2EE distributed Application. J2EE provides the distributed programming environment for the users.It is having number of APIs to develop Enterprise Application. RMI is one of the API for developing the distributed Application. Distributed application contains the distributed objects over the network. It communicates with each other by using Transport protocol or basically using TCP/IP protocol. Client sends the request to the server to access the Remote Objects and Server sends the response related to client Request. RMI application basically divides in two programs Client and Server. A Server Program creates some Remote Objects and makes the references to them and waits for the client request to invoke methods on the Remote Objects.
Page 1 of 18 J2EE 2. RMI,Servlet B.C.A. SEM -5
2. RMI Architecture. RMI architecture defines the how the client request to the server for the remote objects and how the server processes for the request. Each layer can perform specific functions, like establish the connection, assemble and disassemble the parameters, transmitting the objects etc.
Application Layer Application layer consists of the client side java program and Server side java programs with remote methods. Here, the high level calls are made in order to access the remote method through an interface that extends java.rmi.Remote. When we want to define set of methods that will be remotely called they must be declared in one or more interface that should extend java.rmi.Remote. Proxy Layer The Stub/Skeleton Layer is responsible for listening to the remote method calls made by the client and redirecting them to the server. This layer consists of a stub and a skeleton. The stub and skeleton are created using the RMI compiler. These are simply class files that represent the client and server side of remote object. A stub is a client-side proxy representing the remote objects. The stub communicates the method in invocations to the remote object through a skeleton that is implemented on the server. The skeleton is a server-side proxy that communicates with the stub. It makes a call to the remote object. Remote Reference Layer The Remote reference layer is interface between the proxy layer and transport layer. The Remote Reference Layer interprets the references made by the client to the remote objects on the server. This layer is presented in the client-side as well as server side. The RRL on the client-side receives the request for the methods from the stub. The request is then transmitting the parameter or object through the network it should be in the form of a stream. The JVM works with the JAVA Byte Codes. It can get the stream-oriented data from the transport layer and give it to the proxy layer and vice versa.
Page 2 of 18 J2EE 2. RMI,Servlet B.C.A. SEM -5
Transport Layer Transport layer manages the connection between client remote reference layer and remote server machine. It receives a request from the client-side RRL and establish a connection with the server through server-side RRL. . It is responsible for handling the actual machine to machine communication; the default communication will take place through a standard TCP/IP. . It creates a stream that is accessed by the remote reference layer to send and receive data to and from other machines. . It sets up the connections to remote machines. . It manage the connection. . It monitors the connections to make sure that they are live . It listens for connections from the machines. 3. Stub and Skeleton. Stub : The stub is a client side proxy of the remote object. It presents the same remote interfaces as the object of server. Therefore from the perspective of the client. The stub is equivalent to the remote object. It works with JVM and RMI System on client machine to serialize any arguments to a remote method call and sends this information to server machine. The stub receives any result from the remote method and returns it to the client.
Skeleton: The skeleton is a server side proxy of the remote object. It receives the remote method call and any associated arguments. It works with the JVM and RMI system on the server machine to desterilize any arguments for remote method call. It invokes the appropriate method in the server using arguments. It receives any return value from this method call and works with the JVM and RMI system on Server machine to serialize this return value and sends the information back to client.
Page 3 of 18 J2EE 2. RMI,Servlet B.C.A. SEM -5
Developing and executing RMI application To develop RMI application, we need to create the following java program. 1) Remote interface 2) Remote object class 3) Server program 4) Client program To develop the following java files we need to use java.rmi.* and java.rmi.server package. 1) Java.rmi package It has the following classes and interfaces which is used to develop RMI application. 1)Remote Interface It is used to create remote interface program. We need to extend the remote interface in remote interface java program. Example import java.rmi.*; public interface Adder extends Remote { public int add(int x,int y)throws RemoteException; } Compile it with javac command and generate the Adder class.
2)Naming class It is used to identify remote objects. It also provides host name and IP address of machine which is running on the server to the client. Client get all these information by using following methods. 1)lookup() It return the name of the remote object. It have a one String parameter URL which is used to look up the remote object.
2)bind() It is used to bind the specified remote name to the remote object. It has two parameters with it first name on the object and second object itself.
3)rebind() It is used to rebind the name with RemoteObject. It’s having two parameters with it first is the string message and second is the new remote object.
4)unbind() It is opposite to the bind method. It destroys the binding object with remote object. It has one string parameter with it.
Page 4 of 18 J2EE 2. RMI,Servlet B.C.A. SEM -5
5)list() It returns the string array with the name of objects bound in the registry. It passes one parameter with it.
3)RMISecurityManager class It is derived from SecurityManager class. The basic form of is Public class RMISecurityManager extends SecurityManager It is used to download the code in RMI application. Without security manager RMI class loader can not download any class from the remotehost. To add RMISecurityManger in your application you can use following code. System.setSecurityManager(new RMISecurityManager()); 4)RemoteException RemoteException is used to handle the runtime errors occurred during the remote methods are used in the application.
2) Java.rmi.server package . It has the following classes and interfaces.
1)RemoteObject class It is used to create the RemoteObject which is located on the server but works as the client object.
2)UnicastRemoteObject It works same as the remote object class because this is concrete subclass of RemoteServer that implements point-to-point remote references over TCP/IP networks.
1)Create remote interface import java.rmi.*; public interface Adder extends Remote { public int add(int x,int y)throws RemoteException; }
2)Create RemoteObject import java.rmi.*; import java.rmi.server.*; public class AdderRemote extends UnicastRemoteObject implements Adder { AdderRemote()throws RemoteException { super(); Page 5 of 18 J2EE 2. RMI,Servlet B.C.A. SEM -5
} public int add(int x,int y){return x+y;} }
3)Create Server Program import java.rmi.*; import java.rmi.registry.*; public class MyServer { public static void main(String args[]) { try { Adder stub=new AdderRemote(); Naming.rebind("rmi://localhost:5000/sonoo",stub); } catch(Exception e) { System.out.println(e); } }
}
4)Create Remoteclient import java.rmi.*; public class MyClient { public static void main(String args[]) { Try { Adder stub=(Adder)Naming.lookup("rmi://localhost:5000/sonoo"); System.out.println(stub.add(34,4)); } catch(Exception e) { System.out.println(e); } } } Introduction
In Core java you have learned Applet Programming which uses the java.applet.Applet class to create an applet and init, start, stop and destroy method of applet class to execute the applet with applet container. As you know we can run the applet on the web browser but the applet is client side programming. If we want to do the server side programming with java we need to go for servlet.
Page 6 of 18 J2EE 2. RMI,Servlet B.C.A. SEM -5
Servlet API javax.servlet package javax.servlet.http package Javax.servlet Package 1. Servlet Interface :- It is having the methods which define the life cycle of the servlet. 2. ServletConfig Interface :- It provides basic or initialization parameter of the servlet. 3. ServlerContext Interfce :- It provides the runtime environment to the servlet also logs the events using log(). 4. Generic Servlet class :- It implements the servlet, ServletConfig and Serialization interface. 5. ServletRequest interface :- It is used to read the client request. 6. ServletResponce interface :- It is used to write the response data. 7. ServletException class :- It defines servlet occurred errors. 8. UnavailableException class :- It defines that servlet is parmanently or temporarily not available. 9. ServletInputStream class :- It provides the input stream to read the data from client request. 10. ServletOutputStream :- It provides the output stream to writing the data as response to client. 11. ServletThreadModel interface :- It provides the mechanism to make servlet thread safe.
Javax.servlet.http package
1. HttpServletRequest interface :- It allows the servlet to read the data from HTTP request. 2. HttpServletResponse interface :- It allows the servlet to write the data to an HTTP response. 3. HttpServlet class :- It provides the methods of handling HTTP requests and HTTP responses. 4. Cookie class :- It is used to store the state information at client side or on the client machine. 5. HttpSession Interface :- It is used to create session and provides the way of reading and writing the session and accessing the information related to session. 6. HttpSessionBuildingListener Interface :- It informs the object that it is bound or unbound to the session. 7. HttpSessionEvent class :- It wrap ups the session change events. 8. HttpSessionBindingEvent class :- It defines that when session should be bound or unbound with the object value and its attributes.
Servlet Implementation
The Servlet Interface The GenericServlet Class SingleThreadModel Interface The Http Servlet Class The Servlet Interface
1. init() It is callled by the servlet container to initialize the servlet itself. It is called only once servlet engine loads the servlet. Syntax:- public abstract void init(ServletConfig config) throws ServletException
Page 7 of 18 J2EE 2. RMI,Servlet B.C.A. SEM -5
2. getServletConfig() It returns the ServletConfig object which contains initialization parameter and start up configuration of servlet. Syntax:- public abstract void getServletConfig() 3. service() It is used to read the client request and write the response data to the client. It passes two parameters with it first the object of the ServletRequest Interface and second object is ServletResponse interface. Syntax:- public abstract void service(ServletRequest req,ServletResponse res) throws IOException,ServletException
4. getServletInfo() It returns the basic information related to the servlet such as author name, version, copyright etc. Syntax:- public abstract void getServletInfo()
5. destroy() This method is call by the servlet automatically at last when servlet will stop its execution. Syntax:- public abstract void destroy()
The GenericServlet Class 1. init() 2. service() 3. destroy() 4. log() GenericServlet classs provides the log() method to write the server log file. Syntax:- public void log (String msg) public void log (String msg, Throwable t) 5. getInitParameter() It is used to get the Initialization parameter. Syntax :- public String getInitParameter(String name)
6. getInitParameterNames() It returns the names of the initialization parameter in the Enumeration format. Syntax:- public Enumeration getInitParameterNames()
7. getServletContext It returns the object of the ServletContext () Syntax:- public ServletContext getServletContext ()
8. getServletName() It returns the name of the servlet. Page 8 of 18 J2EE 2. RMI,Servlet B.C.A. SEM -5
Syntax:- public String getServletName()
The Single thread model
Single Thread model implemented by SingleThread Interface. It ensure that servlets handle only one request at a time. This interface has no methods. If a servlet implements this interface you are guaranted that no two threads will execute concurrently in the servlet’s service method. The servlet container can make this guarantee by synchronizing access to a single instance of the servlet, or by maintaining a pool of servlet instance and dispatching each new request to a free service. SingleThreadModel does not solve all thread safety issues. Session attribute and static variables can still accessed by multiple requests on multiple threads at the same time.
HttpServletClass
The HttpServlet class extends GenericServlet, It is commonly used by programmers when developing servlets that receive and process HTTP requests, because it is having HTTP protocol functionally.
(1) doGet() doGet() is called by the server via the service() method to handle an HTTP GET request. A GET request allows a client to send form data to a server. With the GET request, the form data is attached to the end of the URL sent by the browser to the server as a query string. The amount of form data that can be sent is limited to maximum length of the URL.
Syntax :- public void doGet(HttpServletRequest req, HttpServletResponce res) throws ServletException, IOException
(2) doPost() doPost() is called by the server via the service() method to handle an HTTP POST request. A POST request allows a client to send form data to a server. With the POST request, the form data is sent to the server separately instead of being appended to the URL.This allows a large amount of form data to be sent. Syntax:- public void doPost(HttpServletRequest res, Http ServletResponse res) throws ServletException, IOException
(3) doDelete() doDelete() is called by the server via the service() method to handle HTTP DELETE request. A DELETE request allows a client to remove a document or web page from a server. Syntax:-
Page 9 of 18 J2EE 2. RMI,Servlet B.C.A. SEM -5
public void doDelete(HttpServletRequest res, Http ServletResponse res) throws ServletException, IOException
(4) doOption() doOption () is called by the server via the service() method to handle an HTTP OPTIONS request. An OPTIONS request determines which HTTP methods the server supports and sends the information back to the client by a way of header. Syntax :- public void doOption(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException
(5) doPut() doPut is called by the server via the service() method to handle an HTTP PUT request. A PUT request allows a client to place a file on the server and is conceptually similar to sending the file to server via FTP. Syntax :- public void doPut(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException
(6) doTrace() doTrace() is called by the server via the service() method to handle an HTTP TRACE request. A TRACE request returns the headers sent with the TRACE request back to the client. This can be useful for debugging purposes. This method is rarely overridden. Syntax:- public void doTrace(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException
Life cycle of Servlet init() service() destroy()
First user Type the URL and browser sent this Http request to the appropriate server. Second, The web server receive the request. The server dynamically retrieved and loaded into the address space of the server. Third, the server invokes the init() method of the servlet. This method invokes only when the servlet is first loaded into memory. Forth, the servlet invokes the servlet service() method , which is called by the HTTP request. Servlet can read the data that has been provided in the HTTP request and may also formulate an HTTP reaponse for the servlet remains in the server address space and is available to process any other HTTP requests received from clients. The service method is call for each HTTP request. Finally server call destroy() method to unload the servlet from the memory. The memory allocated for the servlet and its object s can then be garbage collection.
Page 10 of 18 J2EE 2. RMI,Servlet B.C.A. SEM -5
Servlet Request and Response
(1) ServletRequest Interface Servlet Request Interface is a member javax.servlet package. Public interface ServletRequest defines an object to provide client request to a servlet. The Servlet container create a ServletRequest object and passes it as an argument to the service method.
HttpServletRequest A public interface HttpServletRequest extends ServletRequest Interface and it is a member of javax.servlet.http package. It is used to provide request information for HTTP servlets. The Servlet container creates an HttpServletRequest object and passes it as a argument to the service method.
Methods :
1. setAttribute() It is a method of the ServletRequest Interface and stores an attribute in this request. Syntax :- void setAttribute(String name, Object obj) 2. getParameter() It is a method of ServletRequest interface and it returns the value of a request parameter as a String or null if the parameter does not exist. Syntax:- String getParameter(String name) 3. getParameterNames() It is a method of ServletRequest interface and it returns Enumeration of String objects contining the names of the parameters contain in this request. Syntax:-
Page 11 of 18 J2EE 2. RMI,Servlet B.C.A. SEM -5
Enumeration getParameterNames()
4. getParameterValues() It is a method of ServletRequest interface and it returns an array of string objects with all the values that the given request parameter has, or null if the parameter does not exist. Syntax:- String [] getParameterValues(String name) 5. getAttribute() It is a method of ServletRequest interface and it returns the value of named attribute as an Object or null if no attribute of the name exists. Syntax:- Object getAttribute(String arr)
6. getAttributeNames() It is a method of ServletRequest Interface and it returns an Enumeration containing the names of the attribute available to this request. Syntax:- Enumeration getAttributeNames()
7. getRemoteHost() It is a method of ServletRequest interface and it returns the fully qualified name of the client or the last proxy that sent the request. Syntax:- String getRemoteHost() 8. getHeaders() The HttpServletRequest interface provides to return all the values of the specified request header as an Enumeration of String objects. Syntax:- Enumeration getHeaders(String name)
9. getCookies() The HttpServletRequest interface provides the getCookies method to obtain an array cookies that are present in the request. This method will return null if no cookies were sent. Syntax:- Cookies[] getCookies()
10. getQueryString() The HttpServletRequest interface returns the query string that is contained in the request URL after the path. Syntax:- String getQueryString() 11. getSession() The HttpServletRequest interface returns the current session associated with this request or if the request does not have a session creates one. Syntax:- HttpSession getSession()
ServletResponse Interface
Page 12 of 18 J2EE 2. RMI,Servlet B.C.A. SEM -5
A public interface ServletResponse is a member of javax.servlet package. It defines an object to assist a servlet in sending a response to the client. The container of the servlet creates a ServletResponse object and passes it as an argument to its service method.
HttpServletResponse Interface A public interface HttpServletResponse extends ServletResponse interface. HttpServletResponse interface provides Http specific HTTP specific functionalities in sending response. Methods :
1. setContectType() It is a method of ServletResponse interface, which is used to set the contect type of the response being sent to the client. Syntax:- void setContectType(String type)
2. setHeader() It is a method of HttpServletResponse interface and is used to set a response header with the given name and value. If the header had already been set, the new value overwrites the previous one. Syntax:- void setHeader(String name,String value)
3. setStatus() It is a method of HttpServetResponse interface and it sets the status code for HTTP response. Syntax:- void setStatus(int sc)
4. getWriter() It is a method of ServletResponse interface and it returns a PrintWriter object that can be used to send character data to the client. Syntax:- PrintWriter getWriter() throws IOException
5. sendRedirect() It is a method of HttpServletResponse interface and it sends a temporary redirect response to the client using the specified redirect location URL. Syntax :- void sendRedirect(String location) throws IOException 6. addCookies() It is a method of ServletResponse interface and it adds the specified cookie to the HTTP response. Syntax:- void addCookie(Cookie cookie)
7. encodeURL()
Page 13 of 18 J2EE 2. RMI,Servlet B.C.A. SEM -5
It is a method of HttpServletResponse interface and it encode the specified URL by including the session ID in it, if encoding is not needed, return the URL unchanged. The implementation of this method includes the logic to determine weather the session ID needs to be encoded in the URL. Syntax:- String encodeURL(String url)
Session tracking approaches
What is Session ? When a user makes a page request to the server, the server creates a temporary session to identify that user. So when that same user goes to another page on that site the server can recognize that user easily. So a Session is a temporary small unique connection between a server and the user or client enabling it to identify that user across multiple page requests or visit to that site.
Why Session is needed ? More than hundreds of simultaneous users can be visiting website at a time and if we can identify each of them separately then it can provide huge benefits to us.
Session Tracking Approach • URL Rewriting • Using Hidden Field • Using Cookie
URL Rewriting URL rewriting is based on the idea of inserting a unique ID in each URL of the response from the server. In URL rewriting, we append a token or identifier to the URL of the next Servlet or the next resource. We can send parameter name/value pairs using the following format: url?name1=value1&name2=value2&??
Page 14 of 18 J2EE 2. RMI,Servlet B.C.A. SEM -5
A name and a value is separated using an equal = sign, a parameter name/value pair is separated from another parameter using the ampersand(&). When the user clicks the hyperlink, the parameter name/value pairs will be passed to the server. From a Servlet, we can use getParameter() method to obtain a parameter value. Advantage of URL Rewriting 1. It will always work whether cookie is disabled or not (browser independent). 2. Extra form submission is not required on each pages. Disadvantage of URL Rewriting 1. It will work only with links. 2. It can send Only textual information.
Using Hidden Field Other way to support session tracking is to use hidden from fields. As the name implies , these are fields added to an HTML form that are not displayed in the client’s browser. They are sent back to the server when the form that contains them is submitted, Hidden form fields define constant variable for a form. To a servlet receiving a submitted form , there is no difference between a hidden field and a visible field.
Using Cookie Cookie provide a better alternative to explicit URL rewriting, because cookie s are not sent as query string but are exchanged within the bodies of HTTP requests and responses. Since there is no need no rewrite URLs , session handling via cookies does not depend on weather the content is static or dynamic. javax.servlet.http.Cookie class javax.servlet.http.Cookie class provides the functionality of using cookies. Constructor of Cookie class Cookie(String name, String value): Constructs a cookie with a specified name and value. Commonly used methods of Cookie class public void setMaxAge(int expiry):Sets the maximum age of the 1. cookie in seconds. public String getName():Returns the name of the cookie. The name cannot be changed after creation. public String getValue():Returns the value of the cookie. Other methods required for using Cookies public void addCookie(Cookie ck):method of HttpServletResponse interface is used to add cookie in response object. public Cookie[] getCookies():method of HttpServletRequest interface is used to return all the cookies from the browser. Advantage of Cookies 1. Simplest technique of maintaining the state. 2. Cookies are maintained at client side. Disadvantage of Cookies 1. It will not work if cookie is disabled from the browser. 2. Only textual information can be set in Cookie object.
Page 15 of 18 J2EE 2. RMI,Servlet B.C.A. SEM -5
Servlet Collaboration
Servlet Collaboration A servlet can call another servlet’s public method directly, if the two servlets run within the same server. To call another servlet’s public methods directly, we must know the name of the servlet that we want to call. Servlet running together in the same server have serveral ways to communicate with one another. This communication can be called as a sort servlet collaboration. RequestDispatcher Interface A RequestDispatcher is a public interface which defines an object that receives requests from the client and sends them to any resource such as a servlet, HTML file or JSP file on the server. The servlet container creates the ReuestDispatcher object, which is used as a wrapped around a server resources located at a particular path or given by a particular name. Methods : 1. Forward If forwards a client request to another resource. It allows a servlet to serve as a “request Processor”. Forward may not be called if data has been sent to the client. Syntax :- public void forward(ServletRequest req, ServletResponse res) throws ServletException, IOException
figure (just for understanding)
As you see in the above figure, response of second servlet is sent to the client. Response of the first Servlet is not displayed to the user. 2. include() It includes the content of a resource like servlet, JSP page, HTML file in the response. This method is used to include some content to the response has been initiated by opening a PrintWriter or ServletOutputStream back to the client machine. Syntax:- public void include(ServletRequest req, ServletResponse res) throws ServletException, IOException Page 16 of 18 J2EE 2. RMI,Servlet B.C.A. SEM -5
figure (just for understanding)
As you can see in the above figure, response of second servlet is included in the response of the first Servlet that is being sent to the client.
Servlet With JDBC First of create DSN for MSAccess. Then create table in access with field with name and place. And write the following code. import java.io.IOException; import java.io.PrintWriter; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class ConnectDb extends HttpServlet { public void doGet(HttpServletRequest req, HttpServletResponse res) throws IOException, ServletException { res.setContentType("text/html"); PrintWriter pw = res.getWriter(); Connection con = null; Statement stmt = null; ResultSet rs = null; try { Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); con = DriverManager.getConnection("jdbc:odbc:myServlet"); stmt = con.createStatement(); rs = stmt.executeQuery("SELECT* FROM servlet"); pw.println("Id \t \t Name \t \t Place
"); while (rs.next()) { pw.println("\t \t \t \t \t"); pw.println(rs.getObject(1).toString()); pw.println(rs.getObject(2).toString()); pw.println(rs.getObject(3).toString()); pw.println("
"); } } catch (SQLException e) { pw.println(e.getNextException()); } catch (ClassNotFoundException e) { pw.println(e.getException());
Page 17 of 18 J2EE 2. RMI,Servlet B.C.A. SEM -5
} finally { try { if (rs != null) { rs.close(); rs = null; } if (stmt != null) { stmt.close(); stmt = null; } if (con != null) { con.close(); con = null; } } catch (Exception e) { pw.close(); } } } }
web.xml
Now you can see the access table in your output.
Page 18 of 18 J2EE 3. JSP,Java Beans B.C.A. SEM -5
3 JSP,Java Beans
Topics Covered 1. Introduction to JSP and JSP Basics 2. Advantages using JSP 3. Disadvantages of JSP 4. JSP Vs. Servlet 5. JSP Architecture 6. Lifecycle of JSP 7. JSP elements 8. Comments and template data 9. JSP Implicit objects 10. JSP Scope
11. Including and Forwarding from JSP Pages – Include Action , Forward Action
12. Working with Session and Cookie in JSP 13. Error Handling and Exception Handling with JSP 14. JDBC With JSP 15. JavaBean Properties 16. JavaBean Methods 17. JavaBean Packaging
1. Introduction JSP technology is used to create web application just like Servlet technology. It can be thought of as an extension to the servlet because it provides more functionality than servlet. A JSP page contains HTML code and JSP tags. The JSP pages are easier to maintain than servlet because we can separate designing and development. It provides some additional features such as Expression Language, Custom Tag etc. 2. Advantages using JSP Nobody can borrow the code. . The JSP code written runs and remains on the webserver so, issue of copy source code doesn’t arise at all. Faster loading of pages. . With JSP decision can be made about what user want to see at webserver prior the page being dispatched No Browser compatibility issues . The JSP page can run same way in browser the developer end-up sending standard HTML to a user-browser. . Cross browser compatibility. JSP supports . JSP supported by number of webservers like Apache, Microsoft IIS, Microsoft PWS, Netscape FastTrack and Enterprise web servers Compilation . Important benefit of JSP is that it is always compiled before the webserver process it.
Page 1 of 37 J2EE 3. JSP,Java Beans B.C.A. SEM -5
. It allows the server to handle JSP page much much faster, Because older technologies like CGI required server to load an interpreter and the target script each time the page is requested. Embedded with HTML- XML
. JSP pages looks like an HTML or XML pages, it holds text marked with collection of tags.
3. Disadvantages of JSP Java code required . Simple things in JSP actually demands putting a java code in a page. Simple tasks are hard to code . Even including page header and footer is bit difficult with JSP Difficult looping in JSP . In Regular JSP pages lopping is difficult, In advance JSP we can use some custom tags for looping Occupies lot of space . JSP consumes extra hard drive and memory(RAM) space As JSP pages are translated to servlets and compiled, it is difficult to trace errors occurred in JSP pages. JSP pages require double the disk space to hold the JSP page. JSP pages require more time when accessed for the first time as they are to be
4. JSP Vs. Servlet A Servlet is a Java class implementing the javax.servlet.Servlet interface that runs within a Web or application server’s Servlet engine, servicing client requests forwarded to it through the server. A Java Server Page is a slightly more complicated. JSP pages contain a mixture of HTML , Java Scripts, JSP elements and JSP directives. The elements in a Java Server Page will generally be compiled by the JSP engine into a Servlet, but the JSP specification only requires that the JSP page execution entity follow the Servlet protocol. One advantage of JSP over Servlet is that the JSP allows a logical division between what is displayed and the Web server side code specification that dictates what content fills the page. It is easy to modify the look and feel of what is delivered by JSP without having to alter any Web server side , Java code specification. Other advantage of JSP is that they are document – centric. On the other hand, Servlet look and act like programs. A Java Server Page can contain Java program fragments that instantiate and execute Java classes, but these occur inside an HTML template file and are primarily used to generate dynamic content. Some of the JSP functionality can be achieved on the client using Javascript. While it’s true that anything done with a JSP can also be done with using a Servlet, JSPs provides a nice clean separation of the application’s presentation layer from its data manipulating layer. JSP is simple than Servlet. JSPs and Servlets work well together.
Page 2 of 37 J2EE 3. JSP,Java Beans B.C.A. SEM -5
Thus, both Servlets and JSP pages have many features in common, and can be used for developing dynamic Web contents.
5. JSP Architecture Typically, JSP pages are subject to a translation phase and a request phase. The translation phase is carried out only once, unless the JSP page changes. The communication of web browser and web server in terms of JSP is show in next figure.
JSP are built by Sun Microsystems servlet technology . JSP tag contains Java code and its file extension is .jsp .the JSP engine parses the .jsp and creates a java servlet source file. Then it compile the source file into a class file ,this is done first time only time. Step for JSP request which are as follows . When the user goes to a JSP page web browser makes the request via internet. . JSP request gets sent to the Web server. . Web server recognize the .jsp file and passes the JSP file to the JSP Servlet Engine. . If the JSP file has been called the first time the JSP file is parsed , otherwise servlet is instantiated. . The next step is to generate a special servlet file.the entire HTML statement convert into println statement . . The servlet source code is compile into a class. . The servlet is instantiated , calling the init and service methods. . HTML from the sevlet output is sent via the internet . . HTML results are displayed on the user’s web browser.
Page 3 of 37 J2EE 3. JSP,Java Beans B.C.A. SEM -5
6. JSP life cycle JSP allow you to write standard HTML pages containing tags that run powerful programs based on Java technology. The goal of JSP technology is to support separation of presentation and business logic. Web designer can design and update pages without learning the java technology. Similarly, java developer can write codes without dealing with web page design. The process of converting in to the servlet file is done in background by web container .
Javax.servlet.jsp.HttpJspPage interface is used to create servlet from JSP file
Previous figure shows the JSP life cycle. It shows that if the JSP page is requested first time by web client to web container. Then requested JSP code is converted into servlet code into the translation phase. After that in complication phase converted servlet code is complied and byte code is created in the from of servlet class. In next phase servlet class is loaded into servlet engine and servlet instance is created After creating instance it goes to the request process phase. The JSP pages follows these phases: . Translation of JSP Page . Compilation of JSP Page . Class loading (class file is loaded) . Instantiation (Object of the Generated Servlet is created). . Initialization ( jspInit() method is invoked by the container). . Reqeust processing ( _jspService() method is invoked by the container). . Destroy ( jspDestroy() method is invoked by the container). Following in-built methods of Javax.servlet.jsp.HttpJspPage interface is called during the JSP life cycle.
Page 4 of 37 J2EE 3. JSP,Java Beans B.C.A. SEM -5
. jspInit() . When JSP servlet instance (object) is created jspInit() method will be called . It is similar to init() method of servlet. Syntax: public void jspInit() . _jspService() . When JSP servlet instance (object) is called _jspService() method will be called at the time request and response object (implicit obj) are sent. . It is similar to service() method of servlet. Syntax: Public void_jspService(HttpServletRequest req,HttpServletResponse res) throws ServletException ,IOException . jspDestroy() . When JSP servlet instance (object) is destroy _jspDestroy() method will be called . It is similar to jspDestroy() method of servlet. Syntax: Public void jspDestroy()
7. JSP Elements JSP elements are instruction to JSP container about what code to generate and how it should operate. JSP elements have a special identity to JSP complier because it starts and ends with special kind of tags. Template data (HTML code) is not complied by the jsp complier and also not recognize by the JSP container . It is also known as Component of JSP page. JSP elements are as follows: Directive elements Scripting elements Action elements (1) Directive elements The directives are messages that tells the web container how to translate a JSP page into corresponding servlet.There are three types of directives: page directive include directive taglib directive Syntax . <%@ directive attribute=“value” %> 1.1 Page directive The page directive defines attributes that apply to an entire JSP page. Syntax of JSP page directive <%@ page [attribute1=“value” attribute2=“value”……..attributen=“valuen”] %> Following are the attributes….. . import . contentType
Page 5 of 37 J2EE 3. JSP,Java Beans B.C.A. SEM -5
. extends . info . buffer . language . isThreadSafe . session . pageEncoding . errorPage . isErrorPage
Import . The import attribute is used to import class, interface or all the members of a package. It is similar to import keyword in java class or interface. . Following packages are automatically imported with JSP page. Java.servlet.* java.servlet.http.* java.servlet.jsp.* Java.lang.* . Example of import attribute <%@ page import=“java.util.Date” %> contentType . The contentType attribute defines the MIME(Multipurpose Internet Mail Extension) type of the HTTP response.The default value is "text/html;charset=ISO-8859-1". . Example of contentType attribute <%@ page contentType=“text/html” charset=“UTF-8” %> extends . The extends attribute defines the parent class that will be inherited by the generated servlet.It is rarely used. info . This attribute simply sets the information of the JSP page which is retrieved later by using getServletInfo() method of Servlet interface. Example of info attribute <%@ page info=“Composed by abc” %> . The web container will create a method getServletInfo() in the resulting servlet.For example: buffer . The buffer attribute sets the buffer size in kilobytes to handle output generated by the JSP page. The default size of the buffer is 8Kb. Example of buffer attribute . <%@ page buffer=“16kb” %> language . The language attribute specifies the scripting language used in the JSP page. The default value is "java". . Most probably its valid value is java only. isThreadSafe . Servlet and JSP both are multithreaded. If you want to control this behavior of JSP page, you can use isThreadSafe attribute of page directive. The value of isThreadSafe value is true. If you make it false,
Page 6 of 37 J2EE 3. JSP,Java Beans B.C.A. SEM -5
. The web container will serialize the multiple requests, i.e. it will wait until the JSP finishes responding to a . request before passing another request to it. If you make the value of isThreadSafe attribute like: . <%@ page isThreadSafe="false" %> Session . it defines the Boolean indicating value if the jsp page require HTTP session then its value is true otherwise it become false. . The default value is true.
PageEncoding . It define the character encoding of jsp page itself. errorPage . The errorPage attribute is used to define the error page, if exception occurs in the current page, it will be redirected to the error page. isErrorPage . The isErrorPage attribute is used to declare that the current page is the error page. Example
Syntax for all the page directive <% @ page [import=“java.util.*, java.sql.*” ] [contentType=“text/html; charset=ISO-8859-1”] [session=“true/false”] [buffer=“size in kb”] [autoFlush=“true/false”] [info=“Some info message.”] [errorPage=“error.jsp”] [isErrorPage=“false/true”] [isThreadSafe=“true/false”] [language=“java”] [extends=“package.class” ] %> 1.2 Include directive The include directive is used to include the contents of any resource it may be jsp file, html file or text file. The include directive includes the original content of the included resource at page translation time.
Page 7 of 37 J2EE 3. JSP,Java Beans B.C.A. SEM -5
The code of the included file is added to the JSP document. Syntax of include directive <%@ include file=“filename” %> Example //header.jsp
<%=new java.util.Date(); %>
//main.jsp <%@ include file=“header.jsp” %> The above content is included from header.jsp 1.3 Taglib directive The JSP taglib directive is used to define a tag library that defines many tags. We use the TLD (Tag Library Descriptor) file to define the tags. In the custom tag section we will use this tag so it will be better to learn it in custom tag. Syntax JSP Taglib directive <%@ taglib url=“url of the tag library” prefix=“prefix of the tag library” %>Example
<%@ taglib url=”http://www.javascript.com/tags “prefix=”mytag” %>(2) Scripting elements The scripting elements provide the ability to insert java code inside the jsp. There are three types of scripting elements: scriptlet tag expression tag declaration tag
2.1 scriptlet tag A scriptlet tag is used to execute java source code in JSP. Syntax <% java code %> Example <% out.wirte(“welcome to JSP”) %> 2.2 Expression tag The code placed within expression tag is written to the output stream of the response. So you need not write out.print() to write data. It is mainly used to print the values of variable or method. Syntax of JSP expression tag <%= statement %>
Page 8 of 37 J2EE 3. JSP,Java Beans B.C.A. SEM -5
Example <%= “welcome to JSP” %> “Note that do not add the semicolon at the end of statement in the case of expression tag” <%= new java.util.Date() %> 2.3 Declaration tag The JSP declaration tag is used to declare fields and methods. The code written inside the jsp declaration tag is placed outside the service() method of auto generated servlet. So it doesn't get memory at each request.
Syntax of JSP declaration tag <%! Statement %> Example (that declare field) <%! int data=10; %> <%= “value of variable :”+data %> Example (that declare method) In this example of JSP declaration tag, we are defining the method which returns the cube of given number and calling this method from the jsp expression tag.
<%! int cube(int n) { return (n*n*n); } %> <%= “cube of 3:”+cube(3) %> (3) Action elements Action element are high level jsp element which are used to create, modify and use other objects Some standard action element in JSP page are as follows jsp:include jsp:forward jsp:param jsp:plugin (3.1) jsp:include The jsp:include action tag is used to include the content of another resource it may be jsp, html or servlet. The jsp include action tag includes the resource at request time so it is better for dynamic pages because there might be changes in future. SyntaxPage 9 of 37 J2EE 3. JSP,Java Beans B.C.A. SEM -5
Example :jsp:include printdate.jsp
<%=new java.util.Date(); %>
//main.jspEnd of main page
(3.2) jsp:forward The jsp:forward action tag is used to forward (transfer) control request to another resource it may be jsp, html or another resource. Syntax of jsp:forward<%=new java.util.Date(); %>
//main.jspEnd of main page
(3.3) jsp:param This element is used to provide the tag/value pairs of information by including these as sub- attribute of theDemo of Param tag
Page 10 of 37 J2EE 3. JSP,Java Beans B.C.A. SEM -5
<%= "Your given color is:"+request.getParameter("color") %> (3.4) jsp:plugin This element is used to embed an applet and java beans with the jsp page . The tag automatically detects the browser type and insert the appropriate HTML tag either