Professional Documents
Culture Documents
J2EE Full Notes
J2EE Full Notes
2. The challenge Sun Microsystems faced in the late 1990s was to develop a way for Java
developers to write high-level code that accesses all popular DBMSs.
3. Language barrier was one of the major obstacle for Sun. Each DBMS defined its own low-level
way to interact with programs to access data stored in its databases.
4. A low-level code written to communicate with an Oracle database might need to be rewritten to
access a DB2 database.
1. This encouraged third-party vendors & other DBMS manufacturers to build JDBC drivers that
suited Suns specifications.
2. The specifications required a JDBC driver to be a translator that converted low-level proprietary
DBMS messages to low-level messages understood by the JDBC API and vice versa.
3. This meant Java programmers could use high-level Java data objects defined in the JDBC API
to write a routine that interacted with the DBMS.
4. Java data objects convert the routine into low-level messages that conform to the JDBC driver
specification and send them to the JDBC driver.
5. The JDBC driver translates the routine into low-level messages that are understood and
processed by the DBMS.
2. Translate low-level equivalents of SQL statements sent by the j2EE component into
messages that can be processed by DBMS.
3. Return data that conforms to the JDBC specification to the JDBC driver.
4. Return info such as error messages that conforms to the JDBC specification to the JDBC
driver.
KNSIT Page 1
1. JDBC driver specification classifies JDBC drivers into four groups.
They are
1. Microsoft created ODBC (Open Database Connection), which is the basis from which Sun
created JDBC. Both have similar driver specifications and an API.
2. The JDBC-to-ODBC driver, also called the JDBC/ODBC Bridge, is used to translate DBMS
calls between the JDBC specification and the ODBC specification.
3. The JDBC-to-ODBC driver receives messages from a J2EE component that conforms to the
JDBC specification and are translated by the JDBC-to-ODBC driver into the ODBC message
format & later to the format understood by the DBMS.
1. The Java/Native Code driver uses Java classes to generate platform- specific code, that is code
only understood by a specific DBMS.
2. The disadvantage of using a Java/Native Code driver is the loss of some portability of code.
3. The API classes for the Java/Native Code driver probably wont work with another
manufacturers DBMS.
1. Also referred to as the Java Protocol, most commonly used JDBC driver.
2. The Type 3 JDBC driver converts SQL queries into JDBC- formatted statements, in-turn they are
translated into the format required by the DBMS.
2. The driver is similar to Type 3 JDBC driver except SQL queries are translated into the format
required by the DBMS.
JDBC Packages
1. The JDBC API is contained in two packages.
2. The first package is called java.sql and contains core Java data objects of the JDBC API. java.sql
is part of the J2SE
KNSIT Page 2
3. These include Java data objects that provide the basic for connecting to the DBMS and
interacting with data stored in the DBMS.
javax.sql includes the data objects that interact with Java Naming and Directory Interface
(JNDI) and Java data objects that manage connection pooling, among other advanced JDBC
features
1. Though each J2EE component is different, J2EE components use a similar process for interacting
with a DBMS.
1. The JDBC driver must be loaded before the J2EE component can connect to the DBMS.
2. The developer must write a routine that loads the JDBC/ODBC Bridge driver called
sun.jdbc.odbc.JdbcOdbcDriver to work offline and interact with the Microsoft Access on his PC.
3. The driver is loaded by calling the Class.forName() method and passing it the name of the
driver.
Class.forName( sun.jdbc.odbc.JdbcOdbcDriver);
1. Once the driver is loaded, the J2EE component must connect to the DBMS using the
DriverManager.getConnection() method.
The java.sql.DriverManager class is the highest class in the java.sql hierarchy and is responsible for
managing driver information
KNSIT Page 3
String url =
"jdbc:odbc:CustomerInformation";
String userID = "jim";
String password = "keogh";
Statement DataRequest;
private Connection Db;
try
{
Class.forName("sun.jdbc.odbc.JdbcOdbcD
river");
Db =
DriverManager.getConnection(url,userID,pass
word);
}
1. The DriverManager.getConnection() method is passed with the URL of the database, the user ID
and the password if required by DBMS.
2. The URL is a string object that contains the driver name and the name of the database that is
being accessed by the J2EE component.
4. The java.sql.Connection is another interface manages communication between the driver and
the J2EE component.
KNSIT Page 4
1. Next is we have to send a SQL query to the DBMS for processing.
2. A SQL query consists of a series of SQL commands that direct the DBMS to do something such
as to return a rows of data to the J2EE component.
4. The Statement object is then used to execute a query and return a ResultSet object that contains
the response from the DBMS, which is usually one or more rows of information requested by
J2EE component.
5. Once the ResultSet is received from the DBMS, the close() method is called to terminate the
statement.
Statement DataRequest;
ResultSet Results
try
{
String query = " SELECT * FROM
Customers";
DataRequest = Db.createStatement();
Results =
DataRequest.executeQuery(query);
DataRequest.close();
}
Process Data Returned by the DBMS
1. The java.sql.ResultSet object is assigned the result received from the DBMS after the query is
processed.
The java.sql.ResultSet object consists of methods used to interact with data that is returned by the
DBMS to the J2EE component
KNSIT Page 5
ResultSet Results;
String FirstName, LastName, printrow;
boolean Records = Results.next();
if(!Records)
{
System.out.println("No data returned.");
return;
}
else
{
while(Results.next())
{
FirstName = Results.getString(FirstName);
LastName = Results.getString(LastName);
printrow = FirstName + " " + LastName;
System.out.println(printrow);
}
}
Terminate The Connection to the DBMS
1. The connection to the DBMS is terminated by using the close()method of the Connection object
once the J2EE component is finished accessing the DBMS.
KNSIT Page 6
2. The close() method throws an exception if a problem is encountered when disengaging the
DBMS.
Db.close();
KNSIT Page 7
// create statement
Statement s = c.createStatement( );
// execute statement and return resultset &
stored in object
ResultSet r = s.executeQuery("SELECT ename,
eid, addr FROM emp") ;
// iterate the result set
while(r.next())
{
System. out.println (r.getString ("ename")
+"," + r.getString ("eid") +" : "+
r.getString("addr")) ;
}
s.close( ) ;
}catch(Exception e)
{
System.out.println("Could not establish
connection") ;
}
}
}
KNSIT Page 8
Example Program : Connecting to MySql
import java.sql.*;
import java.io.*;
public class DCMysql
{
public static void main (String args[])
{
String url ="jdbc:mysql://localhost:3306/sample";
String user = "root";
String password = "hemanth";
try
{
// load the driver
Class.forName("com.mysql.jdbc.Driver") ;
// create connection.
Connection c = DriverManager.getConnection(url,user,pa
KNSIT Page 9
// create statement
Statement s = c.createStatement( );
// execute statement and return resultset &
stored in object
ResultSet r = s.executeQuery("SELECT
ename, eid, addr FROM emp") ;
// iterate the result set
while(r.next())
{
System. out.println (r.getString ("ename")
+"," + r.getString ("eid") +" : "+
r.getString("addr")) ;
}
s.close( ) ;
}catch(Exception e)
{
System.out.println("Could not establish
connection") ;
}
}
}
Database Connection
1. A J2EE component does not directly connect to DBMS. Instead, the J2EE component connects
with the JDBC driver that is associated with the DBMS.
2. Before the connection is made, the JDBC driver must be loaded and registered with the
DriverManager.
KNSIT Page 10
3. The purpose of loading and registering the JDBC driver is to bring the JDBC driver into the
Java Virtual Machine (JVM).
try
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
}catch (ClassNotFoundException e)
{
System.out.println("Unable to load the JDBC/ODBC
bridge."+e.getMessage());
System.eixt(1);
}
The Connection
1. After the JDBC driver is loaded & registered, the J2EE component must connect to the database.
2. The data source that the JDBC component will connect to is defined using the URL format. The
URL consists of three pats.
1. jdbc which indicates that JDBC protocol is to be used to read the URL.
3. The connection to the database is established by getConnection(), which requests access to the
database from the DBMS.
1. If username & password is required then those information need to be supplied to access the
database.
Connection c = DriverManager.getConnection(url,userID,password) ;
1. Sometimes a DBMS requires extra information besides userID & password to grant access to the
database.
KNSIT Page 11
2. This additional information is referred as properties and must be associated with Properties ob
Sometimes DBMS grants access to a database to anyone without using username or password.
Connection c = DriverManager.getConnection(url) ;
Properties used to access a database are stored in a text file, contents of which are defined by the DBMS
manufacturer
The J2EE component uses a FileInputStream object to open the file and then uses the Properties object
load() method to copy the properties into a Properties object.
KNSIT Page 12
Connection Db;
Properties props = new Properties();
try
{
FileInputStream propFS = new
FileInputStream("DBProps.txt");
props.load(propFS);
}
catch (Exception e){}
try
{
Class.forName("sun.jdbc.odbc.JdbcOdbcD
river");
Db=DriverManager.getConnection(url,pro
ps);
}
catch (Exception e){}
TimeOut
1. The DBMS may not respond quickly for a number of reasons,which might include that database
connections are not available.
2. Rather than waiting for a delayed response from the DBMS, the J2EE component can set a
timeout period after which the DriverManager will cease to attempt to connect to the database.
KNSIT Page 13
3. The public static void DriverManager.setLoginTimeout(int seconds) method can be used by the
J2EE component to establish the maximum time the DriverManager waits for a response from a
DBMS before timing out.
1. We use the ODBC Data Source Administrator to create the association between the database and
the JDBC/ODBC bridge.
4. Select the driver then select Finish. Use the Microsoft Access Driver if we are using Microsoft
Access; otherwise, select the driver for the DBMS that we are using. If we dont find the driver of
our DBMS on the list, we need to install the driver.
5. Enter the name of the database as the Data Source name in the ODBC Microsoft Access Setup
dialog box. This name will be used within the java database program to connect to the DBMS.
6. Enter a description for the data source. This is optional, but will be a reminder of the kind of data
that is stored in database.
7. . Click the Select button. We will be prompted to browse the directory of each hard drive
connected to our computer in order to define the direct path to the database. Click OK once we
locate the database. Then directory path and the name of the database will be displayed in the
ODBC Microsoft Access Setup dialog box.
8. Since this is our database, we can determine if a login name and password is required to access
the database.
9. If so, then click the Advanced button to display the Set Advanced Options dialog box.
10. When the ODBC Microsoft Access Setup dialog box appears, select Ok.
11. Select Ok to close the ODBC Data Source Administrator dialog box.
Once a connection to the database is opened, the J2EE component creates and sends a query to
access data contained in the database.
KNSIT Page 14
These objects are Statement, which executes a query immediately.
1. The Statement object is used whenever J2EE component needs to immediately execute a query
without first having the query compiled.
2. The Statement object contains the executeQuery() method, which passes the query as an
argument. The query is then transmitted to the DBMS for processing.
3. The executeQuery() method returns one ResultSet object that contains rows, columns, and
metadata that represents data requested by query.
4. The execute() method is used when there may be multiple results returned.
The executedUpdate() method returns an integer indicating the number of rows that were updated by
the query.
KNSIT Page 15
String url = "jdbc:odbc:CustomerInformation";
String userID = "jim";
String password = "keogh";
Statement DataRequest;
ResultSet Results;
Connection Db;
try
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Db =
DriverManager.getConnection(url,userID,password);
}catch(Exception e){}
Try
{
String query = SELECT * FROM Customers;
DataRequest = Db.createStatement();
Results = DataRequest.executeQuery(query);
// place code here to interact with the Resutls.
DataRequest.close();
}
KNSIT Page 16
Next is how to use the executeUpdate() of the State
String url = "jdbc:odbc:CustomerInformation";
String userID = "jim";
String password = "keogh";
Statement DataRequest;
int rowsUpdated;
Connection Db;
try
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Db = DriverManager.getConnection(url,userID,password);
}catch(Exception e){}
Try
{
String query = UPDATE Customers SET PAID=Y WHERE
BALANCE=0 ;
DataRequest = Db.createStatement();
rowsUpdated = DataRequest.executeUpdate(query);
DataRequest.close();
}
Db.close();
PreparedStatement Object
1. A SQL query can be precompiled and executed by using the PreparedStatement object.
2. Here a query is created as usual, but a question mark is used as a placeholder for a value that is
inserted into the query after the query is compiled.
KNSIT Page 17
3. The preparedStatement() method of Connection object is called to return the PreparedStatement
object. The preparedStatement() method is passed the query, which is then precompiled.
KNSIT Page 18
1. The CallableStatement object is used to call a stored procedure from within a J2EE object.
3. The type and style of code depends on the DBMS vendor and can be written in PL/SQL,
Transact-SQL, C, or other programming languages.
4. IN, OUT and INOUT are the three parameters used by the CallableStatement object to call a
stored procedure.
5. The IN parameter contains any data that needs to be passed to the stored procedure and whose
value is assigned using the setxxx() method.
6. The OUT parameter contains the value returned by the stored procedures. The OUT parameters
must be registered using the registerOutParameter() method, later retrieved by using the getxxx()
7. The INOUT parameter is a single parameter that is used to pass information to the stored
procedure and retrieve information from the stored procedure.
Connection Db;
try
{
String query = "{CALL LastOrderNumber (?))}";
CallableStatement cstatement = Db.prepareCall(que
cstatement.registerOutParameter(1,Types.VARCHA
cstatement.eqecute();
String lastOrderNumber = cstatement.getString(1);
cstatement.close();
}
catch (Exception e){}
ResultSet
KNSIT Page 19
1. The ResultSet object contains methods that are used to copy data from the ResultSet into a Java
collection object or variable for further processsing.
2. Data in a ResultSet is logically organized into a virtual table consisting of rows and columns.
3. The ResultSet uses a virtual cursor to point to a row of the virtual table.
4. The virtual cursor is positioned above the first row of data when the ResultSet is returned by the
executeQuery(). This means the virtual cursor must be moved to the frist row using the next()
method.
5. The next() returns a boolean true if the row contains data; else false.
6. Once the virtual cursor points to a row, the getxxx() is used to copy data from the row to a
collection, object or a variable.
KNSIT Page 20
Reading The ResultSet
ResultSet Results;
String FirstName, LastName, printrow;
boolean Records = Results.next();
if(!Records)
{
System.out.println("No data returned.");
return;
}
else
{
while(Results.next())
{
FirstName = Results.getString(1);
LastName = Results.getString(2);
printrow = FirstName + " " + LastName;
System.out.println(printrow);
}
}
Scrollable Resultset
1. In JDBC 2.1 API the virtual cursor can be moved backwards or positioned at a specific row.
2. Six methods are there for Resultset object. They are first(), last(), previous(), absolute(),
relative() and getrow().
3. first() method moves the virtual cursor to the first row in the Resultset.
4. last() method positions the virtual cursor at the last row in the Resultset
KNSIT Page 21
5. previous() method moves the virtual cursor to the previous row.
6. absolute() method positions the virtual cursor to a specified row by the an integer value passed
to the method.
7. relative() method moves the virtual cursor the specified number of rows contained in the
parameter.
2. The getRow() method returns an integer that represents the number of the current row in the
Resultset.
3. To handle the scrollable ResultSet , a constant value is passed to the Statement object that is
created using the createStatement(). Three constants.
- TYPE_FORWARD_ONLY
- TYPE_SCROLL_INSENSITIVE
- TYPE_SCROLL_SENSITIVE
The other two allow the virtual cursor to move in both directions
Updatable ResultSet
1. Rows contained in the ResultSet can be updatable similar to how rows in a table can be updated.
2. This is possible by passing the createStatement() method of the Connection object the
CONCUR_UPDATABLE.
5. These are updating values in a row, deleting a row, and inserting a new row.
Update ResultSet
1. Once the executeQuery() of the Statement object returns a ResultSet, the updatexxx() is used to
change the value of column in the current row of the ResultSet.
2. The xxx in the updatexxx() is replaced with the data type of the column that is to be updated.
KNSIT Page 22
3. The updatexxx() requires two parameters. The first is either the number or name of the column
of the ResultSet that is being updated and the second is the value that will replace the value in the
column of the ResultSet.
4. A value in a column of the ResultSet can be replaced with a NULL value by using the
updateNull(). It requires one parameter, which is the number of column in the current row of the
ResultSet. The updateNull() dont accept name of the column as a parameter.
KNSIT Page 23
try
{
String query = "SELECT FirstName, LastName FROM C
WHERE FirstName='Mary' and LastName='Smith'";
DataRequest = Db.createStatement(ResultSet.CONCUR_
Resulsts = DataRequest.executeQuery(query);
}
catch (Exception e){}
boolean Records = Results.next();
if(!Records) from
{ LY
System.out.println("No data returned."); ltSet.
System.exit(4);
}
try
{
Results.updateString("Lastname", "Smith");
Results.updateRow();
DataRequest.close();
}
catch (){}
KNSIT Page 24
2. The deleteRow() is passed an integer that contains the number of the row to be deleted.
3. First use the absolute() method to move the virtual cursor to the row in the Resultset that should
be deleted.
4. The value of that row should be examined by the program to assure it is the proper row before
the deleteRow() is called.
5. The deleteRow() is then passed a zero integer indicating that the current row must be deleted.
Resuts.deleteRow(0);
1. Inserting a row into the ResultSet is accomplished using basically the same technique as is used
to update the ResultSet.
2. The updatexxx() is used to specify the column and value that will place into the column of the
ResultSet.
3. The insertRow() is called after the updatexxx(), which causes a new row to be inserted into the
ResultSet.
KNSIT Page 25
try
{
String query = "SELECT FirstName, LastName FROM Custo
DataRequest = Db.createStatement(ResultSet.CONCUR_UPD
Resulsts = DataRequest.executeQuery(query);
}
catch (Exception e){}
boolean Records = Results.next();
if(!Records)
{
System.out.println("No data returned.");
System.exit(4);
}
try
{
Results.updateString(1, "Smith");
Results.updateString(2, Tom);
Results.insertRow();
DataRequest.close();
}
catch (){}
Transaction Processing
2. A database transaction consists of a set of SQL statements, each of which must be successfully
completed for the transaction to be completed.
KNSIT Page 26
3. If any one fails, then the transaction must be rolled back.
4. The database transaction is not completed until the J2EE component calls the commit() method
of the Connection object.
5. The commit() method must be called regardless if the SQL statement is part of a transaction or
not.
6. The commit() method was automatically called in the previous examples because the DBMS
has an AutoCommit feature that is by default set to true.
Once the transaction is completed, the setAutoCommit() method is called again by passing a true
parameter
KNSIT Page 27
try
{
Db.setAutoCommit(false);
String query1 = "UPDATE Customers SET Street =
'5 Main Street'"+ "WHERE FirstName='Bob'";
String query2 = "UPDATE Customers SET Street =
'10 Main Street'"+ "WHERE FirstName='Tim'";
DataRequest1=Db.createStatement();
DataRequest2=Db.createStatement();
DataRequest1.executeUpdate(quiery1);
DataRequest2.executeUpdate(quiery2);
Db.commit();
DataRequest1.close();
DataRequest2.close();
Db.close();
}
catch (SQLException ex){ }
1. The J2EE component can control the number of tasks that are rolled back by using savepoints.
2. There can be many savepoints used in a transactions. Each savepoint is identified by a unique
name.
The savepoint name is then passed to the rollback() method to specify the point within the transaction
where the rollback is to stop
KNSIT Page 28
String url = "jdbc:odbc:CustomerInformation";
String userID = "jim";
String password = "keogh";
Statement DataRequest1, DataRequest2;
Connection Db;
try
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Db =
DriverManager.getConnection(url,userID,password);
}catch(Exception e){}
KNSIT Page 29
try
{
Db.setAutoCommit(false);
String query1 = "UPDATE Customers SET Street =
'5 Main Street'"+ "WHERE FirstName='Bob'";
String query2 = "UPDATE Customers SET Street =
'10 Main Street'"+ "WHERE FirstName='Tim'";
DataRequest1=Db.createStatement();
Savepoint s1 = Db.setSavepoint("sp1");
DataRequest2=Db.createStatement();
DataRequest1.executeUpdate(quiery1);
DataRequest2.executeUpdate(quiery2);
Db.commit();
DataRequest1.close();
DataRequest2.close();
Db.releaseSavepoint("sp1");
Db.close();
}
catch (SQLException ex){ }
1. Another way to combine SQL statements into a transaction is to batch together these statements
into a single transaction and then execute the entire transaction.
2. This can be done using the addBatch() method of the Statement object.
3. The addBatch() method receives a SQL statement as a parameter and places the SQL statements
in the batch.
4. Once all the SQL statements ahat comprises the transaction are included in the batch, the
executeBatch() method is called to execute the entire batch at the same time.
KNSIT Page 30
The executeBatch() method returns an int array that contains the number of SQL statements that were
executed successfully
KNSIT Page 31
Db.setAutoCommit(false);
String query1 = "UPDATE Customers SET Street =
'5 Main Street'"+ "WHERE FirstName='Bob'";
String query2 = "UPDATE Customers SET Street =
'10 Main Street'"+ "WHERE FirstName='Tim'";
DataRequest=Db.createStatement();
DataRequest1.addBatch(query1);
DataRequest2.addBatch(query2);
int[] updated = DataRequest.executeBatch();
Db.commit();
DataRequest1.close();
DataRequest2.close();
Db.close();
}
catch (SQLException ex){ }
ResultSet Holdability
1. Whenever the commit() method is called, all ResultSet objects that were created for the
transaction are closed.
2. Sometimes a J2EE component needs to keep the ResultSet open even after the commit() method
is called.
3. We can control whether or not ResultSet objects are closed following the call to the commit()
method by passing oen of two constants to the createStatement() method.
KNSIT Page 32
6. CLOSE_CURSORS_AT_COMMIT closes ResultSet objects when the commit() method is
called.
RowSets
1. The JDBC RowSets object is used to encapsulate a ResultSet for use with Enterprise Java
Bean(EJB).
2. A RowSet object contains rows of data from a table(s) that can be used in a disconnected
operation.
Auto-Generated Keys
1. It is common for a DBMS to automatically generate unique keys for a table as rows are inserted
into the table.
2. The getGeneratedKeys() method of the Statement object is called to return keys generated by the
DBMS.
3. The getGeneratedKeys() returns a ResultSet object and can use the ResultSet.getMetaData() to
retrieve metadata relating to the automatically generated key.
Metadata
1. Metadata is data about data. A J2EE component can access metadata using the
DatabaseMetaData interface.
2. The DatabaseMetaData interface is used to retrieve information about database, tables, columns,
and indexes among other information about the DBMS.
ResultSet Metadata
1. There are 2 types of metadata that can be retrieved from the DBMS.
KNSIT Page 33
2. These are metadata that describes the database mentioned earlier and metadata that describes the
ResultSet.
1. ResultSetMetadata rm = Result.getMetaData()
6. getColumnName() gets the name of the column specified by the column number.
7. getColumnType(int number) gets the data type of the column specifed by the column number.
KNSIT Page 34
Data Types
Table contains a list of data
types and their java equivalents.
We can use this list to
determine the proper data name
to use to replace the xxx in the
setxxx() and getxxx() methods.
Exceptions
1. There are three kinds of exceptions that are thrown by JDBC methods.
KNSIT Page 35
3. SQLExceptions commonly reflect a SQL syntax error in the query and are thrown by many of
the methods contained in the java.sql package.
4. The SQLWarning throws warnings received by the Connection from the DBMS.
5. The getWarnings() and getNextWarning() methods of Connection object retrieves warnings and
subsequent warnings respectively.
6. DataTruncation exception is thrown whenever data is lost due to truncation of data value.
END OF JDBC
2. Servlets are server side components that provides a powerful mechanism for developing server
web applications for server side.
3. Just as applets dynamically extend the functionality of a Web browser, servlets dynamically
extend the functionality of a Web server.
4. Using servlets web developers can create fast and efficient server side applications and can run
it on any servlet enabled web server.
6. Since the servlet runs on server side so it does not depend on browser compatibility.
KNSIT Page 36
Background
In order to understand the advantages of servlets,
a
basic understanding of how Web browsers and ser
to
provide content to a user. Webserver maps
Requests for a static web page through web specific file & i
browser & it will generate the HTTP HTTP response
request to appropriate web server.
Client
The HTTP header in response
indicate the type of the content &
MIME is used for this purpose.
1. But the content of the dynamic web pages need to be generated dynamically.
2. In the early days of the Web, a server could dynamically construct a page by creating a separate
process to handle each client request.
3. The process would open connections to one or more databases in order to obtain the necessary
information.
KNSIT Page 37
4. It communicated with the Web server via an interface known as the Common Gateway Interface
(CGI).
5. CGI allowed the separate process to read data from the HTTP request and write data to the
HTTP response.
6. However, CGI suffered serious performance problems. It was expensive in terms of processor
and memory resources to create a separate process for each client request.
It was also expensive to open and close database connections for each client request. In addition, the CGI
programs were not platform-independent. Therefore, other techniques were introduced
4. Third, the Java security manager on the server enforces a set of restrictions to protect the
resources on a server machine.
5. Finally, the full functionality of the Java class libraries is available to a servlet. It can
communicate with applets, databases, or other software via the sockets and RMI mechanisms.
1. init( ), service( ), and destroy( ) are the three methods which are central to the life cycle of a
servlet.
2. They are implemented by every servlet and are invoked at specific times by the server.
KNSIT Page 38
3. Let us consider a user scenario to understand when these methods are called.
4. First, user enters URL, browser then generates an HTTP request for this URL, & this request is
then sent to the appropriate server.
5. second, this HTTP request is received by web server, web server maps this request to a
particular servlet. The servlet is dynamically retrieved & loaded into the address space of the
server.
6. Third, server invokes init( ) method of the servlet. This method is invoked only when the servlet
is first loaded into memory. It is possible to pass initialization parameters to the servlet so it may
configure itself.
7. Fourth, the server invokes the service( ) method of the servlet. This method is called to process
the HTTP request. It may also formulate an HTTP response for the client. The service( ) method
is called for each HTTP request.
8. Finally, the server may decide to unload the servlet from its memory.The server calls the destroy(
) method to relinquish any resources such as file handles that are allocated for the servlet.
A Simple Servlet
2. Start Tomcat.
KNSIT Page 39
This package contains the
A Simple Servlet Code interfaces required to build
import java.io.*;
import javax.servlet.*;
public class HelloServlet extends GenericServlet
{
public void service(ServletRequest request, ServletR
response)throws ServletException, I
{
response.setContentType("text/html");
PrintWriter pw = response.getWriter();
pw.println("<B>Hello!");
pw.close();
}
} Enables the servlet to formulate
the client.
getWriter() obtains PrintWr
written to this stream is sent t
of HTTP response.
GRNICA
1. javax.servlet and javax.servlet.http are the two packages that contains the classes required to
build servlet.
KNSIT Page 40
2. These packages are not part of Java core packages, they are standard extensions provided by
Tomcat.
4. The Servlet API is supported by most Web servers, such as those from Sun, Microsoft, and
others.
1. The javax.servlet package contains a number of interfaces and classes that establish the
framework in which servlets operate.
2. The following table summarizes the core interfaces that are provided in this package.
GRNICA
KNSIT Page 41
The ServletConfig Interface
3. There is only one ServletContext for the entire web application and the components of the web
application can share it.
KNSIT Page 42
5. Each servlet will have its own ServletConfig.
6. The ServetContext is created by the container when the web application is deployed and after
that only the context is available to each servlet in the web application.
KNSIT Page 43
The ServletResponse Interface
KNSIT Page 44
The following table summarizes the core classes that are provided
in the javax.servlet package.
1. The GenericServlet class provides implementations of the basic life cycle methods for a servlet.
3. In addition, a method to append a string to the server log file is available. The signatures of this
method are shown here:
void log(String s)
1. Here, s is the string to be appended to the log, and e is an exception that occurred.
2. A method is provided to read bytes from the stream. Its signature isshown here:
3. Here, buffer is the array into which size bytes are placed starting at
offset.
KNSIT Page 45
The ServletOutputStream Class
2. It is implemented by the server and provides an output stream that a servlet developer can use to
write data to a client response.
3. A default constructor is defined. It also defines the print( ) and println( ) methods, which output
data to the stream.
2. The first is ServletException, which indicates that a servlet problem has occurred.
1. The ServletRequest class includes methods that allow you to readthe names and values of
parameters that are included in a client request.
2. The example contains two files. A Web page is defined in PostParameters.htm and a servlet is
defined in PostParametersServlet.java.
KNSIT Page 46
<html>
<body>
<center>
<form name="Form1" method="post
action="http://localhost:8080/grnica/PostParametersS
<table>
<tr>
<td><B>Employee</td>
<td><input type=textbox name="e" size="25" value=
</tr>
<tr>
<td><B>Phone</td>
<td><input type=textbox name="p" size="25" value
</tr>
</table>
<input type=submit value="Submit">
</body>
</html>
GRNICA
KNSIT Page 47
import java.io.*;
import java.util.*;
import javax.servlet.*;
public class PostParametersServlet extends
GenericServlet
{
public void service(ServletRequest request,
ServletResponse response)
throws ServletException, IOException {
// Get print writer.
PrintWriter pw = response.getWriter();
// Get enumeration of parameter names.
Enumeration e =
request.getParameterNames();
KNSIT Page 48
// Display parameter names and values.
while(e.hasMoreElements())
{
String pname = (String)e.nextElement();
pw.print(pname + " = ");
String pvalue =
request.getParameter(pname);
pw.println(pvalue);
}
pw.close();
}
}
The javax.servlet.http Package
KNSIT Page 49
1. The HttpServletRequest interface is implemented by the server. It enables a servlet to obtain
information about a client request.
KNSIT Page 50
KNSIT Page 51
The HttpServletResponse Interface
2. Several constants are defined. These correspond to the different status codes that can be
assigned to an HTTP response.
3. For example, SC_OK indicates that the HTTP request succeeded and SC_NOT_FOUND
indicates that the requested resource is not available.
KNSIT Page 52
The HttpSession Interface
1. The HttpSession interface is implemented by the server. It enables a servlet to read and write the
state information that is associated with an HTTP session.
KNSIT Page 53
The HttpSessionBindingListener Interface
2. The methods that are invoked when an object is bound or unbound are:
void
valueBound(HttpSessionBindingEvent e)
void
valueUnbound(HttpSessionBindingEvent e)
1. The Cookie class encapsulates a cookie. A cookie is stored on a client and contains state
information.
3. For example, assume that a user visits an online store. A cookie can save the users name,
address, and other information. The user does not need to enter this data each time he or she
visits the store.
4. A servlet can write a cookie to a users machine via the addCookie( ) method of the
HttpServletResponse interface.
5. The names and values of cookies are stored on the users machine. Some of the information that
is saved for each cookie includes the following:
KNSIT Page 54
The name of the cookie
1. The expiration date determines when this cookie is deleted from the users machine.
2. If an expiration date is not explicitly assigned to a cookie, it is deleted when the current browser
session ends. Otherwise, the cookie is saved in a file on the users machine.
3. The domain and path of the cookie determine when it is included in the header of an HTTP
request.
4. There is one constructor for Cookie. It has the signature shown here:
Cookie(String name, String value)
5. Here, the name and value of the cookie are supplied as arguments to the constructor.
KNSIT Page 55
The HttpServlet Class
1. The HttpServlet class extends GenericServlet. It is commonly used when developing servlets that
receive and process HTTP requests.
KNSIT Page 56
The HttpSessionEvent Class
KNSIT Page 57
1. The HttpSessionBindingEvent class extends HttpSessionEvent. It is generated when a listener is
bound to or unbound from a value in an HttpSession object.
4. Here, session is the source of the event and name is the name associated with the object that is
being bound or unbound. If an attribute is being bound or unbound, its value is passed in val.
5. The getName( ) method obtains the name that is being bound or unbound. Its is shown here:
String getName( )
6. The getSession( ) method, obtains the session to which the listener is being bound or unbound:
HttpSession getSession( )
7. The getValue( ) method obtains the value of the attribute that is being bound or unbound. It is
shown here:
Object getValue( )
1. The HttpServlet class provides specialized methods that handle the various types of HTTP
requests.
2. These methods are doDelete( ), doGet( ), doHead( ), doOptions( ), doPost( ), doPut( ), and
doTrace( ).
KNSIT Page 58
<html>
<body>
<center>
<form name="Form1"
action="http://localhost:8080/jnnce/ColorGetServlet">
<B>Color:</B>
<select name="color" size="1">
<option value="Red">Red</option>
<option value="Green">Green</option>
<option value="Blue">Blue</option>
</select>
<br><br>
<input type=submit value="Submit">
</form>
</body>
</html>
KNSIT Page 59
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class ColorGetServlet extends
HttpServlet {
public void doGet(HttpServletRequest
request,
HttpServletResponse response)
throws ServletException, IOException {
String color =
request.getParameter("color");
response.setContentType("text/html");
PrintWriter pw = response.getWriter();
pw.println("<B>The selected color is: ");
pw.println(color);
pw.close();
}
}
Handling HTTP POST Requests
KNSIT Page 60
1. Here we will develop a servlet that handles an HTTP POST request. The servlet is invoked when
a form on a Web page is submitted.
The example contains two files. A Web page is defined in ColorPost.htm and a servlet is defined in
ColorPostServlet.java
<html>
<body>
<center>
<form name="Form1"
method="post"
action="http://localhost:8080/jnnce/ColorPostServlet">
<B>Color:</B>
<select name="color" size="1">
<option value="Red">Red</option>
<option value="Green">Green</option>
<option value="Blue">Blue</option>
</select>
<br><br>
<input type=submit value="Submit">
</form>
</body>
</html>
KNSIT Page 61
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class ColorPostServlet extends HttpServlet {
public void doPost(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
String color = request.getParameter("color");
response.setContentType("text/html");
PrintWriter pw = response.getWriter();
pw.println("<B>The selected color is: ");
pw.println(color);
pw.close();
}
}
GRNICA
Using Cookies
KNSIT Page 62
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class ColorPostServlet extends HttpServlet {
public void doPost(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
String color = request.getParameter("color");
response.setContentType("text/html");
PrintWriter pw = response.getWriter();
pw.println("<B>The selected color is: ");
pw.println(color);
pw.close();
}
}
GRNICA
KNSIT Page 63
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class AddCookieServlet extends HttpServlet {
public void doPost(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
// Get parameter from HTTP request.
String data = request.getParameter("data");
KNSIT Page 64
// Create cookie.
Cookie cookie = new Cookie("MyCookie",
data);
// Add cookie to HTTP response.
response.addCookie(cookie);
// Write output to browser.
response.setContentType("text/html");
PrintWriter pw = response.getWriter();
pw.println("<B>MyCookie has been set
to");
pw.println(data);
pw.close();
}
}
KNSIT Page 65
GetCookiesServlet.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class GetCookiesServlet extends HttpServlet
{
public void doGet(HttpServletRequest request,
HttpServletResponse response) throws
ServletException, IOException
{
// Get cookies from header of HTTP request.
Cookie[] cookies = request.getCookies();
// Display these cookies.
response.setContentType("text/html");
PrintWriter pw = response.getWriter();
pw.println("<B>");
KNSIT Page 66
for(int i = 0; i < cookies.length; i++)
{
String name =
cookies[i].getName();
String value =
cookies[i].getValue();
pw.println("name = " + name + ";
value = " + value);
}
pw.close();
}
}
Session Tracking
2. However, in some applications, it is necessary to save state information so that information can
be collected from several interactions between a browser and a server. Sessions provide
such a mechanism.
4. An HttpSession object is returned. This object can store a set of bindings that associate names
with objects.
KNSIT Page 67
import java.io.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class DateServlet extends HttpServlet {
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
Gets t
// Get the HttpSession object. sessio
HttpSession hs = request.getSession(true);
KNSIT Page 68
// Get writer. Call
response.setContentType("text/html"); obje
to th
PrintWriter pw = response.getWriter();
pw.print("<B>");
// Display date/time of last access.
Date date = (Date)hs.getAttribute("date");
if(date != null) {
pw.print("Last access: " + date + "<br>");
} This
to bi
// Display current date/time. date
date = new Date();
hs.setAttribute("date", date);
pw.println("Current date: " + date);
}
}
KNSIT Page 69
Servlet to check the session and get the session ID
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class CheckingTheSession extends HttpServlet
{
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException,
{
response.setContentType("text/html");
PrintWriter pw = response.getWriter();
pw.println("Checking whether the session is new or o
HttpSession session = request.getSession();
String id = session.getId();
pw.println("Session Id is : " + id);
KNSIT Page 70
if(session.isNew()){
pw.println("You have created a new
session");
}
else{
pw.println("Session already exists");
}
}
}
KNSIT Page 71
Servlets reads Username & password as parameters
<html>
<head>
<title>New Page 1</title>
</head>
<body>
<h2>Login</h2>
<p>Please enter your username and password</p>
<form method="GET action="http://localhost:8080/jnnce/LoginS
<p> Username <input type="text" name="username" size="20">
<p> Password <input type="password" name="password" size=
<p><input type="submit" value="Submit" name="B1"></p>
</form>
<p> </p>
</body>
</html>
KNSIT Page 72
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class LoginServlet extends HttpServlet
{
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException
{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String name = request.getParameter("username");
String pass = request.getParameter("password");
out.println("<html>");
out.println("<body>");
out.println("Thanks " + " " + name + " " + "for visiting our s
out.println("Now you can see your password : " + " " + pass +
out.println("</body></html>");
}
}
GRNICA
KNSIT Page 73
Usage of sendRedirect()
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class SendRedirectServlet extends HttpServlet
{
protected void doPost(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException
{
response.setContentType("text/html");
PrintWriter pw = response.getWriter();
KNSIT Page 74
String name =
request.getParameter("username");
String password =
request.getParameter("password");
if(name.equals("Hemanth")&&
password.equals("Kumar"))
{
response.sendRedirect("/jnnce/ValidUserServl
et");
}
else
{
pw.println("u r not a valid user");
}
}
}
KNSIT Page 75
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class ValidUserServlet extends
HttpServlet
{
protected void doGet(HttpServletRequest
request,
HttpServletResponse response)
throws ServletException, IOException
{
PrintWriter pw = response.getWriter();
pw.println("Welcome to grnica " + " ");
pw.println("how are you");
}
}
KNSIT Page 76
<html>
<head>
<title>New Page 1</title>
</head>
<body>
<form method="POST"
action="http://localhost:8080/jnnce/SendRedir
ectServlet">
<p>Enter your name
<input type="text" name="username"
size="20"></p>
<p>Enter your password <input
type="password" name="password"
size="20"></p>
<p><input type="submit" value="Submit"
name="B1"></p>
</form>
</body>
</html>
KNSIT Page 77
To download a file using servlet
import java.io.*;
import javax.servlet.*;
public class Download extends GenericServlet
{
public void service(ServletRequest request,ServletR
response)throws ServletException,IOException
{
response.setContentType("text/html");
PrintWriter pw=response.getWriter();
pw.println("<a href=/jnnce/photo.jpg> click he
download</a>");
pw.close();
}
}
RequestDispatcher
1. In some circumstances, you may want to include the content from an HTML page or the output
from another servlet.
2. Additionally, there are cases that require that you pass the processing of an HTTP request from
your servlet to another servlet.
KNSIT Page 78
3. The current servlet specification responds to these needs with an interface called
RequestDispatcher, which is found in the javax.servlet package.
4. This interface has two methods, which allow you to delegate the request-response processing to
another resource: include and forward.
1. As the name implies, the include method is used to include content from another resource, such
as another servlet, a JSP page, or an HTML page. The method has the following signature:
1. The forward method is used to forward a request from one servlet to another. The original
servlet can perform some initial tasks on the ServletRequest object before forwarding it. The
signature of the forward method is as follows:
KNSIT Page 79
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import java.util.*;
public class FirstServlet1 extends HttpServlet {
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
RequestDispatcher rd =
request.getRequestDispatcher("/user2.html");
rd.include(request, response);
}
}
GRNICA
KNSIT Page 80
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import java.util.*;
public class LoginServlet3 extends HttpServlet
{
public void doPost(HttpServletRequest
request,HttpServletResponse response)
throws ServletException, IOException
{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String userName =
request.getParameter("userName");
String password =
request.getParameter("password");
KNSIT Page 81
if (userName!=null && password!=null &&
userName.equals("jnnce") &&
password.equals("mca"))
{
RequestDispatcher rd =
request.getRequestDispatcher("WelcomeServl
et1");
rd.forward(request, response);
}
else
{
out.println(<B> Not a valid
user.");
}
}
}
KNSIT Page 82
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
public class WelcomeServlet1 extends HttpServlet {
public void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletExcept
IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<HTML>");
out.println("<BODY>");
out.println("<P>Welcome to the JNNMCA Web Site.
out.println("</BODY>");
out.println("</HTML>");
}
}
GRNICA
<HTML>
<HEAD>
<TITLE>Login</TITLE>
</HEAD><BODY
<p>Please enter your user name and password.
<p><form method="POST" action="http://localhost:8080/jnnce/LoginServlet3">
KNSIT Page 83
<p>User Name: <INPUT TYPE=TEXT
NAME=userName>
<p>Password: <INPUT
TYPE=PASSWORD NAME=password>
<p><INPUT TYPE=SUBMIT
VALUE=Submit>
</form>
</BODY>
</HTML>
Filter API
1. A filter is an object that can transform the header or content or both of a request or response.
2. Filters differ from Web components & in that they usually do not themselves create a response.
Instead, a filter provides functionality that can be "attached" to any kind of Web resource.
3. A filter should not have any dependencies on a Web resource for which it is acting as a filter, so
that it can be composable with more than one type of Web resource.
3. Modify the request headers and data. It is done by providing a customized version of the request.
4. Modify the response headers and data. It is done by providing a customized version of the
response.
7. The filtering API is defined by the Filter, FilterChain, and FilterConfig interfaces in
the javax.servlet package.
9. The most important method in this interface is the doFilter method, which is passed request,
response, and filter chain objects.
KNSIT Page 84
11. Customize the request object if it wishes to modify request headers or data.
12. Customize the response object if it wishes to modify response headers or data.
14. Examine response headers after it has invoked the next filter in the chain.
16. In addition to doFilter, we must implement the init and destroy methods.
17. The init method is called by the container when the filter is instantiated.
18. If we wish to pass initialization parameters to the filter, we retrieve them from
the FilterConfig object passed to init.
19. This example illustrates how one can write Logging Filter servlet to provide control over log
file. We can have additional controls over these log files and these all are available to use by
implementing "Filter" class.
20. We can create filter class by implementing javax.servlet.Filter, which has three methods as
follows:
1. It is called once by the server to get prepared for service and then it calls doFilter() a
number of times for request processing.
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public final class LoggingFilterExample implements Filter
{
private FilterConfig filterConfigObj = null;
public void init(FilterConfig filterConfigObj)
{
this.filterConfigObj = filterConfigObj;
KNSIT Page 85
}
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException
{
String remoteAddress = request.getRemoteAddr();
String uri = ((HttpServletRequest) request).getRequestURI();
String protocol = request.getProtocol();
chain.doFilter(request, response);
filterConfigObj.getServletContext().log("Logging Filter Servlet called");
filterConfigObj.getServletContext().log("********************************");
filterConfigObj.getServletContext().log("User Logged ! " +
" User IP: " + remoteAddress +" Resource File: " + uri + " Protocol: " + protocol );
}
public void destroy()
{}
}
<web-app>
<filter>
<filter-name>LoggingFilterExample</filter-name>
<filter-class>LoggingFilterExample</filter-class>
</filter>
<filter-mapping>
<filter-name>LoggingFilterExample</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
</web-app>
<html>
<head>
<title>EMPLOYEE DETAILS 1</title>
</head>
<body>
<form method="GET" action="ServletHtml">
<p>Enter Name: <input type="text" name="ename" size="20"></p>
<p>Enter EID: <input type="text" name="eid" size="20"></p>
<p>Enter ADDRESS : <input type="text" name="eaddr" size="30"></p>
<p><input type="submit" value="Submit" name="B1"></p>
</form>
</body>
</html>
package access;
import java.io.*;
import java.sql.*;
import javax.servlet.*;
KNSIT Page 86
import javax.servlet.http.*;
public class ServletHtml extends HttpServlet
{
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException,
IOException
{
response.setContentType("text/html");
PrintWriter pw = response.getWriter();
String url="jdbc:odbc:html";
Connection con;
try
{
String ename = request.getParameter("ename");
String eid = request.getParameter("eid");
String eaddr = request.getParameter("eaddr");
pw.println(ename);
pw.println(eid);
pw.println(eaddr);
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
con = DriverManager.getConnection(url);
PreparedStatement pst = con.prepareStatement("insert into emp_info values(?,?,?)");
pst.setString(1,ename);
pst.setString(2,eid);
pst.setString(3,eaddr);
int i = pst.executeUpdate();
if(i!=0)
{
pw.println("<br>Record has been inserted");
}
else
{
pw.println("failed to insert the data");
}
}
catch (Exception e)
{
pw.println(e);
}
}
}
KNSIT Page 87
END OF SERVLETS AND SESSION
KNSIT Page 88
4. A JSP is simple to create, a JSP is written in HTML rather tha with the Java
programming language.
5. A JSP offers basically the same features found in Java servlet because a JSP is converted
to a Java servlet the first time that aclient requests the JSP.
6. JSP pages are translated into servlets, the servlets are compiled, and at request time it is
the compiled servlets that execute. So,writing JSP pages is really just another way of
writing servlets.
7. jspInt(), jspDestroy() and service() are the three methods that are automatically called
when a JSP is requested and terminates normally.
8. The jspInt() is called first when the JSP is requested and is used to initialize objects and
variables that are used throughout the life of JSP.
9. The jspDestroy() is automatically called when the JSP terminates normally. When JSP
abruptly terminated, it is not called.
10. The service() is automatically called and retrieves a connection to HTTP.
Advantages of JSP
11. JSP are translated and compiled into JAVA servlets but are easier to develop than JAVA
servlets.
JSP uses simplified scripting language based syntax for embedding HTML into JSP.
JSP containers provide easy way for accessing standard objects and actions.
JSP reaps all the benefits provided by JAVA servlets and web container environment, but they
have an added advantage of being simpler and more natural program for web enabling enterprise
developer
JSP use HTTP as default request /response communication paradigm and thus make JSP ideal
as Web Enabling Technology.
JSP Tags
1. A JSP programs consists of a combination of HTML tags and JSP tags.
2. JSP tags define Java code that is to be executed before the output of the JSP program is
sent to the browser.
KNSIT Page 89
3. Java codes associated with JSP tags in the JSP program is executed when encountered by
Tomcat, and the result of that process is sent to the browser.
4. The browser knows how to display the result because the JSP tag is enclosed within an
open and closed HTML tag.
Example:
<HTML><HEAD>
<TITLE>Order Confirmation</TITLE>
</HEAD><BODY>
<%String userName=null
userName=request.getParameter("userName");
%>
</BODY></HTML>
14. Variables available to the JSP Scriptlets are:
KNSIT Page 90
15. request: request represents the clients request and is a subclass
of HttpServletRequest. Use this variable to retrieve the data
submitted along the request.
16. response: response is subclass of HttpServletResponse.
17. session: session represents the HTTP session object associated with
the request.
18. out: out is an object of output stream and is used to send any output
to the client.
Expression tags : It opens with <%= and is used for an expression statement. It closes with %>.
Syntax of JSP Expressions are: <%="Any thing" %>
<HTML><HEAD>
<TITLE>Example JSP Program</TITLE>
</HEAD><BODY>
<%="Hello World!" %> </BODY>
</HTML>
KNSIT Page 92
44. info: This attribute simply sets the information of the JSP page which is retrieved later by
using Servlet.getServletInfo() method. The value of the attribute will be a text string.
45. errorPage: This attribute sets a url. If any exception is generated then the attribute refers
to the file which is mentioned in the given url. If no url id specified, then the attribute
refers to the current page of the JSP application when exception generated
46. isErrorPage: This attribute sets the boolean value to either true or false. We can use the
exception object in the JSP page if we set the attribute value to true, otherwise we cannot
use the exception object because the default value of the attribute is false.
47. contentType: This attribute specifies the MIME type and the character encoding used
for the JSP response. The default MIME type is "text/html" and the default character set
is "ISO-88591".
48. pageEncoding: This attribute specifies the language that the page uses when the page is
sent to the browser. This attribute works like the meta tag of the HTML markup
language.
49. isELIgnored: This is a boolean attribute that specifies either true or false value. The
isELIgnored option gives you the ability to disable the evaluation of Expression
Language (EL) expressions which has been introduced in JSP 2.0. If we set the attribute
value to true, then any type of the EL expressions will be ignored in the JSP page.
2. <HTML><HEAD>
<TITLE> JSP Programming </TITLE>
</HEAD><BODY>
<%! int age=25;
float salary;
int empnumber;
%>
</BODY></HTML>
3. <HTML><HEAD>
<TITLE>JSP Programming </TITLE>
</HEAD><BODY>
KNSIT Page 93
<%! String Name;
String [] Telephone = {"201-555-1212", "201-555-4433"};
String Company = new String();
int[] Grade = {100,82,93};
%>
</BODY></HTML>
Methods
4. JSP offers same functionality for defining methods as done by Java.
5. In JSP a method definition is placed within a JSP tag.
6. We can call the method from within the JSP tag once the method is
defined.
7. The JSP tag that calls the method must be a JSP expression tag,
which begins with <%=.
8. <HTML><HEAD>
<TITLE> JSP Programming </TITLE>
</HEAD><BODY>
<%! int curve (int grade)
{
return 10 + grade;
}
int curve(int grade, int curvevalue)
{<HTML><HEAD>
<TITLE> JSP Programming </TITLE>
</HEAD><BODY>
<%! int curve (int grade)
{
return 10 + grade;
}
%>
<p> Your curved grade is : <%=curve(80)%> </p>
</BODY></HTML>
return curvevalue+grade;
}
%>
<p> Your curved grade is : <%=curve(80,10)%> </p>
<p> Your curved grade is : <%=curve(70)%> </p>
</BODY></HTML>
KNSIT Page 94
Control Statement
Using JSP it is easy to create dynamic content for a web page based on conditions
received from the browser.
9. There are two control statements used to change the flow of a JSP program. These are
the if statement and the switch statement, both of which are also used to direct the flow
of a Java program.
10. The power of these codes comes from the fact that the code segment that is executed or
skipped can consists of HTML tags or a combination of HTML tags and JSP tags.
<HTML>
<HEAD>
<TITLE> JSP Programming </TITLE>
</HEAD>
<BODY>
<%! int grade=70;%>
<% if(grade > 69 )
{ %>
<p> You Passed ! </p>
<% }
else { %>
<p> Better luck next time. </p>
<% } %>
<% switch (grade) {
case 90 : %>
<p> Your final grade is a A </p>
<% break;
case 80 : %>
<p> Your final grade is a B </p>
<% break;
case 70 : %>
<p> Your final grade is a C </p>
<% break;
case 60 : %>
<p> Your final grade is a D </p>
<% break;
}
%>
</BODY>
</HTML>
Loops
KNSIT Page 95
JSP loops are nearly identical to loops used in Java programs.
The for loop, while loop, and do.. While loop are the three loops.
Loops play an important role in JSP database programs
<html>
<head>
<title> JSP programming</title>
</head>
<body>
<center>
<%! int[] Grade = {100,82,93};
int x=0;
%>
<table>
<tr>
<td> First </td>
<td> Second </td>
<td> Third </td>
</tr>
<tr>
<% for(int i=0;i<3;i++) { %>
<td><%=Grade[i]%></td>
<% } %>
</tr>
</table>
<table>
<tr>
<td> First </td>
<td> Second </td>
<td> Third </td>
</tr>
<tr>
<% while(x<3) { %>
<td><%=Grade[x]%></td>
<% x++;
} %>
</tr>
</table>
<table>
<tr>
<td> First </td>
KNSIT Page 96
<td> Second </td>
<td> Third </td>
</tr>
<tr>
<% x=0; %>
<% do{ %>
<td><%=Grade[x]%></td>
<%x++; %>
<% }while(x<3); %>
</tr>
</table>
</center>
</body>
</html>
Tomcat
11. JSP programs are executed by JSP Virtual Machine that runs on a web server.
12. Hence there is a need to access to a JSP Virtual Machine to run the JSP programs.
13. One of the most popular JSP Virtual Machines is Tomcat, it is downloadable at free of
cost from www.jakarta.apache.org
14. Installing Java is also required.
15. Request String
16. The browser generates a user request string whenever the Submit button is selected. The
user request string consists of the URL and the query string.
17. http://www.jimkeogh.com/jsp/myprogram.jsp?fname=bob&lname=smith
18. Your program needs to parse the query string to extract values of fields that are to be
processed by your program. You can parse the query string by using methods of the JSP
request object.
19. The getParameter(Name) is the method used to parse a value of a specific field. The
getParameter() method requires an argument, which is the name of the field whose value
you want to retrieve.
Implicit Variables
KNSIT Page 97
20. Implicit objects in jsp are the objects that are created by the container automatically and
the container makes them available to the developers, the developer do not need to
create them explicitly.
21. Since these objects are created automatically by the container and are accessed using
standard variables; hence, they are called implicit objects.
22. The implicit objects are parsed by the container and inserted into the generated servlet
code.
23. They are available only within the jspService method and not in any declaration.
24. Implicit objects are used for different purposes. User defined methods can't access them
as they are local to the service method and are created at the conversion time of a jsp into
a servlet. But we can pass them to our own method if we wish to use them locally in
those functions.
25. Application: These objects has an application scope. These objects are available at the
widest context level, that allows to share the same information between the JSP page's
servlet and any Web components with in the same application.
26. Config: These object has a page scope and is an instance of javax.servlet.ServletConfig
class. Config object allows to pass the initialization data to a JSP page's servlet.
Parameters of this objects can be set in the deployment descriptor (web.xml) inside the
element <jsp-file>. The method getInitParameter() is used to access the initialization
parameters.
27. Exception: This object has a page scope and is an instance of java.lang.Throwable class.
This object allows the exception data to be accessed only by designated JSP "error
pages.
28. Out: This object allows us to access the servlet's output stream and has a page scope.
Out object is an instance of javax.servlet.jsp.JspWriter class. It provides the output
stream that enable access to the servlet's output stream.
29. Page: This object has a page scope and is an instance of the JSP page's servlet class that
processes the current request. Page object represents the current page that is used to call
the methods defined by the translated servlet class. First type cast the servlet before
accessing any method of the servlet through the page.
30. Pagecontext: PageContext has a page scope. Pagecontext is the context for the JSP page
itself that provides a single API to manage the various scoped attributes.
31. This API is extensively used if we are implementing JSP custom tag handlers.
PageContext also provides access to several page attributes like including some static
or dynamic resource.
KNSIT Page 98
32. Request: Request object has a request scope that is used to access the HTTP request data,
and also provides a context to associate the request-specific data.
33. Request object implements javax.servlet.ServletRequest interface. It uses the
getParameter() method to access the request parameter. The container passes this object
to the _jspService() method.
34. Response: This object has a page scope that allows direct access to the
HTTPServletResponse class object.Response object is an instance of the classes that
implements the javax.servlet.ServletResponse class. Container generates to this object
and passes to the _jspService() method as a parameter.
35. Session: Session object has a session scope that is an instance of
javax.servlet.http.HttpSession class. Perhaps it is the most commonly used object to
manage the state contexts. This object
persist information across multiple user connection.
36. There are four predefined implicit objects that are in every JSP
programs. These are request, response, session and out.
37. The request object is an instance of the HTTPServletRequest.
38. The response object is an instance of the HTTPServletResponse.
39. The session object is an instance of the HTTPSession.
40. The out object is an instance of the JSPWriter, used to send a
response to the client.
41. getParameterValues() method helps us to copy a value from a multivalued field such as a
selection list field.
42. <%! String[] EMAIL = request.getParameterValues(ADDR); %>
<P> <%=EMAIL [O]%> </P>
<P> <%=EMAIL [1]%> </P>
43. Field names in the request string can be parsed by using the
getParameterNames() method.
<HTML>
<HEAD>
<TITLE>Order Confirmation</TITLE>
</HEAD>
<BODY>
<H2>Order Confirmation</H2>
KNSIT Page 99
Thanks for ordering <I><%= request.getParameter("title") %></I>!
</BODY>
</HTML>
join_email_list.html
<html>
<head>
<title> Email List application</title>
</head>
<body>
<h1>Join our email list</h1>
<p>To join our email list, enter your name and
email address below. <br>
Then, click on the Submit button.</p>
<form action="http://localhost:8080/jnnce/email.jsp" method="get">
<table cellspacing="5" border="0">
<tr>
<td align="right">First name:</td>
<td><input type="text" name="firstName"></td>
</tr>
<tr>
<td align="right">Last name:</td>
<td><input type="text" name="lastName"></td>
</tr>
<tr>
<td align="right">Email address:</td>
<td><input type="text" name="emailAddress"></td>
</tr>
<tr>
<td></td>
<td><br><input type="submit" value="Submit"></td>
</tr>
</table>
</form>
</body>
</html>
<html>
<head>
<title>Chapter 4 - Email List application</title>
</head>
<body>
KNSIT Page 100
<%
String firstName = request.getParameter("firstName");
String lastName = request.getParameter("lastName");
String emailAddress = request.getParameter("emailAddress");
%>
<h1>Thanks for joining our email list</h1>
<p>Here is the information that you entered:</p>
<table cellspacing="5" cellpadding="5" border="1">
<tr>
<td align="right">First name:</td>
<td><%= firstName %></td>
</tr>
<tr>
<td align="right">Last name:</td>
<td><%= lastName %></td>
</tr>
<tr>
<td align="right">Email address:</td>
<td><%= emailAddress %></td>
</tr>
</table>
<p>To enter another email address, click on the Back <br>
button in your browser or the Return button shown <br>
below.</p>
<form action=email.html method="post">
<input type="submit" value="Return">
</form>
</body></html>
Usage of page directives : first.jsp
pageContext.jsp
User Sessions
49. A JSP program must be able to track a session. There are threecommonly used methods
to track a session.
50. These are by using a hidden field, by a cookier or by Java Bean.
51. A hidden field is a field in an HTML form whose value isnt displayed on the HTML
page.
Cookies
52. Cookie is a small piece of information created by a JSP program that is stored on the
clients hard disk by the browser.
53. Cookies are used to store various kinds of information like user preferences and an ID
that tracks a session with a JSP database system.
Addcookie.jsp
<HTML>
<HEAD>
<TITLE>JSP Programming</TITLE>
</HEAD>
<BODY>
<%! String MyCookieName = "userID";
String MyCookieValue = "HK1917"; %>
<% response.addCookie(new Cookie(MyCookieName, MyCookieValue));
%>
<p> MyCookieName is : <%=MyCookieName%> </p>
Session Objects
54. Each time a session is created, a unique ID is assigned to the session and stored as a
cookie.
55. The unique ID enables JSP programs to track multiple sessions simultaneously while
maintaining data integrity of each session.
56. The session ID is used to prevent intermingling of information from clients.
57. Along with session ID, a session object is also used to store other types of information,
called attributes.
58. An attribute can be login information, preferences, or even purchases placed in an
electronic shopping cart.
setattribute.jsp
<HTML>
<HEAD>
<TITLE>JSP Programming</TITLE>
</HEAD>
<BODY>
1. It inserts the given page and includes 3. The include action tag is used to
the content in the generated servlet included the response generated by
page during the translation phase of executing the specified JSP page or
JSP lifecycle. servlet.
2. In general, the include directive is 4. The response is included during the
used to include files, such as HTML, request processing phase, when the
JSP, XML or simple.txt file into JSP page is requested by the user.
page statically.
Example for <jsp:include>
<HTML>
<BODY>
Going to include hello.jsp...<BR>
<jsp:include page="1.jsp"/>
</BODY>
</HTML>
<html>
<%
double freeMemory = Runtime.getRuntime().freeMemory();
double totalMemory = Runtime.getRuntime().totalMemory();
double percent = freeMemory/totalMemory;
if(percent<0.5)
{
%>
One.jsp
<html>
<body>
<font color="red">
Virtual Memory usage is less than 50 percent
</font>
</body>
</html>
Two.jsp
<html>
<body>
<font color="red">
Virtual Memory usage is greater than 50 percent
</font>
</body>
</html>
Jsp:param
1. The jsp:param tag allows us to pass a name and value pair as parameter to a dynamic
resource, while including it in a JSP page or forwarding a request from a JSP page to
another JSP page.
Syntax : <jsp : param attributes />
2. The name Attribute : The name attribute specifies the parameter name and takes a case-
sensitive literal string. The parameter name should be unique.
3. The value Attribute : The value attribute specifies the parameter value and takes either a
case-sensitive literal String or an expression that is evaluated in the request handling
stage of the JSP life cycle.
4. snippet for <jsp:param>
jsp:useBean
1. This action allows to use java bean in a JSP page.
2. This action instantiates or locates a Bean with a specific name and scope.
<jsp:useBean attributes>
.
</jsp:useBean>
3. Attributes of <jsp:useBean> tag :
4. Attributes add extra characteristics to a tag.
5. id represents the variable name assigned to the id attribute of the jsp:useBean tag.
6. Used to locate an existing bean instance in the appropriate scope specified in the
jsp:useBean action tag.
7. It is case sensitive.
scope represents the scope in which the bean instance has to be located or created.
1. Scopes can be page, request, session and application. Default scope is page.
2. page scope indicates bean can be used within the JSP page. (stored in
the PageContext of the current page).
3. request scope indicates that the bean can be used from any JSP page that is
processing the same request, until a JSP page sends a respond to the client. (stored in the
ServletRequest object).
4. session scope - A value of session indicates that the object is available to all pages
during the life of the current HttpSession. The page in which we create the bean must
have a page directive with session=true.application scope indicates that the bean can
be used from any JSP
page in the same application as the JSP page that created
KNSIT Page 111
5. class accepts the qualified class name to create a bean instance if the bean instance is
not found in the given scope.
6. beanName accepts a qualified class name or an expression that resolves to a qualified
class name or serialized templets.
<jsp:useBean id="mybean"
class="com.sun.corba.se.spi.activation._ActivatorStub"
scope="session"/>
<jsp:useBean id="mybean"
beanName="com.sun.corba.se.spi.activation._Activato
rImplBase"/>
<jsp:useBean id="mybean"
class="com.sun.corba.se.spi.activation._ActivatorStub"
scope="session"
type="com.sun.corba.se.spi.activation._ActivatorImplB
ase"/>
<jsp:useBean id="mybean"scope="session"
type="com.sun.corba.se.spi.activation._ActivatorImplB
ase"/>
jsp:setProperty
1. This action tag sets the value of a property in a bean, using the beans
setter methods.
2. The bean must be instantiated before using this tag.
3. The name attribute of the bean must be same as the reference variable name of the bean
instance.
1. <jsp:setProperty> tag contains four attributes :
2. name : take the name of the already existing bean as a reference
variable to invoke the setter method.
Jsp:getProperty
3. This tag gets the value of a property in a bean by using the beans
getter methods and writes the value to the current Jsp Writer.
syntax : <jsp:getProperty attributes />
4. name : This attribute takes the reference variable name on which we
want to invoke the getter method.
5. property : This attribute gets the value of a bean property and invokes
the getter method of the bean property.
<jsp:setProperty name=mybean property=uname />
jsp:plugin
1. This action tag provides easy support for including a java applet or bean in the client web
browser, using a built-in or downloaded java plug-in.
2. The attributes of the jsp:plugin action tag perform the following operatins:
1. specify whether the component added in the <object> tag is a bean or an applet.
2. locate the code that needs to be run.
Attributes Description
Type Specifies the type of the object that needs to be presented to the browser.
Code Takes the qualified class name of the object that has to be presented
Codebase Takes the base URL where the specified class can be located.
Archieve Specifies comma separated list of pathnames, which loctae archive files that are
preloaded with a class loader in the directory named codebase
Align Specifies the position of applet : botton, top, middle, left, right
Nspluginurl Specifies the URL where the client can download the JRE plug-in for Netscape
Navigator.
Iepluginurl Specifies the URL where the client can download the JRE plug-in for Inter net
Explorer.
move.reshape(Math.abs(r.nextInt())%(size().width-
70),
Math.abs(r.nextInt())%(size().height-
30),70,30);
repaint();
}
return true;
}
}
Using a Bean in JSP
1. To declare a bean in a JSP, follow these steps
RegProcessFinal.jsp
<%@page errorPage="Registration.html"%>
<jsp:useBean id="regform" type="com.kogent.jspex.RegForm" scope="session"/>
<jsp:setProperty name="regform" property="firstName" param="first_name"/>
<jsp:setProperty name="regform" property="lastName" param="last_name"/>
<jsp:setProperty name="regform" property="address"/>
StudeReg.html
<html>
<body><title>STUDENT'S INFORMATION'</title>
<pre>
<form action="Students.jsp"> <b>
First Name: <input type="text" name="fname"/>
Last Name : <input type="text" name="lname"/>
Age : <input type="text" name="age"/>
Department : <input type="text" name="dept"/>
<input type="submit" value="Register"/>
</b></form>
</pre>
</body>
</html>
Students.jsp
html>
<head>
<title>STUDENT INFORMATION</title>
</head>
<body>
<jsp:useBean id="students" class="com.tutorialspoint.StudentsBean" scope="session"/>
<jsp:setProperty name="students" property="firstName" param="fname" />
<jsp:setProperty name="students" property="lastName" param="lname" />
<jsp:setProperty name="students" property="age" param="age"/>
<jsp:setProperty name="students" property="dept" param="dept"/>
<p>Student First Name:
<jsp:getProperty name="students" property="firstName"/>
</p>
<p>Student Last Name:
<jsp:getProperty name="students" property="lastName"/>
</p>
<p>Student Age:
<jsp:getProperty name="students" property="age"/>
</p>
GRNICA
GRNICA
<c:set> tag
1. It allows us to set the value of a variable or property into the given scope. Syntax:
<c:set attribute> [body content ] </c:set>
<c:remove> tag
1. It allows us to remove a variable from the specified scope.
Syntax : <c:remove attributes/>
The attributes are:
1. var name of the variable to be removed
2. scope scope of the variable, scope can be page, request, session or application.
<c:catch> tag
1. It allows jsp pages tohandle exceptions that might be raised to any of the tag inside the
body of the <c:catch> tag.
syntax : <c:catch attributes> body content </c:catch>
The attributes :
1. var takes the name of the variables that stores the exception thrown.
Networking Tags
It contain tags that perform certain operations on URLs, such as
including some other web pages, encoding the URL, and redirecting
the client request.
KNSIT Page 129
1. Networking tags of JSTL contains four tags:
1. <c:import>
2. <c:url>
3. <c:redirect>
4. <c:param>
<c:import> Tag
1. This tag is used to include another resource such as another JSP or HTML page in a JSP
page.
2. The resource can either be static or dynamic.
syntax : <c: import attributes > </c:import>
Attributes are:
1. url specifies the url of the resource to include.
2. context specifies the context name in which the page has to be located, its
optional one.
3. var specifies the name of the variable into which the result has to be stored, if
specified.
4. scope specifies the scope into which the variable has to be stored.
Example for <c:import> tag : import.jsp
<%@ taglib prefix="c" uri="http://java.sun.com/jstl/core" %>
<c:import url="foreach.jsp"/>
<c:out value="Welcome to our web-site!" />
<c:url> Tag
1. It creates a URL and is added with a session ID if the user session needs to be
maintained.
syntax : <c:url attributes> [ zero or more <c:param> tags] </c:url>
Attributes are:
1. url specifies the URL to be written if required added with session ID.
<c:redirect> Tag
2. It is used to redirect a client request.
3. It is similar to sendRedirect() method.
syntax : <c:redirect attributes> [ zero or more <c:param> tag </c:redirect>
Attributes are:
4. value specifies the URL of the resource to which the request has to be redirected.
5. context specifies the context name of another web application, required if the URL
refers to the resource in another servlet context.
Example for <c:redirect> tag : redirect.jsp
6. <%@ page contentType="text/html" %>
7. <%@ taglib prefix="c" uri="http://java.sun.com/jstl/core" %>
8. <c:redirect value="http://localhost:8000/index1.html> </c:redirect>
<c:param> Tag
1. It is used to add a request parameter to the URL.
2. It also can be used in <c:url> and <c:redirect> tags.
syntax: <c:param attributes />
<x:if> tag
1. It evaluates an XPath expression that is given in its select attribute.
2. If the reslting value is true, then the body of the <x:if> tag is evaluated, otherwise not.
syntax : <x:if attributes > body content </x:if>
Attributes are:
1. select takes an Xpath expression that resolves to a Boolean value
2. var takes the name of the scoped variable to store the conditions result.
<x:choose> tag
1. It acts similar to java switch statement.
2. It encloses one or more <x:when> tag and a <x:otherwise> tag.
syntax : <x:choose> body content </x:choose>
<x:when> tag
1. It encloses a single case within the <x:choose> tag.
syntax : <x:when attribute> body content </x:when>
Attributes :
1. select takes an Xpath expression resolving to boolean value.
2. If boolean value is true, <c:when> tags body is evaluated.
<x:otherwise> tag
1. It is equivalent to default case in java switch statement.
2. The body content of this tag is evaluated if none of the <x:when> conditions in the
<x:choose> tag are resolved to true.
Syntax : <x:otherwise> body content </x:otherwise>
<x:forEach> tag
1. It is used for looping over a list of elements obtained after obtaining
the given Xpath expression.
Syntax : <x:forEach attributes > body content </x:forEach>
Attributes are
1. select takes an Xpath expression that results a node list.
2. var specifies the name of the variable into which the current iteration item has
to be set.
3. varStatus specifies the name of the variable that lets us to know the
information about where are we in the overall iteration such as getting count,
index, knowing isFirst, isLast etc, this is optional.
<x:param> tag
1. It is used to set transformation parameters.
2. It should be used within the body of the <x:transform> tag.
syntax : <x:param attributes> [body content] </x:param>
Attributes are :
1. name takes the name of the transformation parameter.
2. value specifies the value of the transformation parameter. It is optional. Value
of the param tag can also be specified.
fmt:setLocale> tag
1. It stores the given locale in the locale configuration variable of the given scope.
syntax : <fmt:setLocale attributes/>
The attributes are :
<fmt:setBundle> tag
1. It creates a ResourceBundle object using the Locale object in the locale configuration
variable and the given base name.
2. It stores ResourceBundle object into the given variable and scope.
syntax : <fmt:setBundle attributes />
Attributes are:
1. basename specifies the resource bundle name
2. var specifies the variable name to which this resource bundle object has to be
set.
3. scope specifies the scope of the variable defined in var attribute.
<fmt:bundle> tag
1. It creates a ResourceBundle object by using the Locale object in the locale configuration
variable and the given base name.
2. It then applies to the formatting actions in its body content.
syntax : <fmt:bundle attributes> body content </fmt:bundle>
Attributes are :
1. basename specifies the resource bundle name
2. prefix specifies prefix that has to be used for the messages in this elements
body content.
<fmt:message> tag
1. It maps key to localized message and performs parameter replacements using the
resource bundle specified in bundle attribute.
Syntax : <fmt:message attributes> body content </fmt:message>
KNSIT Page 141
2. Attributes are:
1. key specifies the key that whose value has to be retrieved.
2. bundle specifies the resource bundle that has to be used to get the value of the
specified key.
3. var specifies the variable to which the retrieved message has to be stored.
4. scope specifies the scope of the variable defined in var attribute.
<fmt:param> tag
1. It is used within the <fmt:message> element.
2. This tag supplies the argument for the parametric replacement in a message.
syntax : <fmt:param attributes/>
Attributes are:
1. value specifies the value of the parameter to be passed.
<fmt:requestEncoding> tag
1. It allows to set the character encoding of a request.
2. It invokes the setCharacterEncoding() method of the ServletRequest interace to set the
character encoding of a request.
3. syntax : <fmt:requestEncoding attributes/>
4. Attributes are:
1. value represents the character encoding to be set.Character encoding is further
used to decode the request parameters.
GRNICA
ApplicationResources_en.properties
welcome.message=Welcome to internationalization <b>{0}</b> (E
ApplicationResources_en_US.properties
welcome.message=Welcome to internationalization <b>{0}</b> (U
ApplicationResources_it.properties
welcome.message=Welcome to internationalization <b>{0}</b> (I
<fmt:formatNumber> tag
1. It allows us to format numbers, currencies, and percentages according to the locale or
customized formatting pattern.
syntax : <fmt:formatNumber attributes > body content </fmt:formatNumber>
Attributes are :
1. value specifies the numeric value that has to be formatted to the locale or
given pattern. It is optional.
2. type specifies the value type, accepted values are number, currency, and
percent. If not specified, takes number as default.
3. pattern specifies custom pattern to which the given value has to be formatted.
4. currencyCode specifies the currency code as per ISO 4217 that has to be used
in formatting.
5. currencySymbol specifies the currency symbol that has to be included into the
formatted number, used as type=currency.
6. groupingUsed specifies whether the formatted output should contain any
grouping separators. It is a boolean, default is true.
7. maxIntegerDigits specifies max number of digits in integer portion of
formatted output.
8. minIntegerDigits - specifies min number of digits in integer portion of formatted
output.
9. maxFractionDigits specifies max number of digits in fractional portion of the
formatted output.
10. minFractionDigits - specifies min number of digits in fractional portion of
formatted output.
11. var specifies the variable name to which the formatted value has to be stored, if
not specified, formatted value is written to JspWriter
12. scope specifies the scope of the variable defined in var attribute.
Attributes are:
1. value specifies the string value that has to be parsed according to the locale or
given pattern. It is optional.
2. type specifies the value type, accepted values are number, currency and
percent. Default is number.
3. pattern specifies the custom formatting pattern that determines how the given
value is to be parsed.
parseLocale specifies the Locale whose default formatting pattern is to be
used during the parse operation.
1. integerOnly specifies whether just the integer portion of the given value should
be parsed. Default is false.
2. var specifies the variable name to which the parsed value has to be stored.
3. scope specifies the scope of the variable defined in var attribute.
index.html
<html> <body>
<form method=post action="TestApp.jsp"> <pre> <b>
Number : <input type="text" name="mynumber"/>
<input type="submit" value="Format Number"/>
</b> </pre> </form>
</body> </html>
<fmt:formatDate> tag
1. It allows us to format dates and times according to the locale or
customized formatting pattern.
Attributes are:
1. value specifies the java.util.Date object whose date and or time to be formatted.
2. pattern specifies the custom pattern to which the given value has to be
formatted.
3. type specifies the components of the given date object which has to be
formatted, accepted values are date, time and both.
4. dateStyle specifies the predefined formatting style for dates. Applicable only if
type is both date and time.
5. timeStyle specifies the predefined formatting style for time. Accepted values
are default, short, medium, long and full.
6. timeZone specifies a string value that may be one of the time zone IDs
supported by the java platform or a custom time zone ID, in which to represent
the formatted time.
7. var specifies the variable name to which the formatted value has to be stored.
8. scope specifies the scope of the variable defined in var attribute
<fmt:parseDate> tag
1. It allows us to parse and format the string representation of dates and times according to
the locale or customized formatting pattern.
syntax : <fmt:parseDate attributes/>
Attributes are:
1. value specifies the Date string to be parsed.
2. type specifies whether the given value contains date or time or both. Default is
date.
3. pattern specifies the custom pattern to which the given value has to be
formatted.
4. dateStyle specifies the predefined formatting style for dates. Accepted values
are default, short, medium, long and full.
5. timeStyle specifies the predefined style for times. Accepted values are default,
short, medium, long and full.
Fmtdate.jsp
<%@taglib uri="http://java.sun.com/jstl/fmt" prefix="fmt"%>
<%@taglib uri="http://java.sun.com/jstl/core" prefix="c"%>
<html> <body>
<%pageContext.setAttribute("mydate",new java.util.Date(),PageContext.P
Current Date and Time:
<b><c:out value="${mydate}"/></b> </br>
Formatting Date: <br/><br/>
<fmt:setLocale value="it"/>
In Italy:
<pre>
Default pattern:<b>
<fmt:formatDate type="both" value="${mydate}"/></b>
Using pattern (dd-MMM-yyyy hh:mm:ss): <b>
<fmt:formatDate type="both" value="${mydate}" pattern="dd-MMM-yyy
</b>
</pre>
<br/>
<fmt:timeZone> Tag
1. The body content of this tag specifies the tags that will be controlled by the time zone
specified in <fmt:timeZone> tag.
Syntax : <fmt:timeZone attributes > body content </fmt:timeZone>
Attributes are:
<fmt:setTimeZone> tag
1. This tag stores the given time zone in time zone configuration variable of the
given scope.
syntax : <fmt:setTimeZone attributes/>
Attributes are:
2. value specifies a string value that may be one of the time zone IDs supported
by the java platform or a custom time zone ID.
3. var specifies the variable name.
4. scope specifies the scope into which this object has to be set.
5. represents a time zone ID.
1. Nested tags:
1. Refer to the set of custom tags in which one custom tag
encloses one or more custom tags. The following code snippet
shows a nested custom tag:
<td1:ifTag condition ?<%=eval>? >
<td2:valueTrue>
The expression evaluates to true
</td2:valueTrue>
</td1:ifTag>/font>
Empty Tag:
1. Assume we want to define a custom tag named <ex:Hello> and we
want to use it in the following fashion without a body:
1. <ex:Hello />
2. To create a custom JSP tag, we must first create a Java class that acts
as a tag handler.
package com.jnnce;
import javax.servlet.jsp.tagext.*;
import javax.servlet.jsp.*;
import java.io.*;
public class HelloTag1 extends SimpleTagSupport
{
StringWriter sw = new StringWriter();
public void doTag() throws JspException, IOException
{
getJspBody().invoke(sw);
getJspContext().getOut().println(sw.toString());
}
}
<taglib>
<tlib-version>1.0</tlib-version>
<jsp-version>2.0</jsp-version>
<short-name>Example TLD with Body</short-name>
<tag>
<name>Hello</name>
<tag-class>com.jnnce.HelloTag1</tag-class>
<body-content>scriptless</body-content>
</tag>
</taglib>
<%@ taglib prefix="ex" uri="WEB-INF/custom1.tld"%>
<html>
<head>
<title>A sample custom tag</title>
</head>
<body>
<ex:Hello>
This is message body
</ex:Hello>
</body>
</html>
JSP file
<%@ taglib uri="WEB-INF/menus.tld" prefix="myTags" %>
<html>
<head>
<title>Nested Custom Tags</title>
</head>
<body>
<myTags:Menu prefix="Out">
<myTags:MenuItem value="01" />
<myTags:MenuItem value="02" />
<myTags:MenuItem value="03" />
<myTags:MenuItem value="04" />
</myTags:Menu>
</body>
</html>
.tld file : menus.tld
END OF JSP
Class PropertyDescriptor
1. A PropertyDescriptor describes one property that a Java Bean exports via a pair of
accessor methods.
2. createPropertyEditor(Object bean) : Constructs an instance of a property editor using
the current property editor class.
3. equals(Object obj) : Compares this PropertyDescriptor against the specified object.
4. getPropertyEditorClass() : Gets any explicit PropertyEditor Class that has been
registered for this property.
5. getPropertyType() : Gets the Class object for the property.
6. getReadMethod() : Gets the method that should be used to read the property value.
7. getWriteMethod() : Gets the method that should be used to write the property value.
8. hashCode() : Returns a hash code value for the object.
9. isBound() : Updates to "bound" properties will cause a "PropertyChange" event to get
fired when the property is changed.
10. isConstrained() : Attempted updates to "Constrained" properties will cause a event to
get fired when the property is changed.
11. setBound(boolean bound) : Updates to "bound" properties will cause a
"PropertyChange" event to get fired when the property is changed.
12. setConstrained(boolean constrained) : Returns the class for the desired PropertyEditor.
Normally, property editors will be found using the property editor manager.
Class EventSetDescriptor
1. An EventSetDescriptor describes a group of events that a given Java bean fires.
2. getAddListenerMethod() : Gets the method used to add event listeners.
3. getGetListenerMethod() : Gets the method used to access the registered event listeners.
4. getListenerMethodDescriptors() : Gets the MethodDescriptors of the target listener
interface.
5. getListenerMethods() : Gets the methods of the target listener interface.
6. getListenerType() : Gets the Class object for the target interface.
7. getRemoveListenerMethod() : Gets the method used to remove event listeners.
8. isInDefaultEventSet() : Reports if an event set is in the "default set.
9. isUnicast() : Normally event sources are multicast.
10. setInDefaultEventSet(boolean inDefaultEventSet) : Marks an event set as being in the
"default" set (or not).
11. setUnicast(boolean unicast) : Mark an event set as unicast (or not)
Class MethodDescriptor
1. A MethodDescriptor describes a particular method that a Java Bean supports for
external access from other components.
2. getMethod() : Gets the method that this MethodDescriptor encapsualtes.
3. getParameterDescriptors() : Gets the ParameterDescriptor for each of this
MethodDescriptor's method's parameters.
A Bean Example
}
} catch (Exception e)
{
e.printStackTrace();
}
}
<html>
<head>
<title>Login</title>
</head>
<body>
<P>
<form action="Welcome.jsp" method=Post>
Enter Login ID: <input type=Text name="id" >
<P>
Enter Password: <input type=Password name="pwd"">
<P>
<input type="Submit" value="Login">
<input type="Reset" >
</form>
</body>
</html>
<jsp:useBean id="login" class="jnnce.Login" scope="session"/>
<jsp:setProperty name="login" property="*"/>
<html>
Enterprise JavaBeans
1. An EJB is a component of the J2EE architecture that primarily provides business logic
to a J2EE application and interacts with other server-side J2EE components.
2. The nature of the business logic and the interactions with other| server-side J2EE
components are dependent on the J2EE application.
3. An EJB is written in the Java programming language.
EJB Interface
Deployment Descriptors
1. A deployment descriptor describes how EJBs are managed at runtime and enables the
customization of EJB behavior without modification to the EJB code.
2. A deployment descriptor is written in a file using XML syntax.
3. A dd file is packed in the Java Archive (JAR) file along with the other files that are
required to deploy the EJB. It includes classes and component interfaces that are
necessary for each EJB in the package.
4. An EJB container references the deployment descriptor file to understand how to deploy
and manage EJBs contained in package.
5. The dd identifies the types of EJBs that are contained in the package as well as other
attributes, such as how transactions aremanaged.
Dd are used in EJB1.1 and EJB2.0 are nearly same with two changes. (<local> & <local-home>
not found in EJB1.1)
<ejb-jar>
<enterprise-beans>
<entity>
<ejb-name>myEJB</ejb-name>
<home>com.jimkeogh.ejb.MyEJBHome</home>
<remote>com.jimkeogh.ejb.MyEJBRemote</remote>
<local-home>com.jimkeogh.ejb.MyEJBHomeLocal</local-home>
<local>com.jimkeogh.ejb.MyEJBLocal</local>
<ejb-class>com.jimkeogh.ejb.MyEJB</ejb-class>
<peristence-type>Container</persistence-type>
<prim-key-class>java.lang.String</prim-key-class>
<reentrant>False</reentrant>
</entity>
</enterprise-beans>
</ejb-jar>
1. A Session bean contains business logic used to provide a service to a client and exists
for the duration of the client server session.
2. A session bean terminates once the session with the client server terminates.
3. A session bean can be stateless or stateful. A stateless session bean doesnt retain state
between method calls and typically performs business logic that doesnt require data to
be maintained during the session.
4. A stateful session bean retains data(state) between method calls with a client during a
session.
When calls are made to multiple methods, the stateful session bean is able to retain state
between calls
1. The session bean can implement the SessionSynchronization interface, which makes the
container notify the session bean of transaction-related events.
2. If implemented, the container will notify the bean of three transactional events:
beforeBegin(), beforeCompletion(), and aferCompletion(boolean committed).
2. The state of the bean is not persistent, existing only for a short period of time (perhaps a few
hours).
3. Stateful session beans are appropriate if any of the following conditions are true:
The bean's state represents the interaction between the bean and a specific client.
4. The bean needs to hold information about the client across method invocations.
5. The bean mediates between the client and the other components of the application, presenting
a simplified view to the client.
6. Behind the scenes, the bean manages the work flow of several enterprise beans.
7. Stateless session beans are appropriate if any of the following conditions are true:
8. The bean's state has no data for a specific client.
9. In a single method invocation, the bean performs a generic task for all clients. For example, you
might use a stateless session bean to send an e-mail that confirms an online order.
10. The bean fetches from a database a set of read-only data that is often used by clients. Such a
bean, for example, could retrieve
import javax.ejb.*;
public class MyEJBBean implements SessionBean
{
public void ejbActivate()
{
System.out.println("Called ejbActivate()");
}
public void ejbRemove()
{
System.out.println("Called ejbRemove()");
}
public void ejbPassivate()
{
System.out.println("Called ejbPassivate()");
}
public void setSessionContext(SessionContext ctx)
{
System.out.println("Called setSessionContext()");
}
public void ejbCreate ()
{
System.out.println("Called ejbCreate()");
}
public String myMethod ()
{
return("Called myMethod()");
KNSIT Page 179
}
}
Container-Managed Persistence
1. The term container-managed persistence means that the EJB container handles all
database access required by the entity bean.
2. The bean's code contains no database access (SQL) calls.
3. As a result, the bean's code is not tied to a specific persistent storage mechanism.
4. Because of this flexibility, even if you redeploy the same entity bean on
different J2EE servers that use different databases, you won't need to modify or
recompile the bean's code.
5. There are 3 groups of methods that are contained in an entity bean.
Bean-Managed Persistence
1. A bean-managed persistence (BMP) bean uses the JDBC API or another appropriate
database API to interface with the database.
2. The EJB container tells the BMP bean when to insert a new record, retrieve data,
modify data, or delete data.
3. There are five methods defined in a BMP bean.
4. They are : ejbLoad(), ejbStore(), ejbCreate(), ejbRemote() and findxxx().
Message-Driven Bean
1. A message-driven bean MDB is designed for clients to invoke server-side business logic
using asynchronous communication.
2. MDB monitors Java Message Service (JMS) communications and reacts to messages
sent by clients.
3. Clients dont directly access a MDB. Instead, the MDB interacts and processes requests
anonymously.
4. The EJB container handles the responsibility for creating and removing an MDB.
5. Requests from clients are sent via JMS.
6. The EJB container listens for messages in the JMS service that MDBs are registered to
receive.
Creating an MDB
1. An MDB defines four methods :
2. ejbCreate() : called when the MDB is created by the container.
3. ejbRemove() : called by the EJB container when the container terminates the instance of
the MDB.
4. setMessageDrivenContext() : creates the context for the MDB.
5. onMessage() : called each time when the EJB container receives a JMS message from a
client.