Uploaded by Nethan Paul

Advanced Java Notes

advertisement
Advanced Java
UNIT 1:
1.1 Introducing JDBC:
Java Database Connectivity (JDBC) is an Application Programming Interface (API), from Sun
microsystem that is used by the Java application to communicate with the relational databases from
different vendors. JDBC and database drivers work in tandem to access spreadsheets and databases.
Java Database Connectivity (JDBC) is an application programming interface (API) for the programming
language Java, which defines how a client may access a database. It is a Java-based data access technology
used for Java database connectivity. It is part of the Java Standard Edition platform, from Oracle
Corporation. It provides methods to query and update data in a database, and is oriented toward relational
databases. A JDBC-to-ODBC bridge enables connections to any ODBC-accessible data source in the Java
virtual machine (JVM) host environment.
1.2 Components of JDBC:
JDBC has four major components that are used for the interaction with the database.
1. JDBC API
2. JDBC Test Suite
3. JDBC Driver Manger
4. JDBC ODBC Bridge Driver
1) JDBC API: JDBC API provides various interfaces and methods to establish easy connection with different
databases.
1. javax.sql.*;
2. java.sql.*;
2) JDBC Test suite: JDBC Test suite facilitates the programmer to test the various operations such as
deletion, updation, insertion that are being executed by the JDBC Drivers.
3) JDBC Driver manager: JDBC Driver manager loads the database-specific driver into an application in
order to establish the connection with the database. The JDBC Driver manager is also used to make the
database-specific call to the database in order to do the processing of a user request.
4) JDBC-ODBC Bridge Drivers: JDBC-ODBC Bridge Drivers are used to connect the database drivers to the
database. The bridge does the translation of the JDBC method calls into the ODBC method call. It makes
the usage of the sun.jdbc.odbc package that encompasses the native library in order to access the ODBC
(Open Database Connectivity) characteristics.
Note: Since Java 8, the JDBC-ODBC drivers have been removed. Oracle suggests using drivers provided by
the vendor of the database.
1.3 Features of JDBC:
Following are the new features of JDBC:
•
Makes JDBC calls: While using JDBC Java applications can make JDBC calls these calls submit
SQL statements to the driver which in turn accesses the data from the database.
•
Portability: JDBC provides wide level portability.
•
Using JDBC you can request any type of queries from the database.
•
You can use JDBC with different Java applications such like Java Applets, Java Servlets, Java Server
Pages (JSPs). Enterprise JavaBeans (EJBs). To communicate with database.
•
JDBC provides support for advanced datatypes such as BLOB, CLOB etc.
•
Using JDBC you can set save points for database and layer you can rollback to desired save point.
•
Using JDBC you can send multiple updates to database and this is known as batch updating.
The important features of JDBC API 4.0 are given below:
o Automatic Loading of Driver class You don't need to write Class.forName() now because it
is loaded bydefault since jdbc4.
o
Subclasses of SQLException Jdbc 4 provides new subclasses of SQLException class for better
readability and handling.
o
New methods There are many new methods introduced in Connection, PreparedStatement,
CallableStatement, ResultSet etc.
o
Improved DataSource Now data source implementation is improved.
o
Event Handling support in Statement for Connection Pooling Now Connection Pooling
can listen statement error and statement closing events.
1.4 JDBC Architecture:
Architecture of JDBC
1) Application: It is the Java or an applet that communicates with the data source.
2) The JDBC API: It allows the Java programs to perform the execution of the SQL
statements and then get the results.
A few of the crucial interfaces and classes defined in the JDBC API are the following:
o
Drivers
o
DriverManager
o
Statement
o
Connection
o
CallableStatement
o
PreparedStatement
o
ResultSet
o
SQL data
3) DriverManager: DriverManager plays a crucial role in the architecture of JDBC.
It uses database-specific drivers to connect the enterprise applications to various databases.
4) JDBC drivers: To interact with a data source with the help of the JDBC, one needs a JDBC driver which
conveniently interacts with the respective data source.
Different Types of Architecture of JDBC
The architecture of the JDBC consists of two and three tiers model in order to access the given database.
Two-tier model: In this model, the application interacts directly with the source of data. The JDBC driver
establishes the interaction between the data source and the application. When a query is sent by the user to the
data source, the reply of those sent queries is sent directly to the user.
The source of data can be located on a different machine, and that machine is connected to the user machine
following a client-server paradigm, where the machine which is sending the query is the client machine, and
the machine that is sending the result of those queries is acting as the server.
Three-tier model: In this model, the queries of the user are being sent to the middle-tier services, from where
the commands are sent again to the source of data. The answers to those queries are reverted to the middle
tier, and from there, it is again sent to the user.
1.5 Types of Divers:
JDBC Driver is a software component that enables java application to interact with the database. There are 4
types of JDBC drivers:
1. JDBC-ODBC bridge driver
2. Native-API driver (partially java driver)
3. Network Protocol driver (fully java driver)
4. Thin driver (fully java driver)
1) JDBC-ODBC bridge driver
The JDBC-ODBC bridge driver uses ODBC driver to connect to the database. The JDBC-ODBC bridge driver
converts JDBC method calls into the ODBC function calls. This is now discouraged because of thin driver.
In Java 8, the JDBC-ODBC Bridge has been removed.
Oracle does not support the JDBC-ODBC Bridge from Java 8. Oracle recommends that you use JDBC
drivers provided by the vendor of your database instead of the JDBC-ODBC Bridge.
Advantages:
o
easy to use.
o
can be easily connected to any database.
Disadvantages:
o
Performance degraded because JDBC method call is converted into the ODBC function calls.
o
The ODBC driver needs to be installed on the client machine.
2) Native-API driver
The Native API driver uses the client-side libraries of the database. The driver converts JDBC method calls into
native calls of the database API. It is not written entirely in java.
Advantage:
o
performance upgraded than JDBC-ODBC bridge driver.
Disadvantage:
o
The Native driver needs to be installed on the each client machine.
o
The Vendor client library needs to be installed on client machine.
3) Network Protocol driver
The Network Protocol driver uses middleware (application server) that converts JDBC calls directly or
indirectly into the vendor-specific database protocol. It is fully written in java.
Advantage:
o
No client side library is required because of application server that can perform many tasks like
auditing, load balancing, logging etc.
Disadvantages:
o
Network support is required on client machine.
o
Requires database-specific coding to be done in the middle tier.
o
Maintenance of Network Protocol driver becomes costly because it requires database-specific coding
to be done in the middle tier.
4) Thin driver
The thin driver converts JDBC calls directly into the vendor-specific database protocol. That is why it is known as
thin driver. It is fully written in Java language.
Advantage:
o
Better performance than all other drivers.
o
No software is required at client side or server side.
Disadvantage:
o
Drivers depend on the Database.
1.6 Advantages and disadvantages of Drivers:
The answer is similar to Q 1.5
1.7 Use of Drivers:
Can be the same answer as Q 1.5
OR:
Structure of JDBC
JDBC Drivers
JDBC drivers are client-side adapters (installed on the client machine, not on the server) that convert
requests from Java programs to a protocol that the DBMS can understand. There are 4 types of JDBC
drivers:
1. Type-1 driver or JDBC-ODBC bridge driver
2. Type-2 driver or Native-API driver
3. Type-3 driver or Network Protocol driver
4. Type-4 driver or Thin driver
Type-1 driver
Type-1 driver or JDBC-ODBC bridge driver uses ODBC driver to connect to the database. The JDBCODBC bridge driver converts JDBC method calls into the ODBC function calls. Type-1 driver is also called
Universal driver because it can be used to connect to any of the databases.
•
As a common driver is used in order to interact with different databases, the data transferred through
this driver is not so secured.
•
The ODBC bridge driver is needed to be installed in individual client machines.
•
Type-1 driver isn’t written in java, that’s why it isn’t a portable driver.
•
This driver software is built-in with JDK so no need to install separately.
•
It is a database independent driver.
Type-2 driver
The Native API driver uses the client -side libraries of the database. This driver converts JDBC method
calls into native calls of the database API. In order to interact with different database, this driver needs their
local API, that’s why data transfer is much more secure as compared to type-1 driver.
•
Driver needs to be installed separately in individual client machines
•
The Vendor client library needs to be installed on client machine.
•
Type-2 driver isn’t written in java, that’s why it isn’t a portable driver
•
It is a database dependent driver.
Type-3 driver
The Network Protocol driver uses middleware (application server) that converts JDBC calls directly or
indirectly into the vendor-specific database protocol. Here all the database connectivity drivers are present in
a single server, hence no need of individual client-side installation.
•
Type-3 drivers are fully written in Java, hence they are portable drivers.
•
No client side library is required because of application server that can perform many tasks like
auditing, load balancing, logging etc.
•
Network support is required on client machine.
•
Maintenance of Network Protocol driver becomes costly because it requires database-specific coding
to be done in the middle tier.
•
Switch facility to switch over from one database to another database.
Type-4 driver
Type-4 driver is also called native protocol driver. This driver interact directly with database. It does not
require any native database library, that is why it is also known as Thin Driver.
•
Does not require any native library and Middleware server, so no client-side or server-side
installation.
•
It is fully written in Java language, hence they are portable drivers.
1.8 JDBC Statementand Methods: Statement,
PreparedStatement, CallableStatement.
The statement interface is used to create SQL basic statements in Java it provides methods to execute
queries with the database. There are three types of statements in JDBC namely, Statement, Prepared Statement,
Callable statement.
1.Statement
The Statement interface represents the static SQL statement. It helps you to create a general purpose SQL
statements using Java.
Creating a statement
You can create an object of this interface using the createStatement() method of the Connection interface.
Create a statement by invoking the createStatement() method as shown below.
Statement stmt = null;
try {
stmt = conn.createStatement( );
...
}
catch (SQLException e) {
...
}
finally {
...
}
Executing the Statement object
Once you have created the statement object you can execute it using one of the execute methods namely,
execute(), executeUpdate() and, executeQuery().
•
execute(): This method is used to execute SQL DDL statements, it returns a boolean value specifying
whether the ResultSet object can be retrieved.
•
executeUpdate(): This method is used to execute statements such as insert, update, delete. It returns
an integer value representing the number of rows affected.
•
executeQuery(): This method is used to execute statements that returns tabular data (example
SELECT statement). It returns an object of the class ResultSet.
2.Prepared Statement
The PreparedStatement interface extends the Statement interface. It represents a precompiled SQL statement
which can be executed multiple times. This accepts parameterized SQL quires and you can pass 0 or more
parameters to this query.
Initially, this statement uses place holders “?” instead of parameters, later on, you can pass arguments to these
dynamically using the setXXX() methods of the PreparedStatement interface.
Creating a PreparedStatement
You can create an object of the PreparedStatement (interface) using the prepareStatement() method of the
Connection interface. This method accepts a query (parameterized) and returns a PreparedStatement object.
When you invoke this method the Connection object sends the given query to the database to compile and
save it. If the query got compiled successfully then only it returns the object.
To compile a query, the database doesn’t require any values so, you can use (zero or
more) placeholders (Question marks “?”) in the place of values in the query.
For example, if you have a table named Employee in the database created using the following query:
CREATE TABLE Employee(Name VARCHAR(255), Salary INT NOT NULL, Location
VARCHAR(255));
Then, you can use a PreparedStatement to insert values into it as shown below.
//Creating a Prepared Statement
String query="INSERT INTO Employee(Name, Salary, Location)VALUES(?, ?, ?)";
Statement pstmt = con.prepareStatement(query);
Setting values to the place holders
The PreparedStatement interface provides several setter methods such as setInt(), setFloat(), setArray(),
setDate(), setDouble() etc.. to set values to the place holders of the prepared statement.
These methods accepts two arguments one is an integer value representing the placement index of the place
holder and the other is an int or, String or, float etc… representing the value you need to insert at that particular
position.
Once you have created a prepared statement object (with place holders) you can set values to the place holders
of the prepared statement using the setter methods as shown below:
pstmt.setString(1, "Amit");
pstmt.setInt(2, 3000);
pstmt.setString(3, "Hyderabad");
Executing the Prepared Statement
Once you have created the PreparedStatement object you can execute it using one of the execute() methods
of the PreparedStatement interface namely, execute(), executeUpdate() and, executeQuery().
•
execute(): This method executes normal static SQL statements in the current prepared statement object
and returns a boolean value.
•
executeQuery(): This method executes the current prepared statement and returns a ResultSet object.
•
executeUpdate(): This method executes SQL DML statements such as insert update or delete in the
current Prepared statement. It returns an integer value representing the number of rows affected.
3.CallableStatement
The CallableStatement interface provides methods to execute stored procedures. Since the JDBC API
provides a stored procedure SQL escape syntax, you can call stored procedures of all RDBMS in a single
standard way.
Creating a CallableStatement
You can create an object of the CallableStatement (interface) using the prepareCall() method of
the Connection interface.
This method accepts a string variable representing a query to call the stored procedure and returns
a CallableStatement object.
A CallableStatement can have input parameters or, output parameters or, both. To pass input parameters to
the procedure call you can use place holder and set values to these using the setter methods (setInt(),
setString(), setFloat()) provided by the CallableStatement interface.
Suppose, you have a procedure name myProcedure in the database you can prepare a callable statement as:
//Preparing a CallableStatement
CallableStatement cstmt = con.prepareCall("{call myProcedure(?, ?, ?)}");
Setting values to the input parameters
You can set values to the input parameters of the procedure call using the setter methods.
These accept two arguments one is an integer value representing the placement index of the input parameter
and the other is an int or, String or, float etc… representing the value you need to pass an input parameter to
the procedure.
Note: Instead of index you can also pass the name of the parameter in String format.
cstmt.setString(1, "Raghav");
cstmt.setInt(2, 3000);
cstmt.setString(3, "Hyderabad");
Executing the Callable Statement
Once you have created the CallableStatement object you can execute it using one of the execute() method.
cstmt.execute();
1.9 Working with Resultset interface:
The java.sql.ResultSet interface represents the result set of a database query.
A ResultSet object maintains a cursor that points to the current row in the result set. The term "result set"
refers to the row and column data contained in a ResultSet object.
The methods of the ResultSet interface can be broken down into three categories −
•
Navigational methods − Used to move the cursor around.
•
Get methods − Used to view the data in the columns of the current row being pointed by the cursor.
•
Update methods − Used to update the data in the columns of the current row. The updates can then
be updated in the underlying database as well.
The cursor is movable based on the properties of the ResultSet. These properties are designated when the
corresponding Statement that generates the ResultSet is created.
JDBC provides the following connection methods to create statements with desired ResultSet −
•
createStatement(int RSType, int RSConcurrency);
•
prepareStatement(String SQL, int RSType, int RSConcurrency);
•
prepareCall(String sql, int RSType, int RSConcurrency);
The first argument indicates the type of a ResultSet object and the second argument is one of two ResultSet
constants for specifying whether a result set is read-only or updatable.
Type of ResultSet
The possible RSType are given below. If you do not specify any ResultSet type, you will automatically get
one that is TYPE_FORWARD_ONLY.
Type
Description
ResultSet.TYPE_FORWARD_ONLY
The cursor can only move forward in the result set.
ResultSet.TYPE_SCROLL_INSENSITIVE
The cursor can scroll forward and backward, and the result set
is not sensitive to changes made by others to the database that
occur after the result set was created.
ResultSet.TYPE_SCROLL_SENSITIVE.
The cursor can scroll forward and backward, and the result set
is sensitive to changes made by others to the database that
occur after the result set was created.
Concurrency of ResultSet
The possible RSConcurrency are given below. If you do not specify any Concurrency type, you will
automatically get one that is CONCUR_READ_ONLY.
Concurrency
Description
ResultSet.CONCUR_READ_ONLY
Creates a read-only result set. This is the default
ResultSet.CONCUR_UPDATABLE
Creates an updateable result set.
All our examples written so far can be written as follows, which initializes a Statement object to create a
forward-only, read only ResultSet object −
try {
Statement stmt = conn.createStatement(ResultSet.TYPE_FORWARD_ONLY,
ResultSet.CONCUR_READ_ONLY);
}
catch(Exception ex) {
....
}
finally {
....
}
Navigating a Result Set
There are several methods in the ResultSet interface that involve moving the cursor, including −
S.N.
1
Methods & Description
public void beforeFirst() throws SQLException
Moves the cursor just before the first row.
2
public void afterLast() throws SQLException
Moves the cursor just after the last row.
3
public boolean first() throws SQLException
Moves the cursor to the first row.
4
public void last() throws SQLException
Moves the cursor to the last row.
5
public boolean absolute(int row) throws SQLException
Moves the cursor to the specified row.
6
public boolean relative(int row) throws SQLException
Moves the cursor the given number of rows forward or backward, from where it is currently pointing.
7
public boolean previous() throws SQLException
Moves the cursor to the previous row. This method returns false if the previous row is off the result
set.
8
public boolean next() throws SQLException
Moves the cursor to the next row. This method returns false if there are no more rows in the result set.
9
public int getRow() throws SQLException
Returns the row number that the cursor is pointing to.
10
public void moveToInsertRow() throws SQLException
Moves the cursor to a special row in the result set that can be used to insert a new row into the database.
The current cursor location is remembered.
11
public void moveToCurrentRow() throws SQLException
Moves the cursor back to the current row if the cursor is currently at the insert row; otherwise, this
method does nothing
Viewing a Result Set
The ResultSet interface contains dozens of methods for getting the data of the current row.
There is a get method for each of the possible data types, and each get method has two versions −
•
One that takes in a column name.
•
One that takes in a column index.
For example, if the column you are interested in viewing contains an int, you need to use one of the getInt()
methods of ResultSet −
S.N.
1
Methods & Description
public int getInt(String columnName) throws SQLException
Returns the int in the current row in the column named columnName.
2
public int getInt(int columnIndex) throws SQLException
Returns the int in the current row in the specified column index. The column index starts at 1, meaning
the first column of a row is 1, the second column of a row is 2, and so on.
Similarly, there are get methods in the ResultSet interface for each of the eight Java primitive types, as well
as common types such as java.lang.String, java.lang.Object, and java.net.URL.
There are also methods for getting SQL data types java.sql.Date, java.sql.Time, java.sql.TimeStamp,
java.sql.Clob, and java.sql.Blob. Check the documentation for more information about using these SQL data
types.
Updating a Result Set
The ResultSet interface contains a collection of update methods for updating the data of a result set.
As with the get methods, there are two update methods for each data type −
•
One that takes in a column name.
•
One that takes in a column index.
For example, to update a String column of the current row of a result set, you would use one of the following
updateString() methods −
S.N.
1
Methods & Description
public void updateString(int columnIndex, String s) throws SQLException
Changes the String in the specified column to the value of s.
2
public void updateString(String columnName, String s) throws SQLException
Similar to the previous method, except that the column is specified by its name instead of its index.
There are update methods for the eight primitive data types, as well as String, Object, URL, and the SQL
data types in the java.sql package.
Updating a row in the result set changes the columns of the current row in the ResultSet object, but not in the
underlying database. To update your changes to the row in the database, you need to invoke one of the
following methods.
S.N.
1
Methods & Description
public void updateRow()
Updates the current row by updating the corresponding row in the database.
2
public void deleteRow()
Deletes the current row from the database
3
public void refreshRow()
Refreshes the data in the result set to reflect any recent changes in the database.
4
public void cancelRowUpdates()
Cancels any updates made on the current row.
5
public void insertRow()
Inserts a row into the database. This method can only be invoked when the cursor is pointing to the
insert row.
1.10 Working with Resultset with metadata
The ResultSetMetaData provides information about the obtained ResultSet object like, the number of
columns, names of the columns, datatypes of the columns, name of the table etc…
Following are some methods of ResultSetMetaData class.
Method
Description
getColumnCount()
Retrieves the number of columns in the current ResultSet object.
getColumnLabel()
Retrieves the suggested name of the column for use.
getColumnName()
Retrieves the name of the column.
getTableName()
Retrieves the name of the table.
Example
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.Statement;
public class ResultSetMetadataExample {
public static void main(String args[]) throws Exception {
//Registering the Driver
DriverManager.registerDriver(new com.mysql.jdbc.Driver());
//Getting the connection
String mysqlUrl = "jdbc:mysql://localhost/TestDB";
Connection con = DriverManager.getConnection(mysqlUrl, "root", "password");
System.out.println("Connection established......");
//Creating a Statement object
Statement stmt = con.createStatement();
//Retrieving the data
ResultSet rs = stmt.executeQuery("select * from Dataset");
ResultSetMetaData rsMetaData = rs.getMetaData();
//Number of columns
System.out.println("Number of columns: "+rsMetaData.getColumnCount());
//Column label
System.out.println("Column Label: "+rsMetaData.getColumnLabel(1));
//Column name
System.out.println("Column Name: "+rsMetaData.getColumnName(1));
//Number of columns
System.out.println("Table Name: "+rsMetaData.getTableName(1));
}
}
Output
Connection established......
Number of columns: 2
Column Label: mobile_brand
Column Name: mobile_brand
Table Name: dataset
UNIT 2:
2.1 Introducing CGI
The Common Gateway Interface (CGI) provides the middleware between WWW servers and external
databases and information sources. The World Wide Web Consortium (W3C) defined the Common
Gateway Interface (CGI) and also defined how a program interacts with a HyperText Transfer Protocol
(HTTP) server. The Web server typically passes the form information to a small application program that
processes the data and may send back a confirmation message. This process or convention for passing data
back and forth between the server and the application is called the common gateway interface (CGI). The
following image describes how a web server acts as an intermediate between the CGI program and the client
browser.
Disadvantages of CGI
There are many problems in CGI technology:
1. If the number of clients increases, it takes more time for sending the response.
2. For each request, it starts a process, and the web server is limited to start processes.
3. It uses platform dependent language e.g. C, C++, perl.
2.2 Introducing Servlet
A servlet is a Java class which is used to extend the capabilities of servers that host
applications accessed by means of a request-response model. Servlets are mainly used to
extend the applications hosted by webs servers, however, they can respond to other types of
requests too. For such applications, HTTP-specific servlet classes are defined by Java Servlet
technology. All the programs of Servlets are written in JAVA and they get to run on JAVA
Virtual Machine. The following image describes how a request from clients is served with
the help of threads:
Servlet can be described in many ways, depending on the context.
o
Servlet is a technology which is used to create a web application.
o
Servlet is an API that provides many interfaces and classes including documentation.
o
Servlet is an interface that must be implemented for creating any Servlet.
o
Servlet is a class that extends the capabilities of the servers and responds to the
incoming requests. It can respond to any requests.
o
Servlet is a web component that is deployed on the server to create a dynamic web
page.
The following table explains the difference between the servlet and CGI:
Basis
Servlet
CGI
Approach
It is thread based i.e. for every
new request new thread is
created.
It is process based i.e. for every new
request new process is created.
Language
Used
The codes are written in JAVA
programming language.
The codes are written any
programming language.
Object
Oriented
Since codes are written in Java,
it is object oriented and the
user will get the benefits of
OOPs
Since codes are written in any
language, all the languages are not
object oriented. So, the user will not
get the benefits of OOPs
Portability
It is portable.
It is not portable.
Persistence
It remains in the memory until
it is not explicitly destroyed.
It is removed from the memory after
the completion of request.
Server
Independent
It can use any of the webserver.
It can use the web-server that supports
it.
Data Sharing
Data sharing is possible.
Data sharing is not possible.
Link
It links directly to the server.
It does not links directly to the server.
HTTP server
It can read and set HTTP
servers.
It can neither read nor set HTTP
servers.
Cost
Construction and destruction of
new thread is not costly.
Construction and destruction of new
process is costly.
2.3 Advantages of Servlet over CGI
Advantages of Servlet
There are many advantages of Servlet over CGI. The web container creates threads for handling the multiple
requests to the Servlet. Threads have many benefits over the Processes such as they share a common
memory area, lightweight, cost of communication between the threads are low. The advantages of Servlet
are as follows:
1. Better performance: because it creates a thread for each request, not process.
2. Portability: because it uses Java language.
3. Robust: JVM manages Servlets, so we don't need to worry about the memory leak, garbage
collection, etc.
4. Secure: because it uses java language.
2.4 Features of Servlet
Main Features of Servlet are given blow;
Advantage of Servlet
1.Better performance: Because it creates a thread for each request not process (like CGI).
2.Portability: Because it uses java language and java is robust language.
3.Robust: Servlet are managed by JVM so no need to worry about memory leak, garbage collection etc.
4.Secure: Because it uses java language and java is a secure language. Java have automatic garbage
collection mechanism and a lack of pointers protect the servlets from memory management problems.
5.Inexpensive There are number of free web servers available for personal use or for commercial purpose.
Mostly web server are very costly. So by using free web server you can reduce project development price.
6.Extensibility The servlet API is designed in such a way that it can be easily extensible. Servlets being
written in Java, can be extended and polymorphed into the objects that suits the user requirement.
7.Efficiency Servlets invocation is highly efficient as compared to any CGI programs.
8.Integration Servlets are tightly integrated with the server. Servlet can use the server to translate the file
paths, check authorization, perform logging and MIME type mapping etc.
9.Persistent: Servlets remain in memory until explicitly destroyed. This helps in serving several incoming
requests. Servlets establishes connection only once with the database and can handle several requests on
the same database.
10.Server Independent: Servlets are compatible with any web server available today.
11.Protocol Independent: Servlets can be created to support any protocols like FTP commands, Telnet
sessions, NNTP newsgroups, etc. It also provides extended support for the functionality of HTTP protocol.
12.Fast: Since servlets are compiled into bytecodes, they can execute more quickly as compared to other
scripting languages. The bytecode compilation feature helps servlets to give much better performance. In
addition, it also provides advantage of strong error and type checking.
2.5 Introducing Servlet API :
Servlets are the Java programs that run on the Java-enabled web server or application server. They are used
to handle the request obtained from the webserver, process the request, produce the response, then send a
response back to the webserver. In Java, to create web applications we use Servlets. To create Java Servlets,
we need to use Servlet API which contains all the necessary interfaces and classes. Servlet API has 2
packages namely,
1) javax.servlet:
The javax.servlet package contains many interfaces and classes that are used by the servlet or web
container. These are not specific to any protocol.
•
This package provides the number of interfaces and classes to support Generic servlet which is
protocol independent.
•
These interfaces and classes describe and define the contracts between a servlet class and the runtime
environment provided by a servlet container
2) javax.servlet.http:
The javax.servlet.http package contains interfaces and classes that are responsible for http requests only.
•
This package provides the number of interfaces and classes to support HTTP servlet which is HTTP
protocol dependent.
•
These interfaces and classes describe and define the contracts between a servlet class running under
HTTP protocol and the runtime environment provided by a servlet container.
2.6 Javax.servlet package
2.7 Javax.servlet.http package
2.8 Servlet life
The web container maintains the life cycle of a servlet instance. Let's see the life cycle of the servlet:
1. Servlet class is loaded.
2. Servlet instance is created.
3. init method is invoked.
4. service method is invoked.
5. destroy method is invoked.
As displayed in the above diagram, there are three states of a servlet: new, ready and end. The servlet is in
new state if servlet instance is created. After invoking the init() method, Servlet comes in the ready state. In
the ready state, servlet performs all the tasks. When the web container invokes the destroy() method, it shifts
to the end state.
1) Servlet class is loaded
The classloader is responsible to load the servlet class. The servlet class is loaded when the first request for
the servlet is received by the web container.
2) Servlet instance is created
The web container creates the instance of a servlet after loading the servlet class. The servlet instance is created
only once in the servlet life cycle.
3) init method is invoked
The web container calls the init method only once after creating the servlet instance. The init method is used to initializ
the servlet. It is the life cycle method of the javax.servlet.Servlet interface. Syntax of the init method is given below:
1. public void init(ServletConfig config) throws ServletException
4) service method is invoked
The web container calls the service method each time when request for the servlet is received. If servlet is not
initialized, it follows the first three steps as described above then calls the service method. If servlet is
initialized, it calls the service method. Notice that servlet is initialized only once. The syntax of the service
method of the Servlet interface is given below:
1. public void service(ServletRequest request, ServletResponse response)
2.
throws ServletException, IOException
5) destroy method is invoked
The web container calls the destroy method before removing the servlet instance from the service. It gives the
servlet an opportunity to clean up any resource for example memory, thread etc. The syntax of the destroy
method of the Servlet interface is given below:
1. public void destroy()
2.9 Working with GenericServlet and HttpServlet :
1)GenericServlet
implements the Servlet interface and provides an implementation for all its method except the service()
method hence it is abstract. GenericServlet class defines a protocol-independent(HTTP-less) servlet.
However, while building a website or an online application, we may want to have HTTP protocol, in that
case, we must extend HttpServlet instead of GenericServlet. Developing Servlet by extending
GenericServlet is very easy because we have to provide implementation only for the service() method.
GenericServlet class is in javax.servlet package (javax.servlet.GenericServlet).
service() method
The prototype of service( ) method is :
public void service (ServletRequest req, ServletResponse resp) throws ServletException,IOException
This method is automatically called by the server whenever a request for a GenericServlet arrives.
The service() method accepts two parameters:
1. A ServletRequestObject
2. A SerlvetResponseObject
The ServletRequest object allows to read data provided by the client request and the ServletResponse object
is used to send the response to the client.
GenericServlet class:
GenericServlet class implements the Servlet and ServletConfig interfaces. GenericServlet is protocolindependent. It not provides the implementation of service method.
public abstract class GenericServlet implements Servlet, ServletConfig
GenericServlet class is in javax.servlet package (javax.servlet.GenericServlet).
Methods of GenericServlet class:
1. init(ServletConfig config): It is used to initialize the servlet. This method is called only once by the web
container when it loads the servlet.
Syntax:
public void init(ServletConfig config)throws ServletException
2. service(ServletRequest request,ServletResponse response): It is used to respond to a request. It is
called for every new request by web container.
Syntax:
public abstract void service(ServletRequest req,ServletResponse res)
throws ServletException, IOException
3. destroy(): It is used to destroy the servlet. This method is called only once by the web container when all
threads of the servlet have exited or in a timeout case.
Syntax:
public void destroy()
4. getServletConfig(): It returns a servlet config object. This config object is passed in init method. Servlet
config object contains initialization parameters and startup configuration for this servlet.
Syntax:
public ServletConfig getServletConfig()
5. getServletInfo(): It returns a string of information about servlet’s author, version, and copyright etc.
Syntax:
public String getServletInfo()
6. Init(): It is a convenience method which can be overridden so that there is no need to
call super.init(config).
Syntax:
public void init() throws ServletException
7. getServletContext():It returns the ServletContext object in which this servlet is running.
Syntax:
public ServletContext getServletContext()
8. getInitParameter(String name): It returns the value for given parameter name. It returns null if
parameter not exist.
Syntax:
public String getInitParameter(String name)
9. getInitParameterNames(): It returns the names of the servlet’s initialization parameters defined in
web.xml file.
Syntax:
public Enumeration getInitParameterNames()
10. getServletName(): It returns the name of this servlet object.
Syntax:
public String getServletName()
11. log(String msg): This method writes the specified message to the servlet log file.
Syntax:
public void log(String msg)
12. log(String msg,Throwable t): This method writes an explanatory message and a stack trace for a
given exception to the servlet log file.
Syntax:
public void log(String msg,Throwable t)
Servlet “Hello World” example by extending GenericServlet class.
HelloWorld.java
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.GenericServlet;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
/**
* This servlet program is used to print "Hello World" on
* client browser using GenericServlet class.
* @author w3spoint
*/
public class HelloWorld extends GenericServlet {
private static final long serialVersionUID = 1L;
//no-argument constructor.
public HelloWorld() {
}
@Override
public void service(ServletRequest request, ServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<h1>Hello World example using" +
" GenericServlet class.</h1>");
out.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">
<servlet>
<servlet-name>HelloWorld</servlet-name>
<servlet-class>
com.w3spoint.business.HelloWorld
</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>HelloWorld</servlet-name>
<url-pattern>/HelloWorld</url-pattern>
</servlet-mapping>
</web-app>
Output:
_______________________________________________________________________________________
2)HttpServelt is an abstract class, it comes under package ‘javax.servlet.http.HttpServlet‘ .
To create a servlet the class must extend the HttpServlet class and override at least one of its methods
(doGet, doPost, doDelete, doPut). The HttpServlet class extends the GenericServlet class and implements a
Serializable interface.
HttpServlet class:
HttpServlet class extends the GenericServlet. It is protocol-dependent.
public abstract class HttpServlet extends GenericServlet
HttpServlet class is in javax.servlet.http package (javax.servlet.http.HttpServlet).
Methods of HttpServlet class:
1. service(ServletRequest req,ServletResponse res):Dispatches the requests to the
protected service method. It converts the request and response object into http type before
dispatching request.
Syntax:
public void service(ServletRequest req, ServletResponse res)
throws ServletException, IOException
2. service(HttpServletRequest req, HttpServletResponse res):Receives HTTP requests from the
public service method and dispatches the request to the doXXX methods defined in this class.
Syntax:
protected void service(HttpServletRequest req, HttpServletResponse res)
throws ServletException,IOException
3. doGet(HttpServletRequest req, HttpServletResponse res): This method is called by web
container for handling GET requests.
Syntax:
protected void doGet(HttpServletRequest req, HttpServletResponse res)
throws ServletException,IOException
4. doPost(HttpServletRequest req, HttpServletResponse res): This method is called by web
container for handling POST requests.
Syntax:
protected void doPost(HttpServletRequest req, HttpServletResponse res)
throws ServletException,IOException
5. doHead(HttpServletRequest req, HttpServletResponse res): This method is called by web
container for handling HEAD requests.
Syntax:
protected void doHead(HttpServletRequest req, HttpServletResponse res)
throws ServletException,IOException
6. doOptions(HttpServletRequest req, HttpServletResponse res): This method is called by web
container for handling OPTIONS requests.
Syntax:
protected void doOptions(HttpServletRequest req, HttpServletResponse res)
throws ServletException,IOException
7. doPut(HttpServletRequest req, HttpServletResponse res): This method is called by web
container for handling PUT requests.
Syntax:
protected void doPut(HttpServletRequest req, HttpServletResponse res)
throws ServletException,IOException
8. doTrace(HttpServletRequest req, HttpServletResponse res): This method is called by web
container for handling TRACE requests.
Syntax:
protected void doTrace(HttpServletRequest req, HttpServletResponse res)
throws ServletException,IOException
9. doDelete(HttpServletRequest req, HttpServletResponse res): This method is called by web
container for handling DELETE requests.
Syntax:
protected void doDelete(HttpServletRequest req, HttpServletResponse res)
throws ServletException,IOException
10. getLastModified(HttpServletRequest req): It returns the time the HttpServletRequest object
was last modified since midnight January 1, 1970 GMT. It returns a negative number if time is
unknown.
Syntax:
protected long getLastModified(HttpServletRequest req)
2.10 RequestDispatcher interface
RequestDispacher is an interface that provides the facility to forward a request to another resource or
include the content of another resource. RequestDispacher provides a way to call another resource from a
servlet. Another resource can be servlet, jsp or html.
The RequestDispatcher is an Interface that comes under package javax.servlet. Using this interface we get
an object in servlet after receiving the request. Using the RequestDispatcher object we send a request to
other resources which include (servlet, HTML file, or JSP file). A RequestDispatcher object can be used to
forward a request to the resource or to include the resource in a response. The resource can be dynamic or
static.
Methods of RequestDispacher interface:
1. forward(ServletRequest request,ServletResponse response): This method forwards a request from a
servlet to another resource on the server.
Syntax:
public void forward(ServletRequest request,ServletResponse response)
throws ServletException, IOException
2. include(ServletRequest request,ServletResponse response): This method includes the content of a
resource in the response.
Syntax:
public void include(ServletRequest request,ServletResponse response)
throws ServletException, IOException
How to get an object of RequestDispacher?
RequestDispacher object can be gets from HttpServletRequest object.ServletRequest’s
getRequestDispatcher()method is used to get RequestDispatcher object.
RequestDispatcher requestDispatcher = request.getRequestDispatcher(“/another resource”);
After creating RequestDispatcher object you call forword or include method as per your requirement.
requestDispatcher.forward(request, response);
or
requestDispatcher.include(request, response);
2.11 Use of RequestDispatcher
Ans.: Q 2.10
2.12 Session in Servlet: Introducing session
The time interval in which two systems(i.e. the client and the server) communicate with each other can be
termed as a session. In simpler terms, a session is a state consisting of several requests and response between
the client and the server.
It is a known fact that HTTP and Web Servers are both stateless. Hence, the only way to maintain the state
of the user is by making use of technologies that implement session tracking.
Session tracking in servlets can be implemented by a number of methods, cookies being one of them.
However, they have multiple disadvantages:
•
Only textual information can be kept by them.
•
If cookies are disabled by a user, the web application is unable to make use of them.
•
Not more than 4kb of data can be contained by a single cookie.
•
Another way to implement session tracking is by creating sessions with unique session ids for every
user in a java servlet.
2.14 Session tracking mechanism
Session simply means a particular interval of time. Session Tracking is a way to maintain state (data) of an
user. It is also known as session management in servlet.
Http protocol is a stateless so we need to maintain state using session tracking techniques. Each time user
requests to the server, server treats the request as the new request. So we need to maintain the state of an
user to recognize to particular user.
HTTP is stateless that means each request is considered as the new request. It is shown in the figure given
below:
Why is Session Tracking Required?
•
Because the HTTP protocol is stateless, we require Session Tracking to make the client-server
relationship stateful.
•
Session tracking is important for tracking conversions in online shopping, mailing applications, and
E-Commerce applications.
•
The HTTP protocol is stateless, which implies that each request is treated as a new one. As you can
see in the image below.
Session Tracking employs Four Different techniques
1. Cookies
2. Hidden Form Field
3. URL Rewriting
4. HttpSession
A. Cookies
Cookies are little pieces of data delivered by the web server in the response header and kept by the browser.
Each web client can be assigned a unique session ID by a web server. Cookies are used to keep the session
going. Cookies can be turned off by the client.
B. Hidden Form Field
The information is inserted into the web pages via the hidden form field, which is then transferred to the
server. These fields are hidden from the user’s view.
Illustration:
<input type = hidden' name = 'session' value = '12345' >
C. URL Rewriting
With each request and return, append some more data via URL as request parameters. URL rewriting is a
better technique to keep session management and browser operations in sync.
D. HttpSession
A user session is represented by the HttpSession object. A session is established between an HTTP client
and an HTTP server using the HttpSession interface. A user session is a collection of data about a user that
spans many HTTP requests.
Illustration:
HttpSession session = request.getSession( );
Session.setAttribute("username", "password");
The request must be made. Before sending any document content to the client, you must first call
getSession().
2.15 Cookies : Advantages & disadvantages, use of
cookies
Cookie:
A cookie is a small piece of information as a text file stored on client’s machine by a web application.
How cookie works?
As HTTP is a stateless protocol so there is no way to identify that it is a new user or previous user for every
new request. In case of cookie a text file with small piece of information is added to the response of first
request. They are stored on client’s machine. Now when a new request comes cookie is by default added
with the request. With this information we can identify that it is a new user or a previous user.
Types of cookies:
1. Session cookies/Non-persistent cookies: These types of cookies are session dependent i.e. they are
accessible as long as session is open and they are lost when session is closed by exiting from the web
application.
2. Permanent cookies/Persistent cookies: These types of cookies are session independent i.e. they are not
lost when session is closed by exiting from the web application. They are lost when they expire.
Advantages of cookies:
1. They are stored on client side so don’t need any server resource.
2. Easy technique for session management.
Disadvantages of cookies:
1. Cookies can be disabled from the browser.
2. Security risk is there because cookies exist as a text file so any one can open and read user’s
information.
Cookie Class:
Cookie class provides the methods and functionality for session management using cookies. Cookie class is
in javax.servlet.http
Package javax.servlet.http.Cookie.
Commonly used constructor of Cookie class:
1. Cookie(String name,String value): Creates a cookie with specified name and value pair.
Syntax:
public Cookie(String name,String value)
Commonly used methods of cookie class:
1. setMaxAge(int expiry):Sets the maximum age of the cookie.
Syntax:
public void setMaxAge(int expiry)
2. getMaxAge(): Returns the maximum age of the cookie. Default value is -1.
Syntax:
public int getMaxAge()
3. setValue(String newValue): Change the value of the cookie with new value.
Syntax:
public void setValue(String newValue)
4. getValue(): Returns the value of the cookie.
Syntax:
public String getValue()
5. getName(): Returns the name of the cookie.
Syntax:
public String getName()
How to create cookie?
HttpServletResponse interface’s addCookie(Cookie ck) method is used to add a cookie in response object.
Syntax: public void addCookie(Cookie ck)
Example:
//create cookie object
Cookie cookie=new Cookie(“cookieName”,”cookieValue”);
//add cookie object in the response
response.addCookie(cookie);
How to get cookie?
HttpServletRequest interface’s getCookies() method is used to get the cookies from request object.
Syntax: public Cookie[] getCookies()
Example:
//get all cookie objects.
Cookie[] cookies = request.getCookies();
//iterate cookies array to get individual cookie objects.
for(Cookie cookie : cookies){
out.println(“Cookie Name: ” + cookie.getName());
out.println(“Cookie Value: ” + cookie.getValue());
}
How to remove or delete cookies?
Cookies can be removed by setting its expiration time to 0 or -1. If expiration time set to 0 than cookie will
be removed immediately. If expiration time set to -1 than cookie will be removed when browser closed.
Example:
//Remove value from cookie
Cookie cookie = new Cookie(“cookieName”, “”);
//Set expiration time to 0.
cookie.setMaxAge(0);
//add cookie object in the response.
response.addCookie(cookie);
2.16 Hidden form filed
Hidden form field is used to store session information of a client. In this method, we create a hidden form
which passes the control to the servlet whose path is given in the form action area. Using this, the
information of the user is stored and passed to the location where we want to send data.
The main advantage of using Hidden form filed that it doesn’t depend on the browser. Even If the cookies
are disabled or not hidden, form filed will work perfectly.
Another example:
Let's see the code to store value in hidden field:
<input type="hidden" name="uname" value="Vimal Jaiswal">
Here, uname is the hidden field name and Vimal Jaiswal is the hidden field value.
Real application of hidden form field:
It is widely used in comment form of a website. In such case, we store page id or page name in the hidden
field so that each page can be uniquely identified.
Advantage of Hidden Form Field:
1. It will always work whether cookie is disabled or not.
2. All browsers support hidden fields.
3. Simple to use.
Disadvantage of Hidden Form Field:
1. It is maintained at server side.
2. Extra form submission is required on each pages.
3. Only textual information can be used.
4. Not secure
2.17 URL rewritten
URL rewriting is a process of appending or modifying any url structure while loading a page.
The request made by client is always a new request and the server can not identify whether the current
request is send by a new client or the previous same client. Due to This property of HTTP protocol and Web
Servers are called stateless. But many times we should know who is client in the processing request.
URL rewriting:
URL rewriting is a way of appending data at the end of URL. Data is appended in name value pair form.
Multiple parameters can be appended in one URL with name value pairs.
Syntax:
URL?paramName1=paramValue1& paramName2=paramValue2
How to get parameter value from url in servlet?
HttpServletRequest interface’s getParameter() method is used to get parameter value from url in servlet.
Syntax:
String value = request.getParameter(“fieldName”);
Advantages of URL rewriting:
1. As data is appended in the URL it is easy to debug.
2. It is browser independent.
Disadvantages of URL rewriting:
1. Not secure because data is appended in the URL.
2. Can’t append large no. of parameters because URL length is limited.
2.18 HttpSession.
HttpSession:
HttpSession is an interface that provides a way to identify a user in multiple page requests. A unique session
id is given to the user when first request comes. This id is stored in a request parameter or in a cookie.
How to get session object?
HttpServletRequest interface’s getSession() method is used to get the session object.
Syntax:
HttpSession session = request.getSession();
How to set attribute in session object?
HttpSession interface’s setAttribute() method is used to set attribute in session object.
Syntax:
public void setAttribute(String name,Object value);
Example:
session.setAttribute("attName", "attValue");
How to get attribute from session object?
HttpSession interface’s getAttribute() method is used to get attribute from session object.
Syntax:
public Object getAttribute(String name);
Example:
String value = (String) session.getAttribute("attName");
Advantages of Http Sessions
•
Any kind of object can be stored into a session, be it a text, database, dataset etc.
•
Usage of sessions is not dependent on the client’s browser.
•
Sessions are secure and transparent
Disadvantages of Http session
•
Performance overhead due to session object being stored on server
•
Overhead due to serialization and de-serialization of data
Commonly used methods of HttpSession interface
1. public String getId():Returns a string containing the unique identifier value.
2. public long getCreationTime():Returns the time when this session was created, measured in
milliseconds since midnight January 1, 1970 GMT.
3. public long getLastAccessedTime():Returns the last time the client sent a request associated with this
session, as the number of milliseconds since midnight January 1, 1970 GMT.
4. public void invalidate():Invalidates this session then unbinds any objects bound to it.
UNIT 3:
3.1 Introduction to JSP :
Java Server Pages (JSP) is a server-side programming technology that enables the creation of dynamic,
platform-independent method for building Web-based applications. JSP have access to the entire family of
Java APIs, including the JDBC API to access enterprise databases. This tutorial will teach you how to use
Java Server Pages to develop your web applications in simple and easy steps.
3.2 Advantages of JSP over Servlet
Introduction
•
It stands for Java Server Pages.
•
It is a server side technology.
•
It is used for creating web application.
•
It is used to create dynamic web content.
•
In this JSP tags are used to insert JAVA code into HTML pages.
•
It is an advanced version of Servlet Technology.
•
It is a Web based technology helps us to create dynamic and platform independent web pages.
•
In this, Java code can be inserted in HTML/ XML pages or both.
•
JSP is first converted into servlet by JSP container before processing the client’s request.
JSP pages are more advantageous than Servlet:
•
They are easy to maintain.
•
No recompilation or redeployment is required.
•
JSP has access to entire API of JAVA .
•
JSP are extended version of Servlet.
Features of JSP
•
Coding in JSP is easy :- As it is just adding JAVA code to HTML/XML.
•
Reduction in the length of Code :- In JSP we use action tags, custom tags etc.
•
Connection to Database is easier :-It is easier to connect website to database and allows to read or
write data easily to the database.
•
Make Interactive websites :- In this we can create dynamic web pages which helps user to interact
in real time environment.
•
Portable, Powerful, flexible and easy to maintain :- as these are browser and server independent.
•
No Redeployment and No Re-Compilation :- It is dynamic, secure and platform independent so no
need to re-compilation.
•
Extension to Servlet :- as it has all features of servlets, implicit objects and custom tags
JSP syntax
Syntax available in JSP are following
1. Declaration Tag :-It is used to declare variables.
Syntax:<%! Dec var %>
Example:<%! int var=10; %>
2. Java Scriplets :- It allows us to add any number of JAVA code, variables and expressions.
Syntax:<% java code %>
3. JSP Expression :- It evaluates and convert the expression to a string.
Syntax:<%= expression %>
Example:<% num1 = num1+num2 %>
4. JAVA Comments :- It contains the text that is added for information which has to be ignored.
Syntax:<% -- JSP Comments %>
Process of Execution
Steps for Execution of JSP are following:•
•
•
•
•
•
•
Create html page from where request will be sent to server eg try.html.
To handle to request of user next is to create .jsp file Eg. new.jsp
Create project folder structure.
Create XML file eg my.xml.
Create WAR file.
Start Tomcat
Run Application
Example of Hello World
We will make one .html file and .jsp file
demo.jsp
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Hello World - JSP tutorial</title>
</head>
<body>
<%= "Hello World!" %>
</body>
</html>
Advantages of using JSP
•
•
•
It does not require advanced knowledge of JAVA
It is capable of handling exceptions
Easy to use and learn
•
•
•
It can tags which are easy to use and understand
Implicit objects are there which reduces the length of code
It is suitable for both JAVA and non JAVA programmer
Disadvantages of using JSP
•
•
•
Difficult to debug for errors.
First time access leads to wastage of time
It’s output is HTML which lacks features.
3.3 JSP architecture
How JSP pages are processed?
1. When a user navigates to a page ending with a .jsp extension in their web browser, the web browser
sends an HTTP request to the webserver.
2. The webserver checks if a compiled version of the JSP page already exists.
3. If the JSP page's compiled version does not exist, the file is sent to the JSP Servlet engine, it
converts it into servlet content (with .java extension). This process is known as translation.
4. Then after translated .java file of the servlet is compiled into the Java servlet .class file. This
process is known as compilation.
5. In the last step, the compiled .class file of the servlet is executed, and the result (HTML) is sent back
to the client machine as an HTTP response.
3.4 JSP life cycle
A Java Server Page life cycle is defined as the process that started with its creation which later translated to
a servlet and afterward servlet lifecycle comes into play. This is how the process goes on until its
destruction.
Paths Followed By JSP
The following are the paths followed by a JSP −
•
Translation
•
Compilation
•
Initialization
•
Execution
•
Cleanup
1.Translation of JSP page to Servlet :
This is the first step of the JSP life cycle. This translation phase deals with the Syntactic correctness of
JSP. Here test.jsp file is translated to test.java.
2. JSP Compilation
When a browser asks for a JSP, the JSP engine first checks to see whether it needs to compile the page. If the
page has never been compiled, or if the JSP has been modified since it was last compiled, the JSP engine
compiles the page.
The compilation process involves three steps −
•
•
•
Parsing the JSP.
Turning the JSP into a servlet.
Compiling the servlet.
3. JSP Initialization
When a container loads a JSP it invokes the jspInit() method before servicing any requests. If you need to
perform JSP-specific initialization, override the jspInit() method −
public void jspInit(){
// Initialization code...
}
Typically, initialization is performed only once and as with the servlet init method, you generally initialize
database connections, open files, and create lookup tables in the jspInit method.
4. JSP Execution
This phase of the JSP life cycle represents all interactions with requests until the JSP is destroyed.
Whenever a browser requests a JSP and the page has been loaded and initialized, the JSP engine invokes
the _jspService() method in the JSP.
The _jspService() method takes an HttpServletRequest and an HttpServletResponse as its parameters as
follows −
void _jspService(HttpServletRequest request, HttpServletResponse response) {
// Service handling code...
}
The _jspService() method of a JSP is invoked on request basis. This is responsible for generating the
response for that request and this method is also responsible for generating responses to all seven of the HTTP
methods, i.e, GET, POST, DELETE, etc.
5. JSP Cleanup
The destruction phase of the JSP life cycle represents when a JSP is being removed from use by a container.
The jspDestroy() method is the JSP equivalent of the destroy method for servlets. Override jspDestroy when
you need to perform any cleanup, such as releasing database connections or closing open files.
The jspDestroy() method has the following form −
public void jspDestroy() {
// Your cleanup code goes here.
}
3.5 Implicit objects in JSP
These Objects are the Java objects that the JSP Container makes available to the developers in each page and
the developer can call them directly without being explicitly declared. JSP Implicit Objects are also
called pre-defined variables.
JSP provide you Total 9 implicit objects which are as follows
1. request: This is the object of HttpServletRequest class associated with the request.
2. response: This is the object of HttpServletResponse class associated with the response to the client.
3. config: This is the object of ServletConfig class associated with the page.
4. application: This is the object of ServletContext class associated with the application context.
5. session: This is the object of HttpSession class associated with the request.
6. page context: This is the object of PageContext class that encapsulates the use of server-specific
features. This object can be used to find, get or remove an attribute.
7. page object: The manner we use the keyword this for current object, page object is used to refer to
the current translated servlet class.
8. exception: The exception object represents all errors and exceptions which is accessed by the
respective jsp. The exception implicit object is of type java.lang.Throwable.
9. out: This is the PrintWriter object where methods like print and println help for displaying the
content to the client.
3.6 JSP tag elements‐ Declarative, Declaration,
scriplet, expression, Action Tags.
Scripting elements in JSP must be written within the <% %> tags. The JSP engine will process any code
you write within the pair of the <% and %> tags, and any other texts within the JSP page will be treated as
HTML code or plain text while translating the JSP page.
Here are five different scripting elements:
•
•
•
•
•
•
Comment <%-- Set of comment statements --%>
Directive <%@ directive %>
Declaration <%! declarations %>
Scriptlet <% scriplets %>
Expression <%= expression %>
Action
1.Comment:
Comments are marked as text or statements that are ignored by the JSP container. They are useful when you
want to write some useful information or logic to remember in the future.
Syntax:
<%-- This is JSP comment --%>
Example:
<%@ page import="java.util.Date"%>
<!DOCTYPE html>
<html>
<head>
<title>Comments in JSP Page</title>
</head>
<body>
<%-- A JSP comment --%>
<!-- An HTML comment -->
<!—The current date is <%= new Date() %>
-->
</body>
</html>
2.Directive
These tags are used to provide specific instructions to the web container when the page is translated. It has
three subcategories:
•
•
•
Page: <%@ page ... %>
Include: <%@ include ... %>
Taglib: <%@ taglib ... %>
3.Declaration
As the name suggests, it is used to declare methods and variables you will use in your Java code within a
JSP file. According to the rules of JSP, any variable must be declared before it can be used.
Syntax:
<%! declaration; [ declaration; ]+ ... %>
Example:
<!DOCTYPE html>
<html>
<body>
<%! int variable_value=62; %>
<%= " Your integer data is :"+ variable_value %>
</body>
</html>
4.JSP Scriptlet Tag
The scriptlet tag allows writing Java code statements within the JSP page. This tag is responsible for
implementing the functionality of _jspService() by scripting the java code.
Syntax:
<% JAVA CODE %>
Example:
<!DOCTYPE html>
<html>
<head>
<title>Scriptlet Tag</title>
</head>
<% int count = 2; %>
<body>
Calculated page count <% out.println(cnt); %>
</body>
</html>
Another code snippet that shows how to write and mix scriptlet tags with HTML:
Example:
<table border="1">
<% for ( int g = 1; g <= cnt; g++ ) { %>
<tr>
<td>Number</td>
<td><% = g+1 %></td>
</tr>
<% } %>
</table>
5.Expressions
Expressions elements are responsible for containing scripting language expression, which gets evaluated and
converted to Strings by the JSP engine and is meant to the output stream of the response. Hence, you are not
required to write out.print() for writing your data. This is mostly used for printing the values of variables or
methods in the form of output.
Syntax:
<%= expression %>
Example:
<!DOCTYPE html>
<html>
<body>
<%= "A JSP based string" %>
</body>
</html>
6.Action
JSP actions use constructs in XML syntax to control the behavior of the servlet engine. You can dynamically
insert a file, reuse JavaBeans components, forward the user to another page, or generate HTML for the Java
plugin.
There is only one syntax for the Action element, as it conforms to the XML standard −
<jsp:action_name attribute="value" />
3.7 Java Bean‐ Advantages & Disadvantages
JavaBeans are classes that encapsulate many objects into a single object (the bean). Using JavaBeans in the
Java program allows us to encapsulate many objects into a single object called a bean. Java is an objectoriented programming language that makes the develop once, run and reuse the program everywhere most
important.
However, JavaBeans add reusability into the Java program by maintaining a single object encapsulating
many data members and member functions. In other words, we can say that a JavaBean
is a platform-independent component that allows us to reuse the class object in our Java
code.
It is a java class that should follow following conventions:
1. Must implement Serializable.
2. It should have a public no-arg constructor.
3. All properties in java bean must be private with public getters and setter methods.
Advantages of JavaBean
o
The JavaBean properties and methods can be exposed to another application.
o
It provides an easiness to reuse the software components.
Disadvantages of JavaBean
o
JavaBeans are mutable. So, it can't take advantages of immutable objects.
o
Creating the setter and getter method for each property separately may lead to the boilerplate code.
3.8 useBean tag‐ setProperty and getProperty
JavaBean Properties
A JavaBean property is a named feature that can be accessed by the user of the object. The feature can be of
any Java data type, containing the classes that you define.
A JavaBean property may be read, write, read-only, or write-only. JavaBean features are accessed through
two methods in the JavaBean's implementation class:
1. getPropertyName ()
For example, if the property name is firstName, the method name would be getFirstName() to read that
property. This method is called the accessor.
Syntax for getter methods:
1. It should be public in nature.
2. The return-type should not be void i.e. according to our requirement we have to give return-type.
3. The getter method should be prefixed with get.
4. It should not take any argument.
For Boolean properties getter method name can be prefixed with either “get” or “is”. But recommended to use
“is”.
2. setPropertyName ()
For example, if the property name is firstName, the method name would be setFirstName() to write that
property. This method is called the mutator.
Syntax for setter methods:
1. It should be public in nature.
2. The return-type should be void.
3. The setter method should be prefixed with set.
4. It should take some argument i.e. it should not be no-arg method.
useBean
The useBean action is quite versatile. It first searches for an existing object utilizing the id and scope variables.
If an object is not found, it then tries to create the specified object.
The simplest way to load a bean is as follows −
<jsp:useBean id = "name" class = "package.class" />
The jsp:useBean action tag is used to locate or instantiate a bean class. If bean object of the Bean class is
already created, it doesn't create the bean depending on the scope. But if object of bean is not created, it
instantiates the bean.
Example:
UNIT 4:
4.1 JSTL core tag:
The JSTL core tag provides variable support, URL management, flow control etc. The syntax used for
including JSTL core library in your JSP is:
1. <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
JSTL Core Tags List
Tags
Description
c:out
It display the result of an expression, similar to the way <%=...%> tag work.
c:import
It Retrives relative or an absolute URL and display the contents to either a String in
'var',a Reader in 'varReader' or the page.
c:set
It sets the result of an expression under evaluation in a 'scope' variable.
c:remove
It is used for removing the specified scoped variable from a particular scope.
c:catch
It is used for Catches any Throwable exceptions that occurs in the body.
c:if
It is conditional tag used for testing the condition and display the body content only
if the expression evaluates is true.
c:choose,c:when,
c:otherwise
It is the simple conditional tag that includes its body content if the evaluated condition
is true.
c:forEach
It is the basic iteration tag. It repeats the nested body content for fixed number of
times or over collection.
c:forTokens
It iterates over tokens which is separated by the supplied delimeters.
c:param
It adds a parameter in a containing 'import' tag's URL.
c:redirect
It redirects the browser to a new URL and supports the context-relative URLs.
c:url
It creates a URL with optional query parameters.
X4.2 General purpose tag,
4.3 conditional tag,
c:if
It is conditional tag used for testing the condition and display the body content only if the expression
evaluates is true.
The < c:if > tag is used for testing the condition and it display the body content, if the expression evaluated
is true.
It is a simple conditional tag which is used for evaluating the body content, if the supplied condition is true.
Attribute
The <c:if> tag has the following attributes −
Attribute
Description
Required
Default
test
Condition to evaluate
Yes
None
var
Name of the variable to store the condition's result
No
None
scope
Scope of the variable to store the condition's result
No
page
Let's see the simple example program of c:if tag:
X4.4 networking tag ,
4.5 JSTL SQL tags ,
The JSTL sql tags provide SQL support. The url for the sql tags is http://java.sun.com/jsp/jstl/sql and
prefix is sql.
The SQL tag library allows the tag to interact with RDBMSs (Relational Databases) such as Microsoft SQL
Server, mySQL, or Oracle. The syntax used for including JSTL SQL tags library in your JSP is:
1. <%@ taglib uri="http://java.sun.com/jsp/jstl/sql" prefix="sql" %>
JSTL SQL Tags List
SQL Tags
Descriptions
sql:setDataSource
It is used for creating a simple data source suitable only for prototyping.
sql:query
It is used for executing the SQL query defined in its sql attribute or the body.
sql:update
It is used for executing the SQL update defined in its sql attribute or in the tag body.
sql:param
It is used for sets the parameter in an SQL statement to the specified value.
sql:dateParam
It is used for sets the parameter in an SQL statement to a specified java.util.Date value.
sql:transaction
It is used to provide the nested database action with a common connection.
4.6 JSTL formatting tags ,
The JSTL formatting tags are used to format and display text, the date, the time, and numbers for
internationalized Websites. Following is the syntax to include Formatting library in your JSP −
<%@ taglib prefix = "fmt" uri = "http://java.sun.com/jsp/jstl/fmt" %>
Following table lists out the Formatting JSTL Tags −
S.No.
Tag & Description
1
<fmt:formatNumber>: To render numerical value with specific precision or format.
2
<fmt:parseNumber>: Parses the string representation of a number, currency, or percentage.
3
<fmt:formatDate>: Formats a date and/or time using the supplied styles and pattern.
4
<fmt:parseDate>: Parses the string representation of a date and/or time
S.No.
Tag & Description
5
<fmt:bundle>: Loads a resource bundle to be used by its tag body.
6
<fmt:setLocale>: Stores the given locale in the locale configuration variable.
7
<fmt:setBundle>: Loads a resource bundle and stores it in the named scoped variable or the
bundle configuration variable.
8
<fmt:timeZone>: Specifies the time zone for any time formatting or parsing actions nested in its
body.
9
<fmt:setTimeZone>: Stores the given time zone in the time zone configuration variable
10
<fmt:message>: Displays an internationalized message.
11
<fmt:requestEncoding>: Sets the request character encoding
4.7 JSTL xml tags ,
The JSTL XML tags are used for providing a JSP-centric way of manipulating and creating XML
documents.
The xml tags provide flow control, transformation etc. The url for the xml tags
is http://java.sun.com/jsp/jstl/xml and prefix is x. The JSTL XML tag library has custom tags used for
interacting with XML data. The syntax used for including JSTL XML tags library in your JSP is:
1. <%@ taglib uri="http://java.sun.com/jsp/jstl/xml" prefix="x" %>
JSTL XML tags List
XML
Tags
Descriptions
x:out
Similar to <%= ... > tag, but for XPath expressions.
x:parse
It is used for parse the XML data specified either in the tag body or an attribute.
x:set
It is used to sets a variable to the value of an XPath expression.
x:choose
It is a conditional tag that establish a context for mutually exclusive conditional operations.
x:when
It is a subtag of that will include its body if the condition evaluated be 'true'.
x:otherwise
It is subtag of that follows tags and runs only if all the prior conditions evaluated be 'false'.
x:if
It is used for evaluating the test XPath expression and if it is true, it will processes its body content.
x:transform
It is used in a XML document for providing the XSL(Extensible Stylesheet Language)
transformation.
x:param
It is used along with the transform tag for setting the parameter in the XSLT style sheet.
4.8 Introducing internationalization & Java:
Internationalization is also abbreviated as I18N because there are total 18 characters between the first letter
'I' and the last letter 'N'.
Internationalization is a mechanism to create such an application that can be adapted to different languages
and regions.
Internationalization is one of the powerful concept of java if you are developing an application and want to
display messages, currencies, date, time etc. according to the specific region or language.
Localization is also abbreviated as I10N because there are total 10 characters between the first letter 'L' and
last letter 'N'. Localization is the mechanism to create such an application that can be adapted to a specific
language and region by adding locale-specific text and component.
4.9 local class,
Within Java, we have a fantastic feature at our disposal called the Locale class.
It allows us to quickly differentiate between cultural locales and format our content appropriately. It's
essential for within the internationalization process. The same as i18n, Localization also has its abbreviation
– l10n.
The main reason for using Locale is that all required locale-specific formatting can be accessed without
recompilation. An application can handle multiple locales at the same time so supporting new language is
straightforward.
Constructors of Locale class:
1. Locale(String language)
2. Locale(String language, String country)
3. Locale(String language, String country, String variant)
Commonly used methods of Locale class:
1. public static Locale getDefault() it returns the instance of current Locale
2. public static Locale[] getAvailableLocales() it returns an array of available locales.
3. public String getDisplayCountry() it returns the country name of this locale object.
4. public String getDisplayLanguage() it returns the language name of this locale object.
5. public String getDisplayVariant() it returns the variant code for this locale object.
6. public String getISO3Country() it returns the three letter abbreviation for the current locale's
country.
7. public String getISO3Language() it returns the three letter abbreviation for the current locale's
language.
4.10 ResourseBundle class.
The ResourceBundle class is used to internationalize the messages. In other words, we can say that it provides
a mechanism to globalize the messages.
The hardcoded message is not considered good in terms of programming, because it differs from one country
to another. So we use the ResourceBundle class to globalize the massages. The ResourceBundle class loads
these informations from the properties file that contains the messages.
Conventionally, the name of the properties file should be filename_languagecode_country code for
example MyMessage_en_US.properties.
Commonly used methods of ResourceBundle class
There are many methods in the ResourceBundle class. Let's see the commonly used methods of the
ResourceBundle class.OOPs Concepts in Java
o
public static ResourceBundle getBundle(String basename) returns the instance of the
ResourceBundle class for the default locale.
o
public static ResourceBundle getBundle(String basename, Locale locale) returns the instance of
the ResourceBundle class for the specified locale.
o
public String getString(String key) returns the value for the corresponding key from this resource
bundle.
_______________________________________________________________________________________
ResourceBundle: The class ResourceBundle is an abstract class. It defines methods that enable you to
manage a collection of locale-sensitive resources. Resource bundles are identified by their family name. To
the family name is added a two-character lowercase language code that specifies the language. We can also
specify a country code after the language code. It is a two-character uppercase identifier and is preceded by
an underscore when linked to a resource bundle name.
Class Hierarchy:
java.lang.Object
↳java.util.ResourceBundle
Constructors:
1. ResourceBundle(): The default constructor which is mainly designed for use by the subclasses and the
factory methods.
public ResourceBundle()
Methods:
1. clearCache(): This method deletes all resource bundles from the cache that were loaded by the default
class loader.
static final void clearCache()
2. containsKey(): This method returns true if the passed string argument is a key within the invoking
resource bundle.
boolean containsKey(String k)
3. getBundle(): This method loads the resource bundle with the given name and the specified locale.
static final ResourceBundle getBundle(String familyName)
static final ResourceBundle getBundle(String familyName, Locale loc)
4. setParent(): This method sets the passed bundle as parent of the invoking bundle. In case of a lookup, if
the key is not found in the invoking object, then it is looked up in the parent bundle.
protected void setParent(ResourceBundle parent)
5. getObject(): This method retrieves and returns the Object associated with the key passed as argument
either from the current resource bundle or the parent.
public final Object getObject(String key)
6. getHandleObject(): This method returns the object associated with the given key from the resource
bundle. If no object is available null is returned.
protected abstract Object handleGetObject(String key)
7. getString(): This method retrieves and returns the string associated with the key passed as argument
either from the current resource bundle or the parent.
public final String getString(String key)
8. getStringArray(): This method retrieves and returns the string array associated with the key passed as
argument either from the current resource bundle or the parent.
public final String[] getStringArray(String key)
9. getLocale(): This method returns the Locale associated with the current bundle.
public Locale getLocale()
10. containsKey(): This method checks whether a given key exists within a resource bundle or its parent or
not.
public boolean containsKey(String key)
11. keySet(): This method returns the set of all the keys in the current bundle or its parent bundle.
public Set keySet()
4.11 Introduction to Frameworks in java:
What is Framework in Java?
Java Framework is the body or platform of pre-written codes used by Java developers to develop Java
applications or web applications. In other words, Java Framework is a collection of predefined classes and
functions that is used to process input, manage hardware devices interacts with system software. It acts like
a skeleton that helps the developer to develop an application by writing their own code.
What is a framework?
Framework are the bodies that contains the pre-written codes (classes and functions) in which we can add
our code to overcome the problem. We can also say that frameworks use programmer's code because the
framework is in control of the programmer. We can use the framework by calling its methods, inheritance,
and supplying "callbacks", listeners, or other implementations of the Observer pattern.
Some of the most popular Java frameworks are:
o
Spring
o
Hibernate
o
Grails
o
Play
o
JavaServer Faces (JSF)
o
Google Web Toolkit (GWT)
o
Quarkus
1) Spring
It is a light-weighted, powerful Java application development framework. It is used for JEE
. Its other modules are Spring Security, Spring MVC, Spring Batch, Spring ORM, Spring Boot
and Spring Cloud, etc.
Advantages
o
Loose coupling
o
Lightweight
o
Fast Development
o
Powerful abstraction
o
Easy to test
2) Hibernate
is ORM (Object-Relation Mapping) framework that allows us establish communication between Java
programming language and the RDBMS.
Advantages
o
Portability, productivity, maintainability.
o
Open source framework.
o
It avoids repetitive code from the JDBC API.
3)JavaServer Faces
It stands for JavaServer Faces. It is a component-based UI framework developed by Oracle that is used to
build user interfaces for Java-based applications. It follows MVC design pattern. The application developed
using JSF
has an architecture that defines a distinction
Advantages
o
It is an important part of JEE.
o
Provides rich libraries.
4)Grails
It is a dynamic framework created by using the Groovy programming language
. It is an OOPs language. Its purpose is to enhance the productivity. The syntax of Grails is matched with
Java and the code is compiled to JVM
. It also works with Java, JEE, Spring and Hibernate.
Advantages
o
It uses Groovy programming standard instead of Java programming standard because Groovy is
similar to Java.
o
Its object mapping feature is easy to use.
o
It provides the facility of reusing the code (in the form of plugin) between different Grail
applications.
o
Provides flexible profiles.
5)Play
It is a unique Java framework because it does not follow JEE standards. It follows MVC architecture pattern.
It is used when we want to develop highly scalable Java application. Using Play framework, we can develop
lightweight and web-friendly Java application for both mobile and desktop.
Advantages
o
No configuration is required.
o
It enhances the developer productivity and target the RESTful architectures.
o
It offers hot code reload and error message in the browser.
o
It also supports popular IDEs.
6) Google Web Toolkit (GWT)
It is an open-source framework that allows developers to write client-side Java code. With the help of GWT,
we can rapidly develop complex browse application. The advantages to use GWT
is that we can easily develop and debug Ajax application. the product of Google, such as Google AdSense,
Blogger are developed using GWT.
Advantages
o
It employs reusability for web application development
o
We can use Google API to develop application.
o
It provides functionality such as, internationalization, UI abstraction, and history management.
7)Quarkus
It is a modern, full-stack, and Kubernetes-native Java framework. It offers small memory footprint and
reduced boot time. It works well if the infrastructure is cloud-native. It optimizes Java specifically for
Kubernetes and enables it to become an effective platform for serverless, cloud, and Kubernetes
environments.
Advantages
o
It is used in cloud, containers, and serverless environments.
o
It supports microservices architecture and development.
o
The developers are free to choose own development model.
o
It is compatible with popular frameworks like, Eclipse, Spring Dependency Injection, and Hibernate.
The advantages of the Java Frameworks are as follows:
o
Security: It is the most important advantage of the Java framework. If we found any security loop
hole or vulnerability in an application, we can directly move to the official website of the framework
to fix the security related issues.
o
Support: The widely used framework provides large forums or groups where we can put our
problem for the solution. It also provides the documentation of the framework that helps us to
understand the working of the framework.
o
Efficiency: If we are doing a task without using the framework, it may take time to complete. But if
we are doing the same work by using the framework, we can complete that task in easy and fast way.
Therefore, using the Java framework development become faster, easier and effective. It also saves
time and efforts.
o
Expenses: Another advantage of using the framework is to reduce the cost of the application.
Because the maintenance cost of the framework is low.
4.12 Java Server Faces Struts, Springs, Hibernate.
1) JavaServer Faces Struts
It is a server side component based user interface framework. It is used to develop web applications. It
provides a well-defined programming model and consists of rich API and tag libraries. The latest version JSF
2 uses Facelets as its default templating system. It is written in Java.
The JSF API provides components (inputText, commandButton etc) and helps to manage their states. It also
provides server-side validation, data conversion, defining page navigation, provides extensibility, supports for
internationalization, accessibility etc.
The JSF Tag libraries are used to add components on the web pages and connect components with objects on
the server. It also contains tag handlers that implements the component tag. With the help of these features
and tools, you can easily and effortlessly create server-side user interface.
JavaServer Faces technology simplifies building user interfaces for JavaServer applications. Developers of
various skill levels can quickly build web applications by: assembling reusable UI components in a page;
connecting these components to an application data source; and wiring client-generated events to server-side
event handlers.
The JSF Plugin provides support for JavaServer Faces components with no additional configuration.
The JSF support works by breaking up the JSF Licycle class into Struts Interceptors, one for each JSF phase.
When you include the jsfStack stack, you are ensuring the JSF page has its phases execute correctly. At the
end of the phases, the Struts Action itself is executed just like non-JSF pages. The String return code of the
Action is treated like any other Action as well. Finally, the JSF “render” phase has been transformed into a
Result.
JavaServer Faces also has a concept of an “action”, which are generally executed in response to a button click.
The handling of the JSF action is preserved through the jsfStack Interceptor stack, but its String result code,
rather than being applied against a JSF navigation rule, is treated as a Struts result code thereby keeping the
navigation responsibility within Struts.
The limitations of this approach include:
1. Any custom Lifecycle class is ignored
2. Any custom NavigationHandler is delegated to only when a Struts 2 navigation option cannot be found
On the other hand, the rest of the JSF functionality, including PhaseListeners, components, multiple backing
beans, etc. are preserved. The Showcase example has a section demonstrating the JSF integration approach.
Features
•
•
•
•
Allows JSF components on normal Struts pages
Requires no additional configuration
Allows the JSF lifecycle to be completely customized
Preserves most JSF framework features so even complex components should work out of the box
Usage
The JSF plugin splits the JSF lifecycle into an optional Interceptor stack and Result, yet retains the page’s
Action and navigation. Therefore, to use a page with JSF components, you need to:
1. Add the jsfStack interceptor stack to your action definition. This is easiest done by having your
package extend jsf-default.
2. Add a jsf result associated with the name successYou can still add additional interceptors and results,
including those that don’t use JSF at all. In fact, the recommended approach is to use regular Struts
results to handle inter-page navigation to avoid a common problem of JSF applications where every
page request is a HTTP POST.
This approach brings an additional advantage to JSF - every page can have an Action to execute page setup
code, and the same Action instance will be automatically available later in the JSF page’s expression language
as action. This means any common page logic such as retrieving data from a database can remain in your
Action, and having that instance available later in your JSF components means the JSF configuration file is
completely optional. The JSF configuration file, faces-config.xml, generally contains backing bean definitions
and navigation rules, both of which can be solely handled by Struts.
2)Springs
JSF is a component based framework with great focus on user interfaces. Whereas Spring framework core
principle is Dependency Injection. So it makes sense to integrate JSF with Spring framework where JSF will
be used for user interfaces and Spring framework will be used for backend server side business logic.
Spring provides special class DelegatingVariableResolver to integrate JSF and Spring together in a seamless
manner.
Following steps are required to integrate Spring Dependency Injection (IOC) feature in JSF.
Step 1: Add DelegatingVariableResolver
Add a variable-resolver entry in faces-config.xml to point to spring class DelegatingVariableResolver.
<faces-config>
<application>
<variable-resolver>
org.springframework.web.jsf.DelegatingVariableResolver
</variable-resolver>
...
</faces-config>
Step 2: Add Context Listeners
Add ContextLoaderListener and RequestContextListener listener provided by spring framework in
web.xml.
<web-app>
...
<!-- Add Support for Spring -->
<listener>
<listener-class>
org.springframework.web.context.ContextLoaderListener
</listener-class>
</listener>
<listener>
<listener-class>
org.springframework.web.context.request.RequestContextListener
</listener-class>
</listener>
...
</web-app>
Step 3: Define Dependency
Define bean(s) in applicationContext.xml which will be used as dependency in managed bean.
<beans>
<bean id = "messageService"
class = "com.tutorialspoint.test.MessageServiceImpl">
<property name = "message" value = "Hello World!" />
</bean>
</beans>
Step 4: Add Dependency
DelegatingVariableResolver first delegates value lookups to the default resolver of the JSF and then to
Spring's WebApplicationContext. This allows one to easily inject springbased dependencies into one's JSFmanaged beans.
We've injected messageService as spring-based dependency here.
<faces-config>
...
<managed-bean>
<managed-bean-name>userData</managed-bean-name>
<managed-bean-class>com.tutorialspoint.test.UserData</managed-bean-class>
<managed-bean-scope>request</managed-bean-scope>
<managed-property>
<property-name>messageService</property-name>
<value>#{messageService}</value>
</managed-property>
</managed-bean>
</faces-config>
Step 5: Use Dependency
//jsf managed bean
public class UserData {
//spring managed dependency
private MessageService messageService;
public void setMessageService(MessageService messageService) {
this.messageService = messageService;
}
public String getGreetingMessage() {
return messageService.getGreetingMessage();
}
}
Struts vs JSF vs Spring
1. Struts and JSF are web frameworks, which we will provide an excellent environment to prepare and
execute web applications only.
Spring Framework is an application framework. It will provide an excellent environment to prepare and
execute all applications like standalone applications, web applications, distributed applications.
2. Struts and JSF are designed based on the MVC design pattern.
In Spring, only WEB Module is designed based on the MVC design pattern. Spring uses several other
design patterns like IOC [Dependency Injection], Locater design patterns, Creational Design Patterns,
Decorator Design pattern.
3. Struts is a controller layered framework. It has an excellent focus on the controller layer in MVC.
JSF is a view layered Framework. It has an excellent focus on the View layer in MVC. Spring Framework
has provided excellent support for all Controller Layer, Model Layer, and View Layer.
4. In Enterprise Application Development, Struts and JSF are used to prepare mainly the Presentation layer.
In Enterprise Application Development, Spring Framework will cover all the layers like Presentation Layer,
Business Layer, Persistence Layer.
5. Struts and JSF provide support for the basic services like I18N, Validations, Exception Handling, etc. but,
Struts and JSF are not providing support for the middleware services like JAAS, JNDI, JTA, Java Mail, JMS
etc.
Spring Framework provides very good support for all basic services like I18N, Validations, Exception
Handling … and the Middleware services like JAAS, JNDI, JTA, Java Mail, JMS, JCA, etc.
6. Struts and JSF have not modularized Frameworks. To prepare any application in Struts and JSF, we have
to load all the jar files irrespective of their utilization.
Spring framework is a modularized framework. To prepare applications in the spring framework, we will
load only the module respective jar files, not unnecessarily load other modules respective jar files.
7. Struts and JSF are more API dependent; they are not having POJO/POJI kind of implementations.
Spring is less API-dependent. It has POJO/POJI kind of implementations.
8. Due to the above reasons, debugging and testing is difficult in Struts and JSF.
Testing and Debugging are very simple in the Spring framework.
9. Struts and JSF are heavy-weight Frameworks.
Spring is a lightweight Framework.
10. Struts and JSF are not providing any predefined support to integrate the other applications like JDBC,
EJB, Hibernate, JPA, RMI, etc.
Spring has provided excellent predefined support to integrate the other applications like JDBC, EJB,
Hibernate, JPA, RMI, etc.
11. Struts and JSF allow the basic view-related technologies like Html, JSP, etc., to prepare the view part.
Spring Framework allows the most advanced view-related technologies like Velocity, Free marker, etc., and
basic view-related tech to prepare view part.
12. Struts and JSF do not have Aspect-Oriented Programming to prepare applications.
Spring has provided excellent Aspect-Oriented Programming to prepare Applications.
3) Hibernate
Hibernate is the Object to Relational Mapping (ORM) tool given to transfer the data between a Java (object)
application and a database (relational) in the form of the objects. It is a non-invasive framework meaning it
never forces the programmers to extend or implement any class or interface, thus making the database
operations lightweight.
It implements JPA interface and in case programmer wish to understand the Hibernate architecture, they
might consider this option
There are many advantages of using the hibernate framework, for e.g.
1. Takes care of mapping Java classes to database tables using XML files and without writing any line
of code.
2. Provides simple APIs for storing and retrieving Java objects directly to and from the database.
3. Provides the facility to create the tables of the database automatically. So, there is no need to create
tables in the database manually.
4. If there is a change in a database or in any table then the only need to change XML file properties.
5. Minimize database access with smart fetching strategies as Hibernate framework internally uses the
cache technique.
6. Provides simple querying of data.
Download