Professional Documents
Culture Documents
Advanced Java Notes From Famous Hyderabad Institute
Advanced Java Notes From Famous Hyderabad Institute
Advanced Java Notes From Famous Hyderabad Institute
com
1. 24 * 7 business enabling.
2. Optimized automation (more turn over, more business).
ARCHITECTURE OF
ENTERPRISE APPLICATION IMPLEMENTED IN JAVA
Client Tier (Layer): End user interacts with the application through the
client interface (Client Tier/Browser soft ware / cell phone).
This tier offers user interface to the end users i.e. any internet
based web application is used by the end user with the help of
client-tier. Here browser is nothing but an application running in
the client-tier.
In the client tier HTML and java script are executed. But in the
client machine no code is stored.
Client tier is the mediator between the end user and presentation
tier. It takes the user requests and submits them to the presentation
tier. It also receives the output from the presentation tier and gives
to the end user.
Data Tier: It is the data base server process any companys data is
stored mostly in the RDBMS.
www.JavaEra.com
EX:
Oracle
Sybase server
SQL server
Note: SERVLETS, EJBS, JSPS make use of JDBC Technology to interact
with the data tier.
Presentation Business
Client Tier Tier
Tier
Servlets,jsp EJB
Data Tier
Oracle,sqlservr
,Sybase server
1. 2_tier Architecture
2. 3_tier Architecture
3. n_tier Architecture
client server
View: it is responsible to take the requests from the client. and presenting the
response to the clients.
client DBserver
AWT RDBMS
Draw backs:
Draw Backs:
Middle Tier (Middle Ware Server): Middle Tier has the additional
responsibility to prepare presentation content that can explain generic web
client about what to present and how to present
www.JavaEra.com
Yahoo
Sun
Browser
IBM
Rediff
Here one client (browser) is able to communicate with more than one server
there is no need to install separate soft ware for separate servers. It is a
generic client it can communicate with any other app server.
In general Two possible out comes can occur from server to clients
Correct
Wrong (Exception)
But it is not in all the cases
What we can do
if the number of outcomes increases
if the same application(server) has to connect to the different
databases
if different type of requests are sent to communicate with
different Data Base servers
1.1.3.N-Tier Architecture:
1
Browser Http
Per Logic
Mobile
2
B.L
Awt/vb
Pre Logic
3
In the given above example we divide our middle tier into 3 divisions
(components)
One of the central and unique features of RMI is its ability to download the
bytecodes (or simply code) of an object's class if the class is not defined in
the receiver's virtual machine. The types and the behavior of an object,
previously available only in a single virtual machine, can be transmitted to
another, possibly remote, virtual machine. RMI passes objects by their true
type, so the behavior of those objects is not changed when they are sent to
another virtual machine. This allows new types to be introduced into a
www.JavaEra.com
RMI treats a remote object differently from a non remote object when the
object is passed from one virtual machine to another. Rather than making a
copy of the implementation object in the receiving virtual machine, RMI
passes a remote stub for a remote object. The stub acts as the local
representative, or proxy, for the remote object and basically is, to the caller,
the remote reference. The caller invokes a method on the local stub, which is
responsible for carrying out the method call on the remote object.
A stub for a remote object implements the same set of remote interfaces that
the remote object implements. This allows a stub to be cast to any of the
interfaces that the remote object implements. However, this also means that
only those methods defined in a remote interface are available to be called in
the receiving virtual machine.
import java.rmi.*;
public interface RemoteInf extends Remote
{
String getMessage () throwsRemoteException;
}
methods (which are available only locally). If any local classes are to
be used as parameters or return values to any of these methods, they
must be implemented as well.
The server needs to create and to install the remote objects. This
setup procedure can be encapsulated in a main method in the
remote object implementation class itself, or it can be included in
another class entirely. The setup procedure should
import java.rmi.*;
import java.rmi.server.*;
public class RemoteObj extends UnicastRemoteObject implements
RemoteInf
{
public RemoteObj()throws RemoteException
{
}
public String getMessage()throwsRemoteException
{
Return "Hello "+new java.util.Date();
}
public static void main(String args[])throws Exception
{
if (System.getSecurityManager() == null)
www.JavaEra.com
{System.setSecurityManager(newRMISecurityManager());
}
RemoteInf ro=null;
ro=new RemoteObj();
String name = "msg";
Naming. rebind (name, ro);
System.out.println ("Object is ready......."+new java.util.Date
());
}
}
This declaration states that the class implements the RemoteInf remote
interface (and therefore defines a remote object)and extends the class
java.rmi.server.UnicastRemoteObject.
The RemoteObj class has a single constructor that takes no arguments. The
code for the constructor is
public RemoteObj() throws RemoteException {
super();
}
This constructor simply calls the super class constructor, which is the no-
argument constructor of the UnicastRemoteObject class. Although the super
class constructor gets called even if omitted from the RemoteObj
constructor, we include it for clarity.
This method implements the protocol between the RemoteObj and its
clients. Clients can call the RemoteObjs getMessage (). The RemoteObj
executes the getMessage() and returns the result to the caller.
server for accepting calls from clients. This method is not a remote method,
which means that it cannot be called from a different virtual machine. Since
the main method is declared static, the method is not associated with an
object at all but rather with the class RemoteObj.
All programs using RMI must install a security manager, or RMI will not
download classes (other than from the local class path) for objects received
as parameters, return values, or exceptions in remote method calls. This
restriction ensures that the operations performed by downloaded code go
through a set of security checks.
Here's the code that creates and installs the security manager:
if (System.getSecurityManager() == null)
{
System.setSecurityManager (new RMISecurityManager ());
}
Next, the main method creates an instance of the RemoteObj. This is done
with the statement
RemoteInf ro = new RemoteObj();
Before a caller can invoke a method on a remote object, that caller must first
obtain a reference to the remote object. This can be done in the same way
that any other object reference is obtained in a program, such as getting it as
part of the return value of a method or as part of a data structure that
contains such a reference.
The system provides a particular remote object, the RMI registry, for finding
references to remote objects. The RMI registry is a simple remote object
name service that allows remote clients to get a reference to a remote object
by name. The registry is typically used only to locate the first remote object
an RMI client needs to use. That first remote object then provides support
for finding other objects.
The RemoteObj class creates a name for the object with the statement
name, that identifies the remote object in the registry. The code then needs to
add the name to the RMI registry running on the server. This is done later
(within the try block) with the statement
Calling the rebind method makes a remote call to the RMI registry on the
local host. This call can result in a RemoteException being generated, so the
exception needs to be handled. The RemoteObj class handles the exception
within the try/catch block. If the exception is not handled in this way,
RemoteException would have to be added to the throws clause (currently
nonexistent) of the main method.
Once the server has registered with the local RMI registry, it prints out a
message indicating that it's ready to start handling calls and then the main
method exits. It is not necessary to have a thread wait to keep the server
alive. As long as there is a reference to the RemoteObj object in another
virtual machine, local or remote, the RemoteObj object will not be shut
down, or garbage collected. Because the program binds a reference to the
RemoteObj in the registry, it is reachable from a remote client, the registry
itself! The RMI system takes care of keeping the RemoteObj's process up.
The RemoteObj is available to accept calls and won't be reclaimed until its
binding is removed from the registry,
The final piece of code in the RemoteObj.main method deals with handling
any exception that might arise. The only exception that could be thrown in
the code is a RemoteException, thrown either by the constructor of the
RemoteObj class or by the call to the RMI registry to bind the object to the
name msg
www.JavaEra.com
RemoteClient.java
import java.rmi.*;
import java.net.*;
if (System.getSecurityManager() == null)
System.setSecurityManager(new RMISecurityManager());
RemoteInf ri=null;
ri=(RemoteInf)Naming.lookup("rmi://localhost:1099/msg");
System.out.println(ri.getMessage());
}
www.JavaEra.com
lookup method takes a String argument i.e.. rmi means rmi protocol to
connect to the rmiregistry localhost means system where the rmiregistry
existed 1099 is the default port number of the rmiregistry and msg is the
binded object name
Javac *.java
And generate stub class by compiling the class which implements
UnicastRemoteObject
Rmic RemoteObj
Now we can run the program steps to run the java application:
Java has an API for working with databases, and this technology is
known as JDBC. JDBC provides the developer with tools that allow clients
to connect to databases, and send commands to the database. These
commands are written in the Structured Query Language. However, JDBC
can be used with any kind of data base. That is because JDBC abstracts
common database functions into a set of common classes and methods.
Database-specific code is contained in a code library, commonly called a
driver library. If there is a driver library for a database, you can use the
JDBC API to send commands to the database and extract data from the
database.
Connect to Database:
The first step in being able to work with a database is to connect to
that database. Its a process thats analogous to a web browser making a
connection to a web server. The browser makes a connection to a server,
sends a specially formatted message to the server, and receives a response
www.JavaEra.com
back from the server. When working with a database, your code will use the
JDBC API to get a connection to a database server, send a specially
formatted message to the server, and receive a response back from the
server. The JDBC API is an abstraction, and it uses a database-specific code
library to communicate with a particular database. When making a database
connection, your code does not need to open any sockets, or use any classes
of the java.net package to make a connection to the database. All the
connection details are handled primarily by a class in the database-specific
library. This class is known as driver. Your code simply tells a class known
as the DriverManager that it needs a connection, and the DriverManager
works with the driver to create a connection to the database that your code
can use.
3.1Drivers:
JDBC provides a database-neutral set of classes and interfaces that
can be used by your Java class. The database-specific code is included in a
driver library that is developed by the database vendor or third parties. The
primary advantage of using a driver library is that your code can use the
same JDBC API to talk to many different databases simply by changing the
library used by your code. Also, by using a driver library, your code is
simpler to develop, debug, and maintain, since the lower-level networking
details are handled by the driver.
Driver Types:
The JDBC specification identifies four types of drivers that can be
used to communicate with data bases.
Type 1 Driver:
This driver provides a mapping between JDBC and some other data
access API. The other data access API then calls a native API library to
complete the communication to the database. Since native APIs are platform
specific, this type of driver is generally less portable.
www.JavaEra.com
T
Client y OD Nati Data
Appli pe BC- ve Base
cation -1 API API
Ex: JDBC-ODBC
This driver comes as a standard part of the Java SDK. Like JDBC, ODBC is
an API for talking to databases.
Type 2 Driver:
This type of driver is similar to the Type 1 driver because it communicates
to the database through a native API and bypasses the additional data access
layer, this type of driver tends to be more efficient than Type 1. Like a Type
1 driver, it is dependent upon the existence of the native API library.
Client T
Appli y Nati Data
cation pe ve Base
-2 API
Type 3 Driver:
This type of driver sends database calls to a middleware component running
on another server. This communication uses a database-independent net
protocol. The middleware server then communicates with the database using
a database-specific protocol. The middle ware server translates the JDBC
call received from the client into a database call.
www.JavaEra.com
Client T Middle
Appli y ware- Data
cation pe server Base
-
3
Type 4 driver:
The type 4 driver, also commonly known as a thin driver, is completely
written in Java. It communicates directly with a database using the
databases native protocol. Since it is written completely in Java without any
platform-specific code, it can be directly used on any platform with a Java
virtual machine. The driver translates JDBC directly into the databases
native protocol without the use of ODBC or native C APIs. Thus, the thin
driver makes an excellent choice for distributed database applications. If you
are developing a client application that must communicate with a database,
and the client could be installed on various platforms (Windows, UNIX,
Mac), then you would almost certainly use a Type 4 driver. Using a Type 4
driver, you could deploy the same client code (including the driver) to each
platform and the client would work without any other modifications.
Client T
Appli y Data
cation pe Base
-4
Choosing a Driver:
In general you will want to choose either a Type 2 or a Type 4 driver
for your web application. Type 1 and Type3 drivers add a communication
layer between the JDBC driver and the database, so they tend to be less
efficient. The difference between a Type 2 and a Type 4 driver depends on
whether you need to support a single platform or multiple platforms. If you
must support multiple platforms, and native libraries do not exist for all
platforms, then you will have to use a Type 4 driver. If a native library exists
www.JavaEra.com
for all platforms. Then there is no great difference between a Type 2 and
Type 4 driver.
Loading a Driver:
Before the driver manager can provide connections, a driver class must be
loaded by your application and registered with the driver manager. There are
various ways to accomplish this:
registerDriver (Driver) method. The JVM creates the instance for you, and
the driver itself does the registration.
The other way to load the driver is to put the driver name into the
jdbc.drivers system property. When any code calls one of the methods of the
driver manager, the driver manager looks for the jdbc.drivers property. If it
finds this property, it attempts to load each driver listed in the property. You
can specify multiple drivers in the jdbc.drivers property.
Ex:
System.setProperty (jdbc.drivers,sun.jdbc.odbc.JdbcOdbcDriver);
Or
System.setProperty (jdbc.drivers,oracle.jdbc.driver.OracleDriver);
3.3Connections:
Once we have loaded our driver, the next step is to create a connection to the
database.
Getting a Connection:
To get a connection you need to interact with the driver manager. The driver
manager acts as a factory for Connection objects. The method used to get a
Connection object is getConnection () and there are three overloaded forms
of this method:
Common to each of the methods is the url parameter. Just as with an HTTP
URL, the JDBC URL provides a means to identify a resource (the database)
that the client wishes to connect to.
The URL for each database will vary depending on the database and the
driver. However, all URLs will have the general form
jdbc:<subprotocol>:<subname>, with the <subprotocol> usually
identifying the vendor and <subname> identifying the database and
providing additional information needed to make the connection.
Ex: Jdbc:odbc:oradsn
Releasing Connections:
After open the connection our responsibility is close the connection
The Connection class has a method for releasing the connections.
The correct way to use close () is to put it inside the finally block of a
trycatchfinally exception handler. Thus, you are ensured that close ()
will be called no matter what happens with the JDBC code. And since close
() also throws an SQLException, it needs to be inside a trycatch block as
well.
3.4 SQLException:
try
{
//Some JDBC CODE
} catch (SQLException e)
{
While (e!=null)
{
System.out.println(The Error code is +e.getErrorCode());
e=e.getNextException();
}
}
3.5 DataBaseMetaData:
www.JavaEra.com
Below statement returns an object that contains data about the database. This
object is an instance of DatabaseMetaData. From the DatabaseMetaData
object, we were able to get the name and version of both the database and
the driver:
DatabaseMetaData dbmd=conn.getMetaData();
3.6 Statements
already we saw how to get a connection to a database. However, the
connection does not provide any methods that allow us to do anything to the
database. To actually create, retrieve, update, or delete data from the
database, we need the Statement class.Statement objects are your primary
interface to the tables in a database. We will look at using statements to
insert new rows into a table, update a row in a table, and delete a row from a
table.
or scrollable.
Public Statement The two parameters determine
createStatement(int, int, int) whether the resultset returned by the
excuteQuery () method is updatable
or scrollable. And The third
parameter determines holdability
Once you have a statement object, you use it to send SQL to the database
with one of three four methods.
Batch Updates:
Releasing Statements:
This mean s that when the Statement object goes out of scope or is otherwise
no longer reachable, it is eligible for garbage collection; when the object is
garbage collected, its resources will be released.
3.7 ResultSets:
When you perform a query of a table in a database, the results of the query
are returned in a ResultSet object. The ResultSet object allows you to scroll
through each row of the results, and read the data from each column in the
row.
www.JavaEra.com
The ResultSet interface defines a number of methods that can be used for
moving through the results returned. Here again are the three methods that
create Statement objects:
When you use the first method to create a Statement object, the ResultSet
object that is returned by executeQuery () is a no Scrollable ResultSet, or
one that is of type forward only. This means that you can only move from
the first row to the last row, and cannot scroll backwards through the results.
The only methods for moving through the ResultSet object that can be used
is
Now, lets take a look at the other two forms of createStatement (). These
two forms have method parameters, and the first parameter sets the type.
The type refers to whether you can move backwards through the resultset.
The second parameter defines whether you can update the table through the
resultset.
For the first parameter, you can pass one of these three arguments:
ResultSet.TYPE_SCROLL_SENSITIVE
www.JavaEra.com
ResultSet.TYPE_SCROLL_INSENSITIVE
ResultSet.TYPE_FORWARD_ONLY
The first two values create a scrollable resultset, a resultset through which
you can move forwards or backwards. If changes occur to the database while
you are going through a ResultSet, TYPE_SCROLL_SENSITIVE means
you will see those changes; TYPE_SCROLL_INSENSITIVE means you
will not see the changes. The third value creates a non-scrollable resultset.
With a scrollable resultset, you can use these methods for moving the cursor.
The resultset also contains a number of methods for reading the data
in a query result. These methods allow you to reference the column by
number or by name, and to retrieve just about any data type. Here are two of
the methods:
Double getDouble(int)
Double getDouble(String)
These methods allow you to read a double from the ResultSet. The first
method gets a double from the column with the index given by the int
parameter. The second method gets the double from the column with the
name given by the String parameter. There are getXXX () methods for every
Java primitive, and for several objects.
Working with Null Values: For primitives and for Booleans, the JDBC
driver cannot return a null. When the column data for the return type,. For
all the methods that return an object, getDate () for example, the methods
return a Java null for SQL NULL. All of the getXXX() numeric methods,
getFloat () for example return the value 0 for SQL NULL. The getBoolean
() method return false for SQL NULL. If you call getFloat (), and the return
value is 0, how do you know if the column value is really 0 or NULL? The
ResultSet instance provides a method that can give you this information.
Here is its signature:
It does not take a column number or a column name. it provides its answer
based on the most recently read column.
JDBC2.0 intorduced the ability to update the data in the table directly
through the resultset, so as you move through the data, you can call methods
www.JavaEra.com
that insert, update, or delete the data. Here are some methods you would
use:
If, before you call updateRow(), you may decide that you dont want to
update the row, you can call cancelRowUpdates().
You can also insert a new row of data through the resultset. This is
accomplished by moving to a special row in the resultset; this row is known
as the insert row. You can move to the insert row by calling
rs.moveToInsertRow () here rs is the ResultSet.
When you move to the insert row, the resultset remembers the position you
were at; this remembered position is know as the current row. Then, you
update each column with the appropriate value using the updateXXX()
methods. When you are finished entering data for the new row, you can call
rs.insertRow(); you can cancel an insert by calling moveToCurrentRow ()
before you call insertRow().
Finally, you can delete a row from the table and the result set by calling
rs.deleteRow();
Holdable ResultSets:
When you execute another SQL command with a statement, any open
resultsets are closed. Also, when commit () is called with a JDBC2.0 or 1.0
driver, the resultset is closed. JDBC 3.0 adds a new ResultSet object feature
www.JavaEra.com
The first statement in each method is a SQL string. The SQL string can have
placeholders (variables) that represent data that will be set at a later time.
The place holder is represented by the question mark symbol (?)
When the SQL in the prepared statement is sent to the database, the database
compiles the SQL Before you execute a prepared statement, you must set the
placeholders with data. The driver sends the data to the database when the
prepared statement is executed. Then, the database sets the variables with the
data, and executes the SQL.
Note: Most databases keep previously executed SQL in a cache. If you send
a SQL command that matches one in the cache, the databases reuses the
SQL from cache because it has already been compiled and optimized. This
improves performance. To reuse a command, the SQL command you send
must match one in the cache exactly.
After creating the PreparedStatement object, but before the SQL command
can be executed, the placeholders in the command must be set. The
PreparedStatement interface defines various methods for doing this. You can
also use the PreparedStatement object for setting null values in a table. And
also you can perform batch updating with a prepared statement.
If you do not set all the parameters before executing the SQL, the driver will
throw a SQLException
3.9 CallableStatements:
To run stored procedures of database we need to use the CallableStatement.
JDBC code can call stored procedures using a CallableStatement object. A
www.JavaEra.com
Common between all the forms is the SQL keyword call that appears before
the procedure name, and the curly braces that surround the SQL. This
signals the driver that the SQL is not an ordinary SQL statement and that the
SQL must be converted into thee correct form for calling a procedure in the
target database.
{call procedure_name}
{call procedure_name(?,?)}
{?=call function_name(?)}
Ex:
//String sql={call procedure_name};
//String sql={call procedure_name(?,?)};
String sql={?=call function_name(?)};
CallableStatement cs=conn.prepareCall (sql);
www.JavaEra.com
4. Java Servlets
After JDBC, Servlets were the second J2EE technology invented.
Servlet is a j2ee component. Used to Create Server-side Web applications. It
has the ability to take the request from client process it and sends the
response to the clients. They run inside a Servlet container that
communicates with the user's Web browser by exchanging HTTP request
and response objects. Servlet container can run stand alone or a s a
component of a web server or a j2ee server.
Servlet are designed to be extensions to servers, and to extend the
capabilities of servers. Servlets were originally intended to be able to extend
any servers such as FTP server, or an SMTP (e-mail) server. However in
practice, only servlets that respond to HTTP requests have been widely
implemented.
To create a Servlet for a web application we'll have to derive our class
from the javax.servlet.http.HttpServlet class, which in turn is derived from
the javax.servlet.GenericServlet class.
Generic Servlet
Service ()
Init ()
Destroy ()
Http Servlet
doGet ()
DoPost ()
MyServlet
doPost()
(or)
www.JavaEra.com
doGet()
init (): The servlet container calls the init() method exactly ones
after instantiating the servlet. this method is called when the servlet is
initially loaded by the container. or It may happen during the application
server's startup, or when the servlet is being requested for the first time. This
method is a good place to write code that creates non-user-specific
resources, namely the creation of object pools.
This method init() is overloaded and one of its versions receives the
object ServletConfig as an argument. This object provides the method get
InitParameter() to find the values of the configuration parameters, if any.
When you use an online store or bank or when you search form
some information on the internet, your request is usually processed on the
server side. Only limited no of operations, such as simple calculations and
input validation, are performed on the client's machine using java applets
and JavaScript.
www.JavaEra.com
The server software supporting the HTTP protocol has to run on the
server side. This web server will listen for the user's requests, usually on
default port. If the web server receives a simple request for a static HTML
page, it can handle this request without any additional software.
Login.html
<html>
<body bgcolor=black >
<form action="http://localhost:8888/servlets-examples/MyServlet"
method=get>
<CENTER>
<font color=green SIZE=5>Login_Id Form</font>
<table border=2>
<tr>
<td><font color=red SIZE=5>Enter Login_Id</td><td><input type=text
name="id"></td>
</tr>
<tr>
<td><font color=red SIZE=5>PassWord:</td><td><input type=password
name="pwd"></td>
</tr>
</table>
<input type=submit value="ClickMe">
</body>
</form>
<html>
Let's write the login servlet shown below that will be invoked
by login.html. This servlet checks the user's ID and, if it is correct, greets the
user otherwise it displays an error message. To stay focus on servlet coding
techniques we'll just compare the id and pwd with "padma" and "gsjm".
MyServlet.java
www.JavaEra.com
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
public class MyServlet extends HttpServlet
{
public void doGet(HttpServletRequest req, HttpServletResponse
res)throws ServletException, IOException
{
res. setContentType("text/html");
PrintWriter out=res. getWriter();
String id=req. getParameter("id");
String pwd=req.getParameter("pwd");
if(id.equalsIgnoreCase("padma")&&pwd.equalsIgnoreCase("gsjm"))
{
out.println("<html>");
out.println("<body
bgcolor=lightpink><h2><center><br><br><br><br><br><br><br>Hellow
"+id+" Welcome to our organization");
}
else
{
out.println("<body
bgcolor=lightpink><h2><center><br><br><br><br><br><br><br>Hellow
"+id+" You are Not Valid User......");
out.println("</html>");
}
out.close();
}
}
The servlet gets the parameters supplied by the user's browser fro the
request object. It can do this with the help of such methods as getParameter
(), getParameterValues () and getParameterNames ().
After applying some business rules, the servlet forms the content of
the output page and sends it to the output stream PrintWriter.
At this point the servlet has to be compiled as any other java class and
deployed.
Deploying Servlets:
A web application is a collection of
Servlets, HTML pages, classes and other resources that make up a complete
application on a web server.
A servlet is a small Java program that runs within a Web server. Servlets
receive and respond to requests from Web clients, usually across HTTP, the
Hyper Text Transfer Protocol.
To implement this interface, you can write a generic servlet that extends
javax.servlet.GenericServlet or an HTTP Servlet that extends
javax.servlet.http.HttpServlet.
www.JavaEra.com
1. The servlet is constructed, and then initialized with the init method.
2. Any calls from clients to the service method are handled.
3. The servlet is taken out of service, then destroyed with the destroy
method, then garbage collected and finalized.
Destroy():
Called by the servlet container to indicate to a servlet that the servlet is
being taken out of service.
GetServletConfig()
Returns a ServletConfig object, which contains initialization and
startup parameters for this servlet.
GetServletInfo()
Returns information about the servlet, such as author, version, and
copyright.
Init(ServletConfig config)
Called by the servlet container to indicate to a servlet that the servlet is
being placed into service.
GenericServlet:
To write a generic servlet, you need only override the abstract service
method.
Deployment Descriptors:
Weve seen several examples of deployment descriptors for our
web applications contained in a file called web.xml. However, weve
postponed a full coverage of deployment descriptors until now. Now we can
take a deeper look at the deployment descriptor.
"http://java.sun.com/dtd/web-app_2_3.dtd">
<web-app>
</web-app>
<web-app>
<context-param>
www.JavaEra.com
<param-name>debug</param-name>
<param-value>true</param-value>
</context-param>
</web-app>
Note: because the web.xml file is in text format, you can only pass
parameters to the application as strings.
1. <servlet-name>
2. <display-name>
3. <description>
4. <servlet-class>
5. <jsp-file>
6. <init-param>
7. <load-on-startup>
Ex:
<servlet>
<servlet-name>Login</servlet-name>
www.JavaEra.com
<servlet-class>login.Login</servlet-class>
</servlet>
The <servlet-name> sub-element used to create name for the servlet and we
can use this name to invoke Login servlet in the descriptor (web.xml file)
The <servlet-class> sub-element told the servlet container that all requests for
Login should be handled by the login.Login class.
The other elements of servlet that you will often used are <load-on-startup>
and <init-param>
<load-on-startup>5</load-on-startup>
<Init-param>
<param-name>jdbc.name</param-name>
<param-value>jdbc:odbc:oradsn</param-value>
</init-param>
<Servlet-mapping>
<servlet-name>Login</servlet-name>
<url-pattern>/Login</url-pattern>
</servlet-mapping>
This told tomcat that if it received any URI that matched the pattern /Login, it
should pass the request to the servlet with the name Login
How does the servlet container know which servlets to load? it knows
by reading the deployment descriptors from a well-known location. For
example, for tomcat, that location is the webapps directory. Each
subdirectory under webapps is a web application. Within each subdirectory
that uses servlets will be a WEB-INF directory that contains a web.xml file.
The servlet container reads each web.xml file, and loads the servlet classes
identified in the deployment descriptor. Then it instantiates each servlet by
calling its no-argument constructor
Initialization:
After the servlet is loaded and instantiated, the servlet must be
initialized. This occurs when the container calls the init (ServletConfig). If
your servlet does not need to perform any initialization, the servlet does not
need to implement this method. The method is provided for you by the
Generic Servlet class. The init () method allows the servlet to read
initialization parameters or configuration data, initialize external resources
such as database connections, and perform other one-time activities. Generic
Servlet provides two overloaded forms of the method.
Note: if your code encounters a problem during init (), you should throw a
ServletExcception, or its subclass UnavailableException. This tells the
container that there was a problem with initialization and that it should not
use the servlet for any requests.
Note: Tomcat, for example, will return an HTTP 500 error to the client
if init () throws a ServletException when it is called as a result of a client
request. Subsequent client requests will receive an HTTP 404 (resource
unavailable) error.
4.2What is a Filter?
Like a servlet, a filter object is instantiated and managed by the container
and follows a lifecycle that is similar to that of a servlet. As we shall see
later in this chapter, a filter has four stages: instantiate, initialize, filter, and
destroy. These stages are similar to a servlets instantiate, initialize, service,
and destroy.
Filters also follow a deployment process close to that of servlets. In fact the
API of a filter is very similar to that of the servlet interface a filter also
operates on HTTP requests to produce and manipulate further HTTP
requests and responses. So, how is a filter different from a servlet? In order
to see the difference, let us consider how filters participate in the HTTP
request-response process:
Web resource
[Static: html,
Filter-1 Filter-2 Filter-3 images etc...]
[Dynamic:
Servlets/jsp]
www.JavaEra.com
In this process, after each filter is processed, the control is transferred to the
following filter in the chain. Similarly, after the web resource has been
processed, the container returns the thread of execution back to the last filter.
This step continues till the control is handed back to the first filter. In this
manner, each filter gets an opportunity to participate both before and after
invoking the web resource.
Lets now to take a look at some of the possibilities that filter offer:
serving any web resource. Not e that in the previous figure, the web resource
could be any standard resource a static resource such as an HTML file, an
image, a class file for an applet, and so on, or a dynamic resource such as a
servlet or a JSP page.
The request dispatcher API is mean for servlets and JSP pages to
forward the processing to another web resource, or include the contents of
another web resource. However, forward and include can only happen from
servlets or JSPs which themselves are first classed as web resources. We
cant use this API to control what happens before the request reaches a
servlet or JSP. On the other hand, a filter is invoked before the request
reaches a servlet, a JSP or in fact, any other resource.
We cannot use the request dispatcher API to intervene in the invocation of
non-servlet or JSP resources, such as a static file. A filter, however, can be
used to do so.
4.3SessionTracking
The Need for Session Tracking:
A protocol is state full if the response to a given request may depend not
only on the current request, but also on the outcome of previous requests.
Approches To SessionTracking:
There are essentially four approaches to session tracking:
1. URL rewriting :
2. Hidden form fields
3. Cookies
4. Session tracking support of cookies
the client submits a form, the additional fields will also be sent in the
request. The server can use these parameters to establish and maintain a
session.
Cookies:
Cookies were invented by Netscape, and are one of the most refined forms
of token that clients and servers can exchange. Unlike URL rewriting or
using hidden form fields, cookies
Can be exchanged in request and response headers, and therefore do not
involve manipulating the generated response to contain a token.
<web-app>
<servlet>
<servlet-name>FirstServlet</servlet-name>
<servlet-class>MyServlet</servlet-class>
</servlet>
<servlet>
<servlet-name>FirstServlet1</servlet-name>
<servlet-class>MyServlet</servlet-class>
</servlet>
<servlet-mapping>
www.JavaEra.com
<servlet-name>FirstServlet</servlet-name>
<url-pattern>/MyServlet</url-pattern>
</servlet-mapping>
</web-app>
PROGRAMS
GenServlet.java
import javax.servlet.*;
import java.io.*;
public class GenServlet extends GenericServlet
{
String inf;
public void init(ServletConfig config)throws ServletException
{
inf="init";
}
public void service(ServletRequest req,ServletResponse res)throws
ServletException,IOException
{
res.setContentType("text/html");
PrintWriter out=res.getWriter();
out.println("<html>");
out.println("<body bgcolor=black text=red>");
out.println("Gen Servlet "+new java.util.Date());
out.println("</body>");
out.println("</html>");
out.close();
}
public void destroy()
{
www.JavaEra.com
}
}
Web.xml
<servlet>
<servlet-name>GenServlet</sertlet-name>
<servlet-class>InitParam</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>GenServlet</sertlet-name>
<url-pattern>/GenServlet</url-pattern>
</servlet-mapping>
I.e. we can write dynamic parts (in jsp code ) in HTML page using special
tags most which starts with <% and end with %> .
Introduction to Jsp
call the HTML and JSP pages in our j2ee application is HTTP, the same
protocol used by browsers to get HTML pages from a web server.
Note: Note that this last step can actually occur at various times. Even
though it is listed last here you can translate and compile the JSP prior to
deployment, and deploy the class file directly. Compiling first allows us to
catch and fix syntax errors in our code prior to deployment. Alternatively,
the JSP container can compile the JSP when it is deployed to the server.
Finally, the usual process is that when the first request is made for the JSP,
the server translates and compiles the JSP. This is known as translation at
request time.
occur right after loading, or it can occur when the first request is
made.
2. Initialization: The JSP page is initialized. If you need to execute
code during initialization, you can add a method to the page that will
be called during initialization.
3. Request Processing: The page responds to a request. After
performing its processing a response is returned to the client. The
response consists solely of HTML tags or other data; none of the java
code is sent to the client.
4. End of Life: The server stops sending requests to the JSP. After
all current requests are finished processing, any instances of the class
are released. If you need to execute and perform any cleanup actions,
you can implement a method that will be called before the class
instance is released.
JSP JSP
Web Server
Container
Translated
INTO
When a client sends a request for a JSP, the web server gives the request to
the JSP container, and the JSP container determines which JSP page
implementation class should handle the request. The JSP container then calls
a method of the JSP page implementation class that processes the request
and returns a response through the container and web server to the client.
The first time a JSP is loaded by the JSP container (also called the JSP
engine), the servlet code necessary to implement the JSP tags is
automatically generated, compiled, and loaded into the servlet container.
www.JavaEra.com
This occurs at translation time. It is important to note that this occurs only
the first time a JSP page is requested. There will be a slow response the first
time a JSP page is accessed, but subsequent requests the previously
compiled servlet simply processes the requests. This occurs at run time.
If we modify the source code for the JSP, it is automatically recompiled and
reloaded the next time that page is requested. A lot of work is happening
behind the scenes, and you, the developer, are receiving the payoff, in the
form of authoring convenience. (The servlet engine will usually manage this
by making the generated servlet class expose a timestamp. Before each
request, this timestamp can be compared with the file systems modification
timestamp on the JSP file. Recompilation will be necessary only if the JSP
files timestamp is later than the classs timestamp.)
Translation unit: the JSP page and dependent files are together known as a
translation unit.
Ex:1
JSP Directives:
www.JavaEra.com
JSP directives are used to set global values such as class declarations,
methods to be implemented, output content type, and so on, and do not
produce any output to the client. Directives have scope for the entire JSP
page; in other words, a directive affects the whole JSP page, but only that
page. Directives begin with <%@ and end with %>, and the general syntax
is:
<%@ directivename attribute=value attribute=value %>
You can down load complete list of attributes and their meanings in the JSP
specification from http://java.sun.com/product/jsp.
Attribute Description
page Import To import packages into JSP page
Example: import=java.util.*,java.sql.*
Session The valid values are true or false. The
default value is true. If true, the page
participates in a session; otherwise not.
isThreadSafe If true the container can use the JSP for
multiple concurrent request threads. The
default value is true.
errorPage Path (url) of the web page that should be
www.JavaEra.com
When u use include directive in JSP page the file is included when the page
is translated into its Java form.
Scripting elements:
Declarations:
You can also declare and define methods within a declaration element:
%>
Scriptlets:
Scriptlets contain Java code statements. The code in the scriptlet
appears in the translated JSP, but not in the output to the client.
For example , to repeat the phrase Hello, World! ten times in the output
page, you could use this scriptlet.
<%
for(int i=0;i<10;i++)
{
%>
Hellow, Wold!
<%
}
%>
www.JavaEra.com
<%
Vector v=new Vector();
_ _ _ _ _ _ _
_ _ _ _ _ _ _
%>
Note:
Scriptlets cannot be used to diine a method; only declarations can be used
for that.
Variables declared in a declaration are instance variables of the JSP page
implemented class. But variables declared in a scriptlet are local to a method
in the JSP page implementation class.
Expressions:
Expressions are used to output the value of a Java expression to the
client. For example
Would result in the text The number of tokens in this statement is 9. Being
displatyed in the browser Here is the same expression using XML style:
<jsp:expression>
countTokens(The number of tokens in this statement is n)
</jsp:expression>
www.JavaEra.com
Comments:
You can use standard HTML comments within the JSP and those
comments will appear in the page received by the client browser.
HTML comments:
<!-- this comment will appear in the clients browser -->
You also include JSP-specific comments that use this syntax:
<%-- this comment will not appear in the clients browser --%>
Template data:
Everything that is not a directive, declaration, scriptlet, expression, or
JSP comment (usually all the HTML and text in the page) is termed
template data.
Implicit objects:
request : HTTP request
response: HTTP request
out :Output Stream
session :HTTP session
config : to obtain JSP specific init parameters.
exception: exception object it only available with in error pages. It is the
reference to the java.lang.Throwable object that caused the server to call
the erro page.
application: this object represents the web application environment.
Used to get context parameters (application level configuration
parameters).
Scope:
page: With page scope, the object is only accessible within the page
in which it is defined. (Objects with page scope are thread-safe)
request: With request scope, Object is available within the page in
which it is created, and within pages to which the request is forwarded
or included. (Objects with request scope are thread-safe)
session: Objects with session scope are available to all application
components that participate in the clients session. (Objects with
session scope are not thread-safe)
application: Objects that are created with application scope are
available to the entire application for the life of the application.
(Objects with application scope are not thread-safe)
JSP PROGRAMS
One.jsp
Two.jsp
b=<%=b%><br>
sum=<%=a+b%><br>
</center>
Web.xml
<welcome-file-list>
<welcome-file>
first.jsp
</welcome-file>
</welcome-file-list>
First.jsp
Second.jsp
<%
for(int i=0;i<a.length;i++)
a[i]=i+1;
out.println("Element in the Array<br>");
for(int i=0;i<a.length;i++)
out.print(a[i]);
%><br>
End Of The JSP Page<hr>
</body>
Third
Web.xml
<welcome-file-list>
<welcome-file>
login.html
</welcome-file>
</welcome-file-list>
Login.html
<html>
<body background="back.gif" text=red>
<center><b><font size=5>
<marquee behavior=alternate>Login Page
</marquee></font>
<form action="http://localhost:8888/login/login.jsp">
<hr>
User Name:<input type=text name="uname"><br>
Password:<input type=password name="pwd"><br>
<hr>
<input type=submit value="Login">
<input type=reset>
</form>
</body>
</html>
Login.jsp
Fourth
Web.xml
<welcome-file-list>
<welcome-file>
emp.html
</welcome-file>
</welcome-file-list>
Emp.html
<html>
<body background="back.gif" text=red>
<center><b><font size=5>
<marquee behavior=alternate>Enter Emp Details
</marquee></font>
<form action="http://localhost:8888/emp/emp.jsp">
<hr>
<table bordercolor=green>
<tr>
<td>Eno:</td><td><input type=text name="eno"></td>
</tr>
<tr>
www.JavaEra.com
Error.jsp
Conn.jsp
con.close();
}
Connection open(String uname,String pwd)throws Exception
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
con=DriverManager.getConnection("jdbc:odbc:oradsn",uname,pwd);
return con;
}
%>
Emp.jsp
Fifth
www.JavaEra.com
Math.jsp
<html>
<body>
<%! int a=10,b=20; %>
<%! int getSum()
{
return a+b;
}
int getDifference()
{
return a-b;
}
int getProduct()
{
return a*b;
}
int getDivision()
{
return a/b;
}
%>
<font face="Georgia" color= "blue" size=4>
<center>
A is<%=a%><br>
B is<%=b%><br>
<font color= "green" size=4>
<%="Arithmetic Operations"%><br>
<font color= "maroon" size=4>
sum is <%=getSum() %><br>
Difference is <%=getDifference() %><br>
Product is <%getProduct() %><br>
Division is <%getDivision() %><br>
</center>
</body>
</html>
One.jsp
<html>
<b><center>This is First Page</b>
</html>
Two.jsp
<html>
<h2><center>This is Second Page</center></h2>
</html>
Three.jsp
<html>
<h2><center>This is Third Page</center></h2>
</html>
Error.jsp
<html>
<h2>Error................</h2>
</html>
Main.jsp
<%}else if(count==2){%>
<jsp:forward page="/second.jsp"/>
<%}else if(count==3){%>
<jsp:forward page="/third.jsp"/>
<%}else{ %>
www.JavaEra.com
<jsp:forward page="error.jsp"/>
<%}%>
<jsp:forward page=next.jsp>
<jsp:forward page=next.jsp>
<jsp:param name=image value=house.gif >
</jsp:forward>
Tag Name
A JSP tag is uniquely identified in a page by a combination of a prefix
(in this case jsp), and suffix(in this case forward), separated by a
www.JavaEra.com
Scripting Variables:
Tags can define variables that can be used within the JSP page in tag
body content or (depending on the scope of the variables) after the tag
has been closed. The <jsp: useBean> standard action is an example of
a tag that defines a scripting variable available throughout the
remainder of the JSP.
A Simple Tag:
Well call our simple tag hello, and heres how we might use it in a
JSP page. The first line is a declaration used to import the tag library,
which we will discuss in detail later:
The tag handler class must react to callbacks from the JSP engine
when it encounters tags in JSP pages at run time. The most important
of these callbacks are doStartTag (), which is called when the opening
of the tag is encountered, and doEndTag (), which is called when the
closing tag is encountered. The implementation of HelloTag is very
simple, as most of the work of implementing the custom tag is done
by the TagSupport superclass provided by the JSP API.
The tag library descriptor, which well name hello.tld, maps the tag to
the tag handler class and defines the way JSP pages may interact with
the HelloTag class:
The tags suffix when used in any JSP must be hello, and its prefix is
example when imported into this JSP page. So to use the tag in a JSP
we should use <examples: hello>
Before tags can be used in a JSP, the taglib directive must be used to
import a tag library and associate the tags it contains with a prefix.
Tag Handlers:
available for further use. The programmer has no control over any
pooling that may occur.
Note: the JSP engine will not use an instance of a tag handler to
handle a tag unless it is free. After all invocations of the tag handler are
completed, the container will invoke the tag handlers release () method.
This will free any remaining resources and prepare the tag handler for
garbage collection. Many tags do not need to implement the release ()
method and can simply rely on the empty default implementation inherited
from the abstract super classes provided by the tag extension API.
The Tag interface defines a simple interaction between the JSP engine and
the tag handler, which is sufficient for tags that dont need to manipulate
their body content or evaluate it repeatedly. Its core methods are the calls
received when the JSP engine encounters the tags opening and closing tags:
doStartTag () and doEndTag(). Before we look at the method contracts in
more detail, a sequence diagram helps to visualize the calls made to the tag
handler by the compiled servlet. Assume that the container already has a tag
handler instances available, and is in the default state:
Lets look at the messages in more detail:
The container initializes the tag handler by setting the tag handlers
pageContext property, which the tag handler can use to access
information available to the JSP page using it.
The container sets the tag handlers parent property. (The parent will
be set to null if the tag is not enclosed in another tag.)
Any tag attributes defined by the developer will be set. This is a
mapping from the XML attributes of the tag to the corresponding
properties of the tag handler bean. For example, in the case of a tag
invoked like this : <mytags:test name=john age=43 />, the
container will attempt to call the setName() and setAge() methods on
the tag handler. The container will attempt to convert each attribute to
the type of the corresponding bean property: for example, the string
43 would be converted to an int in this case. If the type conversion
fails, and exception will be thrown and must be handled by the calling
JSP page.
The container calls the tag handlers doStartTag() method and then the
doEndTag() method.
www.JavaEra.com
This message may not occur after all tag invocations. The container
calls the release () method. Tag handlers differ from page beans in
that their lifecycle is entirely independent of that of the JSP pages that
use them. Tag handlers must support repeated use before destruction,
possibly in a number of JSP pages. The implementation of the release
() method must ensure that any resources required during the tags
execution are freed. The JSP specification states that release () is
guaranteed to be called before the tag handler is eligible for garbage
collection.
This is called after the tag has been initialized, when the JSP engine
encounters the opening of a tag at run time. Its return value should be one
of two constants defined in the Tag interface: EVAL_BODY_INCLUDE,
which instructs thee JSP engine to evaluate both the tags body and any
child tags it has, or SKIP_BODY, which instructs the JSP engine to
ignore the body. This method can throw a JspException, (as will most of
the methods in the tag handler API WHEN AN ERROR CONDITION IS
ENCOUNTERED) BUT HOW IT WILL BE HANDLED WILL
DEPEND ON THE jsp page using the tag. Most JSP pages will use an
error page, so an exception thrown in a tag will typically abort the
rendering of the page.
void release()
release () is a call to the tag handler to release any resources, perhaps to
close a JSBC connection.
The javax.servlet.jsp.tagext.IterationTag Interface: the IterationTag interface
has been added in JSP 1.2, and extends that Tag interface. It provides a
single new method that allows the tag to repeat the evaluation of the tag
body content:
www.JavaEra.com
doAfterBody () is called each time the tags body has been processed (where
doEndTag (() would have been cvalled in the case of an implementation of
the Tag interface). The valid return values of doAfterBody () are
EVAL_BODY_AGAIN and SKIP_BODY. A return value of
EVAL_BODY_AGAIN directs the JSP engine to evaluate the tags body
and any child tags again, resulting in at lease one more call to this method. A
return value of SKIP_BODY causes the processing ofbody content to
terminate, which can be used to conditionally loop through the tag content.
<taglib>
<taglib-uri>/hello</taglib-uri>
<taglib-location>
/WEB-INF/jsp/example-taglib.tld
</taglib-location>
</taglib>
1. Expression Language
2. Custom action
3. JSTL (Java Standard Tag Library)
Operators:
Arithmetic +,-,*,/,div,%,mod
Relational == and eq
!= and ne
< and lt
>and gt
<= and le
>=and ge
Logical && and and
|| and or
! and not
Other (),empty,[],.
www.JavaEra.com
PageContext:
The javax.servlet.jsp.PageContext object for the page. Can be used to
accesss the JSP implicit objects such as request, reaponse, session,out,etc.
for example, ${pageContext.request} evaluates to the request object for the
page.
pageScope:
<jsp:useBean id=questions scope=page class=ch04.Questions>
<jsp:setProperty name=questions property=topic />
</jsp:useBean>
${pageScope.questions.topic}
requestScope:
sessionScope:
applicationScope:
param:
paramValues
cookie
initParam
ExpressioLangaugeEx.jsp
${1}+${2}=${1+2}<br>
${ 2*(4+3) }<br>
${(2*4)+2}<br>
<jsp:useBean id="sm" class="smarket.SuperMarket"scope="page">
<jsp:setProperty name="sm" property="item" value="Rice" />
<jsp:setProperty name="sm" property="qty" value="50" />
<jsp:setProperty name="sm" property="price" value="1500" />
</jsp:useBean>
price:${pageScope.sm.price}<br>
%>
${empty someName}
${sessionScope.address}
${pageScope.value}
${a}
JavaStandardTagLibrary.jsp
<h2>Formating numbers</h2>
result in<fmt:formatNumber value="23.456" type="number"/><br>
result in<fmt:formatNumber value="23.456" type="currency"/><br>
result in<fmt:formatNumber value=".23456" type="percent"/><br>
result in<fmt:formatNumber value="23.456" type="currency"
minFractionDigits="1"/><br>
</body>
</html>
Note: PLACE THE c.tld AND fmt.tld FILES in TLDS directory AND
PLACE THE TLDS DIRECTORY IN WEB-INF FOLDER.
Web.xml
<taglib>
<taglib-uri>http://java.sun.com/jstl/core</taglib-uri>
<taglib-location>
/WEB-INF/tlds/c.tld
</taglib-location>
</taglib>
<taglib>
<taglib-uri>http://java.sun.com/jstl/format</taglib-uri>
www.JavaEra.com
<taglib-location>
/WEB-INF/tlds/fmt.tld
</taglib-location>
</taglib>