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.
In 1996 Sun developed a JDBC driver, and it wasnt a driver at all
1.
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.
5.
Page 1
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.
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.
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.
3.
4.
JDBC Packages
1.
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.
4.
Though each J2EE component is different, J2EE components use a similar process for interacting
with a DBMS.
2.
2.
3.
4.
5.
The JDBC driver must be loaded before the J2EE component can connect to the DBMS.
2.
The developer must write a routine that loads the JDBC/ODBC Bridge driver called
sun.jdbc.odbc.JdbcOdbcDriver to work offline and interact with the Microsoft Access on his PC.
3.
The driver is loaded by calling the Class.forName() method and passing it the name of the
driver.
Class.forName( sun.jdbc.odbc.JdbcOdbcDriver);
Connect to the DBMS
1.
Once the driver is loaded, the J2EE component must connect to the DBMS using the
DriverManager.getConnection() method.
The java.sql.DriverManager class is the highest class in the java.sql hierarchy and is responsible for
managing driver information
KNSIT
Page 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.
3.
4.
The java.sql.Connection is another interface manages communication between the driver and
the J2EE component.
5.
Page 4
1.
2.
A SQL query consists of a series of SQL commands that direct the DBMS to do something such
as to return a rows of data to the J2EE component.
3.
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.
KNSIT
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.
Page 6
2.
The close() method throws an exception if a problem is encountered when disengaging the
DBMS.
Db.close();
import java.sql.*;
import java.io.*;
public class DC
{
public static void main (String args[])
{
String url ="jdbc:odbc:access";
String user = " ";
String password = " ";
try
{
// load the driver
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"
// create connection.
Connection c = DriverManager.getConnection(u
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") ;
KNSIT
Page 8
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.
2.
3.
3.
The connection to the database is established by getConnection(), which requests access to the
database from the DBMS.
4.
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.
KNSIT
Sometimes a DBMS requires extra information besides userID & password to grant access to the
database.
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) ;
1.
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.
4.
5.
We use the ODBC Data Source Administrator to create the association between the database and
the JDBC/ODBC bridge.
1.
2.
3.
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.
9.
If so, then click the Advanced button to display the Set Advanced
10.
11.
12.
Statement Objects
select Ok.
box.
Once a connection to the database is opened, the J2EE component creates and sends a query to
access data contained in the database.
One of the three types of Statement objects is used to execute thequery.
KNSIT
Page 14
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
KNSIT
Page 16
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.
Page 18
1.
The CallableStatement object is used to call a stored procedure from within a J2EE object.
2.
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
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.
6.
absolute() method positions the virtual cursor to a specified row by the an integer value passed
to the method.
7.
relative() method moves the virtual cursor the specified number of rows contained in the
parameter.
1.
2.
The getRow() method returns an integer that represents the number of the current row in the
Resultset.
3.
To handle the scrollable ResultSet , a constant value is passed to the Statement object that is
created using the createStatement(). Three constants.
- TYPE_FORWARD_ONLY
- TYPE_SCROLL_INSENSITIVE
- TYPE_SCROLL_SENSITIVE
1.
The other two allow the virtual cursor to move in both directions
Updatable ResultSet
1.
Rows contained in the ResultSet can be updatable similar to how rows in a table can be updated.
2.
This is possible by passing the createStatement() method of the Connection object the
CONCUR_UPDATABLE.
3.
4.
5.
These are updating values in a row, deleting a row, and inserting a new row.
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.
5.
KNSIT
Page 23
try
{
ltSet.
LY
from
}
catch (Exception e){}
boolean Records = Results.next();
if(!Records)
{
System.out.println("No data returned.");
System.exit(4);
}
try
{
Results.updateString("Lastname", "Smith");
Results.updateRow();
DataRequest.close();
}
catch (){}
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);
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
{
}
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
1.
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.
4.
The database transaction is not completed until the J2EE component calls the commit() method
of the Connection object.
5.
The commit() method must be called regardless if the SQL statement is part of a transaction or
not.
6.
The commit() method was automatically called in the previous examples because the DBMS
has an AutoCommit feature that is by default set to true.
7.
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
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.
4.
5.
KNSIT
Page 32
6.
RowSets
1.
The JDBC RowSets object is used to encapsulate a ResultSet for use with Enterprise Java
Bean(EJB).
2.
A RowSet object contains rows of data from a table(s) that can be used in a disconnected
operation.
Auto-Generated Keys
1.
It is common for a DBMS to automatically generate unique keys for a table as rows are inserted
into the table.
2.
The getGeneratedKeys() method of the Statement object is called to return keys generated by the
DBMS.
3.
The getGeneratedKeys() returns a ResultSet object and can use the ResultSet.getMetaData() to
retrieve metadata relating to the automatically generated key.
Metadata
1.
Metadata is data about data. A J2EE component can access metadata using the
DatabaseMetaData interface.
2.
The DatabaseMetaData interface is used to retrieve information about database, tables, columns,
and indexes among other information about the DBMS.
3.
4.
5.
6.
7.
8.
9.
ResultSet Metadata
1.
KNSIT
There are 2 types of metadata that can be retrieved from the DBMS.
Page 33
2.
These are metadata that describes the database mentioned earlier and metadata that describes the
ResultSet.
3.
ResultSetMetadata rm = Result.getMetaData()
4.
5.
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.
2.
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
Servlets are small programs that execute on the server side of a Web connection.
2.
Servlets are server side components that provides a powerful mechanism for developing server
web applications for server side.
3.
Just as applets dynamically extend the functionality of a Web browser, servlets dynamically
extend the functionality of a Web server.
4.
Using servlets web developers can create fast and efficient server side applications and can run
it on any servlet enabled web server.
5.
6.
Since the servlet runs on server side so it does not depend on browser compatibility.
KNSIT
Page 36
Background
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
1.
2.
3.
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
1.
KNSIT
2.
Start Tomcat.
3.
Page 39
KNSIT
javax.servlet and javax.servlet.http are the two packages that contains the classes required to
build servlet.
Page 40
2.
These packages are not part of Java core packages, they are standard extensions provided by
Tomcat.
3.
4.
The Servlet API is supported by most Web servers, such as those from Sun, Microsoft, and
others.
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
2.
2.
3.
There is only one ServletContext for the entire web application and the components of the web
application can share it.
4.
KNSIT
Page 42
5.
6.
The ServetContext is created by the container when the web application is deployed and after
that only the context is available to each servlet in the web application.
Several of its methods are summarized in table below.
2.
KNSIT
Page 43
2.
KNSIT
Page 44
The following table summarizes the core classes that are provided
in the javax.servlet package.
The GenericServlet class provides implementations of the basic life cycle methods for a servlet.
2.
3.
In addition, a method to append a string to the server log file is available. The signatures of this
method are shown here:
void log(String s)
void log(String s, Throwable e)
1.
Here, s is the string to be appended to the log, and e is an exception that occurred.
The ServletInputStream Class
1.
2.
A method is provided to read bytes from the stream. Its signature isshown here:
int readLine(byte[ ] buffer, int offset, int size) throws IOException
3.
KNSIT
Here, buffer is the array into which size bytes are placed starting at
offset.
Page 45
2.
It is implemented by the server and provides an output stream that a servlet developer can use to
write data to a client response.
3.
A default constructor is defined. It also defines the print( ) and println( ) methods, which output
data to the stream.
The Servlet Exception Classes
1.
2.
The first is ServletException, which indicates that a servlet problem has occurred.
3.
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
Page 49
1.
2.
KNSIT
Page 50
KNSIT
Page 51
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
KNSIT
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.
Page 53
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.
2.
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 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
KNSIT
The HttpServlet class extends GenericServlet. It is commonly used when developing servlets that
receive and process HTTP requests.
The methods of the HttpServlet class are summarized in Table
Page 56
2.
3.
4.
5.
Page 57
1.
2.
3.
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( )
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
The servlet is invoked when a form on a Web page is submitted
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
2.
However, in some applications, it is necessary to save state information so that information can
be collected from several interactions between a browser and a server. Sessions provide
such a mechanism.
3.
4.
An HttpSession object is returned. This object can store a set of bindings that associate names
with objects.
5.
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 {
// Get the HttpSession object.
HttpSession hs = request.getSession(true);
KNSIT
Page 68
Gets t
sessio
// Get writer.
response.setContentType("text/html");
PrintWriter pw = response.getWriter();
pw.print("<B>");
Call
obje
to th
KNSIT
Page 69
This
to bi
date
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
<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
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.
5.
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:
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
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
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.
2.
3.
Modify the request headers and data. It is done by providing a customized version of the request.
4.
Modify the response headers and data. It is done by providing a customized version of the
response.
5.
6.
7.
The filtering API is defined by the Filter, FilterChain, and FilterConfig interfaces in
the javax.servlet package.
8.
9.
The most important method in this interface is the doFilter method, which is passed request,
response, and filter chain objects.
11.
12.
13.
14.
Examine response headers after it has invoked the next filter in the chain.
15.
16.
17.
The init method is called by the container when the filter is instantiated.
18.
This example illustrates how one can write Logging Filter servlet to provide control over log
file. We can have additional controls over these log files and these all are available to use by
implementing "Filter" class.
20.
We can create filter class by implementing javax.servlet.Filter, which has three methods as
follows:
21.
22.
23.
It is called once by the server to get prepared for service and then it calls doFilter() a
number of times for request processing.
void destroy()
void doFilter(ServletRequest request, ServletResponse response, FilterChain
filterchainObject) throws IOException, ServletException
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public final class LoggingFilterExample implements Filter
{
private FilterConfig filterConfigObj = null;
public void init(FilterConfig filterConfigObj)
{
this.filterConfigObj = filterConfigObj;
KNSIT
Page 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>
Multi-tier Applications Using Database Connectivity
<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
2.
3.
A JSP processes the request by using logic built into the JSP or by calling other web
components built using Java servlet technology or Enterprise Java Bean technology or
other technology.
KNSIT
Page 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.
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.
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.
Comment tag : A comment tag opens with <%-- and closes with --%>.
6.
Declaration Statement tags : It opens with <%! and is followed by a Java declaration
statement(s) that define variables, objects, and methods that are available to other
components of the JSP program.
7.
Directive tags : A directive tag opens with <%@ and commands the JSP virtual engine
to perform a specific task, such as importing a Java package required by objects and
methods.
8.
The directive tag closes with %>. There are three commonly used
directives. They are :
9.
10.
11.
12.
13.
We can embed any amount of java code in the JSP Scriptlets. JSP
Engine places these code in the _jspService() method.
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.
16.
17.
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>
The Page Directives
Page directives apply different properties for the page like language support, page
information and import etc. by using the different attributes of the directives.
19.
20.
Page Directive
21.
Include Directive
22.
Taglib Directive
Syntax of the declaration of the page directive with it's attributes is
attributeName="values" %>
<%@ page
Following are name of the attributes of the page directive used in JSP:
23.
Language
24.
extends
25.
import
26.
session
27.
buffer
KNSIT
Page 91
28.
autoFlush
29.
isThreadSafe
30.
info
31.
errorPage
32.
contentType
33.
isErrorPage
34.
pageEncoding
35.
isELIgnored
36.
language: This attribute of page directive of JSP is used for specifying some other
scripting languages to be used in the JSP page.
37.
extends: This is used for specifying some other java classes to be used in the JSP page
like packagename.classname. The fully qualified name of the superclass of the Java class
will be accepted.
38.
import: This attribute imports the java packages and it's classes. We can import more
than one java packages and classes by separating with comma (,).
39.
We can set the name of the class with the package name directly like
packagename.classname or import all classes of the package by using packagename.*
40.
session: This attribute sets a boolean value to either true or false. If the value of session
attribute is true then the session object refers to the current or a new session because the
client must be in the HTTP session for running the JSP page on the server. If we set the
value of session object to false then we can not use the session object.
41.
buffer: This attribute sets the buffer size in kilobytes i.e. used by the out object to handle
output generated by the JSP page on the client web browser. If we specify the buffer
size then the output will be buffered with at least 8kb because the default and minimum
value of the buffer attribute is 8kb.
42.
autoFlush: This attribute of the page directive supports for flushing buffer automatically
when the buffer is full. The value of the autoFlush attribute is either true or false. If we
specify it as true, then buffer will be flushed.
43.
isThreadSafe: This attribute support the facility of maintaining thread for sending
multiple and concurrent requests from the JSP container to the JSP page if the value the
of attribute is set to true, otherwise if we set the value of attribute to false, then the JSP
container can send only one request at one time. The default value of the attribute is true.
KNSIT
Page 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.
Variables & Objects
1.
<HTML><HEAD>
<TITLE>Order Confirmation</TITLE>
</HEAD><BODY>
<%! int age=25; %>
<p> Your age is : <%=age%> </p>
</BODY></HTML>
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
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
Page 96
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.
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.
<%! String Firstname = request.getParameter(fname);
String Firstname = request.getParameter(lname); %>
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.
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.
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.
36.
There are four predefined implicit objects that are in every JSP
programs. These are request, response, session and out.
37.
38.
39.
40.
41.
42.
43.
<HTML>
<HEAD>
<TITLE>Order Confirmation</TITLE>
</HEAD>
<BODY>
<H2>Order Confirmation</H2>
KNSIT
Page 99
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
<%@ page import= "java.util.*" language="java" contentType="text/html;
charset=ISO-8859-1 pageEncoding="ISO-8859-1"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<center><h1> using scripting elements</h1></center>
<%! int count,a,b;
int fun(int a)
{
KNSIT
Page 101
return 10*a;
}
%>
<% a=1;
count++;
for(int i=0;i<5;i++)
{
out.println("value of i in iteration
no."+i+": <b>"+i+"<b><br/>");
}
b=fun(a);
out.println("value returned by fun():<b>"+b+"</b><br/>");
%>
<b>This page is requested by <b><%=count %></b>number of times on date </b>
<b> <%= new Date() %></b>.
</body>
</html>
Use of Implicit objects: page, session, out & application
Home.html
<html>
<head>
<title>Insert title here</title>
</head>
<body>
<form action="request.jsp">
name: <input type="text" name="name">
<input type="submit" value="Invoke JSP"/>
</form>
</body>
</html>
Request.jsp
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<html>
<head>
<title>Implicit Objects</title>
</head>
<body>
Hello. <b> <%=request.getParameter("name") %></b><br/><br/>
Your request details are <br/><br/>
KNSIT
Page 102
<table border="1">
<tr><th>Name</th><th>Value</th></tr>
<tr><td>request method</td>
<td><%=request.getMethod() %></td></tr>
<tr><td>request URI</td>
<td><%=request.getRequestURI() %></td></tr>
<tr><td>request protocol</td>
<td><%=request.getProtocol() %></td></tr>
<td><%=request.getHeader("user-agent") %></td></tr>
</table>
<% if (session.getAttribute("sessionVar")==null)
{
session.setAttribute("sessionVar", new Integer(0));
}%>
<table>
<tr><th align=left> Would you like to see use of remaining implicit objects?</th></tr>
<tr>
<form name=form1 action="pageContext.jsp" method="post">
<td><input type="radio" name="other" value="yes">Yes</td>
<td><input type="radio" name="other" value="No">No</td></tr>
<tr><td><input type="submit" value="Submit"></td></tr>
</form>
</table>
</body>
</html>
pageContext.jsp
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<html>
<head>
<title>Intermediate</title>
</head>
<body>
<% if ("yes".equals(request.getParameter("other")))
{
pageContext.forward("first.jsp");
}
%>
</body>
</html>
KNSIT
Page 103
The request string sent to the JSP by the browser is divided into two general components
separated by question mark.
45.
The URL component appears to the left of the question mark and the query string is to
the right of the question mark.
46.
The URL is divided into four parts, beginning with the protocol.
47.
The first three parts commonly used protocols like HTTP, HTTPS
(secured version of HTTP) and FTP.
48.
Next is host and port combination. The host and port is the virtual path of the JSP
programs. The server maps the virtual path to the physical path.
User Sessions
49.
A JSP program must be able to track a session. There are threecommonly used methods
to track a session.
50.
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>
KNSIT
Page 104
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.
57.
Along with session ID, a session object is also used to store other types of information,
called attributes.
58.
KNSIT
Page 105
Page 106
Page 107
</p>
<p> pswd
<input type="password" name="pswd" size="20"> </p>
<input type="submit" name="submit">
<input type="reset" name="reset">
</form>
</body>
</html>
JSP Standard Actions
59.
JSP Standard action are predefined tags which perform some action based on
information that is required at the time the JSP page is requested by a browser.
60.
61.
When the JSP container encounters an action tag while converting a JSP page into a
servlet, it generates the java code that corresponds to the required predefined task.
62.
An action can be for instance, access parameters sent with the request to do a database
lookup.
63.
It can also dynamically generate HTML, such as a table filled with information retrieved
from an external system.
64.
They can be used to include a file at the request time, to find or instantiate a JavaBean,
to forward a request to a new page, to generate a browser-specific code, etc.
65.
The JSP standard actions affect the overall runtime behavior of a JSP page and also the
response sent back to the client.
Action element
Description
<jsp:useBean>
<jsp:getProperty
<jsp:setProperty>
<jsp:include>
KNSIT
Page 108
<jsp:forward>
<jsp:param>
<jsp:plugin>
Generates HTML that contains the appropriate browserdependent elements (OBJECT or EMBED) needed to execute an
applet with the Java Plug-in software
2.
4.
Page 109
<jsp:forward page="one.jsp"/>
<%
}
else
{
%>
<jsp:forward page="two.html"/>
<% } %>
</html>
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 casesensitive 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.
KNSIT
Page 110
5.
6.
7.
8.
</jsp:include>
jsp:useBean
1.
2.
This action instantiates or locates a Bean with a specific name and scope.
<jsp:useBean attributes>
.
</jsp:useBean>
3.
4.
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.
<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.
3.
The name attribute of the bean must be same as the reference variable name of the bean
instance.
1.
2.
KNSIT
Page 112
3.
property : takes property name that has to set, and specifies the setter
to be invoked.
4.
usage ->1. * matches all the properties of a bean with the request parameter names.
2. for specific name, specify it with a value for property.
1.
value : accepts the value as the string type or as an expression that is evaluated at run
time.
2.
param : the param attribute is used to specify the name of the request parameter whose
value we want to assign to a bean property.
<jsp:setProperty property="*" name="name of the reference variable" />
<jsp:setProperty property="property name" name="name of the reerence variable"
value="property value as string"/>
<jsp:setProperty property="property name" name=" reference variable name" param="
request parameter name" />
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.
5.
property : This attribute gets the value of a bean property and invokes
the getter method of the bean property.
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:
KNSIT
1.
specify whether the component added in the <object> tag is a bean or an applet.
2.
3.
4.
5.
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.
Name
Archieve
Specifies comma separated list of pathnames, which loctae archive files that are
preloaded with a class loader in the directory named codebase
Width
Height
Align
Hspace
Vspace
KNSIT
Page 114
Jreversion
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.
KNSIT
Page 115
import java.io.*;
import java.awt.*;
import java.util.*;
import java.applet.*;
import java.awt.event.*;
/*<Applet code="ButtonMoveApplet" height=500 width=500> </A
public class ButtonMoveApplet extends Applet {
Button move;
Random r;
public void init()
{
setLayout(null);
move = new Button("Click me");
add(move);
move.reshape(10,10,70,30);
r = new Random();
setBackground(Color.red);
setForeground(Color.yellow);
}
GRNICA
KNSIT
Page 116
1. Create a bean
2. Delcare the Bean in a JSP using <jsp:useBean> tag
3. Access the Bean properties.
4. Generate Dynamic Content
5. Deploy and run the application
Creating a Bean : RegForm.java
package com.kogent.jspex;
public class RegForm implements java.io.Serializable {
private String uname, pass, repass, email, fn, ln, address;
public void setUserName(String s){uname=s;}
public void setPassword(String s){pass=s;}
public void setRePassword(String s){repass=s;}
public void setEmail(String s){email=s;}
public void setFirstName(String s){fn=s;}
public void setLastName(String s){ln=s;}
public void setAddress(String s){address=s;}
public String getUserName(){return uname;}
public String getPassword(){return pass;}
public String getRePassword(){return repass;}
public String getEmail(){return email;}
public String getFirstName(){return fn;}
public String getLastName(){return ln;}
public String getAddress(){return address;}
}//class
Declaring the Bean in a JSP : RegProcess.jsp
<%@page errorPage="Registration.html"%>
<html>
<body>
<jsp:useBean id="regform" class="com.kogent.jspex.RegForm" scope="session"/>
<jsp:setProperty name="regform" property="*"/>
<form action="RegProcessFinal.jsp"><pre> <b>
First Name : <input type="text" name="first_name"/>
Last Name : <input type="text" name="last_name"/>
Address : <input type="text" name="address"/>
<input type="submit" value="Register"/>
</b></pre></form>
</body>
KNSIT
Page 118
</html>
Accessing the Bean Properties : ViewRegistrationDetails.jsp
<jsp:useBean id="regform" type="com.kogent.jspex.RegForm" scope="session"/>
<%@page errorPage="Registration.html"%>
<html>
<body>
<pre>
<b>User Name :</b> <jsp:getProperty name="regform" property="userName"/>
<b>Password :</b> <jsp:getProperty name="regform" property="password"/>
<b>Email ID :</b> <jsp:getProperty name="regform" property="email"/>
<b>First Name :</b> <jsp:getProperty name="regform" property="firstName"/>
<b>last Name :</b> <jsp:getProperty name="regform" property="lastName"/>
<b>Address :</b> <jsp:getProperty name="regform" property="address"/>
</pre>
<form method=post action="javascript:alert('The remaining process is under development');">
<input type="submit" value="Register"/>
</form>
</body>
</html>
Generating Dynamic Content within a JSP : Registration.html
<html>
<body>
<pre>
<form action="RegProcess.jsp"><pre><b>
UserName : <input type="text" name="userName"/>
Password : <input type="password" name="password"/>
RePassword : <input type="password" name="rePassword"/>
EMail ID : <input type="text" name="email"/>
<input type="submit" value="Register"/>
</b></pre></form>
</pre>
</body>
</html>
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"/>
KNSIT
Page 119
<html>
<body>
<pre> Your registration details are valid,
<a href="ViewRegistrationDetails.jsp">Click</a> to view Registration Details and confirm.
</pre>
</body>
</html>
Lab List Example : StudentsBean.java
package com.tutorialspoint;
public class StudentsBean implements java.io.Serializable
{
private String firstName, lastName, dept;
private int age = 0;
public StudentsBean()
{
}
public String getFirstName()
{
return firstName;
}
public String getLastName()
{
return lastName;
}
public int getAge()
{
return age;
}
public String getDept()
{
return dept;
}
public void setFirstName(String firstName)
{
this.firstName = firstName;
}
public void setLastName(String lastName)
{
this.lastName = lastName;
}
public void setAge(int age)
{
KNSIT
Page 120
this.age = age;
}
public void setDept(String dept)
{
this.dept = dept;
}
}
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>
KNSIT
Page 121
<p>
Student Department:
<jsp:getProperty name="students" property="dept"/>
</p>
</body>
</html>
JSP Standard Tag Library (JSTL)
1.
JSTL is a collection of custom tag libraries, which provides core functionality used for
JSP documents.
2.
3.
The use of JSTL tags allows developers to use predefined tags instead of writing the java
code.
4.
2.
The XML tag library used for parsing, selecting and transforming XML data in
a jsp page.
3.
The format Tag library used for formatting the data used in jsp page.
4.
The SQL Tag library used to access the database in a jsp page.
The core tags are used to perform iteration, conditional processing, and also provide
support of expression language for the tags in jsp pages.
2.
The core tag library can be used in a JSP page by accessing the following tag library :
The core tags in jsp can be accessed by using prefix c, a preferred prefix for core tab
libraries.
2.
KNSIT
1.
General-purpose Tags
2.
3.
Networking Tags
Page 122
General-purpose Tags:
1.
It includes tags for writing the values to the output stream, retrieving, setting and
removing attributes and for catching exceptions.
2.
<c:out>
2.
<c:set>
3.
<c:remove>
<c:catch>
It evaluates an expression that may be given in its value attribute or in its tag body and
the resulting value is written in the output.
Syntax : <c:out attributes> [body content] </c:out>
Attributes are:
2.
3.
4.
KNSIT
1.
If boolean escapeXML is true, then tag converts XML special characters <,>,&
to <, >, and &.
2.
If boolean escapeXML is false, then it does not convert XML special characters.
The default value is true.
default takes the value to be written to output if the given value resolves to null. If
value does not resolve to null, the value specified in the value attribute is displayed.
Page 123
<%@taglib uri="http://java.sun.com/jstl/core"prefix="c"%
<html>
<body>
<b>Requested URL: </b><br/>
<c:out value="${pageContext.request.requestURL}"/><b
<br/><h4>Request Path information:</h4>
<table border='1'>
<tr><th>Name</th><th>Value</th></tr>
<tr><td>HTTP Request method</td>
<td><c:out value="${pageContext.request.method}"/></t
<tr><td>Request URI</td>
<td><c:out value="${pageContext.request.requestURI}"/>
<tr><td>Context Path</td>
<td><c:out value="${pageContext.request.contextPath}"/
GRNICA
KNSIT
Page 124
<tr><td>Servlet path</td>
<td><c:out value="${pageContext.request.servletPath}"/>
<tr><td>Path info</td>
<td><c:out value="${pageContext.request.pathInfo}"/><
<tr><td>Path translated</td>
<td><c:out
value="${pageContext.request.pathTranslated}"/></td><
</table><br/>
<h4>Accessing Request Parameter value:</h4>
Value of parameter <b>uname</b> is:
<b><c:out value="${param.uname}"/></b>
</body>
</html>
GRNICA
<c:set> tag
1.
KNSIT
It allows us to set the value of a variable or property into the given scope. Syntax:
<c:set attribute> [body content ] </c:set>
Page 125
Attributes are :
1.
2.
3.
4.
5.
<c:remove> tag
1.
var takes the name of the variables that stores the exception thrown.
2.
2.
<c:if test="${param.uname==''}">
KNSIT
Page 126
2.
2.
test takes a boolean value. If true, the body content of <c:when> is evaluated,
otherwise skipped.
2.
2.
3.
KNSIT
The attributes :
1.
2.
varStatus specifies the name of the variable that defines the status of the
variable given in the var attribute. Its optional one.
Page 127
3.
begin takes the starting index for the loop, optional one.
4.
end takes the ending index for the loop, optional one.
5.
2.
var specifies the name of the variable into which the current iteration item has
to be set.
3.
4.
varStatus defines the status of the variable given in var attributes, it is optional.
5.
begin takes the starting index for the loop, optional one.
6.
end - takes the ending index for the loop, optional one.
7.
2.
3.
4.
5.
6.
7.
</c:forEach>
KNSIT
Page 128
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.
<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.
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.
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.
KNSIT
url specifies the URL to be written if required added with session ID.
Page 130
2.
3.
var specifies the name of the variable into which the new
to be stored.
4.
required if the
3.
</c:redirect>
Attributes are:
4.
5.
context specifies the context name of another web application, required if the URL
refers to the resource in another servlet context.
has to be redirected.
7.
8.
<c:param> Tag
1.
2.
KNSIT
Page 131
Attributes are:
1.
The XML tag library is used to work with XML data used in JSP pages.
2.
3.
These operations can be done by using the Xpath expression associated with an XML
document.
4.
An Xpath expression includes both the relative and absolute path of XML element.
5.
XML tags can be used with JSP pages after importing the following tag library by using
the following code snippet.
KNSIT
2.
3.
It includes the tags for parsing XML document and performing Xpath operations.
2.
<x:parse>
2.
<x:out>
3.
<x:set>
This tag parses the given XML document and stores the resulted XML Document
Object Model (DOM) into the specified variable.
syntax : <x:parse attributes> [ body content] </x:parse>
Attributes are:
1.
2.
systemId accepts the system identifier (URI) for parsing the XML document.
3.
4.
5.
6.
7.
It evaluates an XML Xpath expression and stores the result of the evaluation in a scoped
variable.
syntax : <x:set attributes/>
Attributes are:
1.
KNSIT
2.
var specifies the name of the scooped variable to hold the result.
3.
It evaluates an XML Xpath expression and writes the result of the evaluation to the
current JspWriter.
syntax : <x:out attributes />
Attributes are:
1.
2.
escapeXML accepts boolean value which describes whether the characters like
>,<, & , in the result string has to be converted to their corresponding character
entity codes. Default value is true.
It helps to parse, access XML data, iterate over elements in an XML document, and
conditionally process JSP code fragment.
2.
<x:if>
2.
<x:choose>
3.
<x:when>
4.
<x:otherwise>
<x:forEach>
<x:if> tag
1.
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:
KNSIT
1.
2.
var takes the name of the scoped variable to store the conditions result.
Page 134
3.
<x:choose> tag
1.
2.
<x:when> tag
1.
2.
<x:otherwise> tag
1.
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.
KNSIT
1.
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.
Page 135
4.
begin takes the starting index for the loop, this is optional.
5.
end takes the end index for the loop, optional one.
6.
It provides support to transform the XML document with the given XSL stylesheet.
doc takes an XML doc to be parsed in the form of a string or a Reader object.
2.
xslt takes an XSLT stylesheet doc for transformation in the form of a string or a
Reader object.
3.
4.
1.
var takes the variable name to which the transformed XML doc
has to be set.
2.
3.
<x:param> tag
1.
2.
KNSIT
1.
2.
3.
To use XML tags in your program you have to firstly download these jar files in your
Tomcat's "lib"folder.
4.
jstl.jar
2.
resolver.jar
3.
serializer.jar
4.
standard.jar
5.
xercesImpl.jar
6.
xercesSamples.jar
7.
xml-apis.jar
xalan.jar
KNSIT
Page 137
user.xml
<?xml version="1.0"?>
<user>
<information>
<fname>Hemanth</fname>
<mname>kumar</mname>
<lname>M L</lname>
<age>29</age>
</information>
<information>
<fname>Sudeep</fname>
<mname>Manohar</mname>
<lname>R</lname>
<age>29</age>
</information>
</user>
KNSIT
Page 138
xmlinjsp.jsp
<%@ taglib uri="http://java.sun.com/jstl/xml" prefix="
<%@ taglib uri="http://java.sun.com/jstl/core" prefix="
<html>
<head><title>Use of Core XML tags</title></head>
<body>
<h2>Example of using Core XML tags</h2>
<c:import url="http://localhost:8000/hemanth/user.xml
<x:parse xml="${user}" var="doc" />
<h3>Information of user.xml file</h3>
<x:forEach select="$doc/user/information" var="n">
First Name:<x:out select="$n/fname"/><br>
Middle Name:<x:out select="$n/mname"/><br>
Last Name:<x:out select="$n/lname"/><br>
Age: <x:out select="$n/age"/><br>
</x:forEach>
</body>
GRNICA
</html>
JSTL Formatting Tags
1.
KNSIT
2.
3.
The data can be date, numbers or the time specifications in different domains.
4.
The format tag library can be used in a JSP page by using the following specification:
<%@ taglib prefix=fmt uri=http://java.sun.com/jsp/jstl/fmt %>
5.
2.
3.
2.
These tags parse the data based on the current locale and provide support for
internationalization.
Types of basic formatting tags
1.
<fmt:setLocale>
2.
<fmt:setBundle>
3.
<fmt:bundles>
4.
<fmt:message>
5.
<fmt:param>
6.
<fmt:requestEncoding>
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 :
KNSIT
Page 140
1.
2.
3.
<fmt:setBundle> tag
1.
It creates a ResourceBundle object using the Locale object in the locale configuration
variable and the given base name.
2.
2.
var specifies the variable name to which this resource bundle object has to be
set.
3.
<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.
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.
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.
<fmt:param> tag
1.
2.
This tag supplies the argument for the parametric replacement in a message.
syntax : <fmt:param attributes/>
Attributes are:
1.
<fmt:requestEncoding> tag
1.
2.
3.
4.
Attributes are:
1.
KNSIT
Page 142
GRNICA
KNSIT
Page 143
KNSIT
Page 144
ApplicationResources_en.properties
ApplicationResources_en_US.properties
ApplicationResources_it.properties
2.
KNSIT
Page 145
<fmt:formatNumber>
2.
<fmt:parseNumber>
<fmt:formatNumber> tag
1.
KNSIT
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.
7.
8.
9.
10.
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.
<fmt:parseNumber> tag
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.
used during
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.
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>
KNSIT
Page 147
TestApp.jsp
KNSIT
Page 148
In US:
<fmt:setLocale value="en_US"/>
<pre>
Default pattern:<b>
<fmt:formatNumber type="currency"
value="${param.mynumber}"/></b>
Using pattern (0,00,00.0000):<b>
<fmt:formatNumber type="currency"
value="${param.mynumber}" currencySymbol="$"
pattern="0,00,00.0000" var="fmt_mynumber"/>
<c:out value="${fmt_mynumber}"/></b>
</pre>
<br/>
After parsing the formatted mynumber:
<fmt:parseNumber value="${fmt_mynumber}"
type="currency" pattern="0,00,00.0000"/>
</body></html>
Date Formatting Tags
1.
2.
<fmt:formatDate>
2.
<fmt:parseDate>
<fmt:formatDate> tag
1.
KNSIT
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.
<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:
KNSIT
1.
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.
Page 150
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
7.
8.
var specifies the variable name to which the formatted value has to be stored.
If not specified, written to current JspWriter.
9.
Fmtdate.jsp
KNSIT
Page 151
In US:
<fmt:setLocale value="en_US"/>
<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-yyyy hh:mm:ss"
var="fmt_mydate"/> </b>
<c:out value="${fmt_mydate}"/></b>
</pre>
<br/>
After parsing the formatted mydate: <fmt:parseDate
value="${fmt_mydate}" type="both"
pattern="dd-MMM-yyyy hh:mm:ss"/>
</body></html>
Time Zone Formatting Tags
1.
<fmt:timeZone>
2.
<fmt:setTimeZone>
<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:
KNSIT
Page 152
This tag stores the given time zone in time zone configuration variable of the
given scope.
syntax : <fmt:setTimeZone attributes/>
Attributes are:
KNSIT
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.
4.
scope specifies the scope into which this object has to be set.
5.
Page 153
Fmttime.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.PAGE_SCOPE);%>
Current Date and Time:
<b><c:out value="${mydate}"/></b> </br>
Formatting Date based on Time Zone: <br/><br/>
GMT:
<pre>
<b><fmt:timeZone value="GMT">
<fmt:formatDate type="both" value="${mydate}"/>
</fmt:timeZone></b>
</pre>
<br/>
KNSIT
Page 154
The SQL tag library is used to access the relational database used in the JSP pages.
SQL tag libraries can be accessed in a jsp page by importing the following tag library in
JSP page :
1.
<%@ taglib prefix=sql uri=http://java.sun.com/jsp/jstl/sql%>
Page 155
1.
2.
3.
4.
5.
6.
sql specifies the sql query that has to be executed, optional, can be executed in tag
body. SQL query can be parameterized.
var sepcifies the variable to wich result of query is set.
scope specifies the scope of the variable.
dataSource specifies the datasource JNDI name or java.sql.DataSource object.
maxRows specifies the max number of rows that has to be included in result.
startRow specifes the starting row number.
Page 156
5.
6.
7.
Page 157
</td> <td>
<c:out value="${row.sal}"/>
</td> <td>
<a href= "RemoveEmp.jsp?empno=<c:out
value="${row.empno}"/>">
Remove</a> </td> </tr>
</c:forEach>
</table>
</body> </html>
Using SQL Tags : RemoveEmp.jsp
<%@taglib uri="http://java.sun.com/jstl/core" prefix="c"%>
<%@taglib uri="http://java.sun.com/jstl/sql" prefix="sql"%>
<sql:setDataSource driver="com.mysql.jdbc.Driver"
url="jdbc:mysql://localhost:3306/sample"
user="root"
password="root" var="myds" scope="request"/>
<sql:update dataSource="${requestScope.myds}" sql="delete from emp where empno=?"
var="count">
<sql:param value="${param.empno}"/>
</sql:update>
<c:if test="${count eq 1}">
<b>Employee Removed</b>
</c:if>
<c:if test="${count ne 1}">
<b>Problem in removing Employee</b>
</c:if>
<br/>
<a href="GetEmpDetails.jsp">View Employees</a>
JSP Custom Tags
1.
A custom tag is a user-defined JSP language element.
2.
JSP tag extensions lets us to create new tags that we can insert directly into a Java
Server Page.
3.
The JSP 2.0 specification introduced Simple Tag Handlers for writing these custom
tags.
4.
To write a custom tag we can simply extend SimpleTagSupport class and override the
doTag() method, where we can place our code to generate content for the tag.
5.
JSP custom tags enable you to perform various functions, such as:
1.
Accessing all implicit variables of a JSP page, such as request,
response, in, and out.
2.
Modifying the response generated by a calling JSP page.
3.
Initializing and instantiating a JavaBean component.
KNSIT
Page 158
1.
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>
Page 159
package com.jnnce;
import javax.servlet.jsp.tagext.*;
import javax.servlet.jsp.*;
import java.io.*;
public class HelloTag extends SimpleTagSupport
{
public void doTag() throws JspException, IOException {
JspWriter out = getJspContext().getOut();
out.println("Hello Custom Tag!");
}
}
Create following tab library file: \tomcat\webapps\<directory>\WEBINF\custom.tld.
<taglib>
<tlib-version>1.0</tlib-version>
<jsp-version>2.0</jsp-version>
<short-name>Example TLD</short-name>
<tag>
<name>Hello</name>
<tag-class>com.jnnce.HelloTag</tag-class>
<body-content>empty</body-content>
</tag>
</taglib>
Use the defined custom tab in a jsp file.
<%@ taglib prefix="ex" uri="WEB-INF/custom.tld"%>
<html>
<head>
<title>A sample custom tag</title>
</head>
<body>
<ex:Hello/>
</body>
</html>
1.
2.
KNSIT
Page 160
<ex:Hello>
This is message body
</ex:Hello>
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>
Custom Tag Attributes
1.
You can use various attributes along with your custom tags.
2.
To accept an attribute value, a custom tag class needs to implement
setter methods, identical to JavaBean setter methods.
KNSIT
Page 161
package com.jnnce;
import javax.servlet.jsp.tagext.*;
import javax.servlet.jsp.*;
import java.io.*;
public class HelloTag2 extends SimpleTagSupport
{
private String message;
public void setMessage(String msg)
{
this.message = msg;
}
StringWriter sw = new StringWriter();
public void doTag() throws JspException, IOException
{
if (message != null)
{
/* Use message from attribute */
JspWriter out = getJspContext().getOut();
out.println( message );
}
else
{
/* use message from the body */
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.HelloTag2</tag-class>
<body-content>scriptless</body-content>
<attribute>
<name>message</name>
</attribute>
</tag>
</taglib>
<%@ taglib prefix="ex" uri="WEB-INF/custom2.tld"%>
<html>
KNSIT
Page 162
<head>
<title>A sample custom tag</title>
</head>
<body>
<ex:Hello message="This is custom tag" />
</body>
</html>
Page 163
}
out.println("</table>");
}
}
package mca;
import java.io.IOException;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.tagext.SimpleTagSupport;
public class MenuItemTag extends SimpleTagSupport
{
private String value;
public void setValue(String value)
{
this.value = value;
}
public String getValue() {
return this.value;
}
public void doTag() throws JspException, IOException
{
MenuTag parent = (MenuTag)getParent();
if(parent != null) {
parent.addMenuItem(this);
}
}
}
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
KNSIT
Page 164
<taglib>
<tlib-version>1.2</tlib-version>
<jsp-version>2.0</jsp-version>
<tag>
<name>Menu</name>
<tag-class>mca.MenuTag</tag-class>
<body-content>scriptless</body-content>
<attribute>
<name>prefix</name>
<required>true</required>
<rtexprvalue>true</rtexprvalue>
</attribute>
</tag>
<tag>
<name>MenuItem</name>
<tag-class>mca.MenuItemTag</tag-class>
<body-content>empty</body-content>
<attribute>
<name>value</name>
<required>true</required>
<rtexprvalue>true</rtexprvalue>
</attribute>
</tag>
</taglib>
END OF JSP
KNSIT
Page 165
6:Java Beans
What is a Java Bean?
1.
A Java Bean is a software component that has been designed to be reusable in variety of
different environments.
2.
3.
4.
5.
2.
The properties, events, and methods of a Bean that are exposed to an application
builder tool can be controlled.
KNSIT
Page 166
3.
A Bean may be designed to operate correctly in different locales, which makes it useful
in global markets.
4.
Auxiliary software can be provided to help a person configure a Bean. This software is
only needed when the design-time parameters for that component are being set.
5.
The configuration settings of a Bean can be saved in persistent storage and restored at a
later time.
A Bean may register to receive events from other objects and can generate events that are sent
to other objects
The Java Beans functionality is provided by a set of classes and interfaces in the
java.beans package.
Class Introspector
2.
The Introspector class provides a standard way for tools to learn about the properties,
events, and methods supported by a target Java Bean.
3.
For each of those three kinds of information, the Introspector will separately analyze the
bean's class and superclasses looking for information and use that information to build a
BeanInfo object that describes the target bean.
For each class "Foo", explicit information may be available if there exists a
corresponding "FooBeanInfo" class that provides a non-null value when queried for the
information.
1.
If a class provides explicit BeanInfo about itself then we add that to the BeanInfo
information we obtained from analyzing any derived classes.
2.
We then proceed to analyze the class's superclass and add in the information from it.
3.
decapitalize(String name) : Utility method to take a string and convert it to normal Java
variable name.
4.
5.
6.
getBeanInfo(Class beanClass) : Introspect on a Java Bean and learn about all its
properties, exposed methods, and events.
KNSIT
Page 167
7.
getBeanInfo(Class beanClass, Class stopClass) : Introspect on a Java bean and learn all
about its properties, exposed methods, below a given "stop" point.
8.
getBeanInfo(Class beanClass, int flags) : Introspect on a Java bean and learn about all
its properties, exposed methods, and events, subject to some control flags.
9.
getBeanInfoSearchPath() : Gets the list of package names that will be used for finding
BeanInfo classes.
10.
Class PropertyDescriptor
1.
A PropertyDescriptor describes one property that a Java Bean exports via a pair of
accessor methods.
2.
3.
4.
5.
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.
9.
10.
11.
12.
KNSIT
Page 168
13.
14.
setReadMethod(Method readMethod) : Sets the method that should be used to read the
property value.
15.
Class EventSetDescriptor
1.
2.
3.
getGetListenerMethod() : Gets the method used to access the registered event listeners.
4.
5.
6.
7.
8.
9.
10.
11.
Class MethodDescriptor
1.
2.
3.
A Bean Example
KNSIT
Page 169
import java.beans.BeanInfo;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
public class IntrospectorTest
{
private static final String PROP_NAME = "testProperty";
public static void main(String[] args)
{
try
{
Introspector.flushCaches();
BeanInfo beanInfo = Introspector.getBeanInfo(TestSubclass.class);
PropertyDescriptor[] propDescriptors =
beanInfo.getPropertyDescriptors();
for (PropertyDescriptor descr : propDescriptors)
{
if (descr.getDisplayName().contains(prop_name))
{
System.out.println("Getter for property: " + descr.getName() + " =
" + descr.getReadMethod());
System.out.println("Setter for property :" + descr.getName() + " =
" + descr.getWriteMethod());
System.out.println("Property Type:" + descr.getName()+ " = " +
descr.getPropertyType());
System.out.println("Property Editor Class:" + descr.hashCode());
System.out.println("Property Editor Class:" +
descr.isConstrained());
System.out.println("Property Editor Class:" + descr.isBound());
}
}
} catch (Exception e)
{
e.printStackTrace();
}
}
public class TestSubclass extends TestSuperclass
{
private boolean testProperty;
public boolean isTestProperty()
{
KNSIT
Page 170
return testProperty;
}
public void setTestProperty(boolean testProperty)
{
this.testProperty = testProperty;
}
}
public class TestSuperclass
{
private boolean testProperty;
public boolean getTestProperty()
{
return testProperty;
}
public void setTestProperty(boolean testProperty)
{
this.testProperty = testProperty;
}
}
}
JSP with Java beans
<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>
KNSIT
Page 171
<head>
<title>WELCOME</title>
<body>
<% if (login.checkCredentials())
{ %>
Welcome <%=request.getParameter("id") %> !
<% } else { %>
Invalid credentials.
<% } %>
</body></html>
package jnnce;
public class Login
{
private String id;
private String password;
public void setId(String value)
{
id=value;
}
public void setPwd(String value)
{
password=value;
}
public boolean checkCredentials()
{
if("hemanth".equalsIgnoreCase(id) &&
"kumar".equalsIgnoreCase(password))
{
return true;
}
else
{
return false;
}
}
}
Page 172
1.
JSP, Java Servlets and EJB form the nucleus of J2EE application.
2.
3.
An HTML form collects information from a user and formulates a request for web
services, which is passed to the server-side component.
4.
A java servlet or JSP perform a intermediary function, a Java servlet or JSP receive a request
for web service from a client and fulfil the request by calling other server-side components that
contain the business logic needed to comply with part or all of the request
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 container is a vendor-provided entity located on the EBJ server that manages
system-level services for EJB.
2.
The EJB container is one of several containers, each of which handles a J2EE
component such as a Java servlets or JSP.
An EJB container provides a reusable pool of distributed components. Each EJB must be
installed in an EJB container
EJB Classes
1.
Types of EBJ
1.
2.
Message-Driven JavaBean class ( message-driven bean) : used to receive messages from a JMS
(Java
Message Service) resource
EJB Interface
KNSIT
Page 173
1.
2.
3.
Both interfaces are declared by the developer of the EJB and are implemented by the
EJB container.
4.
You should consider using enterprise beans if your application has any of the following
requirements:
The application must be scalable. To accommodate a growing number of users,
you may need to distribute an application's components across multiple
machines. Not only can the enterprise beans of an application run on different
machines, but their location will remain transparent to the clients.
1.
2.
The application will have a variety of clients. With just a few lines of code, remote
clients can easily locate enterprise beans. These clients can be thin, various, and
numerous.
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.
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)
KNSIT
Page 174
<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>
Session Java Bean
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).
KNSIT
Page 175
Though a stateful bean retains state during a session, a session bean by its nature is not
persistent, transitional state is maintained for the life of the session
KNSIT
Page 176
Data flow
KNSIT
Page 177
Application component
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.
5.
6.
7.
8.
9.
10.
KNSIT
The bean needs to hold information about the client across method invocations.
The bean mediates between the client and the other components of the application, presenting
a simplified view to the client.
Behind the scenes, the bean manages the work flow of several enterprise beans.
Stateless session beans are appropriate if any of the following conditions are true:
The bean's state has no data for a specific client.
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.
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
Page 178
the table rows that represent the products that are on sale this
month.
2.
The SessionBean interface requires five methods to be defined in the session bean class.
3.
4.
The EJB container calls each of these methods at an appropriate time during the life of
the session bean.
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
}
}
Entity Java Bean
1.
2.
An entity bean inserts, updates, and removes data while maintaining the integrity of
data.
3.
Data collected and managed by an entity bean is referred to as persistent data and is
managed in one of two ways:
using Bean-Managed Persistence (BMP) ( it requires the bean to manage persistence)
using Container-Managed Persistence (CMP) (it requires the container to
managepersistence)
4.
An entity bean can have a remote interface, a local interface or both interfaces.
5.
6.
7.
A local interface provides access to clients running within the same environment.
8.
Container-Managed Persistence
1.
The term container-managed persistence means that the EJB container handles all
database access required by the entity bean.
2.
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.
KNSIT
Page 180
6.
7.
ejbCreate() : EJB container calls this method when a client calls the EJBHome client
method.
8.
9.
10.
They are getxxx() and setxxx(), xxx refers to the type of object that is either being
retrieved from a database or written to a database.
11.
12.
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.
4.
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.
6.
The EJB container listens for messages in the JMS service that MDBs are registered to
receive.
KNSIT
Page 181
7.
The developer provide all the logic to process a message in the onMessage() method.
8.
The JMS service enables the client and MDB to work independently and without having
to wait until the other is finished processing.
2.
3.
ejbRemove() : called by the EJB container when the container terminates the instance of
the MDB.
4.
5.
onMessage() : called each time when the EJB container receives a JMS message from a
client.
EJB classes and related files are packaged together into a Java Archive (JAR) file for
deployment.
2.
The JAR file is a compressed file format that was originally designed to reduce the size
of software to transport it easily.
3.
The JAR file used to package an EJB must contain the following:
1.
EJB classes
2.
Dependent classes
3.
Remote interfaces
4.
Home interfaces
5.
Dependent interfaces
6.
1.
KNSIT
Page 182
END OF EJB
KNSIT
Page 183