the j2ee platform,jdbc(java database...

121
Sub : J2EE Chapter – 1 The J2EE platform B.C.A. Sem -5 Page 1 of 24 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)

Upload: others

Post on 30-May-2020

27 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: The J2EE Platform,JDBC(Java Database Connectivity)mmghodasaracollege.in/admin-cp/images/download_doc/down_doc/… · Other JDBC API The J2EE Platform,JDBC(Java Database Connectivity)

Sub : J2EE Chapter – 1 The J2EE platform B.C.A. Sem -5

Page 1 of 24

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 2: The J2EE Platform,JDBC(Java Database Connectivity)mmghodasaracollege.in/admin-cp/images/download_doc/down_doc/… · Other JDBC API The J2EE Platform,JDBC(Java Database Connectivity)

Sub : J2EE Chapter – 1 The J2EE platform B.C.A. Sem -5

Page 2 of 24

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 3: The J2EE Platform,JDBC(Java Database Connectivity)mmghodasaracollege.in/admin-cp/images/download_doc/down_doc/… · Other JDBC API The J2EE Platform,JDBC(Java Database Connectivity)

Sub : J2EE Chapter – 1 The J2EE platform B.C.A. Sem -5

Page 3 of 24

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 4: The J2EE Platform,JDBC(Java Database Connectivity)mmghodasaracollege.in/admin-cp/images/download_doc/down_doc/… · Other JDBC API The J2EE Platform,JDBC(Java Database Connectivity)

Sub : J2EE Chapter – 1 The J2EE platform B.C.A. Sem -5

Page 4 of 24

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 5: The J2EE Platform,JDBC(Java Database Connectivity)mmghodasaracollege.in/admin-cp/images/download_doc/down_doc/… · Other JDBC API The J2EE Platform,JDBC(Java Database Connectivity)

Sub : J2EE Chapter – 1 The J2EE platform B.C.A. Sem -5

Page 5 of 24

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 6: The J2EE Platform,JDBC(Java Database Connectivity)mmghodasaracollege.in/admin-cp/images/download_doc/down_doc/… · Other JDBC API The J2EE Platform,JDBC(Java Database Connectivity)

Sub : J2EE Chapter – 1 The J2EE platform B.C.A. Sem -5

Page 6 of 24

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 7: The J2EE Platform,JDBC(Java Database Connectivity)mmghodasaracollege.in/admin-cp/images/download_doc/down_doc/… · Other JDBC API The J2EE Platform,JDBC(Java Database Connectivity)

Sub : J2EE Chapter – 1 The J2EE platform B.C.A. Sem -5

Page 7 of 24

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 8: The J2EE Platform,JDBC(Java Database Connectivity)mmghodasaracollege.in/admin-cp/images/download_doc/down_doc/… · Other JDBC API The J2EE Platform,JDBC(Java Database Connectivity)

Sub : J2EE Chapter – 1 The J2EE platform B.C.A. Sem -5

Page 8 of 24

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 9: The J2EE Platform,JDBC(Java Database Connectivity)mmghodasaracollege.in/admin-cp/images/download_doc/down_doc/… · Other JDBC API The J2EE Platform,JDBC(Java Database Connectivity)

Sub : J2EE Chapter – 1 The J2EE platform B.C.A. Sem -5

Page 9 of 24

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 10: The J2EE Platform,JDBC(Java Database Connectivity)mmghodasaracollege.in/admin-cp/images/download_doc/down_doc/… · Other JDBC API The J2EE Platform,JDBC(Java Database Connectivity)

Sub : J2EE Chapter – 1 The J2EE platform B.C.A. Sem -5

Page 10 of 24

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 11: The J2EE Platform,JDBC(Java Database Connectivity)mmghodasaracollege.in/admin-cp/images/download_doc/down_doc/… · Other JDBC API The J2EE Platform,JDBC(Java Database Connectivity)

Sub : J2EE Chapter – 1 The J2EE platform B.C.A. Sem -5

Page 11 of 24

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 12: The J2EE Platform,JDBC(Java Database Connectivity)mmghodasaracollege.in/admin-cp/images/download_doc/down_doc/… · Other JDBC API The J2EE Platform,JDBC(Java Database Connectivity)

Sub : J2EE Chapter – 1 The J2EE platform B.C.A. Sem -5

Page 12 of 24

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 13: The J2EE Platform,JDBC(Java Database Connectivity)mmghodasaracollege.in/admin-cp/images/download_doc/down_doc/… · Other JDBC API The J2EE Platform,JDBC(Java Database Connectivity)

Sub : J2EE Chapter – 1 The J2EE platform B.C.A. Sem -5

Page 13 of 24

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 14: The J2EE Platform,JDBC(Java Database Connectivity)mmghodasaracollege.in/admin-cp/images/download_doc/down_doc/… · Other JDBC API The J2EE Platform,JDBC(Java Database Connectivity)

Sub : J2EE Chapter – 1 The J2EE platform B.C.A. Sem -5

Page 14 of 24

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 15: The J2EE Platform,JDBC(Java Database Connectivity)mmghodasaracollege.in/admin-cp/images/download_doc/down_doc/… · Other JDBC API The J2EE Platform,JDBC(Java Database Connectivity)

Sub : J2EE Chapter – 1 The J2EE platform B.C.A. Sem -5

Page 15 of 24

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 16: The J2EE Platform,JDBC(Java Database Connectivity)mmghodasaracollege.in/admin-cp/images/download_doc/down_doc/… · Other JDBC API The J2EE Platform,JDBC(Java Database Connectivity)

Sub : J2EE Chapter – 1 The J2EE platform B.C.A. Sem -5

Page 16 of 24

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 17: The J2EE Platform,JDBC(Java Database Connectivity)mmghodasaracollege.in/admin-cp/images/download_doc/down_doc/… · Other JDBC API The J2EE Platform,JDBC(Java Database Connectivity)

Sub : J2EE Chapter – 1 The J2EE platform B.C.A. Sem -5

Page 17 of 24

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 18: The J2EE Platform,JDBC(Java Database Connectivity)mmghodasaracollege.in/admin-cp/images/download_doc/down_doc/… · Other JDBC API The J2EE Platform,JDBC(Java Database Connectivity)

Sub : J2EE Chapter – 1 The J2EE platform B.C.A. Sem -5

Page 18 of 24

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 19: The J2EE Platform,JDBC(Java Database Connectivity)mmghodasaracollege.in/admin-cp/images/download_doc/down_doc/… · Other JDBC API The J2EE Platform,JDBC(Java Database Connectivity)

Sub : J2EE Chapter – 1 The J2EE platform B.C.A. Sem -5

Page 19 of 24

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 20: The J2EE Platform,JDBC(Java Database Connectivity)mmghodasaracollege.in/admin-cp/images/download_doc/down_doc/… · Other JDBC API The J2EE Platform,JDBC(Java Database Connectivity)

Sub : J2EE Chapter – 1 The J2EE platform B.C.A. Sem -5

Page 20 of 24

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 21: The J2EE Platform,JDBC(Java Database Connectivity)mmghodasaracollege.in/admin-cp/images/download_doc/down_doc/… · Other JDBC API The J2EE Platform,JDBC(Java Database Connectivity)

Sub : J2EE Chapter – 1 The J2EE platform B.C.A. Sem -5

Page 21 of 24

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 22: The J2EE Platform,JDBC(Java Database Connectivity)mmghodasaracollege.in/admin-cp/images/download_doc/down_doc/… · Other JDBC API The J2EE Platform,JDBC(Java Database Connectivity)

Sub : J2EE Chapter – 1 The J2EE platform B.C.A. Sem -5

Page 22 of 24

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 23: The J2EE Platform,JDBC(Java Database Connectivity)mmghodasaracollege.in/admin-cp/images/download_doc/down_doc/… · Other JDBC API The J2EE Platform,JDBC(Java Database Connectivity)

Sub : J2EE Chapter – 1 The J2EE platform B.C.A. Sem -5

Page 23 of 24

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 24: The J2EE Platform,JDBC(Java Database Connectivity)mmghodasaracollege.in/admin-cp/images/download_doc/down_doc/… · Other JDBC API The J2EE Platform,JDBC(Java Database Connectivity)

Sub : J2EE Chapter – 1 The J2EE platform B.C.A. Sem -5

Page 24 of 24

} 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 25: The J2EE Platform,JDBC(Java Database Connectivity)mmghodasaracollege.in/admin-cp/images/download_doc/down_doc/… · Other JDBC API The J2EE Platform,JDBC(Java Database Connectivity)

J2EE 2. RMI,Servlet B.C.A. SEM -5

Page 1 of 18

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.

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

Page 26: The J2EE Platform,JDBC(Java Database Connectivity)mmghodasaracollege.in/admin-cp/images/download_doc/down_doc/… · Other JDBC API The J2EE Platform,JDBC(Java Database Connectivity)

J2EE 2. RMI,Servlet B.C.A. SEM -5

Page 2 of 18

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 27: The J2EE Platform,JDBC(Java Database Connectivity)mmghodasaracollege.in/admin-cp/images/download_doc/down_doc/… · Other JDBC API The J2EE Platform,JDBC(Java Database Connectivity)

J2EE 2. RMI,Servlet B.C.A. SEM -5

Page 3 of 18

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 28: The J2EE Platform,JDBC(Java Database Connectivity)mmghodasaracollege.in/admin-cp/images/download_doc/down_doc/… · Other JDBC API The J2EE Platform,JDBC(Java Database Connectivity)

J2EE 2. RMI,Servlet B.C.A. SEM -5

Page 4 of 18

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 29: The J2EE Platform,JDBC(Java Database Connectivity)mmghodasaracollege.in/admin-cp/images/download_doc/down_doc/… · Other JDBC API The J2EE Platform,JDBC(Java Database Connectivity)

J2EE 2. RMI,Servlet B.C.A. SEM -5

Page 5 of 18

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 30: The J2EE Platform,JDBC(Java Database Connectivity)mmghodasaracollege.in/admin-cp/images/download_doc/down_doc/… · Other JDBC API The J2EE Platform,JDBC(Java Database Connectivity)

J2EE 2. RMI,Servlet B.C.A. SEM -5

Page 6 of 18

} 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 31: The J2EE Platform,JDBC(Java Database Connectivity)mmghodasaracollege.in/admin-cp/images/download_doc/down_doc/… · Other JDBC API The J2EE Platform,JDBC(Java Database Connectivity)

J2EE 2. RMI,Servlet B.C.A. SEM -5

Page 7 of 18

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 32: The J2EE Platform,JDBC(Java Database Connectivity)mmghodasaracollege.in/admin-cp/images/download_doc/down_doc/… · Other JDBC API The J2EE Platform,JDBC(Java Database Connectivity)

J2EE 2. RMI,Servlet B.C.A. SEM -5

Page 8 of 18

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 33: The J2EE Platform,JDBC(Java Database Connectivity)mmghodasaracollege.in/admin-cp/images/download_doc/down_doc/… · Other JDBC API The J2EE Platform,JDBC(Java Database Connectivity)

J2EE 2. RMI,Servlet B.C.A. SEM -5

Page 9 of 18

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 34: The J2EE Platform,JDBC(Java Database Connectivity)mmghodasaracollege.in/admin-cp/images/download_doc/down_doc/… · Other JDBC API The J2EE Platform,JDBC(Java Database Connectivity)

J2EE 2. RMI,Servlet B.C.A. SEM -5

Page 10 of 18

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 35: The J2EE Platform,JDBC(Java Database Connectivity)mmghodasaracollege.in/admin-cp/images/download_doc/down_doc/… · Other JDBC API The J2EE Platform,JDBC(Java Database Connectivity)

J2EE 2. RMI,Servlet B.C.A. SEM -5

Page 11 of 18

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 36: The J2EE Platform,JDBC(Java Database Connectivity)mmghodasaracollege.in/admin-cp/images/download_doc/down_doc/… · Other JDBC API The J2EE Platform,JDBC(Java Database Connectivity)

J2EE 2. RMI,Servlet B.C.A. SEM -5

Page 12 of 18

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 37: The J2EE Platform,JDBC(Java Database Connectivity)mmghodasaracollege.in/admin-cp/images/download_doc/down_doc/… · Other JDBC API The J2EE Platform,JDBC(Java Database Connectivity)

J2EE 2. RMI,Servlet B.C.A. SEM -5

Page 13 of 18

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 38: The J2EE Platform,JDBC(Java Database Connectivity)mmghodasaracollege.in/admin-cp/images/download_doc/down_doc/… · Other JDBC API The J2EE Platform,JDBC(Java Database Connectivity)

J2EE 2. RMI,Servlet B.C.A. SEM -5

Page 14 of 18

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 39: The J2EE Platform,JDBC(Java Database Connectivity)mmghodasaracollege.in/admin-cp/images/download_doc/down_doc/… · Other JDBC API The J2EE Platform,JDBC(Java Database Connectivity)

J2EE 2. RMI,Servlet B.C.A. SEM -5

Page 15 of 18

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 40: The J2EE Platform,JDBC(Java Database Connectivity)mmghodasaracollege.in/admin-cp/images/download_doc/down_doc/… · Other JDBC API The J2EE Platform,JDBC(Java Database Connectivity)

J2EE 2. RMI,Servlet B.C.A. SEM -5

Page 16 of 18

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 41: The J2EE Platform,JDBC(Java Database Connectivity)mmghodasaracollege.in/admin-cp/images/download_doc/down_doc/… · Other JDBC API The J2EE Platform,JDBC(Java Database Connectivity)

J2EE 2. RMI,Servlet B.C.A. SEM -5

Page 17 of 18

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<br>"); 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("<br>"); } } catch (SQLException e) { pw.println(e.getNextException()); } catch (ClassNotFoundException e) { pw.println(e.getException());

Page 42: The J2EE Platform,JDBC(Java Database Connectivity)mmghodasaracollege.in/admin-cp/images/download_doc/down_doc/… · Other JDBC API The J2EE Platform,JDBC(Java Database Connectivity)

J2EE 2. RMI,Servlet B.C.A. SEM -5

Page 18 of 18

} 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 <?xml version="1.0" encoding="UTF-8"?> <web-app id="WebApp_ID" version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd"> <display-name>dbconnection</display-name> <servlet> <servlet-name>ConnectDb</servlet-name> <servlet-class>ConnectDb</servlet-class> </servlet> <servlet-mapping> <servlet-name>ConnectDb</servlet-name> <url-pattern>/ConnectDb</url-pattern> </servlet-mapping> </web-app> Now you can see the access table in your output.

Page 43: The J2EE Platform,JDBC(Java Database Connectivity)mmghodasaracollege.in/admin-cp/images/download_doc/down_doc/… · Other JDBC API The J2EE Platform,JDBC(Java Database Connectivity)

J2EE 3. JSP,Java Beans B.C.A. SEM -5

Page 1 of 37

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.

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

Page 44: The J2EE Platform,JDBC(Java Database Connectivity)mmghodasaracollege.in/admin-cp/images/download_doc/down_doc/… · Other JDBC API The J2EE Platform,JDBC(Java Database Connectivity)

J2EE 3. JSP,Java Beans B.C.A. SEM -5

Page 2 of 37

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 45: The J2EE Platform,JDBC(Java Database Connectivity)mmghodasaracollege.in/admin-cp/images/download_doc/down_doc/… · Other JDBC API The J2EE Platform,JDBC(Java Database Connectivity)

J2EE 3. JSP,Java Beans B.C.A. SEM -5

Page 3 of 37

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 46: The J2EE Platform,JDBC(Java Database Connectivity)mmghodasaracollege.in/admin-cp/images/download_doc/down_doc/… · Other JDBC API The J2EE Platform,JDBC(Java Database Connectivity)

J2EE 3. JSP,Java Beans B.C.A. SEM -5

Page 4 of 37

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 47: The J2EE Platform,JDBC(Java Database Connectivity)mmghodasaracollege.in/admin-cp/images/download_doc/down_doc/… · Other JDBC API The J2EE Platform,JDBC(Java Database Connectivity)

J2EE 3. JSP,Java Beans B.C.A. SEM -5

Page 5 of 37

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 48: The J2EE Platform,JDBC(Java Database Connectivity)mmghodasaracollege.in/admin-cp/images/download_doc/down_doc/… · Other JDBC API The J2EE Platform,JDBC(Java Database Connectivity)

J2EE 3. JSP,Java Beans B.C.A. SEM -5

Page 6 of 37

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 49: The J2EE Platform,JDBC(Java Database Connectivity)mmghodasaracollege.in/admin-cp/images/download_doc/down_doc/… · Other JDBC API The J2EE Platform,JDBC(Java Database Connectivity)

J2EE 3. JSP,Java Beans B.C.A. SEM -5

Page 7 of 37

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 50: The J2EE Platform,JDBC(Java Database Connectivity)mmghodasaracollege.in/admin-cp/images/download_doc/down_doc/… · Other JDBC API The J2EE Platform,JDBC(Java Database Connectivity)

J2EE 3. JSP,Java Beans B.C.A. SEM -5

Page 8 of 37

The code of the included file is added to the JSP document. Syntax of include directive

<%@ include file=“filename” %> Example

//header.jsp <html><body> <h1><%=new java.util.Date(); %></h1> </body></html>

//main.jsp <%@ include file=“header.jsp” %> <html><body> The above content is included from header.jsp </body></html>

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

<html> <body> <%@ taglib url=”http://www.javascript.com/tags “prefix=”mytag” %> <mytag:currentdate> </body> </html> </mytag:currentdate>

(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 51: The J2EE Platform,JDBC(Java Database Connectivity)mmghodasaracollege.in/admin-cp/images/download_doc/down_doc/… · Other JDBC API The J2EE Platform,JDBC(Java Database Connectivity)

J2EE 3. JSP,Java Beans B.C.A. SEM -5

Page 9 of 37

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. <html> <body> <%! int cube(int n) { return (n*n*n); } %> <%= “cube of 3:”+cube(3) %> </body> </html>

(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. Syntax <jsp:include page=“filename” flush=“true/false”> [ <jsp:param name=“Paramname” value=“ParamValue” /> ] </jsp:include>

Where, Page:-Any JSP/HTML file which will be included Flush:-it is an optional parameter used to flush buffer

Page 52: The J2EE Platform,JDBC(Java Database Connectivity)mmghodasaracollege.in/admin-cp/images/download_doc/down_doc/… · Other JDBC API The J2EE Platform,JDBC(Java Database Connectivity)

J2EE 3. JSP,Java Beans B.C.A. SEM -5

Page 10 of 37

Example :jsp:include printdate.jsp

<html><body> <h1><%=new java.util.Date(); %></h1> </body></html>

//main.jsp <html><body> <jsp:include page=“printdate.jsp”/> <h1>End of main page</h1> </body></html>

(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

<jsp:forward page=“destinationpage”> [ <jsp:param name=“Paramname” value=“ParamValue” /> ]

</jsp:forward> Example //printdate.jsp

<html><body> <h1><%=new java.util.Date(); %></h1> </body></html>

//main.jsp <html><body> <jsp:forward page=“printdate.jsp”/> <h1>End of main page</h1></body</html>

(3.3) jsp:param This element is used to provide the tag/value pairs of information by including these as sub-

attribute of the <jsp:include> ,<jsp:forward> and the <jsp:pulgin> actions Syntax <jsp:param name=“pname” value=“pvalue”/> or <jsp:param name=“pname” value=“pvalue”> </jsp:param>

Where, Pname:-is a name of parameter name which is being referenced pvalue-:-is the value of parameter

Example <!-- main.jsp --> <html> <body> <h1> Demo of Param tag</h1> <jsp:forward page="demo.jsp" > <jsp:param name="color" value="red" /> </jsp:forward> </body> </html> <!-- Demo.jsp --> <html>

Page 53: The J2EE Platform,JDBC(Java Database Connectivity)mmghodasaracollege.in/admin-cp/images/download_doc/down_doc/… · Other JDBC API The J2EE Platform,JDBC(Java Database Connectivity)

J2EE 3. JSP,Java Beans B.C.A. SEM -5

Page 11 of 37

<body> <%= "<b>Your given color is:"+request.getParameter("color") %> </body> </html>

(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

<embed> or <object> in the output. Syntax <jsp:plugin type=“plugintype” code=“class filename” codebase=“url” > </jsp:plugin> Example

<html> <head><title>Applet Pulgin Demo</title> </head> <body> <jsp:plugin type="applet" code="Circle1.class" width="300" height="300"> </jsp:plugin> </body> </html>

Circle.java

import java.awt.*; import java.applet.*; /*<applet code=Circle1.class height=500 width=500> </applet>*/ public class Circle1 extends Applet { public void paint(Graphics g) { setBackground(Color.white); Dimension d=getSize(); int x=d.width; int y=d.height; setForeground(Color.magenta); g.fillOval(50,50,x-100,y-100); } }

8. Comments and template data Comments We can use two types of comments with the JSP page one is for HTML and another for JSP

HTML comments:- <!– this is HTML comment --> JSP Specific tag:-<%-- this is JSP comment --%>

- It will not appear in the page output to the client. Template Data In JSP page , everything that is not a directive, declaration , scriplet, expression , action

element or JSP comment is termed as template data .

Page 54: The J2EE Platform,JDBC(Java Database Connectivity)mmghodasaracollege.in/admin-cp/images/download_doc/down_doc/… · Other JDBC API The J2EE Platform,JDBC(Java Database Connectivity)

J2EE 3. JSP,Java Beans B.C.A. SEM -5

Page 12 of 37

Usually , all the HTML and text in the page are called template data. Template data is ignore by JSP translator. This data is output to the client as if it had appeared within a static web page. 9. Implicit objects of JSP In servlet if we want to use the objects like request and response we need to explicitly

declare it within the servlet program. Like these some other objects which are frequently used with the JSP program are implicit

(hidden) within the JSP which are known as Implicit objects of JSP. Implicit objects means the objects which is already created by JSP itself. Implicit Objects are automatically created in JSP pages and can be used without declaring

their objects. Implicit Objects

Request Response Out Session Config Exception Application Page

Request Object This is most important objects which is used in JSP programming. The entire

request coming from the client can be obtained from this objects. Similar to servlet programming request object in JSP also belongs to

javax.Servlet.http.HttpServletRequest Class. You can see all parameters which are sent by client through request object.

Methods Enumeration getParameterNames();

Return the name of all Parameters. String getParameter(String name);

Return the first value of a single request parameter. String getMethod();

Return the Http Method for request weather it is GET or POST HttpSession getSession(), HttpSession getSession(boolean);

Retrieves the session data for the request StringBuffer getRequestURL();

Return the full URL of the request Examples login.jsp <html> <head> <title>Request Object Demo</title> </head> <body>

Page 55: The J2EE Platform,JDBC(Java Database Connectivity)mmghodasaracollege.in/admin-cp/images/download_doc/down_doc/… · Other JDBC API The J2EE Platform,JDBC(Java Database Connectivity)

J2EE 3. JSP,Java Beans B.C.A. SEM -5

Page 13 of 37

<h1>Request Object Demo</h1> <form action="NextPage.jsp" method="get"> <table> <tr> <td> Username &nbsp;&nbsp;&nbsp; <input type="text" name="uname"> </td> </tr> <tr> <td> Password &nbsp;&nbsp;&nbsp; <input type="password" name="password"> </td> </tr> <tr><td><br></td></tr> <tr> <td><input type="submit"></td> </tr> </table> </form> </body> </html> Nextpage.jsp <html> <head> <title>Request Object Demo</title> </head> <body> <h1>Request Object Demo</h1> <% String uname=request.getParameter("uname"); String password=request.getParameter("password"); String method=request.getMethod(); StringBuffer URL=request.getRequestURL(); %> <h2>Username :- &nbsp;&nbsp; <%=uname %></h2> <h2>Password :- &nbsp;&nbsp; <%=password %></h2> <h2>Method you have used:- &nbsp;&nbsp; <%=method %></h2> <h2>Full URL :- &nbsp;&nbsp; <%=URL %></h2> </body> </html>

Page 56: The J2EE Platform,JDBC(Java Database Connectivity)mmghodasaracollege.in/admin-cp/images/download_doc/down_doc/… · Other JDBC API The J2EE Platform,JDBC(Java Database Connectivity)

J2EE 3. JSP,Java Beans B.C.A. SEM -5

Page 14 of 37

Response Object This is another most important objects which is used in JSP programming. If you

want to generate any output for client, then you can generate it using response object. As Similar to servlet programming response objects in JSP in belongs to javax.servlet.http.HttpServletResponse class .

The scope of the objects is page only because it is used to generate output of a particular page.

Methods Enumeration getParameterNames();

Return the name of all Parameters.

Void setContentType(String Content Type); This method is used to set the content type e.g. setContentType(“text/html”);

Void addCookie(Cookie cookie); Adding the specified cookie to the response.

Void setHeader(String name,String value); Assign the specific value to the named header

Void sendRedirect(String location) This method is used to redirect the page to the another location.

Example login.jsp as above code successfully.jsp <html> <head> <title>Response Object Demo</title> </head> <body> <h1>Response Object Demo</h1> <h2>Successfully Login</h2> <% String uname=request.getParameter("uname"); String password=request.getParameter("password"); if(! (uname.equals("Alish") && password.equals("alish123")) ) { response.sendRedirect("Error.jsp"); } %> <h2> Helllo &nbsp;&nbsp; <%=uname %></h2> <h2> Your Password is :- &nbsp;&nbsp; <%=password %></h2> </body> </html>

Page 57: The J2EE Platform,JDBC(Java Database Connectivity)mmghodasaracollege.in/admin-cp/images/download_doc/down_doc/… · Other JDBC API The J2EE Platform,JDBC(Java Database Connectivity)

J2EE 3. JSP,Java Beans B.C.A. SEM -5

Page 15 of 37

error.jsp

<html> <head> <title>Response Object Demo</title> </head> <body> <h1>Response Object Demo</h1> <h2>Invalid Username or Password</h2> <br><br> <form action="Login.jsp" method="get"> <input type="submit" value="Back"> </form> </body> </html>

Out Object

This object is used to write output into the output stream of clients. The scope of out is current page. Out object is created using javax.setrvlet.jsp.JspWriter class. There are several methods under out implicit objects.

Methods Void print(), void println();

This method is used to print the output on the page. Void clear()

Clear the output buffer. If the buffer contents have already been transmitted to the client, this method will cause an IOExceptionto be thrown.

Void clearBuffer() Similar to clear(), but does not throw an exception if the buffer has already

been flushed. Session Object

As the name suggest, this session implicit object is used for session tracking. This belongs to javax.Servlet.http.HttpSession class. Session object for requesting the client is created under session implicit object.

Methods Public Object getAttribute(String name)

Returns the object bound with the specified name in this session, or null if no object is bound under the name.

public void setAttribute(String name, Object value) This method is used to set the attribute to the session

public void removeAttribute(String name) This method is used to remove the attribute to the session

public long getCreationTime() Returns the time when this session was created, measured in milliseconds

Page 58: The J2EE Platform,JDBC(Java Database Connectivity)mmghodasaracollege.in/admin-cp/images/download_doc/down_doc/… · Other JDBC API The J2EE Platform,JDBC(Java Database Connectivity)

J2EE 3. JSP,Java Beans B.C.A. SEM -5

Page 16 of 37

Example Firstpage.jsp <html> <body> <% session.setAttribute("username","ABC"); %> <h1>Session Object Demo</h1> <h2>First Page</h2> <form action="NextPage.jsp" method="get"> <input type="submit" value="Next Page"> </form> </body> </html> Nextpage.jsp <html> <body> <h1>Session Object Demo</h1> <h2>Next Page</h2> <% String uname=session.getAttribute("username").toString(); %> <h2>Username :- &nbsp;&nbsp; <%=uname %></h2> </body> </html> Config Object

This implicit object is similar to servletConfig object of Servlet. Config is created using javax.servlet.ServletConfig class. This is mainly used to read some initial parameters which are passed to particular page.

Methods Public String getInitParameter(String name) Returns a String containing the value of the named initialization parameter, or null

if the parameter does not exist. Public Enumeration getInitParameterNames()

Returns the names of the servlet's initialization parameters as an Enumeration of String objects, or an empty Enumeration if the servlet has no initialization parameters

Example <html> <body> <h1>Config Object Demo</h1> <h2>First Page</h2> <h3><%= config.getServletName() %></h3> </body>

Page 59: The J2EE Platform,JDBC(Java Database Connectivity)mmghodasaracollege.in/admin-cp/images/download_doc/down_doc/… · Other JDBC API The J2EE Platform,JDBC(Java Database Connectivity)

J2EE 3. JSP,Java Beans B.C.A. SEM -5

Page 17 of 37

</html> Exception Object

This object is used to get the information about the exception (runtime errrors). This object is exists in java.lang.Throwable class.

Methods public String getMessage()

Returns the detail message string of this throwable. Example Main.jsp

<%@ page errorPage="Error.jsp" %> <html> <body> <h1>Exception Object</h1> <% int a=10; int b=0; b=a/b; %> <h2>Answer is &nbsp; <%=b %></h2> </body> </html>

Error.jsp <%@ page isErrorPage="true" %> <html> <head> </head> <body> <h3><%=exception.getMessage() %> exception has been occcured. </h3> </body> </html>

Application Object This implicit object is used to set the values and attribute at application level.

Application object of JSP is similar to ServletContext object of Servlet Programming.

Methods public Object getAttribute(String name)

Return the attribute with the specified name public Enumeration getAttributeNames()

Return the attribute with the names available within the application public void setAttribute(String name, Object object)

Store the object with the given object name in the application public void removeAttribute(String name)

Remove the name of the object mentioned in the parameter of this method from the object of the application.

Page 60: The J2EE Platform,JDBC(Java Database Connectivity)mmghodasaracollege.in/admin-cp/images/download_doc/down_doc/… · Other JDBC API The J2EE Platform,JDBC(Java Database Connectivity)

J2EE 3. JSP,Java Beans B.C.A. SEM -5

Page 18 of 37

Example Firstpage.jsp

<html> <body> <h1>Application Object Demo</h1> <h2>First Page</h2> <% application.setAttribute("username","ABC"); %> <form action="NextPage.jsp" method="get"> <input type="submit" value="Next Page"> </form> </body> </html>

//nextpage.jsp

<html> <body> <h1>Application Object Demo</h1> <h2>Next Page</h2> <% String uname=application.getAttribute("username").toString(); %> <h2>Username :- &nbsp;&nbsp; <%=uname %></h2> </body> </html>

Page Object JSP page is converted into Servlet Class at last. Then servlet instance is created of

that particular JSP servlet class. Page is the instance of JSP servlet class created by web container for the current

request. It contains the methods of object class along with all the methods created inside JSP

Page. 10. Scope of the JSP objects or JSP Scope Objects that are created as part of a JSP page have a certain lifetime and may or may not be

accessible to other components in the web application. The lifetime and accessibility of an object is known as scope. In some case, such as with the implicit objects (will discuss in next section), the scope is set

and can’t be changed. There are four valid scope Page scope Request scope Session scope Application scope

Page 61: The J2EE Platform,JDBC(Java Database Connectivity)mmghodasaracollege.in/admin-cp/images/download_doc/down_doc/… · Other JDBC API The J2EE Platform,JDBC(Java Database Connectivity)

J2EE 3. JSP,Java Beans B.C.A. SEM -5

Page 19 of 37

Page scope This scope is the most restrictive. With page scope , the object is accessible only

within the current JSP page in which it is defined. JavaBeans created with page scope and object created by scriplets are thread-safe. JSP implicit objects out, exception , response , config , pageContext and page have

‘page’ scope Request scope

JSP object created using the request scope can be accessed from any pages that serve that request.

This means that the object is available within the page in which it is created , and within the request is forwarded or included .

Object with request scope are thread-safe. Only the execution thread for a particular request can access these objects

JSP implicit objects request have ‘request’ scope Session scope

JSP object created using the session scope are available to all application components that participate in the client’s session these objects are not thread-safe.

If the multiple requests could use the same session object at the same time, you must synchronized access to that object .

JSP implicit objects session have ‘session’ scope Application scope

This scope is the least restrictive. JSP object created using the application scope are available to entire application

for the life of the application. These objects are not thread-safe and access to them must be synchronized If the multiple requests could use the same application object at the same time JSP implicit objects application have ‘application’ scope

11. Including and Forwarding from JSP Page Include Action

Including a JSP Page or Servlet through a standard action differs from the include directive.

Syntax :- <jsp:include file=“Path of File” flush=“true/false”> [ <jsp:param name=“Paramname” value=“ParamValue” /> ] </jsp:include> When the JSP container translate the page, this include directive causes the indicate file to

be included in that place in the page and become part of the java source file that is compiled into the JSP Page implementation class; that is , it is included at translation time. Using the include directive, included file does not need to be a complete and valid JSP Page.

With the “include” standard action, the JSP file stops processing the current request and passes the request to the included file. The included file passes its output to the response.

After that control of the response returns to the calling JSP, which completes further process of response. The output of included page or servlet is included at request time.

Components that are include action must be valid JSP pages or servlet. The included file is neither allowed to modify the headers of response nor to set cookies in

the response. For the include element the page attribute is require and its value is the URL of the page

whose output is included in the response.

Page 62: The J2EE Platform,JDBC(Java Database Connectivity)mmghodasaracollege.in/admin-cp/images/download_doc/down_doc/… · Other JDBC API The J2EE Platform,JDBC(Java Database Connectivity)

J2EE 3. JSP,Java Beans B.C.A. SEM -5

Page 20 of 37

This URL is relative to the JSP page. The flush attribute is optional, and it indicates weather the output buffer should be flushed before the included file is call. The default value is false.

If the JSP needs to pass parameters to the included file, it does so with the <jsp:param> element.

One element is used for each parameter. This element is optional. If it is included, both the name and value attribute are required. The included JSP Page can access the parameters using the getParamenter() and

getParameters method of request object. Example <html> <body> <form method="get"> <table cellspacing="0" cellpadding="0"> <tr> <td> <jsp:include page="header.jsp" flush="false"> <jsp:param name="test" value="JSP Demo"></jsp:param> </jsp:include> </td> </tr> <tr> <td height="500px" width="1500" bgcolor="#22aaff" style="font-size:40px"> This is the content part of the page. </td> </tr> </table> </form> </body> </html> Header.jsp <% String name = request.getParameter("test"); %> <table> <tr> <td height="200px" width="1500" bgcolor="#ff22aa" style="font-size:40px"> This is the header part of page. <br> Name is <%=name%> </td> </tr> </table> Forward Action With the forward action , the current page stops processing the request and forwards the

request to another web components . This other components completes the response and execution never return to calling page.

Unlike the include action , which can occur at any time during a response . The forward action must occur prior to writing any output to the OutputStream. Syntax :-

<jsp:forward page=“URL” > [ <jsp:param name=“Paramname” value=“ParamValue” /> ] </jsp:forward>

The meaning and use of attributes and of the <jsp:param> element are the same as those for include the action.

Page 63: The J2EE Platform,JDBC(Java Database Connectivity)mmghodasaracollege.in/admin-cp/images/download_doc/down_doc/… · Other JDBC API The J2EE Platform,JDBC(Java Database Connectivity)

J2EE 3. JSP,Java Beans B.C.A. SEM -5

Page 21 of 37

Example <html> <body> <h1>Forward Action Demo</h1> <% String uname = "mmg"; if (uname.equals("mmg")) { %> <jsp:forward page="NextPage.jsp" > <jsp:param name="uname" value="<%=uname%>"></jsp:param> </jsp:forward> <% } %> <h2>Invalid username <%=uname%></h2> </body> </html> Nextpage.jsp <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Forward Action Demo</title> </head> <body> <% String uname= request.getParameter("uname"); %> <h1>Forward Action Demo</h1> <h2>Username is &nbsp;&nbsp;<%=uname %></h2> </body> </html> 12. Working with Session and Cookie in JSP Cookie

Cookies are text files stored on the client computer and they are kept for various information tracking purpose. JSP transparently supports HTTP cookies using underlying servlet technology.

There are three steps involved in identifying returning users:

Server script sends a set of cookies to the browser. For example name, age, or identification number etc.

Browser stores this information on local machine for future use. When next time browser sends any request to web server then it sends those cookies

information to the server and server uses that information to identify the user or may be for some other purpose as well.

Cookies are usually set in an HTTP header (although JavaScript can also set a cookie directly on a browser). A JSP that sets a cookie might send headers that look something like this:

HTTP/1.1 200 OK Date: Fri, 04 Feb 2000 21:03:38 GMT Server: Apache/1.3.9 (UNIX) PHP/4.0b3 Set-Cookie: name=xyz; expires=Friday, 04-Feb-07 22:03:38 GMT;

Page 64: The J2EE Platform,JDBC(Java Database Connectivity)mmghodasaracollege.in/admin-cp/images/download_doc/down_doc/… · Other JDBC API The J2EE Platform,JDBC(Java Database Connectivity)

J2EE 3. JSP,Java Beans B.C.A. SEM -5

Page 22 of 37

path=/; domain=tutorialspoint.com Connection: close Content-Type: text/html

As you can see, the Set-Cookie header contains a name value pair, a GMT date, a path and a domain. The name and value will be URL encoded. The expires field is an instruction to the browser to "forget" the cookie after the given time and date.

If the browser is configured to store cookies, it will then keep this information until the expiry date. If the user points the browser at any page that matches the path and domain of the cookie, it will resend the cookie to the server. The browser's headers might look something like this:

GET / HTTP/1.0 Connection: Keep-Alive User-Agent: Mozilla/4.6 (X11; I; Linux 2.2.6-15apmac ppc) Host: zink.demon.co.uk:1126 Accept: image/gif, */* Accept-Encoding: gzip Accept-Language: en Accept-Charset: iso-8859-1,*,utf-8 Cookie: name=xyz

A JSP script will then have access to the cookies through the request method request.getCookies() which returns an array of Cookie objects.

Servlet Cookies Methods:

Following is the list of useful methods associated with Cookie object which you can use while manipulating cookies in JSP:

S.N. Method & Description

1 public void setDomain(String pattern) This method sets the domain to which cookie applies, for example tutorialspoint.com.

2 public String getDomain() This method gets the domain to which cookie applies, for example tutorialspoint.com.

3 public void setMaxAge(int expiry) This method sets how much time (in seconds) should elapse before the cookie expires. If you don't set this, the cookie will last only for the current session.

4 public int getMaxAge() This method returns the maximum age of the cookie, specified in seconds, By default, -1 indicating the cookie will persist until browser shutdown.

5 public String getName() This method returns the name of the cookie. The name cannot be changed after creation.

6 public void setValue(String newValue) This method sets the value associated with the cookie.

7 public String getValue() This method gets the value associated with the cookie.

8 public void setPath(String uri) This method sets the path to which this cookie applies. If you don't specify a path, the cookie is returned for all URLs in the same directory as the current page as well as all

Page 65: The J2EE Platform,JDBC(Java Database Connectivity)mmghodasaracollege.in/admin-cp/images/download_doc/down_doc/… · Other JDBC API The J2EE Platform,JDBC(Java Database Connectivity)

J2EE 3. JSP,Java Beans B.C.A. SEM -5

Page 23 of 37

subdirectories.

9 public String getPath() This method gets the path to which this cookie applies.

10 public void setSecure(boolean flag) This method sets the boolean value indicating whether the cookie should only be sent over encrypted (i.e. SSL) connections.

11 public void setComment(String purpose) This method specifies a comment that describes a cookie's purpose. The comment is useful if the browser presents the cookie to the user.

12 public String getComment() This method returns the comment describing the purpose of this cookie, or null if the cookie has no comment.

Setting Cookies with JSP:

Setting cookies with JSP involves three steps:

(1) Creating a Cookie object: You call the Cookie constructor with a cookie name and a cookie value, both of which are strings.

Cookie cookie = new Cookie("key","value");

Keep in mind, neither the name nor the value should contain white space or any of the following characters:

[ ] ( ) = , " / ? @ : ;

(2) Setting the maximum age: You use setMaxAge to specify how long (in seconds) the cookie should be valid. Following would set up a cookie for 24 hours.

cookie.setMaxAge(60*60*24);

(3) Sending the Cookie into the HTTP response headers: You use response.addCookie to add cookies in the HTTP response header as follows:

response.addCookie(cookie);

Example:

<% // Create cookies for first and last names. Cookie firstName = new Cookie("first_name", request.getParameter("first_name")); Cookie lastName = new Cookie("last_name", request.getParameter("last_name")); // Set expiry date after 24 Hrs for both the cookies. firstName.setMaxAge(60*60*24); lastName.setMaxAge(60*60*24);

Page 66: The J2EE Platform,JDBC(Java Database Connectivity)mmghodasaracollege.in/admin-cp/images/download_doc/down_doc/… · Other JDBC API The J2EE Platform,JDBC(Java Database Connectivity)

J2EE 3. JSP,Java Beans B.C.A. SEM -5

Page 24 of 37

// Add both the cookies in the response header. response.addCookie( firstName ); response.addCookie( lastName ); %> <html> <head> <title>Setting Cookies</title> </head> <body> <center> <h1>Setting Cookies</h1> </center> <ul> <li><p><b>First Name:</b> <%= request.getParameter("first_name")%> </p></li> <li><p><b>Last Name:</b> <%= request.getParameter("last_name")%> </p></li> </ul> </body> </html>

Let us put above code in main.jsp file and use it in the following HTML page:

<html> <body> <form action="main.jsp" method="GET"> First Name: <input type="text" name="first_name"> <br /> Last Name: <input type="text" name="last_name" /> <input type="submit" value="Submit" /> </form> </body> </html>

Keep above HTML content in a file hello.jsp and put hello.jsp and main.jsp in <Tomcat-installation-directory>/webapps/ROOT directory. When you would access http://localhost:8080/hello.jsp, here is the actual output of the above form.

First Name:

Last Name:

Try to enter First Name and Last Name and then click submit button. This would display first name and last name on your screen and same time it would set two cookies firstName and lastName which would be passed back to the server when next time you would press Submit button.

Next section would explain you how you would access these cookies back in your web application.

Reading Cookies with JSP:

To read cookies, you need to create an array of javax.servlet.http.Cookie objects by calling the getCookies( ) method of HttpServletRequest. Then cycle through the array, and use getName() and getValue() methods to access each cookie and associated value.

Page 67: The J2EE Platform,JDBC(Java Database Connectivity)mmghodasaracollege.in/admin-cp/images/download_doc/down_doc/… · Other JDBC API The J2EE Platform,JDBC(Java Database Connectivity)

J2EE 3. JSP,Java Beans B.C.A. SEM -5

Page 25 of 37

Example:

Let us read cookies which we have set in previous example:

<html> <head> <title>Reading Cookies</title> </head> <body> <center> <h1>Reading Cookies</h1> </center> <% Cookie cookie = null; Cookie[] cookies = null; // Get an array of Cookies associated with this domain cookies = request.getCookies(); if( cookies != null ){ out.println("<h2> Found Cookies Name and Value</h2>"); for (int i = 0; i < cookies.length; i++){ cookie = cookies[i]; out.print("Name : " + cookie.getName( ) + ", "); out.print("Value: " + cookie.getValue( )+" <br/>"); } }else{ out.println("<h2>No cookies founds</h2>"); } %> </body> </html>

Now let us put above code in main.jsp file and try to access it. If you would have set first_name cookie as "Dhara" and last_name cookie as "Patel" then running http://localhost:8080/main.jsp would display the following result:

Found Cookies Name and Value

Name : first_name, Value: Dhara Name : last_name, Value: Patel

Delete Cookies with JSP:

To delete cookies is very simple. If you want to delete a cookie then you simply need to follow up following three steps:

Read an already existing cookie and store it in Cookie object. Set cookie age as zero using setMaxAge() method to delete an existing cookie. Add this cookie back into response header.

Example:

Following example would delete an existing cookie named "first_name" and when you would run main.jsp JSP next time it would return null value for first_name.

Page 68: The J2EE Platform,JDBC(Java Database Connectivity)mmghodasaracollege.in/admin-cp/images/download_doc/down_doc/… · Other JDBC API The J2EE Platform,JDBC(Java Database Connectivity)

J2EE 3. JSP,Java Beans B.C.A. SEM -5

Page 26 of 37

<html> <head> <title>Reading Cookies</title> </head> <body> <center> <h1>Reading Cookies</h1> </center> <% Cookie cookie = null; Cookie[] cookies = null; // Get an array of Cookies associated with this domain cookies = request.getCookies(); if( cookies != null ){ out.println("<h2> Found Cookies Name and Value</h2>"); for (int i = 0; i < cookies.length; i++){ cookie = cookies[i]; if((cookie.getName( )).compareTo("first_name") == 0 ){ cookie.setMaxAge(0); response.addCookie(cookie); out.print("Deleted cookie: " + cookie.getName( ) + "<br/>"); } out.print("Name : " + cookie.getName( ) + ", "); out.print("Value: " + cookie.getValue( )+" <br/>"); } }else{ out.println( "<h2>No cookies founds</h2>"); } %> </body> </html>

Now let us put above code in main.jsp file and try to access it. It would display the following result:

Cookies Name and Value

Deleted cookie : first_name Name : first_name, Value: Dhara Name : last_name, Value: Patel

Now try to run http://localhost:8080/main.jsp once again and it should display only one cookie as follows:

Found Cookies Name and Value

Name : last_name, Value: Patel

You can delete your cookies in Internet Explorer manually. Start at the Tools menu and select Internet Options. To delete all cookies, press Delete Cookies.

Page 69: The J2EE Platform,JDBC(Java Database Connectivity)mmghodasaracollege.in/admin-cp/images/download_doc/down_doc/… · Other JDBC API The J2EE Platform,JDBC(Java Database Connectivity)

J2EE 3. JSP,Java Beans B.C.A. SEM -5

Page 27 of 37

JSP - Session Tracking

HTTP is a "stateless" protocol which means each time a client retrieves a Web page, the client opens a separate connection to the Web server and the server automatically does not keep any record of previous client request.

Still there are following three ways to maintain session between web client and web server:

Cookies:

A webserver can assign a unique session ID as a cookie to each web client and for subsequent requests from the client they can be recognized using the received cookie.

This may not be an effective way because many time browser does not support a cookie, so I would not recommend to use this procedure to maintain the sessions.

Hidden Form Fields:

A web server can send a hidden HTML form field along with a unique session ID as follows:

<input type="hidden" name="sessionid" value="12345">

This entry means that, when the form is submitted, the specified name and value are automatically included in the GET or POST data. Each time when web browser sends request back, then session_id value can be used to keep the track of different web browsers.

This could be an effective way of keeping track of the session but clicking on a regular (<A HREF...>) hypertext link does not result in a form submission, so hidden form fields also cannot support general session tracking.

URL Rewriting:

You can append some extra data on the end of each URL that identifies the session, and the server can associate that session identifier with data it has stored about that session.

For example, with http://tutorialspoint.com/file.htm;sessionid=12345, the session identifier is attached as sessionid=12345 which can be accessed at the web server to identify the client.

URL rewriting is a better way to maintain sessions and works for the browsers when they don't support cookies but here drawback is that you would have generate every URL dynamically to assign a session ID though page is simple static HTML page.

The session Object:

Apart from the above mentioned three ways, JSP makes use of servlet provided HttpSession Interface which provides a way to identify a user across more than one page request or visit to a Web site and to store information about that user.

Page 70: The J2EE Platform,JDBC(Java Database Connectivity)mmghodasaracollege.in/admin-cp/images/download_doc/down_doc/… · Other JDBC API The J2EE Platform,JDBC(Java Database Connectivity)

J2EE 3. JSP,Java Beans B.C.A. SEM -5

Page 28 of 37

By default, JSPs have session tracking enabled and a new HttpSession object is instantiated for each new client automatically. Disabling session tracking requires explicitly turning it off by setting the page directive session attribute to false as follows:

<%@ page session="false" %>

The JSP engine exposes the HttpSession object to the JSP author through the implicit session object. Since session object is already provided to the JSP programmer, the programmer can immediately begin storing and retrieving data from the object without any initialization or getSession().

Here is a summary of important methods available through session object:

S.N. Method & Description

1 public Object getAttribute(String name) This method returns the object bound with the specified name in this session, or null if no object is bound under the name.

2 public Enumeration getAttributeNames() This method returns an Enumeration of String objects containing the names of all the objects bound to this session.

3 public long getCreationTime() This method returns the time when this session was created, measured in milliseconds since midnight January 1, 1970 GMT.

4 public String getId() This method returns a string containing the unique identifier assigned to this session.

5 public long getLastAccessedTime() This method returns the last time the client sent a request associated with this session, as the number of milliseconds since midnight January 1, 1970 GMT.

6 public int getMaxInactiveInterval() This method returns the maximum time interval, in seconds, that the servlet container will keep this session open between client accesses.

7 public void invalidate() This method invalidates this session and unbinds any objects bound to it.

8 public boolean isNew( This method returns true if the client does not yet know about the session or if the client chooses not to join the session.

9 public void removeAttribute(String name) This method removes the object bound with the specified name from this session.

10 public void setAttribute(String name, Object value) This method binds an object to this session, using the name specified.

11 public void setMaxInactiveInterval(int interval) This method specifies the time, in seconds, between client requests before the servlet container will invalidate this session.

Page 71: The J2EE Platform,JDBC(Java Database Connectivity)mmghodasaracollege.in/admin-cp/images/download_doc/down_doc/… · Other JDBC API The J2EE Platform,JDBC(Java Database Connectivity)

J2EE 3. JSP,Java Beans B.C.A. SEM -5

Page 29 of 37

Session Tracking Example:

This example describes how to use the HttpSession object to find out the creation time and the last-accessed time for a session. We would associate a new session with the request if one does not already exist.

<%@ page import="java.io.*,java.util.*" %> <% // Get session creation time. Date createTime = new Date(session.getCreationTime()); // Get last access time of this web page. Date lastAccessTime = new Date(session.getLastAccessedTime()); String title = "Welcome Back to my website"; Integer visitCount = new Integer(0); String visitCountKey = new String("visitCount"); String userIDKey = new String("userID"); String userID = new String("ABCD"); // Check if this is new comer on your web page. if (session.isNew()){ title = "Welcome to my website"; session.setAttribute(userIDKey, userID); session.setAttribute(visitCountKey, visitCount); } visitCount = (Integer)session.getAttribute(visitCountKey); visitCount = visitCount + 1; userID = (String)session.getAttribute(userIDKey); session.setAttribute(visitCountKey, visitCount); %> <html> <head> <title>Session Tracking</title> </head> <body> <center> <h1>Session Tracking</h1> </center> <table border="1" align="center"> <tr bgcolor="#949494"> <th>Session info</th> <th>Value</th> </tr> <tr> <td>id</td> <td><% out.print( session.getId()); %></td> </tr> <tr> <td>Creation Time</td> <td><% out.print(createTime); %></td> </tr> <tr> <td>Time of Last Access</td> <td><% out.print(lastAccessTime); %></td> </tr> <tr> <td>User ID</td> <td><% out.print(userID); %></td> </tr> <tr>

Page 72: The J2EE Platform,JDBC(Java Database Connectivity)mmghodasaracollege.in/admin-cp/images/download_doc/down_doc/… · Other JDBC API The J2EE Platform,JDBC(Java Database Connectivity)

J2EE 3. JSP,Java Beans B.C.A. SEM -5

Page 30 of 37

<td>Number of visits</td> <td><% out.print(visitCount); %></td> </tr> </table> </body> </html>

Now put above code in main.jsp and try to access http://localhost:8080/main.jsp. It would display the following result when you would run for the first time:

Welcome to my website

Session Infomation

Session info value

Id 0AE3EC93FF44E3C525B4351B77ABB2D5

Creation Time Tue Jun 08 17:26:40 GMT+04:00 2010

Time of Last Access Tue Jun 08 17:26:40 GMT+04:00 2010

User ID ABCD

Number of visits 0

Now try to run the same JSP for second time, it would display following result.

Welcome Back to my website

Session Infomation

info type value

Id 0AE3EC93FF44E3C525B4351B77ABB2D5

Creation Time Tue Jun 08 17:26:40 GMT+04:00 2010

Time of Last Access Tue Jun 08 17:26:40 GMT+04:00 2010

User ID ABCD

Number of visits 1

Deleting Session Data:

When you are done with a user's session data, you have several options:

Remove a particular attribute: You can call public void removeAttribute(String name) method to delete the value associated with a particular key.

Delete the whole session: You can call public void invalidate() method to discard an entire session.

Page 73: The J2EE Platform,JDBC(Java Database Connectivity)mmghodasaracollege.in/admin-cp/images/download_doc/down_doc/… · Other JDBC API The J2EE Platform,JDBC(Java Database Connectivity)

J2EE 3. JSP,Java Beans B.C.A. SEM -5

Page 31 of 37

Setting Session timeout: You can call public void setMaxInactiveInterval(int interval) method to set the timeout for a session individually.

Log the user out: The servers that support servlets 2.4, you can call logout to log the client out of the Web server and invalidate all sessions belonging to all the users.

web.xml Configuration: If you are using Tomcat, apart from the above mentioned methods, you can configure session time out in web.xml file as follows.

<session-config> <session-timeout>15</session-timeout> </session-config>

The timeout is expressed as minutes, and overrides the default timeout which is 30 minutes in Tomcat.

The getMaxInactiveInterval( ) method in a servlet returns the timeout period for that session in seconds. So if your session is configured in web.xml for 15 minutes, getMaxInactiveInterval( ) returns 900.

13. Handling Errors and Exceptions Dealing with Exception in the page directive Dealing with exception in the Deployment Descriptor Adding Exception Handling in JSP pages Dealing with exception in the page directive This is the first way to handle exception by creating an error page. To create an error page

with JSP we can use isErrorPage=true attribute of page directive. After creating an error page we can handle the exception with any JSP page by invoking

this error page with it using errorPage=“URL of the error page” attribute of the page directive.

Example Index.jsp <html> <body> <form action="NextPage.jsp" method="get"> <table> <tr> <td> Number 1 &nbsp;&nbsp; <input type="text" name="num1"> </td> </tr> <tr> <td> Number 2 &nbsp;&nbsp; <input type="text" name="num2"> </td> </tr> <tr><td><br></td></tr> <tr> <td>

Page 74: The J2EE Platform,JDBC(Java Database Connectivity)mmghodasaracollege.in/admin-cp/images/download_doc/down_doc/… · Other JDBC API The J2EE Platform,JDBC(Java Database Connectivity)

J2EE 3. JSP,Java Beans B.C.A. SEM -5

Page 32 of 37

<input type="submit" value="Answer"> </td> </tr> </table> </form> </body> </html> Nextpage.jsp <%@ page errorPage="Error.jsp" %> <html> <body> <% int a=0; int num1=Integer.parseInt(request.getParameter("num1")); int num2=Integer.parseInt(request.getParameter("num2")); a=num1/num2; %> <h2> Division is &nbsp; <%=a %></h2> <a href="index.jsp">Back</a> </body> </html> Error.jsp <%@ page isErrorPage="true" %> <html> <body> <h2><%= exception.getMessage() %></h2> </body> </html> Dealing with exception in the deployment descriptor This is the second way by which we can handle an exception with the JSP Page.

Deployment Descriptor is a web.xml file which defines the classes, resources and configuration of the application and how the server uses them to serve web requests.

It resides in the application under the WEB-INF/ directory. If an error page is define for handling an exception, the requests is directed to the error

page’s URL. The web application deployment descriptor uses the <error-page> tag to define web

components that handle errors. We can set deployment descriptor for error handling in two ways, either using exception

type or using error code. Exception type <error-page> <exception-type>java.lang.Throwable</exception-type> <location>Error.jsp</location> </error-page> Error code <error-page>

Page 75: The J2EE Platform,JDBC(Java Database Connectivity)mmghodasaracollege.in/admin-cp/images/download_doc/down_doc/… · Other JDBC API The J2EE Platform,JDBC(Java Database Connectivity)

J2EE 3. JSP,Java Beans B.C.A. SEM -5

Page 33 of 37

<error-code>500<error-code> <location>Error.jsp</location> </error-page> Example: Index.jsp <html> <body> <% int a=10,b;

b=a/0; %> <h2>Answer is &nbsp; <%=b %></h2> </body> </html> Error.jsp //Same as above code Web.xml <web-app> <error-page> <exception-type>java.lang.Throwable</exception-type> <location>/Error.jsp</location> </error-page> </web-app> Adding Exception Handling in JSP page Exception can be handle in a scriptlet in the same way as in java, by using the try-catch

block. Example <html> <body> <% int a; try { a=10/0; out.println("Division is " + String.valueOf(a)); } catch(Exception e) { out.println(e.getMessage()); } %> </body> </html>

14. JDBC With JSP Connectivity of JSP with JDBC

Access Database Connectivity Steps:

1)Go to the start<<Control Panel<<Administrative Tools<< data sources.

Page 76: The J2EE Platform,JDBC(Java Database Connectivity)mmghodasaracollege.in/admin-cp/images/download_doc/down_doc/… · Other JDBC API The J2EE Platform,JDBC(Java Database Connectivity)

J2EE 3. JSP,Java Beans B.C.A. SEM -5

Page 34 of 37

2)Click Add button and select the driver Microsoft Access Driver(*.mdb).

3)After selecting the driver, click finish button.

4)Then give Data Source Name and click ok button.

5)Your DSN will get created.

6) Restart your server and run your jsp code.

//Program : To display all the records of Std table

<%@page contentType="text/html" pageEncoding="UTF-8" import="java.sql.*"%> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>JDBC With JSP</title> </head> <body> <%! Connection con; Statement st; ResultSet rs; %> <% try { Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); con = DriverManager.getConnection("jdbc:odbc:std"); st = con.createStatement(); rs = st.executeQuery("Select * from Std"); out.print("<table border=1>"); out.print("<tr><td>RNo</td><td>Name</td><td>Phone</td></tr>"); while (rs.next()) { out.print("<tr>"); out.println("<td>" + rs.getInt(1) + "</td><td>" + rs.getString(2) + "</td><td>" + rs.getString(3) + "</td>"); out.print("</tr>"); } st.close(); con.close();

Page 77: The J2EE Platform,JDBC(Java Database Connectivity)mmghodasaracollege.in/admin-cp/images/download_doc/down_doc/… · Other JDBC API The J2EE Platform,JDBC(Java Database Connectivity)

J2EE 3. JSP,Java Beans B.C.A. SEM -5

Page 35 of 37

} catch (ClassNotFoundException cnfe) { out.println(cnfe); } catch (SQLException se) { out.println(se); } catch (Exception e) { out.println(e); } %> </body> </html>

where std is our DSN.

//Program : To display all the records of emp table

<%@page import="java.sql.*"%> <table border=1> <tr><th>Name</th><th>Address</th></tr> <% try{ Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); Connection con = DriverManager.getConnection("jdbc:odbc:employee"); Statement st=con.createStatement(); ResultSet rs=st.executeQuery("select * from emp"); while(rs.next()){ %> <tr><td><%=rs.getString("name")%></td><td><%=rs.getString("address")%></td> </tr> <% } rs.close(); st.close(); con.close(); } catch(Exception e){} %> </table>

where employee is our DSN.

1. JavaBean Properties A JavaBean is a specially constructed Java class written in the Java and coded according

to the JavaBeans API specifications. A JavaBean is a reusable software component that can be manipulated visually in an

application builder tool. Following are the unique characteristics that distinguish a JavaBean from other Java

classes:

Page 78: The J2EE Platform,JDBC(Java Database Connectivity)mmghodasaracollege.in/admin-cp/images/download_doc/down_doc/… · Other JDBC API The J2EE Platform,JDBC(Java Database Connectivity)

J2EE 3. JSP,Java Beans B.C.A. SEM -5

Page 36 of 37

It provides a default, no-argument constructor. It should be serializable and implement the Serializable interface. It may have a number of properties which can be read or written. It may have a number of "getter" and "setter" methods for the properties.

2. Advantages of JavaBeans It provides the property of “write once and run anywhere”. It can work in different local machines. Beans have the capability of capturing the events sent by other objects . The properties, events and methods of the bean can be controlled by the application

developer. Configuration setting of a bean can be saved in persistent storage.

3. Properties of JavaBeans

A JavaBean property is a named attribute that can be accessed by the user of the object. The attribute can be of any Java data type, including classes that you define. A JavaBean property may be read, write, read only, or write only. Indexed Properties:- An indexed property is an array instead of a single value. In this

case, the bean class provides a method for getting and setting the entire array Bound Properties:- A bound property notifies listeners when its value changes. This has

two implications: The bean class includes addPropertyChangeListener() and

removePropertyChangeListener() methods for managing the bean's listeners. When a bound property is changed, the bean sends a PropertyChangeEvent to its

registered listeners. The javabean property is like tag’s name and value JavaBean properties are accessed through two methods in the JavaBean's implementation

class: Method Description

getPropertyName() For example, if property name is firstName, your method name would be getFirstName() to read that property. This method is called accessor.

setPropertyName() For example, if property name is firstName, your method name would be setFirstName() to write that property. This method is called mutator.

A read-only attribute will have only a getPropertyName() method, and a write-only attribute will have only a setPropertyName() method.

4. JavaBean Method The Beans class is never meant to be instantiated; its static methods provide

miscellaneous JavaBeans features.

1) The instantiate() method creates an instance of a bean. The specified bean name represents either a serialized bean file or a bean class file; it is interpreted relative to the specified ClassLoader object.

2) The setDesignTime() and isDesignTime() methods are used to set and query a flag that indicates whether beans are being used in an application builder environment.

Page 79: The J2EE Platform,JDBC(Java Database Connectivity)mmghodasaracollege.in/admin-cp/images/download_doc/down_doc/… · Other JDBC API The J2EE Platform,JDBC(Java Database Connectivity)

J2EE 3. JSP,Java Beans B.C.A. SEM -5

Page 37 of 37

3) setGuiAvailable() and isGuiAvailable() set and query a flag that indicates whether the Java Virtual Machine is running in an environment in which a GUI is available.

4) isInstanceOf() method is a replacement for the Java instanceof operator for use with beans. Currently, it behaves just like instanceof, but in the future it may work with beans that consist of a set of Java objects, each of which provides a different "view" of a bean.

5) getInstanceOf() method is a replacement for the Java cast operator. It converts a bean to a superclass or interface type. Currently, it behaves just like a cast, but you should use it for future compatibility with multiclass beans.

Common JavaBean Packaging

Java bean are packaged and delivered in JAR files supported since JDK 1.1 JAR files are used to collect class files, serialized objects, images, help files and similar resources files.

A JAR file is a ZIP format archive file that may optionally have a manifest file. A manifest file contains additional information describing the contents of JAR files. A single JAR file may contain more than one java bean. The following is the basic example of a java bean class illustrates the common javabean

packaging mechanism. 1)Writing a first bean

Create a simple bean Compiling and saving the bean into JAR file. Loading the bean into the GUI builder of the netbeans IDE. FirstBean.java Import java.awt.*; Import java.io.Serializable; Public class FirstBean extends Canvas { Public FirstBean() { setSize(60,40); setBackground(Color.red); } } This code set the size and background of canvas.

Make sure that the CLASSPATH environment variable is set to point to all needed .class file. Compile the bean file Javac FirstBean.java Create a manifest file Manifest.tmp Name:FirstBean.class Java-Bean:True Create the jar file which contain the manifest file and FirstBean class file.

Page 80: The J2EE Platform,JDBC(Java Database Connectivity)mmghodasaracollege.in/admin-cp/images/download_doc/down_doc/… · Other JDBC API The J2EE Platform,JDBC(Java Database Connectivity)

J2EE 4. MVC architecture,EJV,Hibernate B.C.A. Sem-5

Page 1 of 30

1. Introduction to MVC. Model-View-Controller (MVC)

Model-View-Controller architecture is used for interactive web-applications. This

model minimizes the coupling between business logic and data presentation to web user.

This model divides the web based application into three layers: 1. Model: Model domain contains the business logics and functions that

manipulate the business data. It provides updated information to view domain and also gives response to query. And the controller can access the functionality which is encapsulated in the model.

2. View: View is responsible for presentation aspect of application according to the model data and also responsible to forward query response to the controller.

3. Controller: Controller accepts and intercepts user requests and controls the business objects to fulfill these requests. An application has one controller for related

4 MVC Architecture,EJB,Hibernate

Topics Covered 1. Introduction to MVC. 2. Implementation of MVC Architecture. 3. Introduction 4. Benefits of EJB 5. Restriction on EJB 6. Types of EJB 7. Session Beans 8. Entity Beans 9. Message-driven Beans 10. Timer Service 11. Introduction to Hibernate 12. Need for hibernate 13. Features of hibernate 14. Disadvantages of Hibernate 15. Exploring Hibernate Architecture 16. Downloading and Configuring and necessary files to Hibernate in Eclipse 17. Jars files of hibernate. 18. Hibernate Configuration file 19. Hibernate Mapping file 20. Basic Example of Hibernate 21. Annotation 22. Hibernate Inheritance 23. Inheritance Annotations 24. Hibernate Sessions

Page 81: The J2EE Platform,JDBC(Java Database Connectivity)mmghodasaracollege.in/admin-cp/images/download_doc/down_doc/… · Other JDBC API The J2EE Platform,JDBC(Java Database Connectivity)

J2EE 4. MVC architecture,EJV,Hibernate B.C.A. Sem-5

Page 2 of 30

functionality. Controller can also be depends on the type of clients.

Figure 1: MVC Architecture

Page 82: The J2EE Platform,JDBC(Java Database Connectivity)mmghodasaracollege.in/admin-cp/images/download_doc/down_doc/… · Other JDBC API The J2EE Platform,JDBC(Java Database Connectivity)

J2EE 7.MVC Architecture B.C.A. SEM -5

Page 3 of 30

MVC architecture MVC or Model View Controller architecture divides display functionality and maintains data to reduce the degree of coupling between components.

J2EE MVC A model presents the state and core business logic. Data present

in database is mapped by the model and holds the core business logic.

A View renders model’s contents. Data is accessed by a view from the model and display logic is added for presentation of the data.

A Controller performs the function of glue b/w a view and a model

Requests are delegated by controller for state and application

Page 83: The J2EE Platform,JDBC(Java Database Connectivity)mmghodasaracollege.in/admin-cp/images/download_doc/down_doc/… · Other JDBC API The J2EE Platform,JDBC(Java Database Connectivity)

J2EE 7.MVC Architecture B.C.A. SEM -5

Page 4 of 30

logic. Logic gets centralized to dispatch the requests to next view that

is dependent upon the input parameters from application state and client.

Servlet and JSP pages are decoupled by controller, by view selection handling.

MVC Responsibilities

1) Model Responsibilities Store data in properties Implement application method Provide method to register/unregister views. Notify views of state changes

2) View Responsibilities Create interface Update interface when model changes Forward input to controller

3) Controller Responsibilities Translate user input into changes in the model.

Advantages of MVC

1) More robust 2) Easier to maintain 3) Permits run time selection of appropriate views. 4) Multiview application 5) Different users 6) Alternate design

Implementation We're going to create a Student object acting as a model.StudentView will be a view class which can print student details on console and StudentController is the controller class responsible to store data in Student object and update view StudentView accordingly.

Page 84: The J2EE Platform,JDBC(Java Database Connectivity)mmghodasaracollege.in/admin-cp/images/download_doc/down_doc/… · Other JDBC API The J2EE Platform,JDBC(Java Database Connectivity)

J2EE 7.MVC Architecture B.C.A. SEM -5

Page 5 of 30

MVCPatternDemo, our demo class will use StudentController to demonstrate use of MVC pattern.

Step 1 Create Model.

Student.java

public class Student { private String rollNo; private String name; public String getRollNo() { return rollNo; } public void setRollNo(String rollNo) { this.rollNo = rollNo; } public String getName() { return name; } public void setName(String name) { this.name = name; } }

Page 85: The J2EE Platform,JDBC(Java Database Connectivity)mmghodasaracollege.in/admin-cp/images/download_doc/down_doc/… · Other JDBC API The J2EE Platform,JDBC(Java Database Connectivity)

J2EE 7.MVC Architecture B.C.A. SEM -5

Page 6 of 30

Step 2 Create View.

StudentView.java

public class StudentView { public void printStudentDetails(String studentName, String studentRollNo){ System.out.println("Student: "); System.out.println("Name: " + studentName); System.out.println("Roll No: " + studentRollNo); } }

Step 3 Create Controller.

StudentController.java

public class StudentController { private Student model; private StudentView view; public StudentController(Student model, StudentView view){ this.model = model; this.view = view; } public void setStudentName(String name){ model.setName(name); } public String getStudentName(){ return model.getName(); } public void setStudentRollNo(String rollNo){ model.setRollNo(rollNo); } public String getStudentRollNo(){ return model.getRollNo(); } public void updateView(){ view.printStudentDetails(model.getName(), model.getRollNo());

Page 86: The J2EE Platform,JDBC(Java Database Connectivity)mmghodasaracollege.in/admin-cp/images/download_doc/down_doc/… · Other JDBC API The J2EE Platform,JDBC(Java Database Connectivity)

J2EE 7.MVC Architecture B.C.A. SEM -5

Page 7 of 30

} }

Step 4 Use the StudentController methods to demonstrate MVC design pattern usage.

MVCPatternDemo.java

public class MVCPatternDemo { public static void main(String[] args) { //fetch student record based on his roll no from the database Student model = retriveStudentFromDatabase(); //Create a view : to write student details on console StudentView view = new StudentView(); StudentController controller = new StudentController(model, view); controller.updateView(); //update model data controller.setStudentName("John"); controller.updateView(); } private static Student retriveStudentFromDatabase(){ Student student = new Student(); student.setName("Robert"); student.setRollNo("10"); return student; } }

Step 5 Verify the output.

Student: Name: Robert Roll No: 10 Student: Name: John Roll No: 10

Page 87: The J2EE Platform,JDBC(Java Database Connectivity)mmghodasaracollege.in/admin-cp/images/download_doc/down_doc/… · Other JDBC API The J2EE Platform,JDBC(Java Database Connectivity)

J2EE 7.MVC Architecture B.C.A. SEM -5

Page 8 of 30

1. Introduction

EJB stands for Enterprise Java Beans. EJB is an essential part of a J2EE platform. EJB id reusable server-side software component. EJB facilitates the distributed java applications, providing an object oriented

transactional environment for building distributed, multi tier enterprise components. The primary goal of EJB is WORA(Write Once Run Anywhere). EJB application is deployed on the server, so it is called server side component. J2EE platform have component based architecture to provide multi-tiered, distributed

and highly transactional features to enterprise level applications. EJB provides an architecture to develop and deploy component based enterprise

applications considering robustness, high scalability and high performance. An EJB application can be deployed on any of the application server compliant with

J2EE 1.3 standard specification.It provides a default, no-argument constructor.

2. Benefits of EJB

Simplified development of large scale enterprise level application. Application Server/ EJB container provides most of the system level services like

transaction handling, logging, load balancing, persistence mechanism, exception handling and so on. Developer has to focus only on business logic of the application.

EJB container manages life cycle of ejb instances thus developer needs not to worry about when to create/delete ejb objects.

Simplicity Application portability Component reusability Ability to build complex application Sepration of business logic and presentation logic Deployment in many operating environments.

3. Restriction of EJB

Read or write nonfinal static fields. Define a class in a package Use the java.awt package to create a user interface. Create or modify class loaders Stop the JVM Load a native library Create,modify or delete files in filesystem.

4. Types of EJB Type Description Session Bean Session bean stores data of a particular user

for a single session. It can be stateful or stateless. It is less resource intensive as compared to entity beans. Session bean gets destroyed as soon as user session terminates.

Entity Bean Entity beans represents persistent data storage. User data can be saved to database via entity beans and later on can be

Page 88: The J2EE Platform,JDBC(Java Database Connectivity)mmghodasaracollege.in/admin-cp/images/download_doc/down_doc/… · Other JDBC API The J2EE Platform,JDBC(Java Database Connectivity)

J2EE 7.MVC Architecture B.C.A. SEM -5

Page 9 of 30

retrieved from the database in the entity bean.

Message Driven Bean Message driven beans are used in context of JMS (Java Messaging Service). Message Driven Beans can consumes JMS messages from external entities And act accordingly.

1)Session Bean

A session bean encapsulates business logic that can be invoked programmatically by a client over local, remote, or web service client views.

To access an application that is deployed on the server, the client invokes the session bean’s methods.

The session bean performs work for its client, shielding it from complexity by executing business tasks inside the server.

A session bean is not persistent. (That is, its data is not saved to a database.)

There are two types of session bean 1)Stateless bean

A stateless session bean is a type of enterprise bean which is normally used to do independent operations.

A stateless session bean as per its name does not have any associated client state, but it may preserve its instance state.

EJB Container normally creates a pool of few stateless bean's objects and use these objects to process client's request.

It is use for the following reasons. o The bean’s state has no data for a specific client. o In a single method invocation, the bean performs a generic task for all clients.

For example, you might use a stateless session bean to send an email that confirms an online order.

o The bean implements a web service.

Stateful bean

A stateful session bean is a type of enterprise bean which preserve the conversational state with client.

A stateful session bean as per its name keeps associated client state in its instance variables.

EJB Container creates a separate stateful session bean to process client's each request. It is use for the following reasons.

o The bean’s state represents the interaction between the bean and a specific client.

o The bean needs to hold information about the client across method invocations. o The bean mediates between the client and the other components of the

application, presenting a simplified view to the client.

Page 89: The J2EE Platform,JDBC(Java Database Connectivity)mmghodasaracollege.in/admin-cp/images/download_doc/down_doc/… · Other JDBC API The J2EE Platform,JDBC(Java Database Connectivity)

J2EE 7.MVC Architecture B.C.A. SEM -5

Page 10 of 30

o Behind the scenes, the bean manages the work flow of several enterprise beans.

2)Entity Bean

customers, orders, and products. In the Application Server, the persistent storage mechanism is a relational database.

Typically, each entity bean has an underlying table in a relational database, and each instance of the bean corresponds to a row in that table.

3) Message Driven Bean

A message-driven bean is an enterprise bean that allows Java EE applications to process messages asynchronously. This type of bean normally acts as a JMS message listener, which is similar to an event listener but receives JMS messages instead of events.

The messages can be sent by any Java EE component (an application client, another enterprise bean, or a web component) or by a JMS application or system that does not use Java EE technology.

Message-driven beans can process JMS messages or other kinds of messages. Message-driven beans have the following characteristics.

They execute upon receipt of a single client message. They are invoked asynchronously. They are relatively short-lived. They do not represent directly shared data in the database, but they can access and

update this data. They can be transaction-aware. They are stateless.

Timer Service

Timer Service is a mechanism using which scheduled application can be build. Timer services are available for building java EE applications that depends upon time based

service. It is generally used in scheduling application which is also known as workflows. A workflow describes a configurable sequence of activities or tasks that will happen at a

particular point of time. It is an enterprise bean container and enables to have scheduled timed notifications for all

types of enterprise beans. For example, salary slip generation on 1st of every month. EJB 3.0 specification has specified @Timeout annotation which helps in programming the

ejb service in a stateless or message driven bean. EJB Container calls the method which is annotated by @Timeout. EJB Timer Service is a service provided by Ejb container which helps to create timer and to

schedule callback when timer expires.

5. Introduction to hibernate

Page 90: The J2EE Platform,JDBC(Java Database Connectivity)mmghodasaracollege.in/admin-cp/images/download_doc/down_doc/… · Other JDBC API The J2EE Platform,JDBC(Java Database Connectivity)

J2EE 7.MVC Architecture B.C.A. SEM -5

Page 11 of 30

hibernate is an Object-Relational Mapping(ORM) solution for JAVA and it raised as an open source

Hibernate is a persistence framework which is used to persist data from java environment for database.

Persistence is a process of storing the data to some permenant medium. Hibernate was created by Gavin King in 2001. It is a powerful, high performance Object-Relational Persistence and Query service

for any Java Application. It make things easier the development of java application to interact with the database. Hibernate maps Java classes to database tables and from Java data types to SQL data

types. Hibernate sits between traditional Java objects and database server to handle all the

work in persisting those objects based on the appropriate O/R mechanisms and patterns. An ORM tool simplifies the data creation, data manipulation and data access. It is a

programming technique that maps the object to the data stored in the database.

6. Features of hibernate

Object/Relational Mapping o Hibernate ORM enables to write applications whose data outlives the

applications process. JPA Provider

o Hibernate has its own “native” API and also implements the JAVA persistence API specification.

Idiomatic persistence o Hibernate allows the development of persistant classes and natural object-

oriented idioms like inheritance, polymorphism, association, composition and the java collection framework.

High performance o Hibernate has proved to provide high performance due to its numerous

techniques like lazy initialization, numerous fetching strategies and optimistic locking with automatic versinning and time stamping.

Reliable o Hibernate is well known due to its excellent stability and quality, which is

proven by the acceptance and use by tens of thousands of java developers.

7. Need for hibernate

Hibernate applications are database independent using POJO(Plain Old Java Object) class for interacting with the database reducing dependency on JDBC.

The exception handling in JDBC is handled by hibernate automatically with the help of the translator for the unchecked exceptions.

Page 91: The J2EE Platform,JDBC(Java Database Connectivity)mmghodasaracollege.in/admin-cp/images/download_doc/down_doc/… · Other JDBC API The J2EE Platform,JDBC(Java Database Connectivity)

J2EE 7.MVC Architecture B.C.A. SEM -5

Page 12 of 30

Hibernate uses ORM which is better approach. In JDBC .properties file is used and in hibernate .xml file is used which is again a better

approach. In hibernate collection mapping is used which are advantageous. Hibernate has good connection pooling rather than JDBC.

8. Advantages of hibernates:

Hibernate supports Inheritance, Associations, Collections. In hibernate if we save the derived class object, then its base class object will also be

stored into the database, it means hibernate supporting inheritance Hibernate supports relationships like One-To-Many,One-To-One, Many-To-Many-to-

Many, Many-To-One In jdbc all exceptions are checked exceptions, so we must write code in try, catch and

throws, but in hibernate we only have Un-checked exceptions, so no need to write try, catch, or no need to write throws. Actually in hibernate we have the translator which converts checked to Un-checked

Hibernate has capability to generate primary keys automatically while we are storing the records into database

Hibernate has its own query language, i.e hibernate query language which is database independent

So if we change the database, then also our application will works as HQL is database independent

HQL contains database independent commands While we are inserting any record, if we don’t have any particular table in the database,

JDBC will rises an error like “View not exist”, and throws exception, but in case of hibernate, if it not found any table in the database this will create the table for us

Hibernate supports caching mechanism by this, the number of round trips between an application and the database will be reduced, by using this caching technique an application performance will be increased automatically.

Hibernate supports annotations, apart from XML Hibernate provided Dialect classes, so we no need to write sql queries in hibernate,

instead we use the methods provided by that API.

9. Disadvantages of hibernates:

You know some thing.., Its saying hibernate is little slower than pure JDBC, actually the reason being hibernate used to generate many SQL statements in run time, but i guess this is not the disadvantage

But there is one major disadvantage, which was boilerplate code issue, actually we need to write same code in several files in the same application, but spring eliminated this

10. Hibernate architecture

The Hibernate architecture is layered to keep you isolated from having to know the underlying APIs.

Hibernate makes use of the database and configuration data to provide persistence services (and persistent objects) to the application.

Page 92: The J2EE Platform,JDBC(Java Database Connectivity)mmghodasaracollege.in/admin-cp/images/download_doc/down_doc/… · Other JDBC API The J2EE Platform,JDBC(Java Database Connectivity)

J2EE 7.MVC Architecture B.C.A. SEM -5

Page 13 of 30

Following is a very high level view of the Hibernate Application Architecture.

Following is a detailed view of the Hibernate Application Architecture with few important core classes.

Page 93: The J2EE Platform,JDBC(Java Database Connectivity)mmghodasaracollege.in/admin-cp/images/download_doc/down_doc/… · Other JDBC API The J2EE Platform,JDBC(Java Database Connectivity)

J2EE 7.MVC Architecture B.C.A. SEM -5

Page 14 of 30

Hibernate uses various existing Java APIs, like JDBC, Java Transaction API(JTA), and Java Naming and Directory Interface (JNDI).

JDBC provides a rudimentary level of abstraction of functionality common to relational databases, allowing almost any database with a JDBC driver to be supported by Hibernate. JNDI and JTA allow Hibernate to be integrated with J2EE application servers.

Following section gives brief description of each of the class objects involved in Hibernate Application Architecture.

Configuration Object

The Configuration object is the first Hibernate object you create in any Hibernate application and usually created only once during application initialization.

It represents a configuration or properties file required by the Hibernate. The Configuration object provides two keys components:

Database Connection: This is handled through one or more configuration files supported by Hibernate.

These files are hibernate.properties and hibernate.cfg.xml. Class Mapping Setup: This component creates the connection between the Java classes

and database tables. SessionFactory Object

Configuration object is used to create a SessionFactory object which inturn configures Hibernate for the application using the supplied configuration file and allows for a Session object to be instantiated.

The SessionFactory is a thread safe object and used by all the threads of an application. The SessionFactory is heavyweight object so usually it is created during application

start up and kept for later use. You would need one SessionFactory object per database using a separate configuration

file. So if you are using multiple databases then you would have to create multiple SessionFactory objects.

Session Object

A Session is used to get a physical connection with a database. The Session object is lightweight and designed to be instantiated each time an

interaction is needed with the database. Persistent objects are saved and retrieved through a Session object. The session objects should not be kept open for a long time because they are not usually

thread safe and they should be created and destroyed them as needed.

Transaction Object

A Transaction represents a unit of work with the database and most of the RDBMS supports transaction functionality.

Transactions in Hibernate are handled by an underlying transaction manager and transaction (from JDBC or JTA).

Page 94: The J2EE Platform,JDBC(Java Database Connectivity)mmghodasaracollege.in/admin-cp/images/download_doc/down_doc/… · Other JDBC API The J2EE Platform,JDBC(Java Database Connectivity)

J2EE 7.MVC Architecture B.C.A. SEM -5

Page 15 of 30

This is an optional object and Hibernate applications may choose not to use this interface, instead managing transactions in their own application code.

Query Object

Query objects use SQL or Hibernate Query Language (HQL) string to retrieve data from the database and create objects.

A Query instance is used to bind query parameters, limit the number of results returned by the query, and finally to execute the query.

Jar files of hibernate most of the web applications developed today, integrating one or more frameworks is a

quite common thing but sometimes it becomes very difficult to identity the actual jar files that are required to build the complete web application.

JAR(Java Archive) files are Java’s version of ZIP file, JAR uses zip file format. It contains a number of compressed source files, which we can use in our program for

reusable functionality. antlr.jar commons-beanutils.jar commons-digester.jar commons-logging.jar commons-validator.jar jakarta-oro.jar commons-fileupload-1.0.j hibernate3.jar

Hibernate configuration file

Hibernate uses a file by name hibernate.cfg.xml. This file creates the connection pool and establishes the required environment. A file named .hbm.xml is used to author mappings. The bootstrap action is configured by

using Configuration interface. There are two types of environment to configure hibernate:

1. Managed Environment: The definitions of database operations such as connections, transaction boundaries, security levels. This environment is provided by application servers such as Jboss,Weblogic,Websphere.

2. Non-managed Environment: The basic configuration template is provided by this interface. Tomcat is one of the examples that best supports this environment.

Explain how to configure Hibernate.

Programmatic configuration

The org.hibernate.cfg.Configuration instance can be instantiated directly by specifying XML mapping documents.

If the mapping files are in the classpath, use addResource().

Page 95: The J2EE Platform,JDBC(Java Database Connectivity)mmghodasaracollege.in/admin-cp/images/download_doc/down_doc/… · Other JDBC API The J2EE Platform,JDBC(Java Database Connectivity)

J2EE 7.MVC Architecture B.C.A. SEM -5

Page 16 of 30

Configuration cfg = new Configuration() .addResource("Item.hbm.xml") .addResource("Bid.hbm.xml");

An alternative way is to specify the mapped class and allow Hibernate to find the mapping document:

Configuration cfg = new Configuration() .addClass(org.hibernate.auction.Item.class) .addClass(org.hibernate.auction.Bid.class);

org.hibernate.cfg.Configuration also allows you to specify configuration properties:

Configuration cfg = new Configuration() .addClass(org.hibernate.auction.Item.class) .addClass(org.hibernate.auction.Bid.class) .setProperty("hibernate.dialect", "org.hibernate.dialect.MySQLInnoDBDialect") .setProperty("hibernate.connection.datasource", "java:comp/env/jdbc/test") .setProperty("hibernate.order_updates", "true");

Alternative options include:

Passing an instance of java.util.Properties to Configuration.setProperties(). Placing a file named hibernate.properties in a root directory of the classpath. Setting System properties using java -Dproperty=value. Including <property> elements in hibernate.cfg.xml (this is discussed later).

Hibernate JDBC Properties: hibernate.connection.driver_class hibernate.connection.url hibernate.connection.username hibernate.connection.password hibernate.connection.pool_size

Hibernate mapping files

An Object/relational mappings are usually defined in an XML document. This mapping file instructs Hibernate how to map the defined class or classes to the database tables. Though many Hibernate users choose to write the XML by hand, a number of tools exist to

generate the mapping document. These include XDoclet, Middlegen and AndroMDA for advanced Hibernate users.

public class Employee {

private int id; private String firstName; private String lastName; private int salary;

public Employee() {}

Page 96: The J2EE Platform,JDBC(Java Database Connectivity)mmghodasaracollege.in/admin-cp/images/download_doc/down_doc/… · Other JDBC API The J2EE Platform,JDBC(Java Database Connectivity)

J2EE 7.MVC Architecture B.C.A. SEM -5

Page 17 of 30

public Employee(String fname, String lname, int salary) { this.firstName = fname; this.lastName = lname; this.salary = salary;

} public int getId() {

return id; } public void setId( int id ) {

this.id = id; } public String getFirstName() {

return firstName; } public void setFirstName( String first_name ) {

this.firstName = first_name; } public String getLastName() {

return lastName; } public void setLastName( String last_name ) {

this.lastName = last_name; } public int getSalary() {

return salary; }

public void setSalary( int salary ) {

this.salary = salary; }

}

There would be one table corresponding to each object you are willing to provide persistence. Consider above objects need to be stored and retrieved into the following RDBMS table:

create table EMPLOYEE (

id INT NOT NULL auto_increment, first_name VARCHAR(20) default NULL, last_name VARCHAR(20) default NULL, salary INT default NULL, PRIMARY KEY (id)

);

Based on the two above entities we can define following mapping file which instructs Hibernate how to map the defined class or classes to the database tables.

Page 97: The J2EE Platform,JDBC(Java Database Connectivity)mmghodasaracollege.in/admin-cp/images/download_doc/down_doc/… · Other JDBC API The J2EE Platform,JDBC(Java Database Connectivity)

J2EE 7.MVC Architecture B.C.A. SEM -5

Page 18 of 30

<?xml version="1.0" encoding="utf-8"?> <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD//EN" "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">

<hibernate-mapping>

<class name="Employee" table="EMPLOYEE">

<meta attribute="class-description"> This class contains the employee detail.

</meta> <id name="id" type="int" column="id">

<generator class="native"/> </id> <property name="firstName" column="first_name" type="string"/> <property name="lastName" column="last_name" type="string"/> <property name="salary" column="salary" type="int"/>

</class> </hibernate-mapping>

You should save the mapping document in a file with the format <classname>.hbm.xml. We saved our mapping document in the file Employee.hbm.xml. Let us see little detail about the mapping elements used in the mapping file:

The mapping document is an XML document having <hibernate-mapping> as the root element which contains all the <class> elements.

The <class> elements are used to define specific mappings from a Java classes to the database tables.

The Java class name is specified using the name attribute of the class element and the database table

name is specified using the table attribute. The <meta> element is optional element and can be used to create the class description. The <id> element maps the unique ID attribute in class to the primary key of the

database table. The name attribute of the id element refers to the property in the class and the column

attribute refers to the column in the database table. The type attribute holds the hibernate mapping type, this

mapping types will convert from Java to SQL data type. either identity, sequence or hilo algorithm to create primary key depending upon the

capabilities of the underlying database. The <property> element is used to map a Java class property to a column in the

database table. The name attribute of the element refers to the property in the class and the column

attribute refers to the column in the database table. The type attribute holds the hibernate mapping type, this

mapping types will convert from Java to SQL data type.

Example of hibernate

Page 98: The J2EE Platform,JDBC(Java Database Connectivity)mmghodasaracollege.in/admin-cp/images/download_doc/down_doc/… · Other JDBC API The J2EE Platform,JDBC(Java Database Connectivity)

J2EE 7.MVC Architecture B.C.A. SEM -5

Page 19 of 30

Here, we are going to create a simple example of hibernate application using eclipse IDE. For creating the first hibernate application in Eclipse IDE, we need to follow following steps:

1. Create the java project 2. Add jar files for hibernate 3. Create the Persistent class 4. Create the mapping file for Persistent class 5. Create the Configuration file 6. Create the class that retrieves or stores the persistent object 7. Run the application

1.Create the java project Create the java project by File Menu - New - project - java project . Now specify the project name e.g. firsthb then next - finish .

2) Add jar files for hibernate To add the jar files Right click on your project - Build path - Add external archives. Now select all the jar files as shown in the image given below then click open.

` In this example, we are connecting the application with oracle database. So you must add the ojdbc14.jar file.

3) Create the Persistent class

Here, we are creating the same persistent class which we have created in the previous topic. To create the persistent class, Right click on src - New - Class - specify the class with package name (e.g. com.javatpoint.mypackage) - finish.

Page 99: The J2EE Platform,JDBC(Java Database Connectivity)mmghodasaracollege.in/admin-cp/images/download_doc/down_doc/… · Other JDBC API The J2EE Platform,JDBC(Java Database Connectivity)

J2EE 7.MVC Architecture B.C.A. SEM -5

Page 20 of 30

Employee.java

package com.javatpoint.mypackage;

public class Employee {

private int id;

private String firstName,lastName;

public int getId() {

return id;

}

public void setId(int id) {

this.id = id;

}

public String getFirstName() {

return firstName;

}

public void setFirstName(String firstName) {

this.firstName = firstName;

}

public String getLastName() {

return lastName;

}

public void setLastName(String lastName) {

this.lastName = lastName;

}

}

package com.javatpoint.mypackage;

public class Employee {

Page 100: The J2EE Platform,JDBC(Java Database Connectivity)mmghodasaracollege.in/admin-cp/images/download_doc/down_doc/… · Other JDBC API The J2EE Platform,JDBC(Java Database Connectivity)

J2EE 7.MVC Architecture B.C.A. SEM -5

Page 21 of 30

private int id;

private String firstName,lastName;

public int getId() {

return id;

}

public void setId(int id) {

this.id = id;

}

public String getFirstName() {

return firstName;

}

public void setFirstName(String firstName) {

this.firstName = firstName;

}

public String getLastName() {

return lastName;

}

public void setLastName(String lastName) {

this.lastName = lastName;

}

}

4) Create the mapping file for Persistent class

Here, we are creating the same mapping file as created in the previous topic. To create the mapping file, Right click on src - new - file - specify the file name (e.g. employee.hbm.xml) - ok. It must be outside the package.

employee.hbm.xml

<?xml version='1.0' encoding='UTF-8'?>

Page 101: The J2EE Platform,JDBC(Java Database Connectivity)mmghodasaracollege.in/admin-cp/images/download_doc/down_doc/… · Other JDBC API The J2EE Platform,JDBC(Java Database Connectivity)

J2EE 7.MVC Architecture B.C.A. SEM -5

Page 22 of 30

<!DOCTYPE hibernate-mapping PUBLIC

"-//Hibernate/Hibernate Mapping DTD 3.0//EN"

"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">

<hibernate-mapping>

<class name="com.javatpoint.mypackage.Employee" table="emp1000">

<id name="id">

<generator class="assigned"></generator>

</id>

<property name="firstName"></property>

<property name="lastName"></property>

</class>

</hibernate-mapping>

<?xml version='1.0' encoding='UTF-8'?>

<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">

<hibernate-mapping>

<class name="com.javatpoint.mypackage.Employee" table="emp1000">

<id name="id">

<generator class="assigned"></generator>

</id>

<property name="firstName"></property>

<property name="lastName"></property>

</class>

</hibernate-mapping>

Page 102: The J2EE Platform,JDBC(Java Database Connectivity)mmghodasaracollege.in/admin-cp/images/download_doc/down_doc/… · Other JDBC API The J2EE Platform,JDBC(Java Database Connectivity)

J2EE 7.MVC Architecture B.C.A. SEM -5

Page 23 of 30

5) Create the Configuration file

The configuration file contains all the informations for the database such as connection_url, driver_class, username, password etc. The hbm2ddl.auto property is used to create the table in the database automatically. We will have in-depth learning about Dialect class in next topics. To create the configuration file, right click on src - new - file. Now specify the configuration file name e.g. hibernate.cfg.xml.

hibernate.cfg.xml

<?xml version='1.0' encoding='UTF-8'?>

<!DOCTYPE hibernate-configuration PUBLIC

"-//Hibernate/Hibernate Configuration DTD 3.0//EN"

"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">

<hibernate-configuration>

<session-factory>

<property name="hbm2ddl.auto">update</property>

<property name="dialect">org.hibernate.dialect.Oracle9Dialect</property>

<property name="connection.url">jdbc:oracle:thin:@localhost:1521:xe</property>

<property name="connection.username">system</property>

<property name="connection.password">oracle</property>

<property name="connection.driver_class">oracle.jdbc.driver.OracleDriver</property>

<mapping resource="employee.hbm.xml"/>

</session-factory>

</hibernate-configuration>

<?xml version='1.0' encoding='UTF-8'?>

<!DOCTYPE hibernate-configuration PUBLIC

"-//Hibernate/Hibernate Configuration DTD 3.0//EN"

"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">

<hibernate-configuration>

Page 103: The J2EE Platform,JDBC(Java Database Connectivity)mmghodasaracollege.in/admin-cp/images/download_doc/down_doc/… · Other JDBC API The J2EE Platform,JDBC(Java Database Connectivity)

J2EE 7.MVC Architecture B.C.A. SEM -5

Page 24 of 30

<session-factory>

<property name="hbm2ddl.auto">update</property>

<property name="dialect">org.hibernate.dialect.Oracle9Dialect</property>

<property name="connection.url">jdbc:oracle:thin:@localhost:1521:xe</property>

<property name="connection.username">system</property>

<property name="connection.password">oracle</property>

<property name="connection.driver_class">oracle.jdbc.driver.OracleDriver</property>

<mapping resource="employee.hbm.xml"/>

</session-factory>

</hibernate-configuration>

6) Create the class that retrieves or stores the persistent object

In this class, we are simply storing the employee object to the database.

package com.javatpoint.mypackage;

import org.hibernate.Session;

import org.hibernate.SessionFactory;

import org.hibernate.Transaction;

import org.hibernate.cfg.Configuration;

public class StoreData {

public static void main(String[] args) {

//creating configuration object

Configuration cfg=new Configuration();

cfg.configure("hibernate.cfg.xml");//populates the data of the configuration file

//creating seession factory object

Page 104: The J2EE Platform,JDBC(Java Database Connectivity)mmghodasaracollege.in/admin-cp/images/download_doc/down_doc/… · Other JDBC API The J2EE Platform,JDBC(Java Database Connectivity)

J2EE 7.MVC Architecture B.C.A. SEM -5

Page 25 of 30

SessionFactory factory=cfg.buildSessionFactory();

//creating session object

Session session=factory.openSession();

//creating transaction object

Transaction t=session.beginTransaction();

Employee e1=new Employee();

e1.setId(115);

e1.setFirstName("sonoo");

e1.setLastName("jaiswal");

session.persist(e1);//persisting the object

t.commit();//transaction is committed

session.close();

System.out.println("successfully saved");

}

}

package com.javatpoint.mypackage;

import org.hibernate.Session;

Page 105: The J2EE Platform,JDBC(Java Database Connectivity)mmghodasaracollege.in/admin-cp/images/download_doc/down_doc/… · Other JDBC API The J2EE Platform,JDBC(Java Database Connectivity)

J2EE 7.MVC Architecture B.C.A. SEM -5

Page 26 of 30

import org.hibernate.SessionFactory;

import org.hibernate.Transaction;

import org.hibernate.cfg.Configuration;

public class StoreData {

public static void main(String[] args) {

//creating configuration object

Configuration cfg=new Configuration();

cfg.configure("hibernate.cfg.xml");//populates the data of the configuration file

//creating seession factory object

SessionFactory factory=cfg.buildSessionFactory();

//creating session object

Session session=factory.openSession();

//creating transaction object

Transaction t=session.beginTransaction();

Employee e1=new Employee();

e1.setId(115);

e1.setFirstName("sonoo");

e1.setLastName("jaiswal");

session.persist(e1);//persisting the object

Page 106: The J2EE Platform,JDBC(Java Database Connectivity)mmghodasaracollege.in/admin-cp/images/download_doc/down_doc/… · Other JDBC API The J2EE Platform,JDBC(Java Database Connectivity)

J2EE 7.MVC Architecture B.C.A. SEM -5

Page 27 of 30

t.commit();//transaction is committed

session.close();

System.out.println("successfully saved");

}

}

7) Run the application Before running the application, determine that directory structure is like this.

Page 107: The J2EE Platform,JDBC(Java Database Connectivity)mmghodasaracollege.in/admin-cp/images/download_doc/down_doc/… · Other JDBC API The J2EE Platform,JDBC(Java Database Connectivity)

J2EE 7.MVC Architecture B.C.A. SEM -5

Page 28 of 30

To run the hibernate application, right click on the StoreData class - Run As - Java Application. Hibernate Annotations

We can create hibernate application with annotation. Following are the annotation that can be used to create Hibernate application such as

@Entity, @Id, @Table etc. It belongs to the javax.persistance.* package. Following are the steps to create the hibernate application with annotation.

1) Add the jar files for oracle and annotation. 2) Create the persistant class 3) Add mapping of persistant class in configuration file. 4) Create the class that retrieves or stores the persistant object.

Environment Setup for Hibernate Annotation

First of all you would have to make sure that you are using JDK 5.0 otherwise you need to upgrade your JDK to

JDK 5.0 to take advantage of the native support for annotations. Second, you will need to install the Hibernate 3.x annotations distribution package,

available from the sourceforge: Hibernate detects that the @Id annotation is on a field and assumes that it should access

properties on an object directly through fields at runtime. If you placed the @Id annotation on the getId() method, you would enable access to

properties through getter and setter methods by default. Hence, all other annotations are also placed on either fields or getter methods, following the

selected strategy. Following section will explain the annotations used in the above class.

@Entity Annotation The EJB 3 standard annotations are contained in the javax.persistence package, so we import this package as the first step. Second we used the @Entity annotation to the Employee class which marks this class as an entity bean, so it must have a no-argument constructor that is visible with at least protected scope.

@Table Annotation

The @Table annotation allows you to specify the details of the table that will be used to persist the entity in the database.

The @Table annotation provides four attributes, allowing you to override the name of the table, its catalogue, and its schema, and enforce unique constraints on columns in the table. For now we are using just table name which is EMPLOYEE.

Page 108: The J2EE Platform,JDBC(Java Database Connectivity)mmghodasaracollege.in/admin-cp/images/download_doc/down_doc/… · Other JDBC API The J2EE Platform,JDBC(Java Database Connectivity)

J2EE 7.MVC Architecture B.C.A. SEM -5

Page 29 of 30

@Id and @GeneratedValue Annotations Each entity bean will have a primary key, which you annotate on the class with the @Id annotation. The primary key can be a single field or a combination of multiple fields depending on your table structure. By default, the @Id annotation will automatically determine the most appropriate primary key generation strategy to be used but you can override this by applying the @GeneratedValue annotation which takes two parameters strategy and generator which I'm not going to discuss here, so let us use only default the default key generation strategy. Letting Hibernate determine which generator type to use makes your code portable between different databases.

@Column Annotation

The @Column annotation is used to specify the details of the column to which a field or property will be mapped. You can use column annotation with the following most commonly used attributes:

name attribute permits the name of the column to be explicitly specified. length attribute permits the size of the column used to map a value particularly for a String value. nullable attribute permits the column to be marked NOT NULL when the schema is generated. unique attribute permits the column to be marked as containing only unique values.

Hibernate Inheritance Compared to JDBC we have one main advantage in hibernate, which is hibernate inheritance. Suppose if we have base and derived classes, now if we save derived(sub) class object, base class object will also be stored into the database. But the thing is we must specify in what table we need to save which object data ( i will explain about this point later, just remember as of now). Class payment { -------- } Class creditcard extends payment { ------- } See if you save CreditCard class object, then payment class object will also be saved into the database Hibernate supports 3 types of Inheritance Mappings:

Page 109: The J2EE Platform,JDBC(Java Database Connectivity)mmghodasaracollege.in/admin-cp/images/download_doc/down_doc/… · Other JDBC API The J2EE Platform,JDBC(Java Database Connectivity)

J2EE 7.MVC Architecture B.C.A. SEM -5

Page 30 of 30

Table per class hierarchy Table per sub-class hierarchy Table per concrete class hierarchy

Hibernate Sessions

A Session is used to get a physical connection with a database. The Session object is lightweight and designed to be instantiated each time an interaction is needed with the database. Persistent objects are saved and retrieved through a Session object. The session objects should not be kept open for a long time because they are not usually thread safe and they should be created and destroyed them as needed. The main function of the Session is to offer create, read and delete operations for instances of mapped entity classes. Instances may exist in one of the following three states at a given point in time: transient: A new instance of a a persistent class which is not associated with a Session and has no representation in the database and no identifier value is considered transient by Hibernate. persistent: You can make a transient instance persistent by associating it with a Session. A persistent instance has a representation in the database, an identifier value and is associated with a Session. detached: Once we close the Hibernate Session, the persistent instance will become a detached instance.

Page 110: The J2EE Platform,JDBC(Java Database Connectivity)mmghodasaracollege.in/admin-cp/images/download_doc/down_doc/… · Other JDBC API The J2EE Platform,JDBC(Java Database Connectivity)

J2EE 5. Spring,Strut B.C.A. Sem-5

Page 1 of 12

1. Introduction to spring framework

spring is the most popular application development framework for enterprise Java.

Millions of developers around the world use Spring Framework to create high performing, easily testable, reusable code.

Spring framework is an open source Java platform and it was initially written by Rod Johnson and was first released under the Apache 2.0 license in June 2003.

Spring is lightweight when it comes to size and transparency. The basic version of spring framework is around 2MB.

The core features of the Spring Framework can be used in developing any Java application, but there are extensions for building web applications on top of the Java EE platform.

Spring framework architecture

spring could potentially be a one-stop shop for all your enterprise applications, however, Spring is modular, allowing you to pick and choose which modules are applicable to you, without having to bring in the rest.

The Spring Framework provides about 20 modules which can be used based on an application requirement.

5 Spring,Strut

Topics Covered 1. Introduction to spring framework 2. spring architecture 3. spring and MVC 4. Spring context definition 5. Inversion of control in spring 6. Ascept oriented programming in spring 7. Understanding Struts Framework 8. Comparision with MVC using RequestDispatcher and the EL 9. Struts Flow of Control 10. Processing Requests with Action Objects 11. Handling Request Parameters with FormBeans 12. Prepopulating and Redisplaying Input Forms 13. Using Properties Files

Page 111: The J2EE Platform,JDBC(Java Database Connectivity)mmghodasaracollege.in/admin-cp/images/download_doc/down_doc/… · Other JDBC API The J2EE Platform,JDBC(Java Database Connectivity)

J2EE 5. Spring,Strut B.C.A. Sem-5

Page 2 of 12

Module

The Core Container consists of the Core, Beans, Context, and Expression Language modules whose detail is as follows:

The Core module provides the fundamental parts of the framework, including the IoC and Dependency Injection features.

The Bean module provides BeanFactory which is a sophisticated implementation of the factory pattern.

The Context module builds on the solid base provided by the Core and Beans modules and it is a medium to access any objects defined and configured. The ApplicationContext interface is the focal point of the Context module.

The Expression Language module provides a powerful expression language for querying and manipulating an object graph at runtime.

Data Access/Integration

The Data Access/Integration layer consists of the JDBC, ORM, OXM, JMS and Transaction modules whose detail is as follows:

The JDBC module provides a JDBC-abstraction layer that removes the need to do tedious JDBC related coding.

The ORM module provides integration layers for popular object-relational mapping APIs, including JPA, JDO, Hibernate, and iBatis.

The OXM module provides an abstraction layer that supports Object/XML mapping implementations for JAXB, Castor, XMLBeans, JiBX and XStream.

The Java Messaging Service JMS module contains features for producing and consuming messages.

Page 112: The J2EE Platform,JDBC(Java Database Connectivity)mmghodasaracollege.in/admin-cp/images/download_doc/down_doc/… · Other JDBC API The J2EE Platform,JDBC(Java Database Connectivity)

J2EE 5. Spring,Strut B.C.A. Sem-5

Page 3 of 12

The Transaction module supports programmatic and declarative transaction management for classes that implement special interfaces and for all your POJOs.

Web

The Web layer consists of the Web, Web-Servlet, Web-Struts, and Web-Portlet modules whose detail is as follows:

The Web module provides basic web-oriented integration features such as multipart file-upload functionality and the initialization of the IoC container using servlet listeners and a web-oriented application context.

The Web-Servlet module contains Spring's model-view-controller (MVC)

Miscellaneous

There are few other important modules like AOP, Aspects, Instrumentation, Web and Test modules whose detail is as follows:

The AOP module provides aspect-oriented programming implementation allowing you to define method-interceptors and pointcuts to cleanly decouple code that implements functionality that should be separated.

The Aspects module provides integration with AspectJ which is again a powerful and mature aspect oriented programming (AOP) framework.

The Instrumentation module provides class instrumentation support and class loader implementations to be used in certain application servers.

The Test module supports the testing of Spring components with JUnit or TestNG frameworks.

Features of spring framework

Transaction management

It provides a generic abstraction layer for transaction management. It allow the developer to add the pluggable transaction manager and making it easy.

JDBC exception handling

It offers a meaningful exception hierarchy, which simplifies the error handling strategy.

AOP Framework

Spring is best AOP framework.

MVC Framework

It comes with MVC web application framework, built on core spring functionality. It is highly configurable via strategy interfaces and accommodates multiple view

technologies like JSP.

Page 113: The J2EE Platform,JDBC(Java Database Connectivity)mmghodasaracollege.in/admin-cp/images/download_doc/down_doc/… · Other JDBC API The J2EE Platform,JDBC(Java Database Connectivity)

J2EE 5. Spring,Strut B.C.A. Sem-5

Page 4 of 12

Spring Architecture

Spring is well organized architecture consisting of 7 modules.

1)Spring AOP:it is one of the key component of spring.AOP is used in spring.it is used to provide declarative enterprise services.

2)Spring ORM:the ORM package is related to the database access.It provides integration layers for popular object-relational mapping API’s.

3)Spring web:it is a part of spring’s web application development stack, which includes spring MVC.

4)Spring DAO:The DAO(Data Access Object) support in spring is primarily for standardizing the data access work using technologies like JDBC and hibernate.

5)Spring context:this package build on the beans package to add support for message sources and for the observer design pattern.

6)Spring web MVC:this is the module which provides the MVC implementation for the web application.

7)Spring Core:It is the most important component of spring framework.It provides the Dependancy injection features.It seprates the dependencies like initialization, creation and access of the objects.

Spring & MVC

Let us see the flow of spring MVC (3.2). I am not going to describe what is M,V,C hope you already know that mess right ? so lets start with the flow…

Page 114: The J2EE Platform,JDBC(Java Database Connectivity)mmghodasaracollege.in/admin-cp/images/download_doc/down_doc/… · Other JDBC API The J2EE Platform,JDBC(Java Database Connectivity)

J2EE 5. Spring,Strut B.C.A. Sem-5

Page 5 of 12

Spring MVC 3.2 Execution Flow Step 1: First request will be received by DispatcherServlet Step 2: DispatcherServlet will take the help of HandlerMapping and get to know the Controller class name associated with the given request

The Spring Web model-view-controller (MVC) framework is designed around a DispatcherServlet that handles all the HTTP requests and responses. The request processing workflow of the Spring Web MVC DispatcherServlet is illustrated in the following diagram:

Following is the sequence of events corresponding to an incoming HTTP request to DispatcherServlet:

1. After receiving an HTTP request, DispatcherServlet consults the HandlerMapping to call the appropriate Controller.

2. The Controller takes the request and calls the appropriate service methods based on used GET or POST method. The service method will set model data based on defined business logic and returns view name to the DispatcherServlet.

Page 115: The J2EE Platform,JDBC(Java Database Connectivity)mmghodasaracollege.in/admin-cp/images/download_doc/down_doc/… · Other JDBC API The J2EE Platform,JDBC(Java Database Connectivity)

J2EE 5. Spring,Strut B.C.A. Sem-5

Page 6 of 12

3. The DispatcherServlet will take help from ViewResolver to pickup the defined view for the request.

4. Once view is finalized, The DispatcherServlet passes the model data to the view which is finally rendered on the browser.

Step 3: So request transfer to the Controller, and then controller will process the request by executing appropriate methods and returns ModeAndView object (contains Model data and View name) back to the DispatcherServlet Step 4: Now DispatcherServlet send the model object to the ViewResolver to get the actual view page Step 5: Finally DispatcherServlet will pass the Model object to the View page to display the result

Spring ApplicationContext Container

The Application Context is spring's more advanced container. Similar to BeanFactory it can load bean definitions, wire beans together and dispense

beans upon request. Additionally it adds more enterprise-specific functionality such as the ability to resolve

textual messages from a properties file and the ability to publish application events to interested event listeners.

This container is defined by the org.springframework.context.ApplicationContext interface.

The ApplicationContext includes all functionality of the BeanFactory, it is generally recommended over the BeanFactory. BeanFactory can still be used for light weight applications like mobile devices or applet based applications.

The most commonly used ApplicationContext implementations are:

FileSystemXmlApplicationContext: This container loads the definitions of the beans from an XML file. Here you need to provide the full path of the XML bean configuration file to the constructor. ClassPathXmlApplicationContext This container loads the definitions of the beans from an XML file. Here you do not need to provide the full path of the XML file but you need to set CLASSPATH properly because this container will look bean configuration XML file in CLASSPATH. WebXmlApplicationContext: This container loads the XML file with definitions of all beans from within a web application.

Inversion of control in spring(IOC)

In spring the IOC principle is implemented using the Dependency Injection(DI) design pattern.

Dependency Injection

Martin fowler is the inventor of DI in IOC. It is a general concept and it can be expressed in many different ways in the spring

framework.

Page 116: The J2EE Platform,JDBC(Java Database Connectivity)mmghodasaracollege.in/admin-cp/images/download_doc/down_doc/… · Other JDBC API The J2EE Platform,JDBC(Java Database Connectivity)

J2EE 5. Spring,Strut B.C.A. Sem-5

Page 7 of 12

The application classes in a complex java application should be independent so that the other java classes can be reused and can be tested independently of other classes while doing unit testing.

DI joins these classes together and at the same time keeps them independent. DI can be well defined when it is distinguish separately in two parts. For example, class A is dependent on class B.The second part, injection states that all

this means is that class B will get injected into class A by the IOC. DI is implemented by passing parameters to the constructor.

Ascept oriented programming in spring

one of the key components of Spring Framework is the Aspect oriented programming (AOP)framework.

It redefines the programming model of OOP. Aspect Oriented Programming entails breaking down program logic into distinct

parts called so-called concerns. The functions that span multiple points of an application are called cross-cutting concerns and these cross-cutting concerns are conceptually separate from the application's business logic.

There are various common good examples of aspects like logging, auditing, declarative transactions, security, and caching etc.

The key unit of modularity in OOP is the class, whereas in AOP the unit of modularity is the aspect.

Spring AOP module provides interceptors to intercept an application, for example, when a method is executed, you can add extra functionality before or after the method execution.

The DI helps to decouple the application objects from each other. AOP provide declarative enterprise services, especially as a replacement for EJB

declarative services like declarative transaction management. It allow users to implement custom aspects, complementing their use of OOP with

AOP.

AOP Terminologies

Before we start working with AOP, let us become familiar with the AOP concepts and terminology. These terms are not specific to Spring, rather they are related to AOP.

Terms Description A module which has a set of APIs providing cross-cutting

requirements. For example, a logging module would be called AOP aspect for logging. An application can have any number of aspects depending on the requirement.

Aspect

This represents a point in your application where you can plug-in AOP aspect. You can also say, it is the actual place in the application where an action will be taken using Spring AOP framework.

Join point This is the actual action to be taken either before or after the

method execution. This is actual piece of code that is invoked during program execution by Spring AOP framework. Advice

Page 117: The J2EE Platform,JDBC(Java Database Connectivity)mmghodasaracollege.in/admin-cp/images/download_doc/down_doc/… · Other JDBC API The J2EE Platform,JDBC(Java Database Connectivity)

J2EE 5. Spring,Strut B.C.A. Sem-5

Page 8 of 12

This is a set of one or more joinpoints where an advice should be executed. You can specify pointcuts using expressions or patterns as we will see in our AOP examples. Pointcut

An introduction allows you to add new methods or attributes to

existing classes. Introduction Understanding Struts Framework Struts2 is popular and mature web application framework based on the MVC design

pattern. Struts2 is not just the next version of Struts 1, but it is a complete rewrite of the Struts architecture.

The strut is introduced in may 2000 which provide a standard MVC framework. In simple MVC framework we know that we can create nice separation between the code

that creates the data with the use of java code that represents the data with the use of HTML and JSP.

It is a free open source framework, used to create java web application. It is differ from because it provides dynamic response. Web application based on JSP includes database code, page design, and control flow

together. these type of larger applications sometimes become difficult to maintain. We can separate these code by using MVC architecture. The strut framework is designed to help developers create web applications that utilize

MVC architecture. The WebWork framework started off with Struts framework as the basis and its goal was

to offer an enhanced and improved framework built on Struts to make web development easier for the developers.

The framework provides three key component: 1) Tag library

That helps developer to create interactive form-based application with sesrver pages.

2) Request handler Provided by the application developer that is mapped to a standard URL.

3) Response handler Transfers control to another resource which complete the response.

Comparison with MVC using RequestDispatcher and the EL The following comparison shows the advantages and disadvantages using strut as

compared to RequestDispatcher and the EL Advantages

1) Centralized file based configuration by this feature we can achieve loose coupling.that means many changes can be

done without modifying or recompiling source code and most of the changes made by editing single file.

By this feature web developer focus on their specific task without knowing about the overall system.

2) Form beans in compare to JSP strut extends capabilities of adding java beans component

which servers to really simplify the processing of request parameter.

Page 118: The J2EE Platform,JDBC(Java Database Connectivity)mmghodasaracollege.in/admin-cp/images/download_doc/down_doc/… · Other JDBC API The J2EE Platform,JDBC(Java Database Connectivity)

J2EE 5. Spring,Strut B.C.A. Sem-5

Page 9 of 12

3) Bean tags

Strut provides a set of custom JSP tags that allows you to easily output the properties of JavaBean component.

4) HTML tags Strut provide a set of custom JSP tag to create HTML forms that are related to

javabean components. It allows us to get initial form-field values from java objects and redisplay

forms with some or all previously entered values intact. 5) Form field validation

It has built in capability for checking that form values are in the required format which is known as form field validation.

If values are missing or in improper format, the form can be automatically reappeared with error message.

The validation can be performed either on the server or both server and client. 6) Consistent approach

Strut push you for regular use of MVC throughout your application. Disadvantages

1) Bigger learning curve To use MVC with struts one has to be comfortable with the standard JSP and

servlet API and a large and complicated framework that is almost equal in size to the core system.

It is specially significant with smaller projects, near-term deadlines and less experience developers mush time can be spent learning struts for building an actual system.

2) Worse documentation With compared to the servlet and JSP API, strut has fewer online resources,

and many first time users find the online apache documentation confusing and poorly organized.

3) Less transparent Strut applications are harder to understand.

Struts Flow of Control

1) the user requests a form the input form is built with the strut html tags. These tags associate a bean with the form so that you can pre populate the

form with values from your application, so that you can redisplay incorrectly filled out forms.

2) the form is submitted to a url of the form blah.do the form contains an ACTION ending in blah.do. the strut system receives the request, where an action mapping in struts-

config.xml associates the address with an action object. 3) the execute method of the action object is invoked

one of the arguments to execute is a form bean that is automatically created and whose properties are automatically populated with the incoming form

Page 119: The J2EE Platform,JDBC(Java Database Connectivity)mmghodasaracollege.in/admin-cp/images/download_doc/down_doc/… · Other JDBC API The J2EE Platform,JDBC(Java Database Connectivity)

J2EE 5. Spring,Strut B.C.A. Sem-5

Page 10 of 12

data. Once it examines the user input data in the bean, the execute method invokes

business logic and data access logic, placing the result in normal beans stored in the request.

4) strut forward the requests to the appropriate JSP page strut normally invokes the result page with RequestDispatcher. Forward although request.sendRedirect is occasionally used.In most real

applications, the results page uses bean:write.

Processing Request with Action Objects There are six basic steps in processing requests with action objects. 1) Modify struts-config.xml

Use WEB-INF/struts-config.xml to: i. Designate action classes to handle requests for xyz.do

ii. Specify the urls that apply in various situation iii. Declare any form beans that are being used.

Be sure to restart the server after modifying struts-config.xml; the file is read only when the web application is first loaded.

2) Define a form bean This bean is a class the extends ActionForm and will represent the data

submitted by the user.It is automatically populated when the input form is submitted.

3) Create results beans In the MVC architecture, the business logic and data access code create the

results and the JSP pages present them. To transfer the results from one layer to the other, they are stored in beans.

4) Create an Action object to handle requests The struts-config.xml file designates the action object that handles requests for

the various URLs. The action objects themselves need to do the real work; invoke the appropriate

business and data access logic store the results in the beans. 5) Create form that invokes xyz.do

Page 120: The J2EE Platform,JDBC(Java Database Connectivity)mmghodasaracollege.in/admin-cp/images/download_doc/down_doc/… · Other JDBC API The J2EE Platform,JDBC(Java Database Connectivity)

J2EE 5. Spring,Strut B.C.A. Sem-5

Page 11 of 12

You need to create an input form whose ACTION corresponds to one of the *.do addresses listed in struts-config.xml.

At a minimum, the input form should look like this: <Form action=”…/xyz.do”…>…</form>

6) Display result in JSP Strut is built around the MVC architecture, these JSP pages should avoid JSP

scripting elements whenever possible.

Handling Request Parameters with FormBeans We call request.getParameter to obtain the form data. We used this manual approach because we wanted to concentrate only on the action

mappings, forward entries and structure of the action class. In a real application this request.getparameter give the error. Strut has a convenient tool for this process is form beans. When a user submit a request, the system institate a bean. Understanding Form beans Form beans are playing a important role in the strut framework.following are the steps for define Form Beans in strut-config.xml 1)Declare the form beans To design form bean, to handle input data, add a form-bean entry to the form beans element in struts-config.xml.position the form-beans elements before the action-mapping elements.when you define a bean, you should also identify the fully qualified class name. <form-beans> <form-bean name=”exampleFormBean” Type=”coreservlets.exampleFormBean”/> </form-beans> 2)Update the action declaration After using form-bean to give your bean a name, you need to change your action element.Normally you need to add name and scope attributes to the action element. <action path=”/register” Type=”coreservlets.ActionWithBean” Name=”exampleFormBean” Scope=”request”> Writing an Action Form with form beans 1)Extend the ActionForm class All form beans must extend the ActionForm class. 2)Zero argument constructor When you instantiating the bean, the system always calls the default constructor. 3)Set bean properties that corresponds to the request parameter names

The bean must have setXXX method corresponding to each incoming request parameter named xxx.

4)Get bean properties for each property that you want to output in the JSP page. The bean must have a getXXX method related to each bean property that you want to display in JSP.after the action process request it routes the request to the output JSP page. PREPOPULATING AND REDISPLAYING INPUT FORMS:

In this section, let’s see how to associate form beans with the input page using the Structs html: tags.

Page 121: The J2EE Platform,JDBC(Java Database Connectivity)mmghodasaracollege.in/admin-cp/images/download_doc/down_doc/… · Other JDBC API The J2EE Platform,JDBC(Java Database Connectivity)

J2EE 5. Spring,Strut B.C.A. Sem-5

Page 12 of 12

Associating form beans with input forms having three advantages. 1) Request parameter names and the bean property names stay in sync:

If you write the form by your own selves, you might change the parameter names but forget to change the bean.

When using the html:tags, you explicitly refer to the bean property names when defining text fields or other input elements ,so if you use the wrong name, you get an immediate error message.

2) Text fields with initial values: By associating a bean with the input page, the initial text field values can

from your application. So, for example, if the available things change in your database, you

don’t have to separately remember to change hard-coded HTML on the page.

3) Redisplay values in the text fields: If you send the user back to the original form, the originally entered

values are automatically filled in. That’s because the form is already associated with a bean, but now the

bean is the one that was just created from the request.

Using Properties Files: Properties files are just text files that contain name, value pairs, and key message pairs. By using bean: message from the Structs tag library, you can easily retrieve messages

from your properties file and display them on your JSP pages. Advantage of Properties Files:

1) Centralized updates: If the application uses a message in several JSP pages, with properties

files you can easily update a message with a single change. This capability is consistent with the Struts of making as many changes

as possible in configuration files, not in Java or JSP code. In short if we do the change at one place it reflects to other.

2)Internationalization If you use messages in your JSP pages, you can easily internationalize

your application by having multiple properties file.simply create a file for each language that requires support.For instance to support English,Japanese etc.